commit 41e72112dcc2c36ab5c67ca5710090a5dbb98543 Author: realaravinth Date: Tue Aug 16 11:41:00 2022 +0000 new deploy: 2022-08-16T11:41:00+00:00 diff --git a/assets/Inter-Black.067c82f7.woff b/assets/Inter-Black.067c82f7.woff new file mode 100644 index 00000000..07800f4b Binary files /dev/null and b/assets/Inter-Black.067c82f7.woff differ diff --git a/assets/Inter-Black.7f1f5616.woff2 b/assets/Inter-Black.7f1f5616.woff2 new file mode 100644 index 00000000..9a615e6e Binary files /dev/null and b/assets/Inter-Black.7f1f5616.woff2 differ diff --git a/assets/Inter-BlackItalic.72d5983b.woff2 b/assets/Inter-BlackItalic.72d5983b.woff2 new file mode 100644 index 00000000..9dfced91 Binary files /dev/null and b/assets/Inter-BlackItalic.72d5983b.woff2 differ diff --git a/assets/Inter-BlackItalic.c628a2cf.woff b/assets/Inter-BlackItalic.c628a2cf.woff new file mode 100644 index 00000000..8790638b Binary files /dev/null and b/assets/Inter-BlackItalic.c628a2cf.woff differ diff --git a/assets/Inter-Bold.20d46cff.woff b/assets/Inter-Bold.20d46cff.woff new file mode 100644 index 00000000..61e1c25e Binary files /dev/null and b/assets/Inter-Bold.20d46cff.woff differ diff --git a/assets/Inter-Bold.6f5e9a23.woff2 b/assets/Inter-Bold.6f5e9a23.woff2 new file mode 100644 index 00000000..6c401bb0 Binary files /dev/null and b/assets/Inter-Bold.6f5e9a23.woff2 differ diff --git a/assets/Inter-BoldItalic.31a185fa.woff b/assets/Inter-BoldItalic.31a185fa.woff new file mode 100644 index 00000000..2de403ed Binary files /dev/null and b/assets/Inter-BoldItalic.31a185fa.woff differ diff --git a/assets/Inter-BoldItalic.e09dcbe1.woff2 b/assets/Inter-BoldItalic.e09dcbe1.woff2 new file mode 100644 index 00000000..80efd484 Binary files /dev/null and b/assets/Inter-BoldItalic.e09dcbe1.woff2 differ diff --git a/assets/Inter-ExtraBold.0ef4267e.woff2 b/assets/Inter-ExtraBold.0ef4267e.woff2 new file mode 100644 index 00000000..5a08b364 Binary files /dev/null and b/assets/Inter-ExtraBold.0ef4267e.woff2 differ diff --git a/assets/Inter-ExtraBold.45bae435.woff b/assets/Inter-ExtraBold.45bae435.woff new file mode 100644 index 00000000..433fb328 Binary files /dev/null and b/assets/Inter-ExtraBold.45bae435.woff differ diff --git a/assets/Inter-ExtraBoldItalic.30a1af87.woff b/assets/Inter-ExtraBoldItalic.30a1af87.woff new file mode 100644 index 00000000..bd97df37 Binary files /dev/null and b/assets/Inter-ExtraBoldItalic.30a1af87.woff differ diff --git a/assets/Inter-ExtraBoldItalic.d1e1f6a0.woff2 b/assets/Inter-ExtraBoldItalic.d1e1f6a0.woff2 new file mode 100644 index 00000000..97bda246 Binary files /dev/null and b/assets/Inter-ExtraBoldItalic.d1e1f6a0.woff2 differ diff --git a/assets/Inter-ExtraLight.d7be68a4.woff b/assets/Inter-ExtraLight.d7be68a4.woff new file mode 100644 index 00000000..39e6f971 Binary files /dev/null and b/assets/Inter-ExtraLight.d7be68a4.woff differ diff --git a/assets/Inter-ExtraLight.da47c335.woff2 b/assets/Inter-ExtraLight.da47c335.woff2 new file mode 100644 index 00000000..442e2255 Binary files /dev/null and b/assets/Inter-ExtraLight.da47c335.woff2 differ diff --git a/assets/Inter-ExtraLightItalic.762fa4d2.woff b/assets/Inter-ExtraLightItalic.762fa4d2.woff new file mode 100644 index 00000000..a6e1d14b Binary files /dev/null and b/assets/Inter-ExtraLightItalic.762fa4d2.woff differ diff --git a/assets/Inter-ExtraLightItalic.b3f94cfe.woff2 b/assets/Inter-ExtraLightItalic.b3f94cfe.woff2 new file mode 100644 index 00000000..db6880b1 Binary files /dev/null and b/assets/Inter-ExtraLightItalic.b3f94cfe.woff2 differ diff --git a/assets/Inter-Italic.7b187d57.woff b/assets/Inter-Italic.7b187d57.woff new file mode 100644 index 00000000..e7da6663 Binary files /dev/null and b/assets/Inter-Italic.7b187d57.woff differ diff --git a/assets/Inter-Italic.bab4e808.woff2 b/assets/Inter-Italic.bab4e808.woff2 new file mode 100644 index 00000000..8559dfde Binary files /dev/null and b/assets/Inter-Italic.bab4e808.woff2 differ diff --git a/assets/Inter-Light.0f7dfe72.woff2 b/assets/Inter-Light.0f7dfe72.woff2 new file mode 100644 index 00000000..80378a31 Binary files /dev/null and b/assets/Inter-Light.0f7dfe72.woff2 differ diff --git a/assets/Inter-Light.38326098.woff b/assets/Inter-Light.38326098.woff new file mode 100644 index 00000000..108c1120 Binary files /dev/null and b/assets/Inter-Light.38326098.woff differ diff --git a/assets/Inter-LightItalic.125c7e6a.woff2 b/assets/Inter-LightItalic.125c7e6a.woff2 new file mode 100644 index 00000000..091ff4ed Binary files /dev/null and b/assets/Inter-LightItalic.125c7e6a.woff2 differ diff --git a/assets/Inter-LightItalic.ec6c76a8.woff b/assets/Inter-LightItalic.ec6c76a8.woff new file mode 100644 index 00000000..b30452af Binary files /dev/null and b/assets/Inter-LightItalic.ec6c76a8.woff differ diff --git a/assets/Inter-Medium.0fc5d904.woff b/assets/Inter-Medium.0fc5d904.woff new file mode 100644 index 00000000..8c36a634 Binary files /dev/null and b/assets/Inter-Medium.0fc5d904.woff differ diff --git a/assets/Inter-Medium.5d308f3d.woff2 b/assets/Inter-Medium.5d308f3d.woff2 new file mode 100644 index 00000000..3b31d335 Binary files /dev/null and b/assets/Inter-Medium.5d308f3d.woff2 differ diff --git a/assets/Inter-MediumItalic.1458af9d.woff b/assets/Inter-MediumItalic.1458af9d.woff new file mode 100644 index 00000000..fb79e91f Binary files /dev/null and b/assets/Inter-MediumItalic.1458af9d.woff differ diff --git a/assets/Inter-MediumItalic.76551c20.woff2 b/assets/Inter-MediumItalic.76551c20.woff2 new file mode 100644 index 00000000..d32c111f Binary files /dev/null and b/assets/Inter-MediumItalic.76551c20.woff2 differ diff --git a/assets/Inter-Regular.5b3a854b.woff b/assets/Inter-Regular.5b3a854b.woff new file mode 100644 index 00000000..7d587c40 Binary files /dev/null and b/assets/Inter-Regular.5b3a854b.woff differ diff --git a/assets/Inter-Regular.89d406b0.woff2 b/assets/Inter-Regular.89d406b0.woff2 new file mode 100644 index 00000000..d5ffd2a1 Binary files /dev/null and b/assets/Inter-Regular.89d406b0.woff2 differ diff --git a/assets/Inter-SemiBold.04cd699f.woff b/assets/Inter-SemiBold.04cd699f.woff new file mode 100644 index 00000000..99df06cb Binary files /dev/null and b/assets/Inter-SemiBold.04cd699f.woff differ diff --git a/assets/Inter-SemiBold.c7c3befe.woff2 b/assets/Inter-SemiBold.c7c3befe.woff2 new file mode 100644 index 00000000..df746af9 Binary files /dev/null and b/assets/Inter-SemiBold.c7c3befe.woff2 differ diff --git a/assets/Inter-SemiBoldItalic.420db54a.woff b/assets/Inter-SemiBoldItalic.420db54a.woff new file mode 100644 index 00000000..91e192b9 Binary files /dev/null and b/assets/Inter-SemiBoldItalic.420db54a.woff differ diff --git a/assets/Inter-SemiBoldItalic.d376ade4.woff2 b/assets/Inter-SemiBoldItalic.d376ade4.woff2 new file mode 100644 index 00000000..ff8774cc Binary files /dev/null and b/assets/Inter-SemiBoldItalic.d376ade4.woff2 differ diff --git a/assets/Inter-Thin.5565b01e.woff b/assets/Inter-Thin.5565b01e.woff new file mode 100644 index 00000000..9d2e3e54 Binary files /dev/null and b/assets/Inter-Thin.5565b01e.woff differ diff --git a/assets/Inter-Thin.5d8e2ac4.woff2 b/assets/Inter-Thin.5d8e2ac4.woff2 new file mode 100644 index 00000000..5f7bc37c Binary files /dev/null and b/assets/Inter-Thin.5d8e2ac4.woff2 differ diff --git a/assets/Inter-ThinItalic.6b3ded18.woff2 b/assets/Inter-ThinItalic.6b3ded18.woff2 new file mode 100644 index 00000000..2ceec604 Binary files /dev/null and b/assets/Inter-ThinItalic.6b3ded18.woff2 differ diff --git a/assets/Inter-ThinItalic.c413497b.woff b/assets/Inter-ThinItalic.c413497b.woff new file mode 100644 index 00000000..885d8d5d Binary files /dev/null and b/assets/Inter-ThinItalic.c413497b.woff differ diff --git a/assets/chevron-down-1956489915.3389f17f.svg b/assets/chevron-down-1956489915.3389f17f.svg new file mode 100644 index 00000000..e0ceb187 --- /dev/null +++ b/assets/chevron-down-1956489915.3389f17f.svg @@ -0,0 +1,36 @@ + + + + + + + + + + + diff --git a/assets/chevron-down-3300400168.d1a083a1.svg b/assets/chevron-down-3300400168.d1a083a1.svg new file mode 100644 index 00000000..c3918616 --- /dev/null +++ b/assets/chevron-down-3300400168.d1a083a1.svg @@ -0,0 +1,36 @@ + + + + + + + + + + + diff --git a/assets/chevron-down.9a7440b9.svg b/assets/chevron-down.9a7440b9.svg new file mode 100644 index 00000000..5435cc39 --- /dev/null +++ b/assets/chevron-down.9a7440b9.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/chevron-left-2611498805.b5555a61.svg b/assets/chevron-left-2611498805.b5555a61.svg new file mode 100644 index 00000000..90d2cedd --- /dev/null +++ b/assets/chevron-left-2611498805.b5555a61.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/chevron-left-3506338632.4e437777.svg b/assets/chevron-left-3506338632.4e437777.svg new file mode 100644 index 00000000..2e0ed1ba --- /dev/null +++ b/assets/chevron-left-3506338632.4e437777.svg @@ -0,0 +1,10 @@ + + + + + + + + + + diff --git a/assets/chevron-left.b8b2c5fc.svg b/assets/chevron-left.b8b2c5fc.svg new file mode 100644 index 00000000..dc017203 --- /dev/null +++ b/assets/chevron-left.b8b2c5fc.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/chevron-right-2390431650.ec9bf561.svg b/assets/chevron-right-2390431650.ec9bf561.svg new file mode 100644 index 00000000..7df48477 --- /dev/null +++ b/assets/chevron-right-2390431650.ec9bf561.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/chevron-right-847198822.23380c56.svg b/assets/chevron-right-847198822.23380c56.svg new file mode 100644 index 00000000..c78cdcee --- /dev/null +++ b/assets/chevron-right-847198822.23380c56.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/chevron-right.885731d1.svg b/assets/chevron-right.885731d1.svg new file mode 100644 index 00000000..2f1e3e7a --- /dev/null +++ b/assets/chevron-right.885731d1.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/chevron-small-4098047679.489e66cc.svg b/assets/chevron-small-4098047679.489e66cc.svg new file mode 100644 index 00000000..95d9bdff --- /dev/null +++ b/assets/chevron-small-4098047679.489e66cc.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/chevron-small-781914114.936b4943.svg b/assets/chevron-small-781914114.936b4943.svg new file mode 100644 index 00000000..bec34926 --- /dev/null +++ b/assets/chevron-small-781914114.936b4943.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/chevron-small.dfd7e618.svg b/assets/chevron-small.dfd7e618.svg new file mode 100644 index 00000000..6c85b97f --- /dev/null +++ b/assets/chevron-small.dfd7e618.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/chevron-thin-left-3078630092.d0d143e3.svg b/assets/chevron-thin-left-3078630092.d0d143e3.svg new file mode 100644 index 00000000..66a541a8 --- /dev/null +++ b/assets/chevron-thin-left-3078630092.d0d143e3.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/chevron-thin-left-3831175135.13f60c05.svg b/assets/chevron-thin-left-3831175135.13f60c05.svg new file mode 100644 index 00000000..cf2e7a2f --- /dev/null +++ b/assets/chevron-thin-left-3831175135.13f60c05.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/chevron-thin-left.d111869b.svg b/assets/chevron-thin-left.d111869b.svg new file mode 100644 index 00000000..3119aad8 --- /dev/null +++ b/assets/chevron-thin-left.d111869b.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/clear-4137897294.7b90e8df.svg b/assets/clear-4137897294.7b90e8df.svg new file mode 100644 index 00000000..96d4672f --- /dev/null +++ b/assets/clear-4137897294.7b90e8df.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/clear-426756705.361f7a30.svg b/assets/clear-426756705.361f7a30.svg new file mode 100644 index 00000000..2e470ef8 --- /dev/null +++ b/assets/clear-426756705.361f7a30.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/clear.0d180c33.svg b/assets/clear.0d180c33.svg new file mode 100644 index 00000000..0f32a77d --- /dev/null +++ b/assets/clear.0d180c33.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/disable-grid-3304422220.8a79cfcb.svg b/assets/disable-grid-3304422220.8a79cfcb.svg new file mode 100644 index 00000000..41d19bbb --- /dev/null +++ b/assets/disable-grid-3304422220.8a79cfcb.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/disable-grid-4240599831.c8dc25a1.svg b/assets/disable-grid-4240599831.c8dc25a1.svg new file mode 100644 index 00000000..c87b7cef --- /dev/null +++ b/assets/disable-grid-4240599831.c8dc25a1.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/disable-grid.371ceaaa.svg b/assets/disable-grid.371ceaaa.svg new file mode 100644 index 00000000..571cecf7 --- /dev/null +++ b/assets/disable-grid.371ceaaa.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/dismiss-2476348673.d0f98560.svg b/assets/dismiss-2476348673.d0f98560.svg new file mode 100644 index 00000000..f5b82e35 --- /dev/null +++ b/assets/dismiss-2476348673.d0f98560.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/dismiss-2743697487.2f1a17f1.svg b/assets/dismiss-2743697487.2f1a17f1.svg new file mode 100644 index 00000000..a51940a8 --- /dev/null +++ b/assets/dismiss-2743697487.2f1a17f1.svg @@ -0,0 +1,4 @@ + + + + diff --git a/assets/download-sandbox.48a866e9.html b/assets/download-sandbox.48a866e9.html new file mode 100644 index 00000000..9666cb9e --- /dev/null +++ b/assets/download-sandbox.48a866e9.html @@ -0,0 +1,46 @@ + + + + + + + Download + + + diff --git a/assets/e2ee-disabled-1470792300.6863c16d.svg b/assets/e2ee-disabled-1470792300.6863c16d.svg new file mode 100644 index 00000000..170ddb07 --- /dev/null +++ b/assets/e2ee-disabled-1470792300.6863c16d.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/assets/e2ee-disabled.8507165d.svg b/assets/e2ee-disabled.8507165d.svg new file mode 100644 index 00000000..a839e4e5 --- /dev/null +++ b/assets/e2ee-disabled.8507165d.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/e2ee-normal-1448349558.af8f5484.svg b/assets/e2ee-normal-1448349558.af8f5484.svg new file mode 100644 index 00000000..0fd19d39 --- /dev/null +++ b/assets/e2ee-normal-1448349558.af8f5484.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/e2ee-normal.bef76bd4.svg b/assets/e2ee-normal.bef76bd4.svg new file mode 100644 index 00000000..ca9802c8 --- /dev/null +++ b/assets/e2ee-normal.bef76bd4.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/element-logo-1551909733.1d59f06a.svg b/assets/element-logo-1551909733.1d59f06a.svg new file mode 100644 index 00000000..0213265e --- /dev/null +++ b/assets/element-logo-1551909733.1d59f06a.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/element-logo-703176763.fc54fc8d.svg b/assets/element-logo-703176763.fc54fc8d.svg new file mode 100644 index 00000000..8e576d45 --- /dev/null +++ b/assets/element-logo-703176763.fc54fc8d.svg @@ -0,0 +1,6 @@ + + + + + + diff --git a/assets/element-logo.86bc8565.svg b/assets/element-logo.86bc8565.svg new file mode 100644 index 00000000..31c3bca9 --- /dev/null +++ b/assets/element-logo.86bc8565.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/enable-grid-2071838379.ab4f40c5.svg b/assets/enable-grid-2071838379.ab4f40c5.svg new file mode 100644 index 00000000..a8308bcc --- /dev/null +++ b/assets/enable-grid-2071838379.ab4f40c5.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/enable-grid-2288309723.f83895c8.svg b/assets/enable-grid-2288309723.f83895c8.svg new file mode 100644 index 00000000..3ee085f6 --- /dev/null +++ b/assets/enable-grid-2288309723.f83895c8.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/enable-grid.eef43c65.svg b/assets/enable-grid.eef43c65.svg new file mode 100644 index 00000000..acf9a283 --- /dev/null +++ b/assets/enable-grid.eef43c65.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/encryption-status-3449529405.c200a9bb.svg b/assets/encryption-status-3449529405.c200a9bb.svg new file mode 100644 index 00000000..de513dd3 --- /dev/null +++ b/assets/encryption-status-3449529405.c200a9bb.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/encryption-status-475927392.2fedc0bd.svg b/assets/encryption-status-475927392.2fedc0bd.svg new file mode 100644 index 00000000..ded7df83 --- /dev/null +++ b/assets/encryption-status-475927392.2fedc0bd.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/encryption-status.8054183e.svg b/assets/encryption-status.8054183e.svg new file mode 100644 index 00000000..0006bdf4 --- /dev/null +++ b/assets/encryption-status.8054183e.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/icon-maskable.965d12c4.png b/assets/icon-maskable.965d12c4.png new file mode 100644 index 00000000..3d96b2d8 Binary files /dev/null and b/assets/icon-maskable.965d12c4.png differ diff --git a/assets/icon.2a39c64c.png b/assets/icon.2a39c64c.png new file mode 100644 index 00000000..b6c70c00 Binary files /dev/null and b/assets/icon.2a39c64c.png differ diff --git a/assets/index.ca5690cf.js b/assets/index.ca5690cf.js new file mode 100644 index 00000000..fe464ae4 --- /dev/null +++ b/assets/index.ca5690cf.js @@ -0,0 +1,21 @@ +var la=Object.defineProperty,ha=Object.defineProperties;var da=Object.getOwnPropertyDescriptors;var cs=Object.getOwnPropertySymbols;var fr=Object.prototype.hasOwnProperty,gr=Object.prototype.propertyIsEnumerable;var _r=(n,e,t)=>e in n?la(n,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):n[e]=t,ft=(n,e)=>{for(var t in e||(e={}))fr.call(e,t)&&_r(n,t,e[t]);if(cs)for(var t of cs(e))gr.call(e,t)&&_r(n,t,e[t]);return n},yr=(n,e)=>ha(n,da(e));var wr=(n,e)=>{var t={};for(var s in n)fr.call(n,s)&&e.indexOf(s)<0&&(t[s]=n[s]);if(n!=null&&cs)for(var s of cs(n))e.indexOf(s)<0&&gr.call(n,s)&&(t[s]=n[s]);return t};function xe(...n){const e={};for(const t of n)e[t]=t;return Object.freeze(e)}function vr(n){try{return new URL(n).origin}catch{return new URL(`https://${n}`).origin}}async function ua(n,e){const t={format:"json",timeout:3e4,method:"GET"};try{const s=`${n}/.well-known/matrix/client`;return await e(s,t).response()}catch(s){if(s.name==="ConnectionError")return null;throw s}}async function ma(n,e){var s;n=vr(n);const t=await ua(n,e);if(t&&t.status===200){const{body:i}=t,r=(s=i["m.homeserver"])==null?void 0:s.base_url;typeof r=="string"&&(n=vr(r))}return n}class ye extends Error{get name(){return"AbortError"}}class Ii{constructor(){this._handlers=new Set}onSubscribeFirst(){}onUnsubscribeLast(){}subscribe(e){return this._handlers.add(e),this._handlers.size===1&&this.onSubscribeFirst(),()=>this.unsubscribe(e)}unsubscribe(e){e&&(this._handlers.delete(e),this._handlers.size===0&&this.onUnsubscribeLast())}unsubscribeAll(){this._handlers.size!==0&&(this._handlers.clear(),this.onUnsubscribeLast())}get hasSubscriptions(){return this._handlers.size!==0}}class kt extends Ii{emit(e){for(const t of this._handlers)t(e)}waitFor(e){return e(this.get())?new _a(Promise.resolve(this.get())):new pa(this,e)}flatMap(e){return new fa(this,e)}}class pa{constructor(e,t){this._promise=new Promise((s,i)=>{this._reject=i,this._subscription=e.subscribe(r=>{t(r)&&(this._reject=null,s(r),this.dispose())})})}get promise(){return this._promise}dispose(){this._subscription&&(this._subscription(),this._subscription=null),this._reject&&(this._reject(new ye),this._reject=null)}}class _a{constructor(e){this.promise=e}dispose(){}}class we extends kt{constructor(e){super(),this._value=e}get(){return this._value}set(e){e!==this._value&&(this._value=e,this.emit(this._value))}}class ci extends we{constructor(e,t){super(e),this._freeCallback=t}onUnsubscribeLast(){super.onUnsubscribeLast(),this._freeCallback()}}class fa extends kt{constructor(e,t){super(),this.source=e,this.mapper=t}onUnsubscribeLast(){super.onUnsubscribeLast(),this.sourceSubscription=this.sourceSubscription(),this.targetSubscription&&(this.targetSubscription=this.targetSubscription())}onSubscribeFirst(){super.onSubscribeFirst(),this.sourceSubscription=this.source.subscribe(()=>{this.updateTargetSubscription(),this.emit(this.get())}),this.updateTargetSubscription()}updateTargetSubscription(){const e=this.source.get();if(e){const t=this.mapper(e);if(t){this.targetSubscription||(this.targetSubscription=t.subscribe(()=>this.emit(this.get())));return}}this.targetSubscription&&(this.targetSubscription=this.targetSubscription())}get(){const e=this.source.get();if(!e)return;const t=this.mapper(e);return t==null?void 0:t.get()}}class Mn{constructor(e){this._abortable=void 0;const t=i=>(this._abortable=i,i);this._progress=new we(void 0);const s=i=>{this._progress.set(i)};this.result=e(t,s)}get progress(){return this._progress}abort(){var e;(e=this._abortable)==null||e.abort(),this._abortable=void 0}}const ga={"image/jpeg":!0,"image/gif":!0,"image/png":!0,"video/mp4":!0,"video/webm":!0,"video/ogg":!0,"video/quicktime":!0,"video/VP8":!0,"audio/mp4":!0,"audio/webm":!0,"audio/aac":!0,"audio/mpeg":!0,"audio/ogg":!0,"audio/wave":!0,"audio/wav":!0,"audio/x-wav":!0,"audio/x-pn-wav":!0,"audio/flac":!0,"audio/x-flac":!0},br="application/octet-stream";class lt{constructor(e,t=null){this._blob=e,this._buffer=t,this._url=null}static fromBuffer(e,t){return t=t?t.split(";")[0].trim():"",ga[t]||(t=br),new lt(new Blob([e],{type:t}),e)}static fromBlob(e){return new lt(e)}get nativeBlob(){return this._blob}async readAsBuffer(){if(this._buffer)return this._buffer;{const e=new FileReader,t=new Promise((s,i)=>{e.addEventListener("load",r=>s(r.target.result)),e.addEventListener("error",r=>i(r.target.error))});return e.readAsArrayBuffer(this._blob),t}}get url(){return this._url||(this._url=URL.createObjectURL(this._blob)),this._url}get size(){return this._blob.size}get mimeType(){return this._blob.type||br}dispose(){this._url&&(URL.revokeObjectURL(this._url),this._url=null)}}function An(n){return Object.entries(n||{}).filter(([,e])=>e!==void 0).map(([e,t])=>(typeof t=="object"&&(t=JSON.stringify(t)),`${encodeURIComponent(e)}=${encodeURIComponent(t)}`)).join("&")}function ya(n){if(n instanceof lt){const e=n;return{mimeType:e.mimeType,body:e}}else{if(n instanceof Map)return{mimeType:"multipart/form-data",body:n};if(typeof n=="object"){const e=JSON.stringify(n);return{mimeType:"application/json",body:e}}else throw new Error("Unknown body type: "+n)}}class xn extends Error{constructor(e,t){super(`${e}: ${t.message}`),this.cause=t}get name(){return"WrappedError"}}class Nn extends Error{constructor(e,t,s,i){super(`${s?s.error:i} on ${e} ${t}`),this.errcode=s?s.errcode:null,this.retry_after_ms=s?s.retry_after_ms:0,this.statusCode=i}get name(){return"HomeServerError"}}class qe extends Error{constructor(e,t){super(e||"ConnectionError"),this.isTimeout=t}get name(){return"ConnectionError"}}class wa{constructor(e,t,s,i){let r;if(i!=null&&i.log){const o=i==null?void 0:i.log;r=o.child({t:"network",url:t,method:e},o.level.Info)}this._log=r,this._sourceRequest=s,this._promise=s.response().then(o=>{var a,c;if(r==null||r.set("status",o.status),o.status>=200&&o.status<300||((a=i==null?void 0:i.allowedStatusCodes)==null?void 0:a.includes(o.status)))return r==null||r.finish(),o.body;if(o.status>=500){const l=new qe("Internal Server Error");throw r==null||r.catch(l),l}else if(o.status>=400&&!((c=o.body)!=null&&c.errcode)){const l=new qe(`HTTP error status ${o.status} without errcode in body, assume this is a load balancer complaining the server is offline.`);throw r==null||r.catch(l),l}else{const l=new Nn(e,t,o.body,o.status);throw r==null||r.set("errcode",l.errcode),r==null||r.catch(l),l}},o=>{if(o.name==="AbortError"&&this._sourceRequest){const a=new qe("Service worker aborted, either updating or hit #187.");throw r==null||r.catch(a),a}else throw o.name==="ConnectionError"&&(r==null||r.set("timeout",o.isTimeout)),r==null||r.catch(o),o})}abort(){var e;this._sourceRequest&&((e=this._log)==null||e.set("aborted",!0),this._sourceRequest.abort(),this._sourceRequest=void 0)}response(){return this._promise}async responseCode(){return(await this._sourceRequest.response()).status}}const ls="/_matrix/client/r0",va="/_matrix/client/v3",ei="/_matrix/client/unstable/org.matrix.msc2697.v2";class Ze{constructor({homeserver:e,accessToken:t,request:s,reconnector:i}){this._homeserver=e,this._accessToken=t,this._requestFn=s,this._reconnector=i}_url(e,t=ls){return this._homeserver+t+e}_baseRequest(e,t,s,i,r,o){const a=An(s);t=`${t}?${a}`;let c;const l=new Map;if(o&&l.set("Authorization",`Bearer ${o}`),l.set("Accept","application/json"),i){const u=ya(i);l.set("Content-Type",u.mimeType),c=u.body}const h=this._requestFn(t,{method:e,headers:l,body:c,timeout:r==null?void 0:r.timeout,uploadProgress:r==null?void 0:r.uploadProgress,format:"json",cache:e!=="GET"}),d=new wa(e,t,h,r);return this._reconnector&&d.response().catch(u=>{u.name==="ConnectionError"&&this._reconnector.onRequestFailed(this)}),d}_unauthedRequest(e,t,s,i,r){return this._baseRequest(e,t,s,i,r)}_authedRequest(e,t,s,i,r){return this._baseRequest(e,t,s,i,r,this._accessToken)}_post(e,t,s,i){return this._authedRequest("POST",this._url(e,(i==null?void 0:i.prefix)||ls),t,s,i)}_put(e,t,s,i){return this._authedRequest("PUT",this._url(e,(i==null?void 0:i.prefix)||ls),t,s,i)}_get(e,t,s,i){return this._authedRequest("GET",this._url(e,(i==null?void 0:i.prefix)||ls),t,s,i)}sync(e,t,s,i){return this._get("/sync",{since:e,timeout:s,filter:t},void 0,i)}context(e,t,s,i){return this._get(`/rooms/${encodeURIComponent(e)}/context/${encodeURIComponent(t)}`,{filter:i,limit:s})}messages(e,t,s){return this._get(`/rooms/${encodeURIComponent(e)}/messages`,t,void 0,s)}members(e,t,s){return this._get(`/rooms/${encodeURIComponent(e)}/members`,t,void 0,s)}send(e,t,s,i,r){return this._put(`/rooms/${encodeURIComponent(e)}/send/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},i,r)}redact(e,t,s,i,r){return this._put(`/rooms/${encodeURIComponent(e)}/redact/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},i,r)}receipt(e,t,s,i){return this._post(`/rooms/${encodeURIComponent(e)}/receipt/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},{},i)}state(e,t,s,i){return this._get(`/rooms/${encodeURIComponent(e)}/state/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{},void 0,i)}getLoginFlows(){return this._unauthedRequest("GET",this._url("/login"))}register(e,t,s,i,r=!0,o={}){o.allowedStatusCodes=[401];const a={auth:i,password:t,initial_device_displayname:s,inhibit_login:r};return e&&(a.username=e),this._unauthedRequest("POST",this._url("/register",va),void 0,a,o)}passwordLogin(e,t,s,i){return this._unauthedRequest("POST",this._url("/login"),void 0,{type:"m.login.password",identifier:{type:"m.id.user",user:e},password:t,initial_device_display_name:s},i)}tokenLogin(e,t,s,i){return this._unauthedRequest("POST",this._url("/login"),void 0,{type:"m.login.token",identifier:{type:"m.id.user"},token:e,txn_id:t,initial_device_display_name:s},i)}createFilter(e,t,s){return this._post(`/user/${encodeURIComponent(e)}/filter`,{},t,s)}versions(e){return this._unauthedRequest("GET",`${this._homeserver}/_matrix/client/versions`,void 0,void 0,e)}uploadKeys(e,t,s){let i="/keys/upload";return e&&(i=i+`/${encodeURIComponent(e)}`),this._post(i,{},t,s)}queryKeys(e,t){return this._post("/keys/query",{},e,t)}claimKeys(e,t){return this._post("/keys/claim",{},e,t)}sendToDevice(e,t,s,i){return this._put(`/sendToDevice/${encodeURIComponent(e)}/${encodeURIComponent(s)}`,{},t,i)}roomKeysVersion(e,t){let s="";return e&&(s=`/${encodeURIComponent(e)}`),this._get(`/room_keys/version${s}`,void 0,void 0,t)}roomKeyForRoomAndSession(e,t,s,i){return this._get(`/room_keys/keys/${encodeURIComponent(t)}/${encodeURIComponent(s)}`,{version:e},void 0,i)}uploadRoomKeysToBackup(e,t,s){return this._put("/room_keys/keys",{version:e},t,s)}uploadAttachment(e,t,s){return this._authedRequest("POST",`${this._homeserver}/_matrix/media/r0/upload`,{filename:t},e,s)}setPusher(e,t){return this._post("/pushers/set",{},e,t)}getPushers(e){return this._get("/pushers",void 0,void 0,e)}join(e,t){return this._post(`/rooms/${encodeURIComponent(e)}/join`,{},{},t)}joinIdOrAlias(e,t){return this._post(`/join/${encodeURIComponent(e)}`,{},{},t)}leave(e,t){return this._post(`/rooms/${encodeURIComponent(e)}/leave`,{},{},t)}forget(e,t){return this._post(`/rooms/${encodeURIComponent(e)}/forget`,{},{},t)}logout(e){return this._post("/logout",{},{},e)}getDehydratedDevice(e={}){return e.prefix=ei,this._get("/dehydrated_device",void 0,void 0,e)}createDehydratedDevice(e,t={}){return t.prefix=ei,this._put("/dehydrated_device",{},e,t)}claimDehydratedDevice(e,t={}){return t.prefix=ei,this._post("/dehydrated_device/claim",{},{device_id:e},t)}profile(e,t){return this._get(`/profile/${encodeURIComponent(e)}`)}createRoom(e,t){return this._post("/createRoom",{},e,t)}setAccountData(e,t,s,i){return this._put(`/user/${encodeURIComponent(e)}/account_data/${encodeURIComponent(t)}`,{},s,i)}}class Dn{constructor(e){this._start=2e3,this._current=2e3;const t=2e3;this._start=t,this._current=t,this._createTimeout=e,this._max=60*5*1e3}async waitForRetry(){this._timeout=this._createTimeout(this._current);try{await this._timeout.elapsed();const e=2*this._current;this._current=Math.min(this._max,e)}catch(e){if(!(e instanceof ye))throw e}finally{this._timeout=void 0}}abort(){this._timeout&&this._timeout.abort()}reset(){this._current=this._start,this.abort()}get nextValue(){return this._current}}var $t=(n=>(n[n.Waiting=0]="Waiting",n[n.Reconnecting=1]="Reconnecting",n[n.Online=2]="Online",n))($t||{});class ba{constructor({retryDelay:e,createMeasure:t,onlineStatus:s}){this._onlineStatus=s,this._retryDelay=e,this._createTimeMeasure=t,this._state=new we(2),this._isReconnecting=!1}get lastVersionsResponse(){return this._versionsResponse}get connectionStatus(){return this._state}get retryIn(){return this._state.get()===0?this._retryDelay.nextValue-this._stateSince.measure():0}async onRequestFailed(e){if(!this._isReconnecting){this._isReconnecting=!0;const t=this._onlineStatus&&this._onlineStatus.subscribe(s=>{s&&this.tryNow()});try{await this._reconnectLoop(e)}catch(s){console.error(s)}finally{t&&t(),this._isReconnecting=!1}}}tryNow(){this._retryDelay&&this._retryDelay.abort()}_setState(e){e!==this._state.get()&&(e===0?this._stateSince=this._createTimeMeasure():this._stateSince=null,this._state.set(e))}async _reconnectLoop(e){for(this._versionsResponse=void 0,this._retryDelay.reset();!this._versionsResponse;)try{this._setState(1);const t=e.versions({timeout:3e4});this._versionsResponse=await t.response(),this._setState(2)}catch(t){if(t.name==="ConnectionError")this._setState(0),await this._retryDelay.waitForRetry();else throw t}}}async function Sa(n,e,t){if(t===void 0||t.key===void 0||t.iv===void 0||t.hashes===void 0||t.hashes.sha256===void 0)throw new Error("Invalid info. Missing info.key, info.iv or info.hashes.sha256 key");const{crypto:s}=n,{base64:i}=n.encoding;var r=i.decode(t.iv),o=i.encode(i.decode(t.hashes.sha256));const a=await s.digest("SHA-256",e);if(i.encode(new Uint8Array(a))!=o)throw new Error("Mismatched SHA-256 digest");var c;return t.v=="v1"||t.v=="v2"?c=64:c=128,await s.aes.decryptCTR({jwkKey:t.key,iv:r,data:e,counterLength:c})}async function Ia(n,e){const{crypto:t}=n,{base64:s}=n.encoding,i=await t.aes.generateIV(),r=await t.aes.generateKey("jwk",256),o=await e.readAsBuffer(),a=await t.aes.encryptCTR({jwkKey:r,iv:i,data:o}),c=await t.digest("SHA-256",a);return{blob:n.createBlob(a,"application/octet-stream"),info:{v:"v2",key:r,iv:s.encodeUnpadded(i),hashes:{sha256:s.encodeUnpadded(c)}}}}class Ea{constructor({homeserver:e,platform:t}){this._homeserver=e,this._platform=t}mxcUrlThumbnail(e,t,s,i){const r=this._parseMxcUrl(e);if(r){const[o,a]=r;return`${this._homeserver}/_matrix/media/r0/thumbnail/${encodeURIComponent(o)}/${encodeURIComponent(a)}`+"?"+An({width:Math.round(t),height:Math.round(s),method:i})}return null}mxcUrl(e){const t=this._parseMxcUrl(e);if(t){const[s,i]=t;return`${this._homeserver}/_matrix/media/r0/download/${encodeURIComponent(s)}/${encodeURIComponent(i)}`}else return null}_parseMxcUrl(e){const t="mxc://";return e.startsWith(t)?e.substr(t.length).split("/",2):null}async downloadEncryptedFile(e,t=!1){const s=this.mxcUrl(e.url),{body:i}=await this._platform.request(s,{method:"GET",format:"buffer",cache:t}).response(),r=await Sa(this._platform,i,e);return this._platform.createBlob(r,e.mimetype)}async downloadPlaintextFile(e,t,s=!1){const i=this.mxcUrl(e),{body:r}=await this._platform.request(i,{method:"GET",format:"buffer",cache:s}).response();return this._platform.createBlob(r,t)}async downloadAttachment(e,t=!1){var s;return e.file?this.downloadEncryptedFile(e.file,t):this.downloadPlaintextFile(e.url,(s=e.info)==null?void 0:s.mimetype,t)}}class ka{constructor(e,t){this.methodName=e,this.args=t,this._responsePromise=new Promise((s,i)=>{this.responseResolve=s,this.responseReject=i})}abort(){var e;this._requestResult?this._requestResult.abort():(this.responseReject(new ye),(e=this.responseCodeReject)==null||e.call(this,new ye))}response(){return this._responsePromise}responseCode(){return this.requestResult?this.requestResult.responseCode():(this._responseCodePromise||(this._responseCodePromise=new Promise((e,t)=>{this.responseCodeResolve=e,this.responseCodeReject=t})),this._responseCodePromise)}async setRequestResult(e){var i,r,o;this._requestResult=e;const t=await((i=this._requestResult)==null?void 0:i.response());this.responseResolve(t);const s=await((r=this._requestResult)==null?void 0:r.responseCode());(o=this.responseCodeResolve)==null||o.call(this,s)}get requestResult(){return this._requestResult}}class Vn{constructor(e){this._scheduler=e}}for(const n of Object.getOwnPropertyNames(Ze.prototype))n!=="constructor"&&!n.startsWith("_")&&(Vn.prototype[n]=function(...e){return this._scheduler._hsApiRequest(n,e)});class Ra{constructor({hsApi:e,clock:t}){this._requests=new Set,this._stopped=!1,this._wrapper=new Vn(this),this._hsApi=e,this._clock=t}get hsApi(){return this._wrapper}stop(){this._stopped=!0;for(const e of this._requests)e.abort();this._requests.clear()}start(){this._stopped=!1}_hsApiRequest(e,t){const s=new ka(e,t);return this._doSend(s),s}async _doSend(e){this._requests.add(e);try{let t;for(;!this._stopped;)try{const s=this._hsApi[e.methodName].apply(this._hsApi,e.args);await e.setRequestResult(s);return}catch(s){if(s instanceof Nn&&s.errcode==="M_LIMIT_EXCEEDED")Number.isSafeInteger(s.retry_after_ms)?await this._clock.createTimeout(s.retry_after_ms).elapsed():(t||(t=new Dn(this._clock.createTimeout)),await t.waitForRetry());else{e.responseReject(s);return}}this._stopped&&e.abort()}finally{this._requests.delete(e)}}}const Ca=3e4,L=xe("InitialSync","CatchupSync","Syncing","Stopped");function Ta(n){var e;try{const t=(e=n==null?void 0:n.timeline)==null?void 0:e.events;return Array.isArray(t)&&t.length===0}catch{return!0}}class Ma{constructor({hsApi:e,session:t,storage:s,logger:i}){this._hsApi=e,this._logger=i,this._session=t,this._storage=s,this._currentRequest=null,this._status=new we(L.Stopped),this._error=null}get status(){return this._status}get error(){return this._error}start(){if(this._status.get()!==L.Stopped)return;this._error=null;let e=this._session.syncToken;e?this._status.set(L.CatchupSync):this._status.set(L.InitialSync),this._syncLoop(e)}async _syncLoop(e){for(;this._status.get()!==L.Stopped;){let t,s,i=this._status.get()===L.CatchupSync||this._status.get()===L.InitialSync;await this._logger.run("sync",async r=>{r.set("token",e),r.set("status",this._status.get());try{const o=this._status.get()===L.Syncing?Ca:0,a=await this._syncRequest(e,o,r);e=a.syncToken,t=a.roomStates,s=a.sessionChanges,this._status.get()!==L.Syncing&&a.hadToDeviceMessages?this._status.set(L.CatchupSync):this._status.set(L.Syncing)}catch(o){if(o.name==="ConnectionError"&&o.isTimeout)return;this._error=o,o.name!=="AbortError"&&(r.error=o,r.logLevel=r.level.Fatal),r.set("stopping",!0),this._status.set(L.Stopped)}this._status.get()!==L.Stopped&&await r.wrap("afterSyncCompleted",o=>this._runAfterSyncCompleted(s,t,o))},this._logger.level.Info,(r,o)=>o.durationWithoutType("network")>=2e3||o.error||i?r.minLevel(o.level.Detail):r.minLevel(o.level.Info))}}async _runAfterSyncCompleted(e,t,s){const i=this._status.get()===L.CatchupSync,r=(async()=>{try{await s.wrap("session",c=>this._session.afterSyncCompleted(e,i,c),s.level.Detail)}catch{}})(),a=t.filter(c=>c.room.needsAfterSyncCompleted(c.changes)).map(async c=>{try{await s.wrap("room",l=>c.room.afterSyncCompleted(c.changes,l),s.level.Detail)}catch{}});await Promise.all(a.concat(r))}async _syncRequest(e,t,s){var p;let{syncFilterId:i}=this._session;typeof i!="string"&&(this._currentRequest=this._hsApi.createFilter(this._session.user.id,{room:{state:{lazy_load_members:!0}}},{log:s}),i=(await this._currentRequest.response()).filter_id);const r=t+80*1e3;this._currentRequest=this._hsApi.sync(e,i,t,{timeout:r,log:s});const o=await this._currentRequest.response(),a=!e,c=new Aa,l=this._parseInvites(o.rooms),{roomStates:h,archivedRoomStates:d}=await this._parseRoomsResponse(o.rooms,l,a,s);try{c.lock=await s.wrap("obtainSyncLock",()=>this._session.obtainSyncLock(o)),await s.wrap("prepare",_=>this._prepareSync(c,h,o,_)),await s.wrap("afterPrepareSync",_=>Promise.all(h.map(f=>f.room.afterPrepareSync(f.preparation,_)))),await s.wrap("write",async _=>this._writeSync(c,l,h,d,o,i,a,_))}finally{c.dispose()}s.wrap("after",_=>this._afterSync(c,l,h,d,_));const u=(p=o.to_device)==null?void 0:p.events;return{syncToken:o.next_batch,roomStates:h,sessionChanges:c.changes,hadToDeviceMessages:Array.isArray(u)&&u.length>0}}_openPrepareSyncTxn(){const e=this._storage.storeNames;return this._storage.readTxn([e.olmSessions,e.inboundGroupSessions,e.timelineFragments,e.timelineEvents])}async _prepareSync(e,t,s,i){var a,c;const r=await this._openPrepareSyncTxn();e.preparation=await i.wrap("session",l=>this._session.prepareSync(s,e.lock,r,l));const o=(a=e.preparation)==null?void 0:a.newKeysByRoom;if(o){const{hasOwnProperty:l}=Object.prototype;for(const h of o.keys())if(!(((c=s.rooms)==null?void 0:c.join)&&l.call(s.rooms.join,h))){let u=this._session.rooms.get(h);u&&t.push(new Sr(u,!1,{},u.membership))}}await Promise.all(t.map(async l=>{const h=o==null?void 0:o.get(l.room.id);l.preparation=await i.wrap("room",async d=>(l.isNewRoom&&await l.room.load(null,r,d),l.room.prepareSync(l.roomResponse,l.membership,h,r,d)),i.level.Detail)})),await r.complete()}async _writeSync(e,t,s,i,r,o,a,c){const l=await this._openSyncTxn();try{e.changes=await c.wrap("session",h=>this._session.writeSync(r,o,e.preparation,l,h)),await Promise.all(t.map(async h=>{h.changes=await c.wrap("invite",d=>h.invite.writeSync(h.membership,h.roomResponse,l,d))})),await Promise.all(s.map(async h=>{h.changes=await c.wrap("room",d=>h.room.writeSync(h.roomResponse,a,h.preparation,l,d))})),await Promise.all(i.map(async h=>{var u;const d=(u=h.roomState)==null?void 0:u.summaryChanges;h.changes=await c.wrap("archivedRoom",p=>h.archivedRoom.writeSync(d,h.roomResponse,h.membership,l,p))}))}catch(h){throw l.abort(c),l.getCause(h)}await l.complete(c)}_afterSync(e,t,s,i,r){r.wrap("session",o=>this._session.afterSync(e.changes,o),r.level.Detail);for(let o of i)r.wrap("archivedRoom",a=>{o.archivedRoom.afterSync(o.changes,a),o.archivedRoom.release()},r.level.Detail);for(let o of s)r.wrap("room",a=>o.room.afterSync(o.changes,a),r.level.Detail);for(let o of t)r.wrap("invite",a=>o.invite.afterSync(o.changes,a),r.level.Detail);this._session.applyRoomCollectionChangesAfterSync(t,s,i,r)}_openSyncTxn(){const e=this._storage.storeNames;return this._storage.readWriteTxn([e.session,e.roomSummary,e.archivedRoomSummary,e.invites,e.roomState,e.roomMembers,e.timelineEvents,e.timelineRelations,e.timelineFragments,e.pendingEvents,e.userIdentities,e.groupSessionDecryptions,e.deviceIdentities,e.outboundGroupSessions,e.operations,e.accountData,e.olmSessions,e.inboundGroupSessions])}async _parseRoomsResponse(e,t,s,i){const r=[],o=[];if(e){const a=["join","leave"];for(const c of a){const l=e[c];if(l)for(const[h,d]of Object.entries(l)){if(s&&Ta(d))continue;const u=this._session.invites.get(h);u&&t.push(new Ir(u,!1,null,c));const p=this._createRoomSyncState(h,d,c,s);p&&r.push(p);const _=await this._createArchivedRoomSyncState(h,p,d,c,s,i);_&&o.push(_)}}}return{roomStates:r,archivedRoomStates:o}}_createRoomSyncState(e,t,s,i){let r=!1,o=this._session.rooms.get(e);if(!o&&(s==="join"||i&&s==="leave")&&(o=this._session.createJoinedRoom(e),r=!0),o)return new Sr(o,r,t,s)}async _createArchivedRoomSyncState(e,t,s,i,r,o){let a;if((t==null?void 0:t.shouldAdd)&&!r?a=this._session.createOrGetArchivedRoomForSync(e):i==="leave"&&(t?a=this._session.createOrGetArchivedRoomForSync(e):a=await this._session.loadArchivedRoom(e,o)),a)return new xa(a,t,s,i)}_parseInvites(e){const t=[];if(e!=null&&e.invite)for(const[s,i]of Object.entries(e.invite)){let r=this._session.invites.get(s),o=!1;r||(r=this._session.createInvite(s),o=!0),t.push(new Ir(r,o,i,"invite"))}return t}stop(){this._status.get()!==L.Stopped&&(this._status.set(L.Stopped),this._currentRequest&&(this._currentRequest.abort(),this._currentRequest=null))}}class Aa{constructor(){this.lock=null,this.preparation=null,this.changes=null}dispose(){var e;(e=this.lock)==null||e.release()}}class Sr{constructor(e,t,s,i){this.room=e,this.isNewRoom=t,this.roomResponse=s,this.membership=i,this.preparation=null,this.changes=null}get id(){return this.room.id}get shouldAdd(){return this.isNewRoom&&this.membership==="join"}get shouldRemove(){return!this.isNewRoom&&this.membership!=="join"}get summaryChanges(){var e;return(e=this.changes)==null?void 0:e.summaryChanges}}class xa{constructor(e,t,s,i,r){this.archivedRoom=e,this.roomState=t,this.roomResponse=s,this.membership=i,this.isInitialSync=r,this.changes=null}get id(){return this.archivedRoom.id}get shouldAdd(){return(this.roomState||this.isInitialSync)&&this.membership==="leave"}get shouldRemove(){return this.membership==="join"}}class Ir{constructor(e,t,s,i){this.invite=e,this.isNewInvite=t,this.membership=i,this.roomResponse=s,this.changes=null}get id(){return this.invite.id}get shouldAdd(){return this.isNewInvite}get shouldRemove(){return this.membership!=="invite"}}class Ls{constructor(){this._handlersByName={}}emit(e,t){const s=this._handlersByName[e];s&&s.forEach(i=>i(t))}disposableOn(e,t){return this.on(e,t),()=>{this.off(e,t)}}on(e,t){let s=this._handlersByName[e];s||(this.onFirstSubscriptionAdded(e),this._handlersByName[e]=s=new Set),s.add(t)}off(e,t){const s=this._handlersByName[e];s&&(s.delete(t),s.size===0&&(delete this._handlersByName[e],this.onLastSubscriptionRemoved(e)))}onFirstSubscriptionAdded(e){}onLastSubscriptionRemoved(e){}}function Na(n){if(n.__esModule)return n;var e=Object.defineProperty({},"__esModule",{value:!0});return Object.keys(n).forEach(function(t){var s=Object.getOwnPropertyDescriptor(n,t);Object.defineProperty(e,t,s.get?s:{enumerable:!0,get:function(){return n[t]}})}),e}var Er=/[\\\"\x00-\x1F]/g,Ne={};for(var hs=0;hs<32;++hs)Ne[String.fromCharCode(hs)]="\\U"+("0000"+hs.toString(16)).slice(-4).toUpperCase();Ne["\b"]="\\b";Ne[" "]="\\t";Ne[` +`]="\\n";Ne["\f"]="\\f";Ne["\r"]="\\r";Ne['"']='\\"';Ne["\\"]="\\\\";function Ln(n){return Er.lastIndex=0,n.replace(Er,function(e){return Ne[e]})}function Ei(n){switch(typeof n){case"string":return'"'+Ln(n)+'"';case"number":return isFinite(n)?n:"null";case"boolean":return n;case"object":return n===null?"null":Array.isArray(n)?Da(n):Va(n);default:throw new Error("Cannot stringify: "+typeof n)}}function Da(n){for(var e="[",t="",s=0;sBa(r,o,t,s,i),n)),n}function Fn(n,e,t){var r,o;const s=(r=n==null?void 0:n.state)==null?void 0:r.events;Array.isArray(s)&&(t=s.reduce(e,t));const i=(o=n==null?void 0:n.timeline)==null?void 0:o.events;return Array.isArray(i)&&(t=i.reduce((a,c)=>(typeof c.state_key=="string"&&(t=e(t,c)),t),t)),t}function Pa(n,e,t,s){e.summary&&(n=Ka(n,e.summary)),t!==n.membership&&(n=n.cloneIfNeeded(),n.membership=t),e.account_data&&(n=e.account_data.events.reduce(Fa,n)),n=Fn(e,(r,o)=>Bn(r,o,s),n);const i=e.unread_notifications;return i&&(n=Ua(n,i)),n}function Ua(n,e){const t=e.highlight_count||0;t!==n.highlightCount&&(n=n.cloneIfNeeded(),n.highlightCount=t);const s=e.notification_count;return s!==n.notificationCount&&(n=n.cloneIfNeeded(),n.notificationCount=s),n}function Fa(n,e){var t;if((e==null?void 0:e.type)==="m.tag"){let s=(t=e==null?void 0:e.content)==null?void 0:t.tags;(!s||Array.isArray(s)||typeof s!="object")&&(s=null),n=n.cloneIfNeeded(),n.tags=s}return n}function Bn(n,e,t){var s,i,r;if(e.type==="m.room.create")n=n.cloneIfNeeded(),n.lastMessageTimestamp=e.origin_server_ts;else if(e.type==="m.room.encryption"){const o=(s=e.content)==null?void 0:s.algorithm;!n.encryption&&o===ve&&(n=n.cloneIfNeeded(),n.encryption=e.content)}else if(e.type==="m.room.name"){const o=(i=e.content)==null?void 0:i.name;o!==n.name&&(n=n.cloneIfNeeded(),n.name=o)}else if(e.type==="m.room.avatar"){const o=(r=e.content)==null?void 0:r.url;o!==n.avatarUrl&&(n=n.cloneIfNeeded(),n.avatarUrl=o)}else if(e.type==="m.room.canonical_alias"){const o=e.content;n=n.cloneIfNeeded(),n.canonicalAlias=o.alias}else if(e.type==="m.room.member"){const o=e.content;if(o.is_direct===!0&&o.membership==="invite"&&!n.isDirectMessage){let a;e.sender===t?a=e.state_key:e.state_key===t&&(a=e.sender),a&&(n=n.cloneIfNeeded(),n.isDirectMessage=!0,n.dmUserId=a)}else o.membership==="leave"&&n.isDirectMessage&&n.dmUserId===e.state_key&&(n=n.cloneIfNeeded(),n.isDirectMessage=!1,n.dmUserId=null)}return n}function Ba(n,e,t,s,i){return e.eventType==="m.room.message"&&((!n.lastMessageTimestamp||e.timestamp>n.lastMessageTimestamp)&&(n=n.cloneIfNeeded(),n.lastMessageTimestamp=e.timestamp),!t&&e.sender!==i&&s&&(n=n.cloneIfNeeded(),n.isUnread=!0)),n}function Ka(n,e){const t=e["m.heroes"],s=e["m.joined_member_count"],i=e["m.invited_member_count"];return t&&Array.isArray(t)&&(n=n.cloneIfNeeded(),n.heroes=t),Number.isInteger(i)&&(n=n.cloneIfNeeded(),n.inviteCount=i),Number.isInteger(s)&&(n=n.cloneIfNeeded(),n.joinCount=s),n}class Ee{constructor(e,t){this.roomId=e?e.roomId:t,this.name=e?e.name:null,this.lastMessageTimestamp=e?e.lastMessageTimestamp:null,this.isUnread=e?e.isUnread:!1,this.encryption=e?e.encryption:null,this.membership=e?e.membership:null,this.inviteCount=e?e.inviteCount:0,this.joinCount=e?e.joinCount:0,this.heroes=e?e.heroes:null,this.canonicalAlias=e?e.canonicalAlias:null,this.hasFetchedMembers=e?e.hasFetchedMembers:!1,this.isTrackingMembers=e?e.isTrackingMembers:!1,this.avatarUrl=e?e.avatarUrl:null,this.notificationCount=e?e.notificationCount:0,this.highlightCount=e?e.highlightCount:0,this.tags=e?e.tags:null,this.isDirectMessage=e?e.isDirectMessage:!1,this.dmUserId=e?e.dmUserId:null,this.cloned=!!e}changedKeys(e){return Object.getOwnPropertyNames(this).filter(s=>s!=="cloned"&&this[s]!==e[s])}cloneIfNeeded(){return this.cloned?this:new Ee(this)}serialize(){return Object.entries(this).reduce((e,[t,s])=>(t!=="cloned"&&s!==null&&(e[t]=s),e),{})}applyTimelineEntries(e,t,s,i){return Oa(this,e,t,s,i)}applySyncResponse(e,t,s){return Pa(this,e,t,s)}get needsHeroes(){return!this.name&&!this.canonicalAlias&&this.heroes&&this.heroes.length>0}isNewJoin(e){return this.membership==="join"&&e.membership!=="join"}}class $a{constructor(e){this._data=null,this.applyChanges(new Ee(null,e))}get data(){return this._data}writeClearUnread(e){const t=new Ee(this._data);return t.isUnread=!1,t.notificationCount=0,t.highlightCount=0,e.roomSummary.set(t.serialize()),t}writeHasFetchedMembers(e,t){const s=new Ee(this._data);return s.hasFetchedMembers=e,t.roomSummary.set(s.serialize()),s}writeIsTrackingMembers(e,t){const s=new Ee(this._data);return s.isTrackingMembers=e,t.roomSummary.set(s.serialize()),s}writeData(e,t){if(e!==this._data)return t.roomSummary.set(e.serialize()),e}writeArchivedData(e,t){if(e!==this._data)return t.archivedRoomSummary.set(e.serialize()),e}async writeAndApplyData(e,t){if(e===this._data)return!1;const s=await t.readWriteTxn([t.storeNames.roomSummary]);try{s.roomSummary.set(e.serialize())}catch(i){throw s.abort(),i}return await s.complete(),this.applyChanges(e),!0}applyChanges(e){this._data=e,this._data.cloned=!1}async load(e){this.applyChanges(new Ee(e))}}var P=(n=>(n.session="session",n.roomState="roomState",n.roomSummary="roomSummary",n.archivedRoomSummary="archivedRoomSummary",n.invites="invites",n.roomMembers="roomMembers",n.timelineEvents="timelineEvents",n.timelineRelations="timelineRelations",n.timelineFragments="timelineFragments",n.pendingEvents="pendingEvents",n.userIdentities="userIdentities",n.deviceIdentities="deviceIdentities",n.olmSessions="olmSessions",n.inboundGroupSessions="inboundGroupSessions",n.outboundGroupSessions="outboundGroupSessions",n.groupSessionDecryptions="groupSessionDecryptions",n.operations="operations",n.accountData="accountData",n))(P||{});const Gt=Object.values(P);class Re extends Error{constructor(e,t=null){super(e),t&&(this.errcode=t.name),this.cause=t}get name(){return"StorageError"}}const F={get minStorageKey(){return 0},get middleStorageKey(){return 2147483647},get maxStorageKey(){return 4294967295}};class B{constructor(e,t){this.fragmentId=e,this.eventIndex=t}nextFragmentKey(){return new B(this.fragmentId+1,F.middleStorageKey)}nextKeyForDirection(e){return e.isForward?this.nextKey():this.previousKey()}previousKey(){return new B(this.fragmentId,this.eventIndex-1)}nextKey(){return new B(this.fragmentId,this.eventIndex+1)}static get maxKey(){return new B(F.maxStorageKey,F.maxStorageKey)}static get minKey(){return new B(F.minStorageKey,F.minStorageKey)}static get defaultLiveKey(){return B.defaultFragmentKey(F.minStorageKey)}static defaultFragmentKey(e){return new B(e,F.middleStorageKey)}toString(){return`[${this.fragmentId}/${this.eventIndex}]`}equals(e){return this.fragmentId===(e==null?void 0:e.fragmentId)&&this.eventIndex===(e==null?void 0:e.eventIndex)}}const li=Number.MAX_SAFE_INTEGER;class Kn{constructor(e){this._fragmentIdComparer=e}compare(e){return this.fragmentId===e.fragmentId?this.entryIndex-e.entryIndex:this.fragmentId===li?1:e.fragmentId===li?-1:this._fragmentIdComparer.compare(this.fragmentId,e.fragmentId)}asEventKey(){return new B(this.fragmentId,this.entryIndex)}}function hi(n){var e;return((e=n.unsigned)==null?void 0:e.prev_content)||n.prev_content}const ge="m.room.redaction";function di(n){var e;return!!((e=n==null?void 0:n.unsigned)!=null&&e.redacted_because)}var U=(n=>(n[n.None=1]="None",n[n.BeingCreated=2]="BeingCreated",n[n.Invited=4]="Invited",n[n.Joined=8]="Joined",n[n.Replaced=16]="Replaced",n[n.Archived=32]="Archived",n))(U||{}),re=(n=>(n[n.DirectMessage=0]="DirectMessage",n[n.Private=1]="Private",n[n.Public=2]="Public",n))(re||{});function ja(n,e){var o,a;let t;const s=c=>{const l=e(c);l instanceof Promise&&(t=t!=null?t:[],t.push(l))},i=(o=n.state)==null?void 0:o.events;if(i)for(let c=0;c{})}const qa="m.reaction",We="m.annotation";function Wa(n,e){return{"m.relates_to":{event_id:n,key:e,rel_type:We}}}function Ri(n){var e;return n.event_id||((e=n["m.in_reply_to"])==null?void 0:e.event_id)}function $n(n,e){n.event_id!==void 0?n.event_id=e:n["m.in_reply_to"]&&(n["m.in_reply_to"].event_id=e)}function Ha(n){if(n.type===ge)return n.redacts;{const e=$e(n);if(e)return Ri(e)}return null}function ze(n){return n==null?void 0:n["m.relates_to"]}function $e(n){return ze(n.content)}class za{constructor(){this._entries=[]}get firstTimestamp(){return this._entries.reduce((e,t)=>t.isRedaction?e:Math.min(t.timestamp,e),Number.MAX_SAFE_INTEGER)}get annotationEntry(){return this._entries.find(e=>!e.isRedaction)}get redactionEntry(){return this._entries.find(e=>e.isRedaction)}get count(){return this._entries.reduce((e,t)=>e+(t.isRedaction?-1:1),0)}add(e){this._entries.push(e)}remove(e){const t=this._entries.indexOf(e);return t===-1?!1:(this._entries.splice(t,1),!0)}get willAnnotate(){const e=this._entries.reduce((t,s)=>!t||s.pendingEvent.queueIndex>t.pendingEvent.queueIndex?s:t,null);return e?!e.isRedaction:!1}get isEmpty(){return this._entries.length===0}}function kr(n){return n.replace(/&/g,"&").replace(//g,">")}function Ga(n){switch(n){case"m.file":return"sent a file.";case"m.image":return"sent an image.";case"m.video":return"sent a video.";case"m.audio":return"sent an audio file."}return null}function Ja(n){return n==="m.emote"?"* ":""}function Qa(n,e,t,s){return{msgtype:e,body:t,format:"org.matrix.custom.html",formatted_body:s,"m.relates_to":{"m.in_reply_to":{event_id:n}}}}function Ya(n,e,t){const s=Ga(n.content.msgtype),i=Ja(n.content.msgtype),r=n.sender,o=n.displayName||r,a=s||n.content.formatted_body||n.content.body&&kr(n.content.body)||"",c=`
In reply to ${i}${o}
${a}
`,h=(s||n.content.body||"").split(` +`);h[0]=`> ${i}<${r}> ${h[0]}`;const u=h.join(` +> `)+` + +`+t,p=c+kr(t);return Qa(n.id,e,u,p)}class jn extends Kn{constructor(e){super(e),this._pendingRedactions=null,this._pendingAnnotations=null,this._contextEntry=null,this._contextForEntries=null}get isReply(){var e;return!!((e=this.relation)!=null&&e["m.in_reply_to"])}get isRedacting(){return!!this._pendingRedactions}get isRedacted(){return this.isRedacting}get isRedaction(){return this.eventType===ge}get redactionReason(){var e;return this._pendingRedactions?(e=this._pendingRedactions[0].content)==null?void 0:e.reason:null}setContextEntry(e){this._contextEntry=e,e._setAsContextOf(this)}_setAsContextOf(e){this._contextForEntries||(this._contextForEntries=[]),this._contextForEntries.push(e)}get contextForEntries(){return this._contextForEntries}get contextEntry(){return this._contextEntry}addLocalRelation(e){if(e.eventType===ge&&e.isRelatedToId(this.id)){if(this._pendingRedactions||(this._pendingRedactions=[]),this._pendingRedactions.push(e),this._pendingRedactions.length===1)return"isRedacted"}else{const t=e.redactingEntry||e;if(t.isRelatedToId(this.id)&&t.relation.rel_type===We&&this._addPendingAnnotation(e))return"pendingAnnotations"}}removeLocalRelation(e){var t;if(e.eventType===ge&&e.isRelatedToId(this.id)&&this._pendingRedactions){const s=this._pendingRedactions.length;if(this._pendingRedactions=this._pendingRedactions.filter(i=>i!==e),this._pendingRedactions.length===0&&(this._pendingRedactions=null,s!==0))return"isRedacted"}else{const s=e.redactingEntry||e;if(s.isRelatedToId(this.id)&&((t=s.relation)==null?void 0:t.rel_type)===We&&this._pendingAnnotations&&this._removePendingAnnotation(e))return"pendingAnnotations"}}_addPendingAnnotation(e){this._pendingAnnotations||(this._pendingAnnotations=new Map);const{key:t}=(e.redactingEntry||e).relation;if(t){let s=this._pendingAnnotations.get(t);return s||(s=new za,this._pendingAnnotations.set(t,s)),s.add(e),!0}return!1}_removePendingAnnotation(e){const{key:t}=(e.redactingEntry||e).relation;if(t){let s=this._pendingAnnotations.get(t);return s.remove(e)&&s.isEmpty&&this._pendingAnnotations.delete(t),this._pendingAnnotations.size===0&&(this._pendingAnnotations=null),!0}return!1}async abortPendingRedaction(){if(this._pendingRedactions)for(const e of this._pendingRedactions)await e.pendingEvent.abort()}get pendingRedaction(){return this._pendingRedactions?this._pendingRedactions[0]:null}annotate(e){return Wa(this.id,e)}reply(e,t){return Ya(this,e,t)}isRelatedToId(e){return e&&this.relatedEventId===e}haveAnnotation(e){var r,o,a;const t=((o=(r=this.annotations)==null?void 0:r[e])==null?void 0:o.me)||!1,s=(a=this.pendingAnnotations)==null?void 0:a.get(e),i=(s==null?void 0:s.willAnnotate)||!1;return t&&(!s||i)||!t&&i}get relation(){return ze(this.content)}get pendingAnnotations(){return this._pendingAnnotations}get annotations(){return null}}class Xa extends jn{constructor({pendingEvent:e,member:t,clock:s,redactingEntry:i}){super(null),this._pendingEvent=e,this._member=t,this._timestamp=s.now()-(100-e.queueIndex),this._redactingEntry=i}get fragmentId(){return li}get entryIndex(){return this._pendingEvent.queueIndex}get content(){return this._pendingEvent.content}get event(){return null}get eventType(){return this._pendingEvent.eventType}get stateKey(){return null}get sender(){var e;return(e=this._member)==null?void 0:e.userId}get displayName(){var e;return(e=this._member)==null?void 0:e.name}get avatarUrl(){var e;return(e=this._member)==null?void 0:e.avatarUrl}get timestamp(){return this._timestamp}get isPending(){return!0}get id(){return this._pendingEvent.txnId}get pendingEvent(){return this._pendingEvent}notifyUpdate(){}isRelatedToId(e){return e&&e===this._pendingEvent.relatedTxnId?!0:super.isRelatedToId(e)}get relatedEventId(){return this._pendingEvent.relatedEventId}get redactingEntry(){return this._redactingEntry}get contextEventId(){var e;return this.isReply?(e=this._pendingEvent.relatedEventId)!=null?e:this._pendingEvent.relatedTxnId:null}}const V=xe("Waiting","EncryptingAttachments","UploadingAttachments","Encrypting","Sending","Sent","Error"),Rr=["m.relates_to"];class Za{constructor({data:e,remove:t,emitUpdate:s,attachments:i}){this._data=e,this._attachments=i,this._emitUpdate=s,this._removeFromQueueCallback=t,this._aborted=!1,this._status=V.Waiting,this._sendRequest=null,this._attachmentsTotalBytes=0,this._attachments&&(this._attachmentsTotalBytes=Object.values(this._attachments).reduce((r,o)=>r+o.size,0))}get roomId(){return this._data.roomId}get queueIndex(){return this._data.queueIndex}get eventType(){return this._data.eventType}get txnId(){return this._data.txnId}get remoteId(){return this._data.remoteId}get content(){return this._data.content}get relatedTxnId(){return this._data.relatedTxnId}get relatedEventId(){const e=ze(this.content);return e?Ri(e):this._data.relatedEventId}setRelatedEventId(e){const t=ze(this.content);t?$n(t,e):this._data.relatedEventId=e}get data(){return this._data}getAttachment(e){return this._attachments&&this._attachments[e]}get needsSending(){return!this.remoteId&&!this.aborted}get needsEncryption(){return this._data.needsEncryption&&!this.aborted}get needsUpload(){return this._data.needsUpload&&!this.aborted}get isMissingAttachments(){return this.needsUpload&&!this._attachments}setEncrypting(){this._status=V.Encrypting,this._emitUpdate("status")}get contentForEncryption(){const e=Object.assign({},this._data.content);for(const t of Rr)delete e[t];return e}_preserveContentFields(e){const t=this._data.content;for(const s of Rr)t[s]!==void 0&&(e[s]=t[s])}setEncrypted(e,t){this._preserveContentFields(t),this._data.encryptedEventType=e,this._data.encryptedContent=t,this._data.needsEncryption=!1}setError(e){this._status=V.Error,this._error=e,this._emitUpdate("status")}setWaiting(){this._status=V.Waiting,this._emitUpdate("status")}get status(){return this._status}get error(){return this._error}get hasStartedSending(){return this._status===V.Sending||this._status===V.Sent}get attachmentsTotalBytes(){return this._attachmentsTotalBytes}get attachmentsSentBytes(){return this._attachments&&Object.values(this._attachments).reduce((e,t)=>e+t.sentBytes,0)}async uploadAttachments(e,t){if(!this.needsUpload)return;if(!this._attachments)throw new Error("attachments missing");if(this.needsEncryption){this._status=V.EncryptingAttachments,this._emitUpdate("status");for(const i of Object.values(this._attachments))if(await t.wrap("encrypt",()=>(t.set("size",i.size),i.encrypt())),this.aborted)throw new ye}this._status=V.UploadingAttachments,this._emitUpdate("status");const s=Object.entries(this._attachments);s.sort(([,i],[,r])=>i.size-r.size);for(const[i,r]of s)await t.wrap("upload",o=>(o.set("size",r.size),r.upload(e,()=>{this._emitUpdate("attachmentsSentBytes")},o))),r.applyToContent(i,this.content);this._data.needsUpload=!1}async abort(){var e;if(!this._aborted){if(this._aborted=!0,this._attachments)for(const t of Object.values(this._attachments))t.abort();(e=this._sendRequest)==null||e.abort(),await this._removeFromQueueCallback()}}get aborted(){return this._aborted}async send(e,t){this._status=V.Sending,this._emitUpdate("status");const s=this._data.encryptedEventType||this._data.eventType,i=this._data.encryptedContent||this._data.content;s===ge?this._sendRequest=e.redact(this.roomId,this._data.relatedEventId,this.txnId,i,{log:t}):this._sendRequest=e.send(this.roomId,s,this.txnId,i,{log:t});const r=await this._sendRequest.response();this._sendRequest=null,this._data.remoteId=r.event_id,t.set("id",this._data.remoteId),this._status=V.Sent,this._emitUpdate("status")}dispose(){if(this._attachments)for(const e of Object.values(this._attachments))e.dispose()}}class ne extends jn{constructor(e,t){super(t),this._eventEntry=e,this._decryptionError=null,this._decryptionResult=null}clone(){const e=new ne(this._eventEntry,this._fragmentIdComparer);return e.updateFrom(this),e}updateFrom(e){e._decryptionResult&&!this._decryptionResult&&(this._decryptionResult=e._decryptionResult),e._decryptionError&&!this._decryptionError&&(this._decryptionError=e._decryptionError),this._contextForEntries=e.contextForEntries,this._contextEntry=e.contextEntry}get event(){return this._eventEntry.event}get fragmentId(){return this._eventEntry.fragmentId}get entryIndex(){return this._eventEntry.eventIndex}get content(){var e,t;return((t=(e=this._decryptionResult)==null?void 0:e.event)==null?void 0:t.content)||this._eventEntry.event.content}get prevContent(){return hi(this._eventEntry.event)}get eventType(){var e,t;return((t=(e=this._decryptionResult)==null?void 0:e.event)==null?void 0:t.type)||this._eventEntry.event.type}get stateKey(){return this._eventEntry.event.state_key}get sender(){return this._eventEntry.event.sender}get displayName(){return this._eventEntry.displayName}get avatarUrl(){return this._eventEntry.avatarUrl}get timestamp(){return this._eventEntry.event.origin_server_ts}get id(){return this._eventEntry.event.event_id}setDecryptionResult(e){this._decryptionResult=e}get isEncrypted(){return this._eventEntry.event.type==="m.room.encrypted"}get isDecrypted(){var e;return!!((e=this._decryptionResult)!=null&&e.event)}get isVerified(){var e;return this.isEncrypted&&((e=this._decryptionResult)==null?void 0:e.isVerified)}get isUnverified(){var e;return this.isEncrypted&&((e=this._decryptionResult)==null?void 0:e.isUnverified)}setDecryptionError(e){this._decryptionError=e}get decryptionError(){return this._decryptionError}get relatedEventId(){return Ha(this.event)}get isRedacted(){return super.isRedacted||di(this._eventEntry.event)}get redactionReason(){var t,s;const e=(t=this._eventEntry.event.unsigned)==null?void 0:t.redacted_because;return e?(s=e.content)==null?void 0:s.reason:super.redactionReason}get annotations(){return this._eventEntry.annotations}get relation(){const e=this._eventEntry.event.content;return e&&ze(e)||ze(this.content)}get contextEventId(){return this.isReply?this.relatedEventId:null}}function qn(n,e,t){return{fragmentId:n.fragmentId,eventIndex:n.eventIndex,roomId:e,event:t}}function jt(n,e,t){t.isForward?n.push(e):n.unshift(e)}function ec(n,e,t){return t.isForward?n.concat(e):e.concat(n)}const oe="m.room.member";class O{constructor(e){this._data=e}static fromUserId(e,t,s){return new O({roomId:e,userId:t,membership:s})}static fromMemberEvent(e,t){const s=t==null?void 0:t.state_key;if(typeof s!="string")return;const i=t.content,r=hi(t),o=i==null?void 0:i.membership,a=(i==null?void 0:i.displayname)||(r==null?void 0:r.displayname),c=(i==null?void 0:i.avatar_url)||(r==null?void 0:r.avatar_url);return this._validateAndCreateMember(e,s,o,a,c)}static fromReplacingMemberEvent(e,t){const s=t&&t.state_key;if(typeof s!="string")return;const i=hi(t);return this._validateAndCreateMember(e,s,i==null?void 0:i.membership,i==null?void 0:i.displayname,i==null?void 0:i.avatar_url)}static _validateAndCreateMember(e,t,s,i,r){if(typeof s=="string")return new O({roomId:e,userId:t,membership:s,avatarUrl:r,displayName:i})}get membership(){return this._data.membership}get displayName(){return this._data.displayName}get name(){return this._data.displayName||this._data.userId}get avatarUrl(){return this._data.avatarUrl}get roomId(){return this._data.roomId}get userId(){return this._data.userId}serialize(){return this._data}equals(e){const t=this._data,s=e._data;return t.roomId===s.roomId&&t.userId===s.userId&&t.membership===s.membership&&t.displayName===s.displayName&&t.avatarUrl===s.avatarUrl}}class Wn{constructor(e,t){this.member=e,this.previousMembership=t}get roomId(){return this.member.roomId}get userId(){return this.member.userId}get membership(){return this.member.membership}get wasInvited(){return this.previousMembership==="invite"&&this.membership!=="invite"}get hasLeft(){return this.previousMembership==="join"&&this.membership!=="join"}get hasJoined(){return this.previousMembership!=="join"&&this.membership==="join"}}function Ci(n){return typeof n=="number"}const tc=["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"].reduce(function(n,e){return n[e]=1,n},{}),sc={"m.room.member":{membership:1},"m.room.create":{creator:1},"m.room.join_rules":{join_rule:1},"m.room.power_levels":{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1},"m.room.aliases":{aliases:1}};function ic(n,e){for(const i of Object.keys(e))tc[i]||delete e[i];const{content:t}=e,s=sc[e.type];for(const i of Object.keys(t))s!=null&&s[i]||delete t[i];e.unsigned=e.unsigned||{},e.unsigned.redacted_because=n}function rc(n,e){const t=[];for(;Ci(n.previousId);){const s=e.get(n.previousId);if(!s)break;if(s.nextId!==n.id)throw new Error(`Previous fragment ${s.id} doesn't point back to ${n.id}`);e.delete(n.previousId),t.unshift(s),n=s}return t}function nc(n,e){const t=[];for(;Ci(n.nextId);){const s=e.get(n.nextId);if(!s)break;if(s.previousId!==n.id)throw new Error(`Next fragment ${s.id} doesn't point back to ${n.id}`);e.delete(n.nextId),t.push(s),n=s}return t}function oc(n){const e=new Map;for(let s of n)e.set(s.id,s);const t=[];for(;e.size;){const s=e.values().next().value;e.delete(s.id);const i=rc(s,e),r=nc(s,e),o=i.concat(s,r);t.push(o)}return t.map(s=>new ac(s))}class ti{constructor(e,t,s){this.id=e,this.previousId=t,this.nextId=s}}class ac{constructor(e){this._idToSortIndex=new Map,e.forEach((t,s)=>{this._idToSortIndex.set(t.id,s)})}compare(e,t){const s=this._idToSortIndex.get(e);if(s===void 0)throw new Error(`first id ${e} isn't part of this island`);const i=this._idToSortIndex.get(t);if(i===void 0)throw new Error(`second id ${t} isn't part of this island`);return s-i}get fragmentIds(){return this._idToSortIndex.keys()}}class Cr extends Error{get name(){return"CompareError"}}class cc{constructor(e){this._fragmentsById=e.reduce((t,s)=>(t.set(s.id,s),t),new Map),this.rebuild(e)}_getIsland(e){const t=this._idToIsland.get(e);if(t===void 0)throw new Cr(`Unknown fragment id ${e}`);return t}compare(e,t){if(e===t)return 0;const s=this._getIsland(e),i=this._getIsland(t);if(s!==i)throw new Cr(`${e} and ${t} are on different islands, can't tell order`);return s.compare(e,t)}rebuild(e){const t=oc(e);this._idToIsland=new Map;for(let s of t)for(let i of s.fragmentIds)this._idToIsland.set(i,s)}add(e){const t=new ti(e.id,e.previousId,e.nextId);this._fragmentsById.set(e.id,t),this.rebuild(this._fragmentsById.values())}append(e,t){const s=new ti(e,t,null),i=this._fragmentsById.get(t);i&&(i.nextId=e),this._fragmentsById.set(e,s),this.rebuild(this._fragmentsById.values())}prepend(e,t){const s=new ti(e,null,t),i=this._fragmentsById.get(t);i&&(i.previousId=e),this._fragmentsById.set(e,s),this.rebuild(this._fragmentsById.values())}}(function(){const e=document.createElement("link").relList;return e&&e.supports&&e.supports("modulepreload")?"modulepreload":"preload"})();function lc(n){return"objectStore"in n?`${n.objectStore.name}.${n.name}`:n.name}function hc(n){var e,t,s,i,r;return"objectStore"in n?(s=(t=(e=n.objectStore)==null?void 0:e.transaction)==null?void 0:t.db)==null?void 0:s.name:(r=(i=n.transaction)==null?void 0:i.db)==null?void 0:r.name}class Hn extends Re{constructor(e,t,s=null){const i=t&&"source"in t?t.source:t,r=i?lc(i):"",o=i?hc(i):"";let a=`${e} on ${o}.${r}`;s&&(a+=": ",typeof s.name=="string"&&(a+=`(name: ${s.name}) `),typeof s.code=="number"&&(a+=`(code: ${s.code}) `)),s&&(a+=s.message),super(a,s),this.storeName=r,this.databaseName=o}}class Ti extends Hn{constructor(e){const t=e.target,s=t.source,i=t.error;super("IDBRequest failed",s,i),this.errorEvent=e}preventTransactionAbort(){this.errorEvent.preventDefault()}}class Ie extends Hn{constructor(e,t,s,i){super(`${e}(${i.map(r=>JSON.stringify(r)).join(", ")}) failed`,t,s)}}const Tr={done:!0},Ge={done:!1};function Rs(n){const e=n.toString(16);return"0".repeat(8-e.length)+e}function ui(n){return parseInt(n,16)}function Mi(n,e,t,s=window.indexedDB){const i=s.open(n,t);return i.onupgradeneeded=async r=>{const o=r.target,a=o.result,c=o.transaction,l=r.oldVersion;try{await e(a,c,l,t)}catch{try{c.abort()}catch{}}},X(i)}function X(n){return new Promise((e,t)=>{n.addEventListener("success",s=>{e(s.target.result)}),n.addEventListener("error",s=>{const i=new Ti(s);t(i)})})}function Jt(n){return new Promise((e,t)=>{n.addEventListener("complete",()=>{e()}),n.addEventListener("abort",s=>{t(new ye)})})}function K(n,e){return new Promise((t,s)=>{n.onerror=i=>{s(new Ti(i))},n.onsuccess=i=>{const r=i.target.result;if(!r){t(!1);return}const o=e(r.value,r.key,r),a=o==null?void 0:o.done,c=o==null?void 0:o.jumpTo;a?t(!0):c?r.continue(c):r.continue()}}).catch(t=>{throw new Re("iterateCursor failed",t)})}async function dc(n,e){const t=[];return await K(n,s=>(t.push(s),{done:e(t)})),t}class Mr{constructor(e,t){this._target=e,this._transaction=t}get idbFactory(){return this._transaction.idbFactory}get IDBKeyRange(){return this._transaction.IDBKeyRange}get databaseName(){return this._transaction.databaseName}_openCursor(e,t){return e&&t?this._target.openCursor(e,t):e?this._target.openCursor(e):t?this._target.openCursor(null,t):this._target.openCursor()}supports(e){return this._target.supports(e)}count(e){return X(this._target.count(e))}get(e){return X(this._target.get(e))}getKey(e){return this._target.supports("getKey")?X(this._target.getKey(e)):X(this._target.get(e)).then(t=>{if(t){let s=this._target.keyPath;return typeof s=="string"&&(s=[s]),s.reduce((i,r)=>i[r],t)}})}reduce(e,t,s){return this._reduce(e,t,s,"next")}reduceReverse(e,t,s){return this._reduce(e,t,s,"prev")}selectLimit(e,t){return this._selectLimit(e,t,"next")}selectLimitReverse(e,t){return this._selectLimit(e,t,"prev")}selectWhile(e,t){return this._selectWhile(e,t,"next")}selectWhileReverse(e,t){return this._selectWhile(e,t,"prev")}async selectAll(e,t){const s=this._openCursor(e,t),i=[];return await K(s,r=>(i.push(r),Ge)),i}selectFirst(e){return this._find(e,()=>!0,"next")}selectLast(e){return this._find(e,()=>!0,"prev")}find(e,t){return this._find(e,t,"next")}findReverse(e,t){return this._find(e,t,"prev")}async findMaxKey(e){const t=this._target.openKeyCursor(e,"prev");let s;return await K(t,(i,r)=>(s=r,Tr)),s}async iterateValues(e,t){const s=this._target.openCursor(e,"next");await K(s,(i,r,o)=>({done:t(i,r,o)}))}async iterateKeys(e,t){const s=this._target.openKeyCursor(e,"next");await K(s,(i,r,o)=>({done:t(r,o)}))}async findExistingKeys(e,t,s){const i=(d,u)=>t?-this.idbFactory.cmp(d,u):this.idbFactory.cmp(d,u),r=e.slice().sort(i),o=r[0],a=r[r.length-1],c=t?"prev":"next",l=this._target.openKeyCursor(this.IDBKeyRange.bound(o,a),c);let h=0;await K(l,(d,u,p)=>{for(;h=r.length?Tr:{done:!1,jumpTo:r[h]}})}_reduce(e,t,s,i){let r=s;const o=this._openCursor(e,i);return K(o,a=>(r=t(r,a),Ge))}_selectLimit(e,t,s){return this._selectUntil(e,i=>i.length===t,s)}async _selectUntil(e,t,s){const i=this._openCursor(e,s),r=[];return await K(i,o=>(r.push(o),{done:t(r,o)})),r}async _selectWhile(e,t,s){const i=this._openCursor(e,s),r=[];return await K(i,o=>{const a=t(o);return a&&r.push(o),{done:!a}}),r}async iterateWhile(e,t){const s=this._openCursor(e,"next");await K(s,i=>({done:!t(i)}))}async _find(e,t,s){const i=this._openCursor(e,s);let r;if(await K(i,a=>{const c=t(a);return c&&(r=a),{done:c}}))return r}}const Ue=!1;function Fe(n,e,t){var r,o;const s=t==null?void 0:t.name,i=(o=(r=t==null?void 0:t.transaction)==null?void 0:r.db)==null?void 0:o.name;console.info(`${i}.${s}.${n}(${e.map(a=>JSON.stringify(a)).join(", ")})`)}class Ar{constructor(e){this._qt=e}get keyPath(){return this._qtStore.keyPath}get _qtStore(){return"objectStore"in this._qt?this._qt.objectStore:this._qt}supports(e){return!!this._qt[e]}openKeyCursor(e,t){try{return this._qt.openKeyCursor?(Ue&&Fe("openKeyCursor",[e,t],this._qt),this._qt.openKeyCursor(e,t)):(Ue&&Fe("openCursor",[e,t],this._qt),this.openCursor(e,t))}catch(s){throw new Ie("openKeyCursor",this._qt,s,[e,t])}}openCursor(e,t){try{return Ue&&Fe("openCursor",[],this._qt),this._qt.openCursor(e,t)}catch(s){throw new Ie("openCursor",this._qt,s,[e,t])}}put(e,t){try{return Ue&&Fe("put",[e,t],this._qt),this._qtStore.put(e,t)}catch(s){throw new Ie("put",this._qt,s,[e,t])}}add(e,t){try{return Ue&&Fe("add",[e,t],this._qt),this._qtStore.add(e,t)}catch(s){throw new Ie("add",this._qt,s,[e,t])}}get(e){try{return Ue&&Fe("get",[e],this._qt),this._qt.get(e)}catch(t){throw new Ie("get",this._qt,t,[e])}}getKey(e){try{return Ue&&Fe("getKey",[e],this._qt),this._qt.getKey(e)}catch(t){throw new Ie("getKey",this._qt,t,[e])}}delete(e){try{return Ue&&Fe("delete",[e],this._qt),this._qtStore.delete(e)}catch(t){throw new Ie("delete",this._qt,t,[e])}}count(e){try{return this._qt.count(e)}catch(t){throw new Ie("count",this._qt,t,[e])}}index(e){try{return this._qtStore.index(e)}catch(t){throw new Ie("index",this._qt,t,[e])}}get indexNames(){return Array.from(this._qtStore.indexNames)}}class zn extends Mr{constructor(e,t){super(new Ar(e),t)}get _idbStore(){return this._target}index(e){return new Mr(new Ar(this._idbStore.index(e)),this._transaction)}put(e,t){const s=this._idbStore.put(e);this._prepareErrorLog(s,t,"put",void 0,e)}add(e,t){const s=this._idbStore.add(e);this._prepareErrorLog(s,t,"add",void 0,e)}async tryAdd(e,t){try{return await X(this._idbStore.add(e)),!0}catch(s){if(s instanceof Ti)return t.log({l:"could not write",id:this._getKeys(e),e:s},t.level.Warn),s.preventTransactionAbort(),!1;throw s}}delete(e,t){const s=this._idbStore.delete(e);this._prepareErrorLog(s,t,"delete",e,void 0)}_prepareErrorLog(e,t,s,i,r){t&&t.ensureRefId(),X(e).catch(o=>{let a;r?a=this._getKeys(r):i&&(a=[i]),this._transaction.addWriteError(o,t,s,a)})}_getKeys(e){const t=[],{keyPath:s}=this._idbStore;try{t.push(this._readKeyPath(e,s))}catch{console.warn("could not read keyPath",s)}for(const i of this._idbStore.indexNames)try{const r=this._idbStore.index(i);t.push(this._readKeyPath(e,r.keyPath))}catch{console.warn("could not read index",i)}return t}_readKeyPath(e,t){if(Array.isArray(t)){let s=e;for(const i of t)if(typeof s=="object")s=s[i];else break;return s}else return e[t]}}function uc(n){return JSON.stringify(Gn(n))}function mc(n){return Jn(JSON.parse(n))}function Gn(n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if(n.byteLength)return{_type:n.constructor.name,value:Array.from(n)};let e={};for(const t in n)n.hasOwnProperty(t)&&(e[t]=Gn(n[t]));return e}else return n}function Jn(n){if(typeof n=="object"&&n!==null&&!Array.isArray(n)){if(typeof n._type=="string")switch(n._type){case"Int8Array":return Int8Array.from(n.value);case"Uint8Array":return Uint8Array.from(n.value);case"Uint8ClampedArray":return Uint8ClampedArray.from(n.value);case"Int16Array":return Int16Array.from(n.value);case"Uint16Array":return Uint16Array.from(n.value);case"Int32Array":return Int32Array.from(n.value);case"Uint32Array":return Uint32Array.from(n.value);case"Float32Array":return Float32Array.from(n.value);case"Float64Array":return Float64Array.from(n.value);case"BigInt64Array":return BigInt64Array.from(n.value);case"BigUint64Array":return BigUint64Array.from(n.value);default:return n.value}let e={};for(const t in n)n.hasOwnProperty(t)&&(e[t]=Jn(n[t]));return e}else return n}class Ai{constructor(e,t){this._sessionStore=e,this._localStorage=t}get _localStorageKeyPrefix(){return`${this._sessionStore.databaseName}.session.`}async get(e){const t=await this._sessionStore.get(e);if(t)return t.value}_writeKeyToLocalStorage(e,t){try{const s=this._localStorageKeyPrefix+e,i=uc(t);this._localStorage.setItem(s,i)}catch(s){console.error("could not write to localStorage",s)}}writeE2EEIdentityToLocalStorage(){this._sessionStore.iterateValues(void 0,(e,t)=>(t.startsWith(ie)&&this._writeKeyToLocalStorage(t,e.value),!1))}async tryRestoreE2EEIdentityFromLocalStorage(e){let t=!1;const s=this._localStorageKeyPrefix,i=s+ie;for(let r=0;r(n[n.All=1]="All",n[n.Debug=2]="Debug",n[n.Detail=3]="Detail",n[n.Info=4]="Info",n[n.Warn=5]="Warn",n[n.Error=6]="Error",n[n.Fatal=7]="Fatal",n[n.Off=8]="Off",n))(_e||{});class mi{constructor(e){this._parentFilter=e}filter(e,t){return!(this._parentFilter&&!this._parentFilter.filter(e,t)||this._min!==void 0&&!Array.isArray(t)&&e.logLevels(t(this.item))).then(Cs,Cs),this.item}async export(){}get level(){return _e}}class fc{constructor(e){this.logger=e}wrap(e,t){return t(this)}log(){return this}set(){return this}runDetached(e,t){return new Promise(s=>s(t(this))).then(Cs,Cs),this}wrapDetached(e,t){return this.refDetached()}refDetached(){}ensureRefId(){}get level(){return _e}get duration(){return 0}catch(e){return e}child(){return this}finish(){}serialize(){}}const gc=new _c;function ae(n,e,t){return`${n}|${Rs(e)}|${Rs(t)}`}function yc(n){const[e,t,s]=n.split("|");return{roomId:e,eventKey:new B(ui(t),ui(s))}}function ms(n,e){return`${n}|${e}`}function Nr(n){const[e,t]=n.split("|");return{roomId:e,eventId:t}}class ps{constructor(e,t,s,i,r=!1,o=!1){this._IDBKeyRange=e,this._only=t,this._lower=s,this._upper=i,this._lowerOpen=r,this._upperOpen=o}asIDBKeyRange(e){try{if(this._only)return this._IDBKeyRange.only(ae(e,this._only.fragmentId,this._only.eventIndex));if(this._lower&&!this._upper)return this._IDBKeyRange.bound(ae(e,this._lower.fragmentId,this._lower.eventIndex),ae(e,this._lower.fragmentId,F.maxStorageKey),this._lowerOpen,!1);if(!this._lower&&this._upper)return this._IDBKeyRange.bound(ae(e,this._upper.fragmentId,F.minStorageKey),ae(e,this._upper.fragmentId,this._upper.eventIndex),!1,this._upperOpen);if(this._lower&&this._upper)return this._IDBKeyRange.bound(ae(e,this._lower.fragmentId,this._lower.eventIndex),ae(e,this._upper.fragmentId,this._upper.eventIndex),this._lowerOpen,this._upperOpen)}catch(t){throw new Re("IDBKeyRange failed with data: "+JSON.stringify(this),t)}}}class wc{constructor(e){this._timelineStore=e}onlyRange(e){return new ps(this._timelineStore.IDBKeyRange,e)}upperBoundRange(e,t=!1){return new ps(this._timelineStore.IDBKeyRange,void 0,void 0,e,void 0,t)}lowerBoundRange(e,t=!1){return new ps(this._timelineStore.IDBKeyRange,void 0,e,void 0,t)}boundRange(e,t,s=!1,i=!1){return new ps(this._timelineStore.IDBKeyRange,void 0,e,t,s,i)}async lastEvents(e,t,s){const i=B.maxKey;return i.fragmentId=t,this.eventsBefore(e,i,s)}async firstEvents(e,t,s){const i=B.minKey;return i.fragmentId=t,this.eventsAfter(e,i,s)}eventsAfter(e,t,s){const i=this.lowerBoundRange(t,!0).asIDBKeyRange(e);return this._timelineStore.selectLimit(i,s)}async eventsBefore(e,t,s){const i=this.upperBoundRange(t,!0).asIDBKeyRange(e),r=await this._timelineStore.selectLimitReverse(i,s);return r.reverse(),r}async getEventKeysForIds(e,t){const s=this._timelineStore.index("byEventId"),i=t.map(o=>ms(e,o)),r=new Map;return await s.findExistingKeys(i,!1,(o,a)=>{const{eventId:c}=Nr(o),{eventKey:l}=yc(a);return r.set(c,l),!1}),r}async findFirstOccurringEventId(e,t){const s=this._timelineStore.index("byEventId"),i=t.map(c=>ms(e,c)),r=new Array(i.length);let o;function a(){for(let c=0;c{const h=i.indexOf(c);return r[h]=l,o=a(),!!o}),o&&Nr(o).eventId}tryInsert(e,t){return e.key=ae(e.roomId,e.fragmentId,e.eventIndex),e.eventIdKey=ms(e.roomId,e.event.event_id),this._timelineStore.tryAdd(e,t)}update(e){this._timelineStore.put(e)}get(e,t){return this._timelineStore.get(ae(e,t.fragmentId,t.eventIndex))}getByEventId(e,t){return this._timelineStore.index("byEventId").get(ms(e,t))}removeAllForRoom(e){const t=ae(e,F.minStorageKey,F.minStorageKey),s=ae(e,F.maxStorageKey,F.maxStorageKey),i=this._timelineStore.IDBKeyRange.bound(t,s);this._timelineStore.delete(i)}}const te="\0",G="\u{10FFFF}";function me(n,e,t,s){return`${n}|${e}|${t}|${s}`}function Dr(n){const[e,t,s,i]=n.split("|");return{roomId:e,targetEventId:t,relType:s,sourceEventId:i}}class vc{constructor(e){this._store=e}add(e,t,s,i){this._store.add({key:me(e,t,s,i)})}remove(e,t,s,i){this._store.delete(me(e,t,s,i))}removeAllForTarget(e,t){const s=this._store.IDBKeyRange.bound(me(e,t,te,te),me(e,t,G,G),!0,!0);this._store.delete(s)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(me(e,te,te,te),me(e,G,G,G),!0,!0);this._store.delete(t)}async getForTargetAndType(e,t,s){const i=this._store.IDBKeyRange.bound(me(e,t,s,te),me(e,t,s,G),!0,!0);return(await this._store.selectAll(i)).map(o=>Dr(o.key))}async getAllForTarget(e,t){const s=this._store.IDBKeyRange.bound(me(e,t,te,te),me(e,t,G,G),!0,!0);return(await this._store.selectAll(s)).map(r=>Dr(r.key))}}function Vr(n,e,t){return`${n}|${e}|${t}`}class bc{constructor(e){this._roomStateStore=e}get(e,t,s){const i=Vr(e,t,s);return this._roomStateStore.get(i)}set(e,t){const s=Vr(e,t.type,t.state_key),i={roomId:e,event:t,key:s};this._roomStateStore.put(i)}removeAllForRoom(e){const t=this._roomStateStore.IDBKeyRange.bound(e,`${e}|${G}`,!0,!0);this._roomStateStore.delete(t)}}function _s(n,e){return`${n}|${e}`}function Sc(n){const[e,t]=n.split("|");return{roomId:e,userId:t}}class Qn{constructor(e){this._roomMembersStore=e}get(e,t){return this._roomMembersStore.get(_s(e,t))}set(e){e.key=_s(e.roomId,e.userId),this._roomMembersStore.put(e)}getAll(e){const t=this._roomMembersStore.IDBKeyRange.lowerBound(_s(e,""));return this._roomMembersStore.selectWhile(t,s=>s.roomId===e)}async getAllUserIds(e){const t=[],s=this._roomMembersStore.IDBKeyRange.lowerBound(_s(e,""));return await this._roomMembersStore.iterateKeys(s,i=>{const r=Sc(i);return r.roomId===e?(t.push(r.userId),!1):!0}),t}removeAllForRoom(e){const t=this._roomMembersStore.IDBKeyRange.bound(e,`${e}|${G}`,!0,!0);this._roomMembersStore.delete(t)}}function fs(n,e){return`${n}|${Rs(e)}`}class Ic{constructor(e){this._store=e}_allRange(e){try{return this._store.IDBKeyRange.bound(fs(e,F.minStorageKey),fs(e,F.maxStorageKey))}catch(t){throw new Re(`error from IDBKeyRange with roomId ${e}`,t)}}all(e){return this._store.selectAll(this._allRange(e))}liveFragment(e){return this._store.findReverse(this._allRange(e),t=>typeof t.nextId!="number"&&typeof t.nextToken!="string")}add(e){e.key=fs(e.roomId,e.id),this._store.add(e)}update(e){this._store.put(e)}get(e,t){return this._store.get(fs(e,t))}removeAllForRoom(e){this._store.delete(this._allRange(e))}}function Qe(n,e){return`${n}|${Rs(e)}`}function Ec(n){const[e,t]=n.split("|"),s=ui(t);return{roomId:e,queueIndex:s}}class kc{constructor(e){this._eventStore=e}async getMaxQueueIndex(e){const t=this._eventStore.IDBKeyRange.bound(Qe(e,F.minStorageKey),Qe(e,F.maxStorageKey),!1,!1),s=await this._eventStore.findMaxKey(t);if(s)return Ec(s).queueIndex}remove(e,t){const s=this._eventStore.IDBKeyRange.only(Qe(e,t));this._eventStore.delete(s)}async exists(e,t){const s=this._eventStore.IDBKeyRange.only(Qe(e,t));return!!await this._eventStore.getKey(s)}add(e){e.key=Qe(e.roomId,e.queueIndex),this._eventStore.add(e)}update(e){this._eventStore.put(e)}getAll(){return this._eventStore.selectAll()}removeAllForRoom(e){const t=Qe(e,F.minStorageKey),s=Qe(e,F.maxStorageKey),i=this._eventStore.IDBKeyRange.bound(t,s);this._eventStore.delete(i)}}class Rc{constructor(e){this._store=e}get(e){return this._store.get(e)}set(e){this._store.put(e)}remove(e){this._store.delete(e)}}function Ye(n,e){return`${n}|${e}`}function Cc(n){const[e,t]=n.split("|");return{userId:e,deviceId:t}}class Tc{constructor(e){this._store=e}getAllForUserId(e){const t=this._store.IDBKeyRange.lowerBound(Ye(e,""));return this._store.selectWhile(t,s=>s.userId===e)}async getAllDeviceIds(e){const t=[],s=this._store.IDBKeyRange.lowerBound(Ye(e,""));return await this._store.iterateKeys(s,i=>{const r=Cc(i);return r.userId===e?(t.push(r.deviceId),!1):!0}),t}get(e,t){return this._store.get(Ye(e,t))}set(e){e.key=Ye(e.userId,e.deviceId),this._store.put(e)}getByCurve25519Key(e){return this._store.index("byCurve25519Key").get(e)}remove(e,t){this._store.delete(Ye(e,t))}removeAllForUser(e){const t=this._store.IDBKeyRange.bound(Ye(e,te),Ye(e,G),!0,!0);this._store.delete(t)}}function Nt(n,e){return`${n}|${e}`}function Mc(n){const[e,t]=n.split("|");return{senderKey:e,sessionId:t}}class Ac{constructor(e){this._store=e}async getSessionIds(e){const t=[],s=this._store.IDBKeyRange.lowerBound(Nt(e,""));return await this._store.iterateKeys(s,i=>{const r=Mc(i);return r.senderKey===e?(t.push(r.sessionId),!1):!0}),t}getAll(e){const t=this._store.IDBKeyRange.lowerBound(Nt(e,""));return this._store.selectWhile(t,s=>s.senderKey===e)}get(e,t){return this._store.get(Nt(e,t))}set(e){e.key=Nt(e.senderKey,e.sessionId),this._store.put(e)}remove(e,t){this._store.delete(Nt(e,t))}}var Os=(n=>(n[n.NotBackedUp=0]="NotBackedUp",n[n.BackedUp=1]="BackedUp",n))(Os||{}),es=(n=>(n[n.DeviceMessage=1]="DeviceMessage",n[n.Backup=2]="Backup",n[n.Outbound=3]="Outbound",n))(es||{});function gt(n,e,t){return`${n}|${e}|${t}`}class xc{constructor(e){this._store=e}async has(e,t,s){const i=gt(e,t,s),r=await this._store.getKey(i);return i===r}get(e,t,s){return this._store.get(gt(e,t,s))}set(e){const t=e;t.key=gt(e.roomId,e.senderKey,e.sessionId),this._store.put(t)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(gt(e,te,te),gt(e,G,G));this._store.delete(t)}countNonBackedUpSessions(){return this._store.index("byBackup").count(this._store.IDBKeyRange.only(0))}getFirstNonBackedUpSessions(e){return this._store.index("byBackup").selectLimit(this._store.IDBKeyRange.only(0),e)}async markAsBackedUp(e,t,s){const i=await this._store.get(gt(e,t,s));i&&(i.backup=1,this._store.put(i))}async markAllAsNotBackedUp(){const e=this._store.IDBKeyRange.only(1);let t=0;return await this._store.index("byBackup").iterateValues(e,(s,i,r)=>(s.backup=0,r.update(s),t+=1,!1)),t}}class Nc{constructor(e){this._store=e}remove(e){this._store.delete(e)}get(e){return this._store.get(e)}set(e){this._store.put(e)}}function gs(n,e,t){return`${n}|${e}|${t}`}class Dc{constructor(e){this._store=e}get(e,t,s){return this._store.get(gs(e,t,s))}set(e,t,s,i){i.key=gs(e,t,s),this._store.put(i)}removeAllForRoom(e){const t=this._store.IDBKeyRange.bound(gs(e,te,te),gs(e,G,G));this._store.delete(t)}}function Ut(n,e){return`${n}|${e}`}class Vc{constructor(e){this._store=e}getAll(){return this._store.selectAll()}async getAllByTypeAndScope(e,t){const s=Ut(t,e),i=[];return await this._store.index("byScopeAndType").iterateWhile(s,r=>r.scopeTypeKey!==s?!1:(i.push(r),!0)),i}add(e){e.scopeTypeKey=Ut(e.scope,e.type),this._store.add(e)}update(e){this._store.put(e)}remove(e){this._store.delete(e)}async removeAllForScope(e){const t=this._store.IDBKeyRange.bound(Ut(e,te),Ut(e,G));await this._store.index("byScopeAndType").iterateValues(t,(i,r,o)=>(o.delete(),!0))}}class Lc{constructor(e){this._store=e}async get(e){return await this._store.get(e)}set(e){this._store.put(e)}}class Oc{constructor(e,t,s,i){this.error=e,this.refItem=t,this.operationName=s,this.keys=i}}class Lr{constructor(e,t,s){this._txn=e,this._allowedStoreNames=t,this._stores={},this._storage=s,this._writeErrors=[]}get idbFactory(){return this._storage.idbFactory}get IDBKeyRange(){return this._storage.IDBKeyRange}get databaseName(){return this._storage.databaseName}get logger(){return this._storage.logger}_idbStore(e){if(!this._allowedStoreNames.includes(e))throw new Re(`Invalid store for transaction: ${e}, only ${this._allowedStoreNames.join(", ")} are allowed.`);return new zn(this._txn.objectStore(e),this)}_store(e,t){if(!this._stores[e]){const s=this._idbStore(e);this._stores[e]=t(s)}return this._stores[e]}get session(){return this._store(P.session,e=>new Ai(e,this._storage.localStorage))}get roomSummary(){return this._store(P.roomSummary,e=>new xr(e))}get archivedRoomSummary(){return this._store(P.archivedRoomSummary,e=>new xr(e))}get invites(){return this._store(P.invites,e=>new pc(e))}get timelineFragments(){return this._store(P.timelineFragments,e=>new Ic(e))}get timelineEvents(){return this._store(P.timelineEvents,e=>new wc(e))}get timelineRelations(){return this._store(P.timelineRelations,e=>new vc(e))}get roomState(){return this._store(P.roomState,e=>new bc(e))}get roomMembers(){return this._store(P.roomMembers,e=>new Qn(e))}get pendingEvents(){return this._store(P.pendingEvents,e=>new kc(e))}get userIdentities(){return this._store(P.userIdentities,e=>new Rc(e))}get deviceIdentities(){return this._store(P.deviceIdentities,e=>new Tc(e))}get olmSessions(){return this._store(P.olmSessions,e=>new Ac(e))}get inboundGroupSessions(){return this._store(P.inboundGroupSessions,e=>new xc(e))}get outboundGroupSessions(){return this._store(P.outboundGroupSessions,e=>new Nc(e))}get groupSessionDecryptions(){return this._store(P.groupSessionDecryptions,e=>new Dc(e))}get operations(){return this._store(P.operations,e=>new Vc(e))}get accountData(){return this._store(P.accountData,e=>new Lc(e))}async complete(e){try{await Jt(this._txn)}catch(t){throw this._writeErrors.length?(this._logWriteErrors(e),this._writeErrors[0].error):t}}getCause(e){return e instanceof Re&&e.errcode==="AbortError"&&this._writeErrors.length?this._writeErrors[0].error:e}abort(e){try{this._txn.abort()}catch{e==null||e.set("couldNotAbortTxn",!0)}this._writeErrors.length&&this._logWriteErrors(e)}addWriteError(e,t,s,i){(e.errcode!=="AbortError"||this._writeErrors.length===0)&&this._writeErrors.push(new Oc(e,t,s,i))}_logWriteErrors(e){const t=i=>{e||i.set("allowedStoreNames",this._allowedStoreNames);for(const r of this._writeErrors)i.wrap({l:r.operationName,id:r.keys},o=>{r.refItem&&o.refDetached(r.refItem),o.catch(r.error)})},s=`${this._writeErrors.length} storage write operation(s) failed`;e?e.wrap(s,t):this.logger.run(s,t)}}const Or="782rh281re38-boguskey";class Pc{constructor(e,t,s,i,r,o){this._db=e,this.idbFactory=t,this.IDBKeyRange=s,this._hasWebkitEarlyCloseTxnBug=i,this.storeNames=P,this.localStorage=r,this.logger=o}_validateStoreNames(e){const t=e.findIndex(s=>!Gt.includes(s));if(t!==-1)throw new Re(`Tried top, a transaction unknown store ${e[t]}`)}async readTxn(e){this._validateStoreNames(e);try{const t=this._db.transaction(e,"readonly");return this._hasWebkitEarlyCloseTxnBug&&await X(t.objectStore(e[0]).get(Or)),new Lr(t,e,this)}catch(t){throw new Re("readTxn failed",t)}}async readWriteTxn(e){this._validateStoreNames(e);try{const t=this._db.transaction(e,"readwrite");return this._hasWebkitEarlyCloseTxnBug&&await X(t.objectStore(e[0]).get(Or)),new Lr(t,e,this)}catch(t){throw new Re("readWriteTxn failed",t)}}close(){this._db.close()}get databaseName(){return this._db.name}}async function Uc(n){const e=n.transaction(Gt,"readonly"),t={};return await Promise.all(Gt.map(async s=>{const i=t[s]=[],r=e.objectStore(s);await K(r.openCursor(),o=>(i.push(o),Ge))})),t}async function Fc(n,e){const t=n.transaction(Gt,"readwrite");for(const s of Gt){const i=t.objectStore(s);for(const r of e[s])i.add(r)}await Jt(t)}const Yn=[Kc,$c,jc,qc,Wc,Hc,zc,Gc,Jc,Qc,Yc,Xc,Zc,el,tl,sl];function Bc(n){return{databaseName:n.name,get idbFactory(){throw new Error("unused")},get IDBKeyRange(){throw new Error("unused")},addWriteError(){}}}function Kc(n){n.createObjectStore("session",{keyPath:"key"}),n.createObjectStore("roomSummary",{keyPath:"roomId"}),n.createObjectStore("timelineFragments",{keyPath:"key"}),n.createObjectStore("timelineEvents",{keyPath:"key"}).createIndex("byEventId","eventIdKey",{unique:!0}),n.createObjectStore("roomState",{keyPath:"key"}),n.createObjectStore("pendingEvents",{keyPath:"key"})}async function $c(n,e){const t=new Qn(n.createObjectStore("roomMembers",{keyPath:"key"})),s=e.objectStore("roomState");await K(s.openCursor(),i=>{if(i.event.type===oe){s.delete(i.key);const r=O.fromMemberEvent(i.roomId,i.event);r&&t.set(r.serialize())}return Ge})}async function jc(n,e,t){const s=e.objectStore("session");try{const r=await X(s.get(1));if(r){s.delete(1);const{syncToken:o,syncFilterId:a,serverVersions:c}=r.value,l=new Ai(s,t);l.set("sync",{token:o,filterId:a}),l.set("serverVersions",c)}}catch(i){e.abort(),console.error("could not migrate session",i.stack)}}function qc(n){n.createObjectStore("userIdentities",{keyPath:"userId"}),n.createObjectStore("deviceIdentities",{keyPath:"key"}).createIndex("byCurve25519Key","curve25519Key",{unique:!0}),n.createObjectStore("olmSessions",{keyPath:"key"}),n.createObjectStore("inboundGroupSessions",{keyPath:"key"}),n.createObjectStore("outboundGroupSessions",{keyPath:"roomId"}),n.createObjectStore("groupSessionDecryptions",{keyPath:"key"}),n.createObjectStore("operations",{keyPath:"id"}).createIndex("byTypeAndScope","typeScopeKey",{unique:!1})}async function Wc(n,e){var r;const t=e.objectStore("roomSummary"),s=e.objectStore("roomState"),i=[];await K(t.openCursor(),o=>(i.push(o),Ge));for(const o of i){const a=await X(s.get(`${o.roomId}|m.room.encryption|`));a&&(o.encryption=(r=a==null?void 0:a.event)==null?void 0:r.content,delete o.isEncrypted,t.put(o))}}function Hc(n){n.createObjectStore("accountData",{keyPath:"type"})}function zc(n){n.createObjectStore("invites",{keyPath:"roomId"})}function Gc(n){n.createObjectStore("archivedRoomSummary",{keyPath:"summary.roomId"})}async function Jc(n,e){try{const t=e.objectStore("operations");t.deleteIndex("byTypeAndScope"),await K(t.openCursor(),(s,i,r)=>{const{typeScopeKey:o}=s;delete s.typeScopeKey;const[a,c]=o.split("|");return s.scopeTypeKey=Ut(c,a),r.update(s),Ge}),t.createIndex("byScopeAndType","scopeTypeKey",{unique:!1})}catch(t){e.abort(),console.error("could not migrate operations",t.stack)}}function Qc(n){n.createObjectStore("timelineRelations",{keyPath:"key"})}function Yc(){}async function Xc(n,e){const t=e.objectStore("session"),s=await X(t.get("ssssKey"));s&&t.put({key:`${ie}ssssKey`,value:s.value})}async function Zc(n,e,t,s){const i=e.objectStore("session"),r=new Ai(new zn(i,Bc(n)),t);r.writeE2EEIdentityToLocalStorage();const o=await r.tryRestoreE2EEIdentityFromLocalStorage(s);s.set("restored",o)}async function el(n,e){for(const t of n.objectStoreNames){const s=e.objectStore(t);switch(t){case"inboundGroupSessions":case"outboundGroupSessions":case"olmSessions":case"operations":continue;case"session":{await K(s.openCursor(),(i,r,o)=>(r.startsWith(ie)||o.delete(),Ge));break}default:{s.clear();break}}}}async function tl(n,e,t,s){e.objectStore("inboundGroupSessions").createIndex("byBackup","backup",{unique:!1})}async function sl(n,e,t,s){const i=e.objectStore("inboundGroupSessions");let r=0,o=0;await K(i.openCursor(),(a,c,l)=>(a.session?(a.backup=Os.NotBackedUp,a.source=es.DeviceMessage,l.update(a),r+=1):o+=1,Ge)),s.set("countWithoutSession",o),s.set("countWithSession",r)}async function il(n){const e="hydrogen_webkit_test_inactive_txn_bug";try{const t=await Mi(e,r=>{r.createObjectStore("test",{keyPath:"key"})},1,n),s=t.transaction(["test"],"readonly");await X(s.objectStore("test").get("somekey")),await new Promise(r=>setTimeout(r,0));const i=t.transaction(["test"],"readwrite");await Promise.resolve(),i.objectStore("test").add({key:"somekey",value:"foo"}),await Jt(i),t.close()}catch(t){if(t.name==="TransactionInactiveError")return!0}return!1}const Xn=n=>`hydrogen_session_${n}`,si=function(n,e,t,s){const i=(r,o,a,c)=>ol(r,o,a,c,t,s);return Mi(Xn(n),i,Yn.length,e)};async function rl(){var e,t;const n=this;if((t=(e=n==null?void 0:n.navigator)==null?void 0:e.storage)!=null&&t.persist)return await n.navigator.storage.persist();if(n!=null&&n.document.requestStorageAccess)try{return await n.document.requestStorageAccess(),!0}catch(s){return console.warn("requestStorageAccess threw an error:",s),!1}else return!1}class nl{constructor(e,t=window.indexedDB,s=window.IDBKeyRange,i=window.localStorage){this._serviceWorkerHandler=e,this._idbFactory=t,this._IDBKeyRange=s,this._localStorage=i}async create(e,t){var r;await((r=this._serviceWorkerHandler)==null?void 0:r.preventConcurrentSessionAccess(e)),rl().then(o=>{o||console.warn("no persisted storage, database can be evicted by browser")});const s=await il(this._idbFactory),i=await si(e,this._idbFactory,this._localStorage,t);return new Pc(i,this._idbFactory,this._IDBKeyRange,s,this._localStorage,t.logger)}delete(e){const t=Xn(e),s=this._idbFactory.deleteDatabase(t);return X(s)}async export(e,t){const s=await si(e,this._idbFactory,this._localStorage,t);return await Uc(s)}async import(e,t,s){const i=await si(e,this._idbFactory,this._localStorage,s);return await Fc(i,t)}}async function ol(n,e,t,s,i,r){const o=t||0;return r.wrap({l:"storage migration",oldVersion:t,version:s},async a=>{for(let c=o;cl(n,e,i,h))}})}class Zn{constructor({roomId:e,ownUserId:t,fragmentIdComparer:s}){this._roomId=e,this._ownUserId=t,this._fragmentIdComparer=s}async writeRelation(e,t,s){const{relatedEventId:i}=e;if(i){const r=$e(e.event);r&&r.rel_type&&t.timelineRelations.add(this._roomId,r.event_id,r.rel_type,e.id);const o=await t.timelineEvents.getByEventId(this._roomId,i);if(o){const a=await this._applyRelation(e,o,t,s);if(a)return a.map(c=>(t.timelineEvents.update(c),new ne(c,this._fragmentIdComparer)))}}return null}async writeGapRelation(e,t,s,i){const r=new ne(e,this._fragmentIdComparer),o=await this.writeRelation(r,s,i);if(t.isBackward&&!di(e.event)){const a=await s.timelineRelations.getAllForTarget(this._roomId,r.id);if(a.length)for(const c of a){const l=await s.timelineEvents.getByEventId(this._roomId,c.sourceEventId);if(l){const h=new ne(l,this._fragmentIdComparer);await this._applyRelation(h,e,s,i)}}}return o}async _applyRelation(e,t,s,i){if(e.eventType===ge)return i.wrap("redact",async r=>{const o=t.event,a=$e(o);if(this._applyRedaction(e.event,t,s,r)){const l=[t];if(a){const h=await this._reaggregateRelation(o,a,s,r);h&&l.push(h)}return l}return null});{const r=$e(e.event);if(r&&!di(t.event)&&r.rel_type===We&&i.wrap("react",c=>this._aggregateAnnotation(e.event,t,c)))return[t]}return null}_applyRedaction(e,t,s,i){const r=t.event;i.set("redactionId",e.event_id),i.set("id",r.event_id);const o=$e(r);return o&&o.rel_type&&s.timelineRelations.remove(this._roomId,o.event_id,o.rel_type,r.event_id),s.timelineRelations.removeAllForTarget(this._roomId,r.event_id),ic(e,r),delete t.annotations,!0}_aggregateAnnotation(e,t){const s=$e(e);if(!s)return!1;let{annotations:i}=t;i||(t.annotations=i={});let r=i[s.key];r||(i[s.key]=r={count:0,me:!1,firstTimestamp:Number.MAX_SAFE_INTEGER});const o=e.sender===this._ownUserId;return r.me=r.me||o,r.count+=1,r.firstTimestamp=Math.min(r.firstTimestamp,e.origin_server_ts),!0}async _reaggregateRelation(e,t,s,i){return t.rel_type===We?i.wrap("reaggregate annotations",r=>this._reaggregateAnnotation(t.event_id,t.key,s,r)):null}async _reaggregateAnnotation(e,t,s,i){const r=await s.timelineEvents.getByEventId(this._roomId,e);if(!r||!r.annotations)return null;i.set("id",e);const o=await s.timelineRelations.getForTargetAndType(this._roomId,e,We);return i.set("relations",o.length),delete r.annotations[t],al(r.annotations)&&delete r.annotations,await Promise.all(o.map(async a=>{const c=await s.timelineEvents.getByEventId(this._roomId,a.sourceEventId);c||i.log({l:"missing annotation",id:a.sourceEventId}),$e(c.event).key===t&&this._aggregateAnnotation(c.event,r,i)})),r}}function al(n){for(const e in n)if(n.hasOwnProperty(e))return!1;return!0}class Me{constructor(e){this.isForward=e}get isBackward(){return!this.isForward}asApiString(){return this.isForward?"f":"b"}reverse(){return this.isForward?Me.Backward:Me.Forward}static get Forward(){return cl}static get Backward(){return ll}}const cl=new Me(!0),ll=new Me(!1);class ce extends Kn{constructor(e,t,s){super(s),this._fragment=e,this._isFragmentStart=t}static start(e,t){return new ce(e,!0,t)}static end(e,t){return new ce(e,!1,t)}get started(){return this._isFragmentStart}get hasEnded(){return!this.started}get fragment(){return this._fragment}get fragmentId(){return this._fragment.id}get entryIndex(){return this.started?F.minStorageKey:F.maxStorageKey}get isGap(){return!!this.token&&!this.edgeReached}get token(){return this.started?this.fragment.previousToken:this.fragment.nextToken}set token(e){this.started?this.fragment.previousToken=e:this.fragment.nextToken=e}get edgeReached(){return this.started?this.fragment.startReached:this.fragment.endReached}set edgeReached(e){this.started?this.fragment.startReached=e:this.fragment.endReached=e}get linkedFragmentId(){return this.started?this.fragment.previousId:this.fragment.nextId}set linkedFragmentId(e){this.started?this.fragment.previousId=e:this.fragment.nextId=e}get hasLinkedFragment(){return Ci(this.linkedFragmentId)}get direction(){return this.started?Me.Backward:Me.Forward}withUpdatedFragment(e){return new ce(e,this._isFragmentStart,this._fragmentIdComparer)}createNeighbourEntry(e){return new ce(e,!this._isFragmentStart,this._fragmentIdComparer)}addLocalRelation(){}removeLocalRelation(){}}function hl(n){const e=new Set;return n.filter(t=>e.has(t.event_id)?!1:(e.add(t.event_id),!0))}class dl{constructor({roomId:e,fragmentIdComparer:t,memberWriter:s,relationWriter:i}){this._roomId=e,this._memberWriter=s,this._relationWriter=i,this._fragmentIdComparer=t,this._lastLiveKey=null}async load(e,t){const s=await e.timelineFragments.liveFragment(this._roomId);if(s){const[i]=await e.timelineEvents.lastEvents(this._roomId,s.id,1),r=i?i.eventIndex:B.defaultLiveKey.eventIndex;this._lastLiveKey=new B(s.id,r)}this._lastLiveKey&&t.set("live key",this._lastLiveKey.toString())}async _createLiveFragment(e,t){const s=await e.timelineFragments.liveFragment(this._roomId);if(s)return s;{t||(t=null);const i={roomId:this._roomId,id:B.defaultLiveKey.fragmentId,previousId:null,nextId:null,previousToken:t,nextToken:null};return e.timelineFragments.add(i),this._fragmentIdComparer.add(i),i}}async _replaceLiveFragment(e,t,s,i){const r=await i.timelineFragments.get(this._roomId,e);if(!r)throw new Error(`old live fragment doesn't exist: ${e}`);r.nextId=t,i.timelineFragments.update(r);const o={roomId:this._roomId,id:t,previousId:e,nextId:null,previousToken:s,nextToken:null};return i.timelineFragments.add(o),this._fragmentIdComparer.append(t,e),{oldFragment:r,newFragment:o}}async _ensureLiveFragment(e,t,s,i,r){if(e){if(s.limited){const o=e.fragmentId;e=e.nextFragmentKey();const{oldFragment:a,newFragment:c}=await this._replaceLiveFragment(o,e.fragmentId,s.prev_batch,i);t.push(ce.end(a,this._fragmentIdComparer)),t.push(ce.start(c,this._fragmentIdComparer)),r.log({l:"live fragment",limited:!0,id:e.fragmentId})}}else{let o=await this._createLiveFragment(i,s.prev_batch);e=new B(o.id,B.defaultLiveKey.eventIndex),t.push(ce.start(o,this._fragmentIdComparer)),r.log({l:"live fragment",first:!0,id:e.fragmentId})}return e}async _writeStateEvents(e,t,s){let i=0;for(const r of e)r.type!==oe&&(t.roomState.set(this._roomId,r),i+=1);s.set("stateEvents",i)}async _writeTimeline(e,t,s,i,r,o){const a=[],c=[];if(e!=null&&e.length){i=await this._ensureLiveFragment(i,a,t,r,o),o.set("timelineEvents",e.length);let l=0;for(const h of e){i=i.nextKey();const d=qn(i,this._roomId,h);let u=await s.lookupMemberAtEvent(h.sender,h,r);if(u&&(d.displayName=u.displayName,d.avatarUrl=u.avatarUrl),!await r.timelineEvents.tryInsert(d,o))continue;const _=new ne(d,this._fragmentIdComparer);a.push(_);const f=await this._relationWriter.writeRelation(_,r,o);f&&c.push(...f),typeof h.state_key=="string"&&h.type!==oe&&(l+=1,r.roomState.set(this._roomId,h))}o.set("timelineStateEventCount",l)}return{currentKey:i,entries:a,updatedEntries:c}}async _handleRejoinOverlap(e,t,s){if(this._lastLiveKey){const{fragmentId:i}=this._lastLiveKey,[r]=await t.timelineEvents.lastEvents(this._roomId,i,1);if(r){const o=r.event.event_id,{events:a}=e,c=a.findIndex(l=>l.event_id===o);if(c!==-1)return s.set("overlap_event_id",o),Object.assign({},e,{limited:!1,events:a.slice(c+1)})}}return e.limited?e:(s.set("force_limited_without_overlap",!0),Object.assign({},e,{limited:!0}))}async writeSync(e,t,s,i,r){let{timeline:o}=e;r.set("isRejoin",t),t&&(o=await this._handleRejoinOverlap(o,i,r));let a;Array.isArray(o==null?void 0:o.events)&&(a=hl(o.events));const{state:c}=e;let l;Array.isArray(c==null?void 0:c.events)&&(l=c.events);const h=this._memberWriter.prepareMemberSync(l,a,s);l&&await this._writeStateEvents(l,i,r);const{currentKey:d,entries:u,updatedEntries:p}=await this._writeTimeline(a,o,h,this._lastLiveKey,i,r),_=await h.write(i);return{entries:u,updatedEntries:p,newLiveKey:d,memberChanges:_}}afterSync(e){this._lastLiveKey=e}get lastMessageKey(){return this._lastLiveKey}}class eo{constructor(e){this.limit=e,this._entries=[]}get size(){return this._entries.length}_get(e){return this._getByIndexAndMoveUp(this._entries.findIndex(e))}_getByIndexAndMoveUp(e){if(e!==-1){const t=this._entries[e];return e>0&&(this._entries.splice(e,1),this._entries.unshift(t)),t}}_set(e,t){let s=t?this._entries.findIndex(t):-1;this._entries.unshift(e),s===-1?this._entries.length>this.limit&&(s=this._entries.length-1):s+=1,s!==-1&&(this.onEvictEntry(this._entries[s]),this._entries.splice(s,1))}onEvictEntry(e){}}class ul extends eo{constructor(e,t){super(e),this._keyFn=t}get(e){return this._get(t=>this._keyFn(t)===e)}set(e){const t=this._keyFn(e);this._set(e,s=>this._keyFn(s)===t)}}class ml{constructor(e){this._roomId=e,this._cache=new ul(5,t=>t.userId)}prepareMemberSync(e,t,s){return new pl(this,e,t,s)}async _writeMember(e,t){let s=this._cache.get(e.userId);if(!s){const i=await t.roomMembers.get(this._roomId,e.userId);i&&(s=new O(i))}if(!s||!s.equals(e))return t.roomMembers.set(e.serialize()),this._cache.set(e),new Wn(e,s==null?void 0:s.membership)}async lookupMember(e,t){let s=this._cache.get(e);if(!s){const i=await t.roomMembers.get(this._roomId,e);i&&(s=new O(i),this._cache.set(s))}return s}}class pl{constructor(e,t,s,i){this._memberWriter=e,this._timelineEvents=s,this._hasFetchedMembers=i,this._newStateMembers=null,t&&(this._newStateMembers=this._stateEventsToMembers(t))}get _roomId(){return this._memberWriter._roomId}_stateEventsToMembers(e){let t;for(const s of e)if(s.type===oe){const i=O.fromMemberEvent(this._roomId,s);i&&(t||(t=new Map),t.set(i.userId,i))}return t}_timelineEventsToMembers(e){let t;for(let s=e.length-1;s>=0;s--){const i=e[s],r=i.state_key;if(i.type===oe&&!(t!=null&&t.has(r))){const o=O.fromMemberEvent(this._roomId,i);o&&(t||(t=new Map),t.set(o.userId,o))}}return t}async lookupMemberAtEvent(e,t,s){var r;let i;return this._timelineEvents&&(i=this._findPrecedingMemberEventInTimeline(e,t),i)||(i=(r=this._newStateMembers)==null?void 0:r.get(e),i)?i:await this._memberWriter.lookupMember(e,s)}async write(e){const t=new Map;let s;if(this._timelineEvents&&(s=this._timelineEventsToMembers(this._timelineEvents)),this._newStateMembers){for(const i of this._newStateMembers.values())if(!(s!=null&&s.has(i.userId))){const r=await this._memberWriter._writeMember(i,e);r&&(!this._hasFetchedMembers&&!r.previousMembership&&(r.previousMembership=i.membership),t.set(r.userId,r))}}if(s)for(const i of s.values()){const r=await this._memberWriter._writeMember(i,e);r&&t.set(r.userId,r)}return t}_findPrecedingMemberEventInTimeline(e,t){let s=-1;for(let i=this._timelineEvents.length-1;i>=0;i--)if(this._timelineEvents[i].event_id===t.event_id){s=i;break}for(let i=s-1;i>=0;i--){const r=this._timelineEvents[i];if(r.type===oe&&r.state_key===e){const o=O.fromMemberEvent(this._roomId,r);if(o)return o}}}}class _l{constructor({roomId:e,storage:t,fragmentIdComparer:s,relationWriter:i}){this._roomId=e,this._storage=t,this._fragmentIdComparer=s,this._relationWriter=i}async _findOverlappingEvents(e,t,s,i){const r=t.map(l=>l.event_id),o=await s.timelineEvents.getEventKeysForIds(this._roomId,r);i.set("existingEvents",o.size);const a=t.filter(l=>!o.has(l.event_id));i.set("nonOverlappingEvents",a.length);let c;if(e.hasLinkedFragment){i.set("linkedFragmentId",e.linkedFragmentId);for(const l of o.values())if(l.fragmentId===e.linkedFragmentId){i.set("foundLinkedFragment",!0);const h=await s.timelineFragments.get(this._roomId,e.linkedFragmentId);c=e.createNeighbourEntry(h);break}}return{nonOverlappingEvents:a,neighbourFragmentEntry:c}}async _findFragmentEdgeEventKey(e,t){const{fragmentId:s,direction:i}=e,r=await this._findFragmentEdgeEvent(s,i,t);return r?new B(r.fragmentId,r.eventIndex):B.defaultFragmentKey(e.fragmentId)}async _findFragmentEdgeEvent(e,t,s){if(t.isBackward){const[i]=await s.timelineEvents.firstEvents(this._roomId,e,1);return i}else{const[i]=await s.timelineEvents.lastEvents(this._roomId,e,1);return i}}async _storeEvents(e,t,s,i,r,o){const a=[],c=[];let l=t;for(let h=0;h=0&&l=0&&l + * Copyright JS Foundation and other contributors + * Released under MIT license + * Based on Underscore.js 1.8.3 + * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors + */function He(n,e,t){let s=0,i=n.length;for(;s>>1,o=t(e,n[r]);o>0?s=r+1:o<0?i=r:s=i=r}return i}class Ct extends Ii{emitReset(){for(let e of this._handlers)e.onReset()}emitAdd(e,t){for(let s of this._handlers)s.onAdd(e,t)}emitUpdate(e,t,s){for(let i of this._handlers)i.onUpdate(e,t,s)}emitRemove(e,t){for(let s of this._handlers)s.onRemove(e,t)}}class qt extends Ct{constructor(e){super(),this._values=new Map(e)}update(e,t){const s=this._values.get(e);return s!==void 0?(this._values.set(e,s),this.emitUpdate(e,s,t),!0):!1}add(e,t){return this._values.has(e)?!1:(this._values.set(e,t),this.emitAdd(e,t),!0)}remove(e){const t=this._values.get(e);return t!==void 0?(this._values.delete(e),this.emitRemove(e,t),!0):!1}set(e,t){return this._values.has(e)?(this._values.set(e,t),this.update(e,void 0)):this.add(e,t)}reset(){this._values.clear(),this.emitReset()}get(e){return this._values.get(e)}get size(){return this._values.size}[Symbol.iterator](){return this._values.entries()}values(){return this._values.values()}keys(){return this._values.keys()}}class fl extends Rt{constructor(e,t){super(),this._sourceMap=e,this._comparator=(s,i)=>t(s.value,i.value),this._sortedPairs=null,this._mapSubscription=null}onAdd(e,t){const s={key:e,value:t},i=He(this._sortedPairs,s,this._comparator);this._sortedPairs.splice(i,0,s),this.emitAdd(i,t)}onRemove(e,t){const s={key:e,value:t},i=He(this._sortedPairs,s,this._comparator);this._sortedPairs.splice(i,1),this.emitRemove(i,t)}onUpdate(e,t,s){if(!this._sortedPairs)return;const i=this._sortedPairs.findIndex(a=>a.key===e);this._sortedPairs.splice(i,1);const r={key:e,value:t},o=He(this._sortedPairs,r,this._comparator);this._sortedPairs.splice(o,0,r),i!==o&&this.emitMove(i,o,t),this.emitUpdate(o,t,s)}onReset(){this._sortedPairs=[],this.emitReset()}onSubscribeFirst(){this._mapSubscription=this._sourceMap.subscribe(this),this._sortedPairs=new Array(this._sourceMap.size);let e=0;for(let[t,s]of this._sourceMap)this._sortedPairs[e]={key:t,value:s},++e;this._sortedPairs.sort(this._comparator),super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._sortedPairs=null,this._mapSubscription=this._mapSubscription()}get(e){return this._sortedPairs[e].value}get length(){return this._sourceMap.size}[Symbol.iterator](){const e=this._sortedPairs.values();return{next(){const t=e.next();return t.value&&(t.value=t.value.value),t}}}}class gl extends Ct{constructor(e,t){super(),this._source=e,this._filter=t,this._included=null,this._subscription=null}setFilter(e){this._filter=e,this._subscription&&this._reapplyFilter()}_reapplyFilter(e=!1){if(this._filter){const t=this._included;this._included=this._included||new Map;for(const[s,i]of this._source){const r=this._filter(i,s);if(this._included.set(s,r),!e){const o=t?t.get(s):!0;this._emitForUpdate(o,r,s,i)}}}else{if(this._included&&!e)for(const[t,s]of this._source)this._included.get(t)||this.emitAdd(t,s);this._included=null}}onAdd(e,t){if(this._filter){const s=this._filter(t,e);if(this._included.set(e,s),!s)return}this.emitAdd(e,t)}onRemove(e,t){const s=!this._filter||this._included.get(e);this._included.delete(e),s&&this.emitRemove(e,t)}onUpdate(e,t,s){if(!!this._included)if(this._filter){const i=this._included.get(e),r=this._filter(t,e);this._included.set(e,r),this._emitForUpdate(i,r,e,t,s)}else this.emitUpdate(e,t,s)}_emitForUpdate(e,t,s,i,r=null){e&&!t?this.emitRemove(s,i):!e&&t?this.emitAdd(s,i):e&&t&&this.emitUpdate(s,i,r)}onSubscribeFirst(){this._subscription=this._source.subscribe(this),this._reapplyFilter(!0),super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._included=null,this._subscription=this._subscription()}onReset(){this._reapplyFilter(),this.emitReset()}[Symbol.iterator](){return new yl(this._source,this._included)}get size(){let e=0;return this._included.forEach(t=>{t&&(e+=1)}),e}get(e){const t=this._source.get(e);if(t&&this._filter(t,e))return t}}class yl{constructor(e,t){this._included=t,this._sourceIterator=e[Symbol.iterator]()}next(){for(;;){const e=this._sourceIterator.next();if(e.done)return e;const t=e.value[0];if(this._included.get(t))return e}}}class wl extends Ct{constructor(e,t,s){super(),this._source=e,this._mapper=t,this._updater=s,this._mappedValues=new Map}_emitSpontaneousUpdate(e,t){const s=this._mappedValues.get(e);s&&this.emitUpdate(e,s,t)}onAdd(e,t){const s=this._emitSpontaneousUpdate.bind(this,e),i=this._mapper(t,s);this._mappedValues.set(e,i),this.emitAdd(e,i)}onRemove(e){const t=this._mappedValues.get(e);this._mappedValues.delete(e)&&this.emitRemove(e,t)}onUpdate(e,t,s){var r;if(!this._mappedValues)return;const i=this._mappedValues.get(e);i!==void 0&&((r=this._updater)==null||r.call(this,i,s,t),this.emitUpdate(e,i,s))}onSubscribeFirst(){this._subscription=this._source.subscribe(this);for(let[e,t]of this._source){const s=this._emitSpontaneousUpdate.bind(this,e),i=this._mapper(t,s);this._mappedValues.set(e,i)}super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._subscription=this._subscription(),this._mappedValues.clear()}onReset(){this._mappedValues.clear(),this.emitReset()}[Symbol.iterator](){return this._mappedValues.entries()}get size(){return this._mappedValues.size}get(e){return this._mappedValues.get(e)}}class vl extends Ct{constructor(e){super(),this._sources=e,this._subscriptions=null}onAdd(e,t,s){if(!this._isKeyAtSourceOccluded(e,t)){const i=this._getValueFromOccludedSources(e,t);i!==void 0&&this.emitRemove(t,i),this.emitAdd(t,s)}}onRemove(e,t,s){if(!this._isKeyAtSourceOccluded(e,t)){this.emitRemove(t,s);const i=this._getValueFromOccludedSources(e,t);i!==void 0&&this.emitAdd(t,i)}}onUpdate(e,t,s,i){!this._subscriptions||this._isKeyAtSourceOccluded(e,t)||this.emitUpdate(t,s,i)}onReset(){this.emitReset()}onSubscribeFirst(){this._subscriptions=this._sources.map(e=>new Sl(e,this).subscribe()),super.onSubscribeFirst()}_isKeyAtSourceOccluded(e,t){const s=this._sources.indexOf(e);for(let i=0;ie+t.size,0)}get(e){for(const t of this._sources){const s=t.get(e);if(s)return s}return null}}class bl{constructor(e){this._sources=e,this._sourceIndex=-1,this._currentIterator=null,this._encounteredKeys=new Set}next(){let e;for(;!e;){if(!this._currentIterator){if(this._sourceIndex+=1,this._sources.length<=this._sourceIndex)return{done:!0};this._currentIterator=this._sources[this._sourceIndex][Symbol.iterator]()}const t=this._currentIterator.next();if(t.done){this._currentIterator=null;continue}else{const s=t.value[0];this._encounteredKeys.has(s)||(this._encounteredKeys.add(s),e=t)}}return e}}class Sl{constructor(e,t){this._source=e,this._joinedMap=t,this._subscription=null}subscribe(){return this._subscription=this._source.subscribe(this),this}dispose(){this._subscription=this._subscription()}onAdd(e,t){this._joinedMap.onAdd(this._source,e,t)}onRemove(e,t){this._joinedMap.onRemove(this._source,e,t)}onUpdate(e,t,s){this._joinedMap.onUpdate(this._source,e,t,s)}onReset(){this._joinedMap.onReset(this._source)}}class Il extends Rt{constructor(e=[]){super(),this._items=e}append(e){this._items.push(e),this.emitAdd(this._items.length-1,e)}remove(e){const[t]=this._items.splice(e,1);this.emitRemove(e,t)}insertMany(e,t){for(let s of t)this.insert(e,s),e+=1}insert(e,t){this._items.splice(e,0,t),this.emitAdd(e,t)}move(e,t){if(e=0&&e=this._items.length||this._comparator(this._items[s],e)!==0?(this._items.splice(s,0,e),this.emitAdd(s,e)):(this._items[s]=e,this.emitUpdate(s,e,t))}get(e){return this._items[e]}remove(e){const t=this._items[e];this._items.splice(e,1),this.emitRemove(e,t)}get array(){return this._items}get length(){return this._items.length}[Symbol.iterator](){return new El(this)}}class El{constructor(e){this._sortedArray=e,this._current=null}next(){if(this._sortedArray){if(this._current?this._current=this._sortedArray._getNext(this._current):this._current=this._sortedArray.get(0),this._current)return{value:this._current};this._sortedArray=null}if(!this._sortedArray)return{done:!0}}}class kl extends Rt{constructor(e,t,s,i){super(),this._sourceUnsubscribe=null,this._mappedValues=null,this._sourceList=e,this._mapper=t,this._updater=s,this._removeCallback=i}findAndUpdate(e,t){return to(e,this._mappedValues,this,t)}get length(){return this._mappedValues.length}[Symbol.iterator](){return this._mappedValues.values()}}function Rl(n,e,t){n._mappedValues.splice(e,0,t),n.emitAdd(e,t)}function Cl(n,e,t,s){const i=n._mappedValues[e];n._updater&&n._updater(i,s,t),n.emitUpdate(e,i,s)}function Tl(n,e){const t=n._mappedValues[e];n._mappedValues.splice(e,1),n._removeCallback&&n._removeCallback(t),n.emitRemove(e,t)}function Ml(n,e,t){const s=n._mappedValues[e];n._mappedValues.splice(e,1),n._mappedValues.splice(t,0,s),n.emitMove(e,t,s)}function Al(n){n._mappedValues=[],n.emitReset()}class xl extends kl{constructor(){super(...arguments),this._eventQueue=null,this._flushing=!1}onSubscribeFirst(){this._sourceUnsubscribe=this._sourceList.subscribe(this),this._eventQueue=[],this._mappedValues=[];let e=0;for(const t of this._sourceList)this._eventQueue.push(new Pr(e,t)),e+=1;this._flush()}async _flush(){if(!this._flushing){this._flushing=!0;try{for(;this._eventQueue.length;)await this._eventQueue.shift().run(this)}finally{this._flushing=!1}}}onReset(){this._eventQueue&&(this._eventQueue.push(new Ll),this._flush())}onAdd(e,t){this._eventQueue&&(this._eventQueue.push(new Pr(e,t)),this._flush())}onUpdate(e,t,s){this._eventQueue&&(this._eventQueue.push(new Nl(e,t,s)),this._flush())}onRemove(e){this._eventQueue&&(this._eventQueue.push(new Dl(e)),this._flush())}onMove(e,t){this._eventQueue&&(this._eventQueue.push(new Vl(e,t)),this._flush())}onUnsubscribeLast(){this._sourceUnsubscribe(),this._eventQueue=null,this._mappedValues=null}}class Pr{constructor(e,t){this.index=e,this.value=t}async run(e){const t=await e._mapper(this.value);Rl(e,this.index,t)}}class Nl{constructor(e,t,s){this.index=e,this.value=t,this.params=s}async run(e){Cl(e,this.index,this.value,this.params)}}class Dl{constructor(e){this.index=e}async run(e){Tl(e,this.index)}}class Vl{constructor(e,t){this.fromIdx=e,this.toIdx=t}async run(e){Ml(e,this.fromIdx,this.toIdx)}}class Ll{async run(e){Al(e)}}class Ol extends Rt{constructor(...e){super(),this._sourceUnsubscribes=null,this._sourceLists=e}_offsetForSource(e){const t=this._sourceLists.indexOf(e);let s=0;for(let i=0;ie.subscribe(this))}onUnsubscribeLast(){for(const e of this._sourceUnsubscribes)e()}onReset(){this.emitReset();let e=0;for(const t of this)this.emitAdd(e,t),e+=1}onAdd(e,t,s){this.emitAdd(this._offsetForSource(s)+e,t)}onUpdate(e,t,s,i){!this._sourceUnsubscribes||this.emitUpdate(this._offsetForSource(i)+e,t,s)}onRemove(e,t,s){this.emitRemove(this._offsetForSource(s)+e,t)}onMove(e,t,s,i){const r=this._offsetForSource(i);this.emitMove(r+e,r+t,s)}get length(){let e=0;for(let t=0;t{let s=t.next();for(;s.done;){if(e+=1,e>=this._sourceLists.length)return s;t=this._sourceLists[e][Symbol.iterator](),s=t.next()}return s}}}}Object.assign(Ct.prototype,{sortValues(n){return new fl(this,n)},mapValues(n,e){return new wl(this,n,e)},filterValues(n){return new gl(this,n)},join(...n){return new vl([this].concat(n))}});function ii(n){typeof n=="function"?n():n.dispose()}function Pl(n){return n&&(typeof n=="function"||typeof n.dispose=="function")}class Ni{constructor(){this._disposables=[]}track(e){if(!Pl(e))throw new Error("Not a disposable");return this.isDisposed?(console.warn("Disposables already disposed, disposing new value"),ii(e),e):(this._disposables.push(e),e)}untrack(e){if(this.isDisposed){console.warn("Disposables already disposed, cannot untrack");return}const t=this._disposables.indexOf(e);t>=0&&this._disposables.splice(t,1)}dispose(){if(this._disposables){for(const e of this._disposables)ii(e);this._disposables=void 0}}get isDisposed(){return this._disposables===void 0}disposeTracked(e){if(e==null||this.isDisposed)return;const t=this._disposables.indexOf(e);if(t!==-1){const[s]=this._disposables.splice(t,1);ii(s)}else console.warn("disposable not found, did it leak?",e)}}class Ur{constructor(e,t){this.decryptRequest=null,this._promise=e(this,t)}complete(){return this._promise}dispose(){this.decryptRequest&&(this.decryptRequest.dispose(),this.decryptRequest=null)}}async function Ul(n,e,t,s,i,r){let o=[];const a=r.timelineEvents,c=r.timelineFragments;for(;o.lengthnew ne(d,i));if(o=ec(o,h,t),o.length{const a=await this._storage.readTxn(this.readTxnStores);return await this._readFrom(e,t,s,r,a,o)},i)}readFromEnd(e,t=null,s){return new Ur(async(i,r)=>{const o=t||await this._storage.readTxn(this.readTxnStores),a=await o.timelineFragments.liveFragment(this._roomId);let c;if(!a)c=[];else{this._fragmentIdComparer.add(a);const l=ce.end(a,this._fragmentIdComparer),h=l.asEventKey();c=await this._readFrom(h,Me.Backward,e,i,o,r),c.unshift(l)}return c},s)}async readById(e,t){let s=[this._storage.storeNames.timelineEvents];this._decryptEntries&&s.push(this._storage.storeNames.inboundGroupSessions);const i=await this._storage.readTxn(s),r=await i.timelineEvents.getByEventId(this._roomId,e);if(r){const o=new ne(r,this._fragmentIdComparer);return this._decryptEntries&&await this._decryptEntries([o],i,t).complete(),o}}async _readFrom(e,t,s,i,r,o){const a=await Ul(this._roomId,e,t,s,this._fragmentIdComparer,r);if(this._decryptEntries){i.decryptRequest=this._decryptEntries(a,r,o);try{await i.decryptRequest.complete()}finally{i.decryptRequest=null}}return a}}class Fl extends ne{get fragmentId(){throw new Error("Cannot access fragmentId for non-persisted EventEntry")}get entryIndex(){throw new Error("Cannot access entryIndex for non-persisted EventEntry")}get isNonPersisted(){return!0}get isRedacting(){return!1}get isRedacted(){return super.isRedacting}}class Bl{constructor(e){this._userId=e}get id(){return this._userId}}class Ts{constructor({roomId:e,storage:t,closeCallback:s,fragmentIdComparer:i,pendingEvents:r,clock:o,powerLevelsObservable:a,hsApi:c}){this._roomId=e,this._storage=t,this._closeCallback=s,this._fragmentIdComparer=i,this._disposables=new Ni,this._pendingEvents=r,this._clock=o,this._remoteEntries=new xi((l,h)=>l.compare(h)),this._ownMember=null,this._timelineReader=new so({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}),this._readerRequest=null,this._allEntries=null,this._contextEntriesNotInTimeline=new Map,this._decryptEntries=null,this._hsApi=c,this.initializePowerLevels(a)}initializePowerLevels(e){e&&(this._powerLevels=e.get(),this._disposables.track(e.subscribe(t=>this._powerLevels=t)))}async load(e,t,s){const i=await this._storage.readTxn(this._timelineReader.readTxnStores.concat(this._storage.storeNames.roomMembers,this._storage.storeNames.roomState)),r=await i.roomMembers.get(this._roomId,e.id);r?this._ownMember=new O(r):this._ownMember=O.fromUserId(this._roomId,e.id,t);const o=this._disposables.track(this._timelineReader.readFromEnd(20,i,s));try{const a=await o.complete();this._loadContextEntriesWhereNeeded(a),this._setupEntries(a)}finally{this._disposables.disposeTracked(o)}}_setupEntries(e){this._remoteEntries.setManySorted(e),this._pendingEvents?this._localEntries=new xl(this._pendingEvents,t=>this._mapPendingEventToEntry(t),(t,s)=>{t.notifyUpdate(s)},t=>this._applyAndEmitLocalRelationChange(t,s=>s.removeLocalRelation(t))):this._localEntries=new Il,this._allEntries=new Ol(this._remoteEntries,this._localEntries)}async _mapPendingEventToEntry(e){let t;e.eventType===ge&&(t=await this._getOrLoadEntry(e.relatedTxnId,e.relatedEventId));const s=new Xa({pendingEvent:e,member:this._ownMember,clock:this._clock,redactingEntry:t});return this._loadContextEntriesWhereNeeded([s]),this._applyAndEmitLocalRelationChange(s,i=>i.addLocalRelation(s)),s}_applyAndEmitLocalRelationChange(e,t){var i,r;const s=o=>{const a=t(o);return a||!1};if(this._findAndUpdateEntryById(e.pendingEvent.relatedTxnId,e.relatedEventId,s),e.redactingEntry){const o=(i=e.redactingEntry.pendingEvent)==null?void 0:i.relatedTxnId;this._findAndUpdateEntryById(o,e.redactingEntry.relatedEventId,s),(r=e.redactingEntry.contextForEntries)==null||r.forEach(a=>this._emitUpdateForEntry(a,"contextEntry"))}}_findAndUpdateEntryById(e,t,s){let i=!1;e&&(i=this._localEntries.findAndUpdate(r=>r.id===e,s)),!i&&t&&this._remoteEntries.findAndUpdate(r=>r.id===t,s)}async getOwnAnnotationEntry(e,t){const s=await this._storage.readWriteTxn([this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineRelations]),i=await s.timelineRelations.getForTargetAndType(this._roomId,e,We);for(const r of i){const o=await s.timelineEvents.getByEventId(this._roomId,r.sourceEventId);if(o&&o.event.sender===this._ownMember.userId&&$e(o.event).key===t){const a=new ne(o,this._fragmentIdComparer);return this._addLocalRelationsToNewRemoteEntries([a]),a}}return null}updateOwnMember(e){this._ownMember=e}_addLocalRelationsToNewRemoteEntries(e){var t;if(!!((t=this._localEntries)!=null&&t.hasSubscriptions))for(const s of this._localEntries){if(s.relatedEventId){const i=e.find(r=>r.id===s.relatedEventId);i==null||i.addLocalRelation(s)}if(s.redactingEntry){const i=s.redactingEntry.relatedEventId,r=e.find(o=>o.id===i);r==null||r.addLocalRelation(s)}}}static _entryUpdater(e,t){var s;return(s=e.contextForEntries)==null||s.forEach(i=>i.setContextEntry(t)),t.updateFrom(e),t}replaceEntries(e){var t;this._addLocalRelationsToNewRemoteEntries(e);for(const s of e)try{this._remoteEntries.getAndUpdate(s,Ts._entryUpdater);const i=this._contextEntriesNotInTimeline.get(s.id);i&&(Ts._entryUpdater(i,s),this._contextEntriesNotInTimeline.set(s.id,s)),(t=s.contextForEntries)==null||t.forEach(r=>this._emitUpdateForEntry(r,"contextEntry"))}catch(i){if(i.name==="CompareError")continue;throw i}}addEntries(e){this._addLocalRelationsToNewRemoteEntries(e),this._updateEntriesFetchedFromHomeserver(e),this._moveEntryToRemoteEntries(e),this._loadContextEntriesWhereNeeded(e),this._remoteEntries.setManySorted(e)}_updateEntriesFetchedFromHomeserver(e){var t;for(const s of e){const i=this._contextEntriesNotInTimeline.get(s.relatedEventId);(i==null?void 0:i.isNonPersisted)&&(i==null?void 0:i.addLocalRelation(s))&&((t=i.contextForEntries)==null||t.forEach(r=>this._emitUpdateForEntry(r,"contextEntry")))}}_moveEntryToRemoteEntries(e){for(const t of e){const s=this._contextEntriesNotInTimeline.get(t.id);s&&(s.contextForEntries.forEach(i=>{i.setContextEntry(t),this._emitUpdateForEntry(i,"contextEntry")}),this._contextEntriesNotInTimeline.delete(t.id))}}_emitUpdateForEntry(e,t){const s=e.isPending?e.id:null,i=e.isPending?null:e.id;this._findAndUpdateEntryById(s,i,()=>t)}async _loadContextEntriesWhereNeeded(e){for(const t of e){if(!t.contextEventId)continue;const s=t.contextEventId;let i=e.find(r=>r.id===s);i||(i=this._findLoadedEventById(s)),i?t.setContextEntry(i):this._loadContextEntryNotInTimeline(t)}}async _loadContextEntryNotInTimeline(e){const t=e.contextEventId;let s=await this._getEventFromStorage(t);s||(s=await this._getEventFromHomeserver(t)),s&&(this._contextEntriesNotInTimeline.set(t,s),e.setContextEntry(s),this._emitUpdateForEntry(e,"contextEntry"))}_findLoadedEventById(e){var t;return(t=this.getByEventId(e))!=null?t:this._contextEntriesNotInTimeline.get(e)}async _getEventFromStorage(e){return await this._timelineReader.readById(e)}async _getEventFromHomeserver(e){const t=await this._hsApi.context(this._roomId,e,0).response(),s=t.event.sender,i=t.state.find(a=>a.type===oe&&a.user_id===s),r={event:t.event,displayName:i.content.displayname,avatarUrl:i.content.avatar_url},o=new Fl(r,this._fragmentIdComparer);return this._decryptEntries&&await this._decryptEntries([o]).complete(),o}async loadAtTop(e){if(this._disposables.isDisposed)return!0;const t=this._remoteEntries.array.find(i=>!!i.eventType);if(!t)return!0;const s=this._disposables.track(this._timelineReader.readFrom(t.asEventKey(),Me.Backward,e));try{const i=await s.complete();return this.addEntries(i),i.lengthnew O(i))}async function $l({summary:n,syncToken:e,roomId:t,hsApi:s,storage:i,setChangedMembersMap:r},o){const a=new Map;r(a);const c=await s.members(t,{at:e},{log:o}).response(),l=await i.readWriteTxn([i.storeNames.roomSummary,i.storeNames.roomMembers]);let h,d;try{h=n.writeHasFetchedMembers(!0,l);const{roomMembers:u}=l,p=c.chunk;if(!Array.isArray(p))throw new Error("malformed");o.set("members",p.length),d=await Promise.all(p.map(async _=>{const f=_==null?void 0:_.state_key;if(!f)throw new Error("malformed");const b=a.get(f);if(b)return b;{const S=O.fromMemberEvent(t,_);return S&&u.set(S.serialize()),S}}))}catch(u){throw l.abort(),u}finally{r(null)}return await l.complete(),n.applyChanges(h),d}async function jl(n,e){const{summary:t}=n;return t.data.hasFetchedMembers?Kl(n):e.wrapOrRun(n.log,"fetchMembers",s=>$l(n,s))}async function ql(n,e){const t=await Wl(n),{summary:s}=n;return!s.data.hasFetchedMembers&&!t?e.wrapOrRun(n.log,"fetchMember",i=>Hl(n,i)):t}async function Wl({roomId:n,userId:e,storage:t}){const i=await(await t.readTxn([t.storeNames.roomMembers])).roomMembers.get(n,e);return i?new O(i):null}async function Hl({roomId:n,userId:e,hsApi:t,storage:s},i){let r;try{r=await t.state(n,"m.room.member",e,{log:i}).response()}catch(c){if(c.name==="HomeServerError"&&c.errcode==="M_NOT_FOUND")return null;throw c}const o=new O({roomId:n,userId:e,membership:r.membership,avatarUrl:r.avatar_url,displayName:r.displayname}),a=await s.readWriteTxn([s.storeNames.roomMembers]);try{a.roomMembers.set(o.serialize())}catch(c){throw a.abort(),c}return await a.complete(),o}class zl{constructor(e){this._retentionCount=1,this._freeCallback=e}retain(){this._retentionCount+=1}release(){this._retentionCount-=1,this._retentionCount===0&&this._freeCallback()}}class Gl extends zl{constructor({members:e,closeCallback:t}){super(t),this._members=new qt;for(const s of e)this._members.add(s.userId,s)}afterSync(e){for(const[t,s]of e.entries())this._members.set(t,s.member)}get members(){return this._members}}function pi(n,e,t){const s=e.joinCount+e.inviteCount-1;if(n.length>=s)if(n.length>1){const i=n[n.length-1];return n.slice(0,n.length-1).map(o=>o.name).join(", ")+" and "+i.name}else{const i=n[0];return i?i.name:(t.log({l:"could get get other member name",length:n.length,otherMember:!!i,otherMemberMembership:i==null?void 0:i.membership}),"Unknown DM Name")}else return n.lengthi.name).join(", ")+` and ${s} others`:null}class Di{constructor(e){this._roomId=e,this._members=new Map}async calculateChanges(e,t,s){const i=new Map,r=[];for(const o of this._members.keys())e.indexOf(o)===-1&&r.push(o);for(const[o,a]of t.entries())(this._members.has(o)||e.indexOf(o)!==-1)&&i.set(o,a.member);for(const o of e)if(!this._members.has(o)&&!i.has(o)){const a=await s.roomMembers.get(this._roomId,o);if(a){const c=new O(a);i.set(c.userId,c)}}return{updatedHeroMembers:i.values(),removedUserIds:r}}applyChanges({updatedHeroMembers:e,removedUserIds:t},s,i){for(const o of t)this._members.delete(o);for(const o of e)this._members.set(o.userId,o);const r=Array.from(this._members.values()).sort((o,a)=>o.name.localeCompare(a.name));this._roomName=pi(r,s,i)}get roomName(){return this._roomName}get roomAvatarUrl(){if(this._members.size===1)for(const e of this._members.values())return e.avatarUrl;return null}get roomAvatarColorId(){if(this._members.size===1)for(const e of this._members.keys())return e;return null}}class Jl{constructor(e){this._map=new Map,this._notifyEmpty=e}observe(e,t=null){let s=this._map.get(e);return s||(s=new Ql(this,t,e),this._map.set(e,s)),s}updateEvents(e){for(let t=0;t{this.hasSubscriptions||(this._eventMap._remove(this._id),this._eventMap=null)})}subscribe(e){if(!this._eventMap)throw new Error("ObservedEvent expired, subscribe right after calling room.observeEvent()");return super.subscribe(e)}onUnsubscribeLast(){this._eventMap._remove(this._id),this._eventMap=null,super.onUnsubscribeLast()}update(e){this._entry=e,this.emit(this._entry)}get(){return this._entry}}function Yl(n){return n||gc.item}const Xl="m.room.power_levels";class Es{constructor({powerLevelEvent:e,createEvent:t,ownUserId:s,membership:i}){this._plEvent=e,this._createEvent=t,this._ownUserId=s,this._membership=i}canRedactFromSender(e){return e===this._ownUserId&&this._membership==="join"?!0:this.canRedact}canSendType(e){return this._myLevel>=this._getEventTypeLevel(e)}get canRedact(){return this._myLevel>=this._getActionLevel("redact")}get _myLevel(){return this._membership!=="join"?Number.MIN_SAFE_INTEGER:this.getUserLevel(this._ownUserId)}getUserLevel(e){var t,s,i,r;if(this._plEvent){let o=(s=(t=this._plEvent.content)==null?void 0:t.users)==null?void 0:s[e];if(typeof o!="number"&&(o=(i=this._plEvent.content)==null?void 0:i.users_default),typeof o=="number")return o}else if(this._createEvent&&e===((r=this._createEvent.content)==null?void 0:r.creator))return 100;return 0}_getActionLevel(e){var s;const t=(s=this._plEvent)==null?void 0:s.content[e];return typeof t=="number"?t:50}_getEventTypeLevel(e){var s,i,r;const t=(i=(s=this._plEvent)==null?void 0:s.content.events)==null?void 0:i[e];if(typeof t=="number")return t;{const o=(r=this._plEvent)==null?void 0:r.content.events_default;return typeof o=="number"?o:0}}}const Zl="m.room.encrypted";class io extends Ls{constructor({roomId:e,storage:t,hsApi:s,mediaRepository:i,emitCollectionChange:r,user:o,createRoomEncryption:a,getSyncToken:c,platform:l}){super(),this._roomId=e,this._storage=t,this._hsApi=s,this._mediaRepository=i,this._summary=new $a(e),this._fragmentIdComparer=new cc([]),this._emitCollectionChange=r,this._timeline=null,this._user=o,this._changedMembersDuringSync=null,this._memberList=null,this._createRoomEncryption=a,this._roomEncryption=null,this._getSyncToken=c,this._platform=l,this._observedEvents=null,this._powerLevels=null,this._powerLevelLoading=null,this._observedMembers=null}async _eventIdsToEntries(e,t){const s=[];return await Promise.all(e.map(async i=>{const r=await t.timelineEvents.getByEventId(this._roomId,i);r&&s.push(new ne(r,this._fragmentIdComparer))})),s}_getAdditionalTimelineRetryEntries(e,t){let s=this._roomEncryption.filterUndecryptedEventEntriesForKeys(this._timeline.remoteEntries,t);const i=e.reduce((r,o)=>(r.add(o.id),r),new Set);return s=s.filter(r=>!i.has(r.id)),s}async notifyRoomKey(e,t,s){var o;if(!this._roomEncryption)return;const i=await this._storage.readTxn([this._storage.storeNames.timelineEvents,this._storage.storeNames.inboundGroupSessions]);let r=await this._eventIdsToEntries(t,i);if(this._timeline){const a=this._getAdditionalTimelineRetryEntries(r,[e]);r=r.concat(a)}if(r.length){await this._decryptEntries(st.Retry,r,i,s).complete(),(o=this._timeline)==null||o.replaceEntries(r);const c=this._summary.data.applyTimelineEntries(r,!1,!1);await this._summary.writeAndApplyData(c,this._storage)&&this._emitUpdate()}}_setEncryption(e){return e&&!this._roomEncryption?(this._roomEncryption=e,this._timeline&&this._timeline.enableEncryption(this._decryptEntries.bind(this,st.Timeline)),!0):!1}_decryptEntries(e,t,s,i=null){return new eh(async(o,a)=>{if(s||(s=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions])),o.cancelled)return;const c=t.filter(_=>_.eventType===Zl).map(_=>_.event);if(o.preparation=await this._roomEncryption.prepareDecryptAll(c,null,e,s),o.cancelled)return;const l=await o.preparation.decrypt();if(o.preparation=null,o.cancelled)return;const h=[this._storage.storeNames.groupSessionDecryptions],d=this._isTimelineOpen;d&&h.push(this._storage.storeNames.deviceIdentities);const u=await this._storage.readWriteTxn(h);let p;try{p=await l.write(u,a),d&&await p.verifySenders(u)}catch(_){throw u.abort(),_}await u.complete(),p.applyToEntries(t),this._observedEvents&&this._observedEvents.updateEvents(t)},Yl(i))}async _getSyncRetryDecryptEntries(e,t,s){let r=(await Promise.all(e.map(async o=>{const a=await t.getEventIdsForMissingKey(o,s);if(a)return this._eventIdsToEntries(a,s)}))).reduce((o,a)=>a?o.concat(a):o,[]);if(this._timeline){const a=this._getAdditionalTimelineRetryEntries(r,e).map(c=>c.clone());r=r.concat(a)}return r}async load(e,t,s){s.set("id",this.id);try{if(e&&this._summary.load(e),this._summary.data.encryption){const i=this._createRoomEncryption(this,this._summary.data.encryption);this._setEncryption(i)}if(this._summary.data.needsHeroes){this._heroes=new Di(this._roomId);const i=await this._heroes.calculateChanges(this._summary.data.heroes,[],t);this._heroes.applyChanges(i,this._summary.data,s)}}catch(i){throw new xn(`Could not load room ${this._roomId}`,i)}}async observeMember(e){this._observedMembers||(this._observedMembers=new Map);const t=this._observedMembers.get(e);if(t)return t;const s=await ql({summary:this._summary,roomId:this._roomId,userId:e,storage:this._storage,hsApi:this._hsApi},this._platform.logger);if(!s)return null;const i=new ci(s,()=>this._observedMembers.delete(e));return this._observedMembers.set(e,i),i}async loadMemberList(e=void 0,t=null){if(this._memberList)return this._memberList.retain(),this._memberList;{const s=await jl({summary:this._summary,roomId:this._roomId,hsApi:this._hsApi,storage:this._storage,txn:e,syncToken:this._getSyncToken(),setChangedMembersMap:i=>this._changedMembersDuringSync=i,log:t},this._platform.logger);return this._memberList=new Gl({members:s,closeCallback:()=>{this._memberList=null}}),this._memberList}}fillGap(e,t,s=null){return this._platform.logger.wrapOrRun(s,"fillGap",async i=>{if(i.set("id",this.id),i.set("fragment",e.fragmentId),i.set("dir",e.direction.asApiString()),e.edgeReached){i.set("edgeReached",!0);return}const r=await this._hsApi.messages(this._roomId,{from:e.token,dir:e.direction.asApiString(),limit:t,filter:{lazy_load_members:!0,include_redundant_members:!0}},{log:i}).response(),o=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents,this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineRelations,this._storage.storeNames.timelineFragments]);let a,c;try{a=await this._writeGapFill(r.chunk,o,i);const l=new Zn({roomId:this._roomId,fragmentIdComparer:this._fragmentIdComparer,ownUserId:this._user.id});c=await new _l({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer,relationWriter:l}).writeFragmentFill(e,r,o,i)}catch(l){throw o.abort(),l}await o.complete(),this._roomEncryption&&await this._decryptEntries(st.Timeline,c.entries,null,i).complete();for(const l of c.fragments)this._fragmentIdComparer.add(l);a&&this._applyGapFill(a),this._timeline&&(this._timeline.replaceEntries(c.updatedEntries),this._timeline.addEntries(c.entries))})}async _writeGapFill(e,t,s){}_applyGapFill(){}get name(){if(this._heroes)return this._heroes.roomName;const e=this._summary.data;return e.name?e.name:e.canonicalAlias?e.canonicalAlias:null}get id(){return this._roomId}get avatarUrl(){return this._summary.data.avatarUrl?this._summary.data.avatarUrl:this._heroes?this._heroes.roomAvatarUrl:null}get avatarColorId(){return this._roomId}get lastMessageTimestamp(){return this._summary.data.lastMessageTimestamp}get isLowPriority(){const e=this._summary.data.tags;return!!(e&&e["m.lowpriority"])}get isEncrypted(){return!!this._summary.data.encryption}get isJoined(){return this.membership==="join"}get isLeft(){return this.membership==="leave"}get canonicalAlias(){return this._summary.data.canonicalAlias}get joinedMemberCount(){return this._summary.data.joinCount}get mediaRepository(){return this._mediaRepository}get membership(){return this._summary.data.membership}isDirectMessageForUserId(e){if(this._summary.data.dmUserId===e)return!0;{const{heroes:t,joinCount:s,inviteCount:i}=this._summary.data;if(t&&t.includes(e)&&s+i===2)return!0}return!1}async _loadPowerLevels(){const e=await this._storage.readTxn([this._storage.storeNames.roomState]),t=await e.roomState.get(this._roomId,"m.room.power_levels","");if(t)return new Es({powerLevelEvent:t.event,ownUserId:this._user.id,membership:this.membership});const s=await e.roomState.get(this._roomId,"m.room.create","");if(s)return new Es({createEvent:s.event,ownUserId:this._user.id,membership:this.membership});{const i=this.membership;return new Es({ownUserId:this._user.id,membership:i})}}async observePowerLevels(){this._powerLevelLoading&&await this._powerLevelLoading;let e=this._powerLevels;if(!e){this._powerLevelLoading=this._loadPowerLevels();const t=await this._powerLevelLoading;e=new ci(t,()=>{this._powerLevels=null}),this._powerLevels=e,this._powerLevelLoading=null}return e}enableKeyBackup(e){var t;(t=this._roomEncryption)==null||t.enableKeyBackup(e),this._timeline&&e&&this._platform.logger.run("enableKeyBackup",s=>this._roomEncryption.restoreMissingSessionsFromBackup(this._timeline.remoteEntries,s))}get _isTimelineOpen(){return!!this._timeline}_emitUpdate(){this.emit("change"),this._emitCollectionChange(this)}openTimeline(e=null){return this._platform.logger.wrapOrRun(e,"open timeline",async t=>{if(t.set("id",this.id),this._timeline)throw new Error("not dealing with load race here for now");this._timeline=new Ts({roomId:this.id,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer,pendingEvents:this._getPendingEvents(),closeCallback:()=>{this._timeline=null,this._roomEncryption&&this._roomEncryption.notifyTimelineClosed()},clock:this._platform.clock,logger:this._platform.logger,powerLevelsObservable:await this.observePowerLevels(),hsApi:this._hsApi});try{this._roomEncryption&&this._timeline.enableEncryption(this._decryptEntries.bind(this,st.Timeline)),await this._timeline.load(this._user,this.membership,t)}catch(s){throw this._timeline.dispose(),s}return this._timeline})}_getPendingEvents(){return null}observeEvent(e){this._observedEvents||(this._observedEvents=new Jl(()=>{this._observedEvents=null}));let t=null;this._timeline&&(t=this._timeline.getByEventId(e));const s=this._observedEvents.observe(e,t);return t||this._readEventById(e).then(i=>{s.update(i)}).catch(i=>{console.warn(`could not load event ${e} from storage`,i)}),s}async _readEventById(e){return await new so({roomId:this._roomId,storage:this._storage,fragmentIdComparer:this._fragmentIdComparer}).readById(e)}dispose(){var e,t;(e=this._roomEncryption)==null||e.dispose(),(t=this._timeline)==null||t.dispose()}}class eh{constructor(e,t){this._cancelled=!1,this.preparation=null,this._promise=t.wrap("decryptEntries",s=>e(this,s))}complete(){return this._promise}get cancelled(){return this._cancelled}dispose(){this._cancelled=!0,this.preparation&&this.preparation.dispose()}}function Ms(){const e=Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(16);return"t"+"0".repeat(14-e.length)+e}function Fr(n){return n.startsWith("t")&&n.length===15}class th{constructor({roomId:e,storage:t,hsApi:s,pendingEvents:i}){i=i||[],this._roomId=e,this._storage=t,this._hsApi=s,this._pendingEvents=new xi((r,o)=>r.queueIndex-o.queueIndex),this._pendingEvents.setManyUnsorted(i.map(r=>this._createPendingEvent(r))),this._isSending=!1,this._offline=!1,this._roomEncryption=null,this._currentQueueIndex=0}_createPendingEvent(e,t=null){const s=new Za({data:e,remove:()=>this._removeEvent(s),emitUpdate:i=>this._pendingEvents.update(s,i),attachments:t});return s}enableEncryption(e){this._roomEncryption=e}_sendLoop(e){this._isSending=!0,this._sendLoopLogItem=e.runDetached("send queue flush",async t=>{try{for(const s of this._pendingEvents)await t.wrap("send event",async i=>{i.set("queueIndex",s.queueIndex);try{this._currentQueueIndex=s.queueIndex,await this._sendEvent(s,i)}catch(r){r instanceof qe?(this._offline=!0,i.set("offline",!0),s.setWaiting()):(i.catch(r),r.name==="HomeServerError"&&(r.statusCode===400||r.statusCode===403||r.statusCode===404)?(i.set("remove",!0),await s.abort()):s.setError(r))}finally{this._currentQueueIndex=0}})}finally{this._isSending=!1,this._sendLoopLogItem=null}})}async _sendEvent(e,t){if(e.needsUpload&&(await t.wrap("upload attachments",s=>e.uploadAttachments(this._hsApi,s)),await this._tryUpdateEvent(e)),e.needsEncryption){e.setEncrypting();const s=e.contentForEncryption,{type:i,content:r}=await t.wrap("encrypt",o=>this._roomEncryption.encrypt(e.eventType,s,this._hsApi,o));e.setEncrypted(i,r),await this._tryUpdateEvent(e)}if(e.needsSending){await e.send(this._hsApi,t);const s=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{await this._tryUpdateEventWithTxn(e,s),await this._resolveRemoteIdInPendingRelations(e.txnId,e.remoteId,s)}catch(i){throw s.abort(),i}await s.complete()}}async _resolveRemoteIdInPendingRelations(e,t,s){const i=this._pendingEvents.array.filter(r=>r.relatedTxnId===e&&r.relatedEventId!==t);for(const r of i)r.setRelatedEventId(t),await this._tryUpdateEventWithTxn(r,s);return i}async removeRemoteEchos(e,t,s){const i=[];for(const r of e){const o=r.unsigned&&r.unsigned.transaction_id;let a;if(o?a=this._pendingEvents.array.findIndex(c=>c.txnId===o):a=this._pendingEvents.array.findIndex(c=>c.remoteId===r.event_id),a!==-1){const c=this._pendingEvents.get(a),l=r.event_id;s.log({l:"removeRemoteEcho",queueIndex:c.queueIndex,remoteId:l,txnId:o}),t.pendingEvents.remove(c.roomId,c.queueIndex),i.push(c),await this._resolveRemoteIdInPendingRelations(o,l,t)}}return i}async _removeEvent(e){if(this._pendingEvents.array.indexOf(e)!==-1){const s=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{s.pendingEvents.remove(e.roomId,e.queueIndex)}catch{s.abort()}await s.complete();const i=this._pendingEvents.array.indexOf(e);i!==-1&&this._pendingEvents.remove(i)}e.dispose()}emitRemovals(e){for(const t of e){const s=this._pendingEvents.array.indexOf(t);s!==-1&&this._pendingEvents.remove(s),t.dispose()}}resumeSending(e){this._offline=!1,this._pendingEvents.length&&e.wrap("resumeSending",t=>{t.set("id",this._roomId),t.set("pendingEvents",this._pendingEvents.length),this._isSending||this._sendLoop(t),this._sendLoopLogItem&&t.refDetached(this._sendLoopLogItem)})}async enqueueEvent(e,t,s,i){const r=ze(t);let o=null;if(r){const a=Ri(r);if(Fr(a)&&(o=a,$n(r,null)),r.rel_type===We&&this._pendingEvents.array.some(l=>{const h=ze(l.content);return l.eventType===e&&h&&h.key===r.key&&(l.relatedTxnId===o||h.event_id===r.event_id)})){i.set("already_annotating",!0);return}}await this._enqueueEvent(e,t,s,o,null,i)}async _enqueueEvent(e,t,s,i,r,o){const a=await this._createAndStoreEvent(e,t,i,r,s);this._pendingEvents.set(a),o.set("queueIndex",a.queueIndex),o.set("pendingEvents",this._pendingEvents.length),!this._isSending&&!this._offline&&this._sendLoop(o),this._sendLoopLogItem&&o.refDetached(this._sendLoopLogItem)}async enqueueRedaction(e,t,s){if(this._pendingEvents.array.some(a=>a.eventType===ge&&(a.relatedTxnId===e||a.relatedEventId===e))){s.set("already_redacting",!0);return}let r,o;if(Fr(e)){r=e;const a=e,c=this._pendingEvents.array.find(l=>l.txnId===a);if(c&&!c.remoteId&&c.status!==V.Sending){s.set("remove",r),await c.abort();return}else if(c)o=c.remoteId;else return}else{o=e;const a=this._pendingEvents.array.find(c=>c.remoteId===o);a&&(r=a.txnId)}s.set("relatedTxnId",r),s.set("relatedEventId",o),await this._enqueueEvent(ge,{reason:t},null,r,o,s)}get pendingEvents(){return this._pendingEvents}async _tryUpdateEvent(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);try{this._tryUpdateEventWithTxn(e,t)}catch(s){throw t.abort(),s}await t.complete()}async _tryUpdateEventWithTxn(e,t){await t.pendingEvents.exists(e.roomId,e.queueIndex)&&t.pendingEvents.update(e.data)}async _createAndStoreEvent(e,t,s,i,r){const o=await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);let a;try{const c=o.pendingEvents,l=await c.getMaxQueueIndex(this._roomId)||0,d=Math.max(l,this._currentQueueIndex)+1,u=e!==ge&&e!==qa&&!!this._roomEncryption;a=this._createPendingEvent({roomId:this._roomId,queueIndex:d,eventType:e,content:t,relatedTxnId:s,relatedEventId:i,txnId:Ms(),needsEncryption:u,needsUpload:!!r},r),c.add(a.data)}catch(c){throw o.abort(),c}return await o.complete(),a}dispose(){for(const e of this._pendingEvents)e.dispose()}}class ro{constructor({filename:e,blob:t,platform:s}){this._filename=e,this._unencryptedBlob=t,this._transferredBlob=this._unencryptedBlob,this._platform=s,this._mxcUrl=null,this._encryptionInfo=null,this._uploadRequest=null,this._aborted=!1,this._error=null,this._sentBytes=0}get size(){return this._transferredBlob.size}get sentBytes(){return this._sentBytes}abort(){var e;(e=this._uploadRequest)==null||e.abort()}get localPreview(){return this._unencryptedBlob}async encrypt(){if(this._encryptionInfo)throw new Error("already encrypted");const{info:e,blob:t}=await Ia(this._platform,this._transferredBlob);this._transferredBlob=t,this._encryptionInfo=e}async upload(e,t,s){this._uploadRequest=e.uploadAttachment(this._transferredBlob,this._filename,{uploadProgress:r=>{this._sentBytes=r,t()},log:s});const{content_uri:i}=await this._uploadRequest.response();this._mxcUrl=i}applyToContent(e,t){if(!this._mxcUrl)throw new Error("upload has not finished");let s=e.substr(0,e.lastIndexOf("url"));ys(`${s}info.size`,t,this._transferredBlob.size),ys(`${s}info.mimetype`,t,this._unencryptedBlob.mimeType),this._encryptionInfo?ys(`${s}file`,t,Object.assign(this._encryptionInfo,{mimetype:this._unencryptedBlob.mimeType,url:this._mxcUrl})):ys(`${s}url`,t,this._mxcUrl)}dispose(){this._unencryptedBlob.dispose(),this._transferredBlob.dispose()}}function ys(n,e,t){const s=n.split(".");let i=e;for(let o=0;ou.event)))),d=d.filter(u=>(u==null?void 0:u.type)===sh),d.length&&(l=await a.prepareDecryptAll(d,s,st.Sync,i))}return{roomEncryption:a,summaryChanges:o,decryptPreparation:l,decryptChanges:null,retryEntries:c}}async afterPrepareSync(e,t){e.decryptPreparation&&await t.wrap("decrypt",async s=>{s.set("id",this.id),e.decryptChanges=await e.decryptPreparation.decrypt(),e.decryptPreparation=null},t.level.Detail)}async writeSync(e,t,{summaryChanges:s,decryptChanges:i,roomEncryption:r,retryEntries:o},a,c){var R;c.set("id",this.id);const l=s.isNewJoin(this._summary.data);l&&(a.roomState.removeAllForRoom(this.id),a.roomMembers.removeAllForRoom(this.id));const{entries:h,updatedEntries:d,newLiveKey:u,memberChanges:p}=await c.wrap("syncWriter",w=>this._syncWriter.writeSync(e,l,s.hasFetchedMembers,a,w),c.level.Detail);if(i){const w=await c.wrap("decryptChanges",I=>i.write(a,I));c.set("decryptionResults",w.results.size),c.set("decryptionErrors",w.errors.size),this._isTimelineOpen&&await w.verifySenders(a),w.applyToEntries(h),o!=null&&o.length&&(w.applyToEntries(o),d.push(...o))}c.set("newEntries",h.length),c.set("updatedEntries",d.length);let _;r&&(_=await r.writeSync(e,p,a,c),c.set("shouldFlushKeyShares",_.shouldFlush));const f=h.concat(d);s=s.applyTimelineEntries(f,t,!this._isTimelineOpen,this._user.id),s.membership!=="join"?a.roomSummary.remove(this.id):s=this._summary.writeData(s,a),s&&c.set("summaryChanges",s.changedKeys(this._summary.data));let b;s!=null&&s.needsHeroes&&(this._heroes||(this._heroes=new Di(this._roomId)),b=await this._heroes.calculateChanges(s.heroes,p,a));let S;Array.isArray((R=e.timeline)==null?void 0:R.events)&&(S=await this._sendQueue.removeRemoteEchos(e.timeline.events,a,c));const k=this._getPowerLevelsEvent(e);return{summaryChanges:s,roomEncryption:r,newEntries:h,updatedEntries:d,newLiveKey:u,removedPendingEvents:S,memberChanges:p,heroChanges:b,powerLevelsEvent:k,encryptionChanges:_}}afterSync(e,t){const{summaryChanges:s,newEntries:i,updatedEntries:r,newLiveKey:o,removedPendingEvents:a,memberChanges:c,powerLevelsEvent:l,heroChanges:h,roomEncryption:d,encryptionChanges:u}=e;if(t.set("id",this.id),this._syncWriter.afterSync(o),this._setEncryption(d),this._roomEncryption&&this._roomEncryption.afterSync(u),c.size){if(this._changedMembersDuringSync)for(const[_,f]of c.entries())this._changedMembersDuringSync.set(_,f.member);if(this._memberList&&this._memberList.afterSync(c),this._observedMembers&&this._updateObservedMembers(c),this._timeline){for(const[_,f]of c.entries())if(_===this._user.id){this._timeline.updateOwnMember(f.member);break}}}let p=!1;if(s&&(this._summary.applyChanges(s),this._summary.data.needsHeroes||(this._heroes=null),p=!0),this._heroes&&h){const _=this.name;this._heroes.applyChanges(h,this._summary.data,t),_!==this.name&&(p=!0)}l&&this._updatePowerLevels(l),p&&this._emitUpdate(),this._timeline&&(this._timeline.replaceEntries(r),this._timeline.addEntries(i)),this._observedEvents&&(this._observedEvents.updateEvents(r),this._observedEvents.updateEvents(i)),a&&this._sendQueue.emitRemovals(a)}_updateObservedMembers(e){for(const[t,s]of e){const i=this._observedMembers.get(t);i&&i.set(s.member)}}_getPowerLevelsEvent(e){var i,r,o;const t=a=>a.state_key===""&&a.type===Xl;return(o=(i=e.timeline)==null?void 0:i.events.find(t))!=null?o:(r=e.state)==null?void 0:r.events.find(t)}_updatePowerLevels(e){if(this._powerLevels){const t=new Es({powerLevelEvent:e,ownUserId:this._user.id,membership:this.membership});this._powerLevels.set(t)}}needsAfterSyncCompleted({encryptionChanges:e}){return e==null?void 0:e.shouldFlush}async afterSyncCompleted(e,t){t.set("id",this.id),this._roomEncryption&&await this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,null,t)}start(e,t){if(this._roomEncryption){const s=e==null?void 0:e.get("share_room_key");s&&t.wrapDetached("flush room keys",i=>(i.set("id",this.id),this._roomEncryption.flushPendingRoomKeyShares(this._hsApi,s,i)))}this._sendQueue.resumeSending(t)}async load(e,t,s){try{await super.load(e,t,s),await this._syncWriter.load(t,s)}catch(i){throw new xn(`Could not load room ${this._roomId}`,i)}}async _writeGapFill(e,t,s){return await this._sendQueue.removeRemoteEchos(e,t,s)}_applyGapFill(e){this._sendQueue.emitRemovals(e)}sendEvent(e,t,s,i=null){return this._platform.logger.wrapOrRun(i,"send",r=>(r.set("id",this.id),this._sendQueue.enqueueEvent(e,t,s,r)))}sendRedaction(e,t,s=null){return this._platform.logger.wrapOrRun(s,"redact",i=>(i.set("id",this.id),this._sendQueue.enqueueRedaction(e,t,i)))}async ensureMessageKeyIsShared(e=null){if(!!this._roomEncryption)return this._platform.logger.wrapOrRun(e,"ensureMessageKeyIsShared",t=>(t.set("id",this.id),this._roomEncryption.ensureMessageKeyIsShared(this._hsApi,t)))}get avatarColorId(){var e;return((e=this._heroes)==null?void 0:e.roomAvatarColorId)||this._roomId}get isUnread(){return this._summary.data.isUnread}get notificationCount(){return this._summary.data.notificationCount}get highlightCount(){return this._summary.data.highlightCount}get isTrackingMembers(){return this._summary.data.isTrackingMembers}async _getLastEventId(){var t;const e=this._syncWriter.lastMessageKey;if(e){const i=await(await this._storage.readTxn([this._storage.storeNames.timelineEvents])).timelineEvents.get(this._roomId,e);return(t=i==null?void 0:i.event)==null?void 0:t.event_id}}async clearUnread(e=null){if(this.isUnread||this.notificationCount)return await this._platform.logger.wrapOrRun(e,"clearUnread",async t=>{t.set("id",this.id);const s=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary]);let i;try{i=this._summary.writeClearUnread(s)}catch(r){throw s.abort(),r}await s.complete(),this._summary.applyChanges(i),this._emitUpdate();try{const r=await this._getLastEventId();r&&await this._hsApi.receipt(this._roomId,"m.read",r)}catch(r){if(r.name!=="ConnectionError")throw r}})}leave(e=null){return this._platform.logger.wrapOrRun(e,"leave room",async t=>{t.set("id",this.id),await this._hsApi.leave(this.id,{log:t}).response()})}_getPendingEvents(){return this._sendQueue.pendingEvents}writeIsTrackingMembers(e,t){return this._summary.writeIsTrackingMembers(e,t)}applyIsTrackingMembersChanges(e){this._summary.applyChanges(e)}createAttachment(e,t){return new ro({blob:e,filename:t,platform:this._platform})}dispose(){super.dispose(),this._sendQueue.dispose()}}class rh extends io{constructor(e){super(e),this._releaseCallback=e.releaseCallback,this._forgetCallback=e.forgetCallback,this._retentionCount=1,this._kickDetails=null,this._kickedBy=null}retain(){this._retentionCount+=1}release(){this._retentionCount-=1,this._retentionCount===0&&this._releaseCallback()}async _getKickAuthor(e,t){const s=await t.roomMembers.get(this.id,e);return s?new O(s):O.fromUserId(this.id,e,"join")}async load(e,t,s){const{summary:i,kickDetails:r}=e;return this._kickDetails=r,this._kickDetails&&(this._kickedBy=await this._getKickAuthor(this._kickDetails.sender,t)),super.load(i,t,s)}async writeSync(e,t,s,i,r){if(r.set("id",this.id),s==="leave"){const o=nh(t,this._user.id);if(o||e){const a=o||this._kickDetails;let c;o&&(c=await this._getKickAuthor(o.sender,i));const l=e||this._summary.data;return i.archivedRoomSummary.set({summary:l.serialize(),kickDetails:a}),{kickDetails:a,kickedBy:c,summaryData:l}}}else s==="join"&&i.archivedRoomSummary.remove(this.id);return{}}afterSync({summaryData:e,kickDetails:t,kickedBy:s},i){i.set("id",this.id),e&&this._summary.applyChanges(e),t&&(this._kickDetails=t),s&&(this._kickedBy=s),this._emitUpdate()}get isKicked(){var e;return((e=this._kickDetails)==null?void 0:e.membership)==="leave"}get isBanned(){var e;return((e=this._kickDetails)==null?void 0:e.membership)==="ban"}get kickedBy(){return this._kickedBy}get kickReason(){var e;return(e=this._kickDetails)==null?void 0:e.reason}isArchived(){return!0}forget(e=null){return this._platform.logger.wrapOrRun(e,"forget room",async t=>{t.set("id",this.id),await this._hsApi.forget(this.id,{log:t}).response();const s=this._storage.storeNames,i=await this._storage.readWriteTxn([s.roomState,s.archivedRoomSummary,s.roomMembers,s.timelineEvents,s.timelineFragments,s.timelineRelations,s.pendingEvents,s.inboundGroupSessions,s.groupSessionDecryptions,s.operations]);i.roomState.removeAllForRoom(this.id),i.archivedRoomSummary.remove(this.id),i.roomMembers.removeAllForRoom(this.id),i.timelineEvents.removeAllForRoom(this.id),i.timelineFragments.removeAllForRoom(this.id),i.timelineRelations.removeAllForRoom(this.id),i.pendingEvents.removeAllForRoom(this.id),i.inboundGroupSessions.removeAllForRoom(this.id),i.groupSessionDecryptions.removeAllForRoom(this.id),await i.operations.removeAllForScope(this.id),await i.complete(),this._retentionCount=0,this._releaseCallback(),this._forgetCallback(this.id)})}join(e=null){return this._platform.logger.wrapOrRun(e,"rejoin archived room",async t=>{await this._hsApi.join(this.id,{log:t}).response()})}}function nh(n,e){var s,i;const t=Fn(n,(r,o)=>(o.type===oe&&o.state_key===e&&o.sender!==o.state_key&&(r=o),r),null);if(t)return{membership:(s=t.content)==null?void 0:s.membership,reason:(i=t.content)==null?void 0:i.reason,sender:t.sender}}async function oh(n,e,t){const s=await Promise.all(n.map(async i=>{const r=await e.profile(i,{log:t}).response();return new ah(i,r.displayname,r.avatar_url)}));return s.sort((i,r)=>i.name.localeCompare(r.name)),s}class ah{constructor(e,t,s){this.userId=e,this.displayName=t,this.avatarUrl=s}get name(){return this.displayName||this.userId}}class ch{constructor(e){this.userId=e}get displayName(){}get name(){return this.userId}get avatarUrl(){}}function lh(n){switch(n){case re.DirectMessage:case re.Private:return!0;case re.Public:return!1}}function hh(n){switch(n){case re.DirectMessage:return"trusted_private_chat";case re.Private:return"private_chat";case re.Public:return"public_chat"}}class dh extends Ls{constructor(e,t,s,i,r,o){var a;if(super(),this.id=e,this.options=t,this.updateCallback=s,this.mediaRepository=i,this.platform=r,this.profiles=[],this._isCancelled=!1,this.isEncrypted=t.isEncrypted===void 0?lh(t.type):t.isEncrypted,t.name)this._calculatedName=t.name;else{const c={joinCount:1,inviteCount:((a=t.invites)==null?void 0:a.length)||0},l=(t.invites||[]).map(h=>new ch(h));this._calculatedName=pi(l,c,o)}}async create(e,t){try{let s;if(this.options.avatar){const{avatar:o}=this.options,a=new ro({filename:o.name,blob:o.blob,platform:this.platform});await a.upload(e,()=>{},t),s={info:o.info},a.applyToContent("url",s)}const i={is_direct:this.options.type===re.DirectMessage,preset:hh(this.options.type),initial_state:[]};this.options.name&&(i.name=this.options.name),this.options.topic&&(i.topic=this.options.topic),this.options.invites&&(i.invite=this.options.invites),this.options.alias&&(i.room_alias_name=this.options.alias),this.options.isFederationDisabled===!0&&(i.creation_content={"m.federate":!1}),this.options.powerLevelContentOverride&&(i.power_level_content_override=this.options.powerLevelContentOverride),this.isEncrypted&&i.initial_state.push(La()),s&&i.initial_state.push({type:"m.room.avatar",state_key:"",content:s});const r=await e.createRoom(i,{log:t}).response();this._roomId=r.room_id}catch(s){this._error=s}this.emitChange()}async loadProfiles(e,t){try{if(!this.options.name&&this.options.invites){this.profiles=await oh(this.options.invites,e,t);const s={joinCount:1,inviteCount:this.options.invites.length};this._calculatedName=pi(this.profiles,s,t),this.emitChange()}}catch{}}emitChange(e){this.updateCallback(this,e),this.emit("change")}get avatarColorId(){var e,t,s;return(s=(t=(e=this.options.invites)==null?void 0:e[0])!=null?t:this._roomId)!=null?s:this.id}get avatarUrl(){var e,t;return(t=(e=this.profiles)==null?void 0:e[0])==null?void 0:t.avatarUrl}get avatarBlobUrl(){var e,t;return(t=(e=this.options.avatar)==null?void 0:e.blob)==null?void 0:t.url}get roomId(){return this._roomId}get name(){return this._calculatedName}get isBeingCreated(){return!0}get error(){return this._error}cancel(){this._isCancelled||(this.dispose(),this._isCancelled=!0,this.emitChange("isCancelled"))}get isCancelled(){return this._isCancelled}dispose(){this.options.avatar&&this.options.avatar.blob.dispose()}async adjustDirectMessageMapIfNeeded(e,t,s,i){if(!this.options.invites||this.options.type!==re.DirectMessage)return;const r=this.options.invites[0],o="m.direct";await i.wrap("set "+o,async a=>{try{const c=await t.readWriteTxn([t.storeNames.accountData]);let l;try{l=await c.accountData.get(o),l||(l={type:o,content:{}});const h=l.content;let d=h[r];d||(h[r]=d=[]),d.push(this._roomId),c.accountData.set(l),await c.complete()}catch(h){throw c.abort(),h}await s.setAccountData(e.id,o,l.content,{log:a}).response()}catch(c){a.catch(c)}})}}class uh extends Ls{constructor({roomId:e,user:t,hsApi:s,mediaRepository:i,emitCollectionRemove:r,emitCollectionUpdate:o,platform:a}){super(),this._roomId=e,this._user=t,this._hsApi=s,this._emitCollectionRemove=r,this._emitCollectionUpdate=o,this._mediaRepository=i,this._platform=a,this._inviteData=null,this._accepting=!1,this._rejecting=!1,this._accepted=!1,this._rejected=!1}get isInvite(){return!0}get id(){return this._roomId}get name(){return this._inviteData.name||this._inviteData.canonicalAlias}get isDirectMessage(){return this._inviteData.isDirectMessage}get avatarUrl(){return this._inviteData.avatarUrl}get avatarColorId(){return this._inviteData.avatarColorId||this.id}get timestamp(){return this._inviteData.timestamp}get isEncrypted(){return this._inviteData.isEncrypted}get inviter(){return this._inviter}isDirectMessageForUserId(e){return this.isDirectMessage&&this._inviter.userId===e}get isPublic(){return this._inviteData.joinRule==="public"}get canonicalAlias(){return this._inviteData.canonicalAlias}async accept(e=null){await this._platform.logger.wrapOrRun(e,"acceptInvite",async t=>{this._accepting=!0,this._emitChange("accepting"),await this._hsApi.join(this._roomId,{log:t}).response()})}async reject(e=null){await this._platform.logger.wrapOrRun(e,"rejectInvite",async t=>{this._rejecting=!0,this._emitChange("rejecting"),await this._hsApi.leave(this._roomId,{log:t}).response()})}get accepting(){return this._accepting}get accepted(){return this._accepted}get rejecting(){return this._rejecting}get rejected(){return this._rejected}get mediaRepository(){return this._mediaRepository}_emitChange(e){this.emit("change"),this._emitCollectionUpdate(this,e)}load(e,t){t.set("id",this.id),this._inviteData=e,this._inviter=e.inviter?new O(e.inviter):null}async writeSync(e,t,s,i){var r;if(e==="invite"){i.set("id",this.id),i.set("add",!0);const o=(r=t.invite_state)==null?void 0:r.events;if(!Array.isArray(o))return null;const a=this._createSummaryData(o);let c;!a.name&&!a.canonicalAlias&&(c=await this._createHeroes(o,i));const l=this._getMyInvite(o);if(!l)return null;const h=this._getInviter(l,o),d=this._createData(o,l,h,a,c);return s.invites.set(d),{inviteData:d,inviter:h}}else return i.set("id",this.id),i.set("membership",e),s.invites.remove(this.id),{removed:!0,membership:e}}afterSync(e,t){t.set("id",this.id),e&&(e.removed?(this._accepting=!1,this._rejecting=!1,e.membership==="join"?this._accepted=!0:this._rejected=!0,this.emit("change")):(this._inviteData=e.inviteData,this._inviter=e.inviter))}_createData(e,t,s,i,r){const o=r?r.roomName:i.name,a=r?r.roomAvatarUrl:i.avatarUrl,c=(r==null?void 0:r.roomAvatarColorId)||this.id;return{roomId:this.id,isEncrypted:!!i.encryption,isDirectMessage:i.isDirectMessage,name:o,avatarUrl:a,avatarColorId:c,canonicalAlias:i.canonicalAlias,timestamp:this._platform.clock.now(),joinRule:this._getJoinRule(e),inviter:s==null?void 0:s.serialize()}}_createSummaryData(e){return e.reduce((t,s)=>Bn(t,s,this._user.id),new Ee(null,this.id))}async _createHeroes(e,t){const s=e.filter(h=>h.type===oe),i=s.filter(h=>h.state_key!==this._user.id),r=i.reduce((h,d)=>{const u=O.fromMemberEvent(this.id,d);return h.set(u.userId,new Wn(u,null)),h},new Map),o=i.map(h=>h.state_key),a=new Di(this.id),c=await a.calculateChanges(o,r,null),l=new Ee(null,this.id);return l.joinCount=s.reduce((h,d)=>{var u;return h+(((u=d.content)==null?void 0:u.membership)==="join"?1:0)},0),l.inviteCount=s.reduce((h,d)=>{var u;return h+(((u=d.content)==null?void 0:u.membership)==="invite"?1:0)},0),a.applyChanges(c,l,t),a}_getMyInvite(e){return e.find(t=>t.type===oe&&t.state_key===this._user.id)}_getInviter(e,t){const s=t.find(i=>i.type===oe&&i.state_key===e.sender);if(s)return O.fromMemberEvent(this.id,s)}_getJoinRule(e){var s;const t=e.find(i=>i.type==="m.room.join_rules");return t?(s=t.content)==null?void 0:s.join_rule:null}}class tt{constructor(e){this._description=e}static httpPusher(e,t,s,i){return new tt({kind:"http",append:!0,data:Object.assign({},i,{url:e+"/_matrix/push/v1/notify"}),pushkey:s,app_id:t,app_display_name:"Hydrogen",device_display_name:"Hydrogen",lang:"en"})}static createDefaultPayload(e){return{session_id:e}}async enable(e,t){try{t.set("endpoint",new URL(this._description.data.endpoint).host)}catch{t.set("endpoint",null)}await e.setPusher(this._description,{log:t}).response()}async disable(e,t){const s=Object.assign({},this._description,{kind:null});await e.setPusher(s,{log:t}).response()}serialize(){return this._description}equals(e){return this._description.app_id!==e._description.app_id||this._description.pushkey!==e._description.pushkey?!1:JSON.stringify(this._description.data)===JSON.stringify(e._description.data)}}function bt(n,e){return Vi(n,e,()=>[],(t,s)=>t.push(s))}function Vi(n,e,t,s){return n.reduce((i,r)=>{const o=e(r);let a=i.get(o);return a||(a=t(),i.set(o,a)),s(a,r),i},new Map)}function Br(n,e){return n.reduce((t,s)=>{const i=e(s);return t[i]?t[i]+=1:t[i]=1,t},{})}class mh{constructor({storage:e}){this._storage=e,this._olmDecryption=null,this._megolmDecryption=null}enableEncryption({olmDecryption:e,megolmDecryption:t}){this._olmDecryption=e,this._megolmDecryption=t}obtainSyncLock(e){var t;return(t=this._olmDecryption)==null?void 0:t.obtainDecryptionLock(e)}async prepareSync(e,t,s,i){i.set("messageTypes",Br(e,a=>a.type));const r=e.filter(a=>a.type==="m.room.encrypted");if(!this._olmDecryption){i.log("can't decrypt, encryption not enabled",i.level.Warn);return}const o=r.filter(a=>{var c;return((c=a.content)==null?void 0:c.algorithm)===ki});if(o.length){const a=await this._olmDecryption.decryptAll(o,t,s);i.set("decryptedTypes",Br(a.results,l=>{var h;return(h=l.event)==null?void 0:h.type}));for(const l of a.errors)i.child("decrypt_error").catch(l);const c=this._megolmDecryption.roomKeysFromDeviceMessages(a.results,i);return new ph(a,c)}}async writeSync(e,t){return e.olmDecryptChanges.write(t),(await Promise.all(e.newRoomKeys.map(i=>this._megolmDecryption.writeRoomKey(i,t)))).some(i=>!!i)}}class ph{constructor(e,t){this.olmDecryptChanges=e,this.newRoomKeys=t,this.newKeysByRoom=bt(t,s=>s.roomId)}}const Ft=ie+"olmAccount",_i=ie+"areDeviceKeysUploaded",ks=ie+"serverOTKCount";async function Kr(n,e,t,s,i){const r=n.pickle(e),o=await i.readWriteTxn([i.storeNames.session]);try{o.session.add(Ft,r),o.session.add(_i,t),o.session.add(ks,s)}catch(a){throw o.abort(),a}await o.complete()}class rt{static async load({olm:e,pickleKey:t,hsApi:s,userId:i,deviceId:r,olmWorker:o,txn:a}){const c=await a.session.get(Ft);if(c){const l=new e.Account,h=await a.session.get(_i);l.unpickle(t,c);const d=await a.session.get(ks);return new rt({pickleKey:t,hsApi:s,account:l,userId:i,deviceId:r,areDeviceKeysUploaded:h,serverOTKCount:d,olm:e,olmWorker:o})}}static async adoptDehydratedDevice({olm:e,dehydratedDevice:t,pickleKey:s,hsApi:i,userId:r,olmWorker:o,storage:a}){const c=t.adoptUnpickledOlmAccount(),l=JSON.parse(c.one_time_keys()),d=Object.entries(l.curve25519).length,u=!0;return await Kr(c,s,u,d,a),new rt({pickleKey:s,hsApi:i,account:c,userId:r,deviceId:t.deviceId,areDeviceKeysUploaded:u,serverOTKCount:d,olm:e,olmWorker:o})}static async create({olm:e,pickleKey:t,hsApi:s,userId:i,deviceId:r,olmWorker:o,storage:a}){const c=new e.Account;o?await o.createAccountAndOTKs(c,c.max_number_of_one_time_keys()):(c.create(),c.generate_one_time_keys(c.max_number_of_one_time_keys()));const l=!1,h=0;return a&&await Kr(c,t,l,h,a),new rt({pickleKey:t,hsApi:s,account:c,userId:i,deviceId:r,areDeviceKeysUploaded:l,serverOTKCount:h,olm:e,olmWorker:o})}constructor({pickleKey:e,hsApi:t,account:s,userId:i,deviceId:r,areDeviceKeysUploaded:o,serverOTKCount:a,olm:c,olmWorker:l}){this._olm=c,this._pickleKey=e,this._hsApi=t,this._account=s,this._userId=i,this._deviceId=r,this._areDeviceKeysUploaded=o,this._serverOTKCount=a,this._olmWorker=l,this._identityKeys=JSON.parse(this._account.identity_keys())}get identityKeys(){return this._identityKeys}setDeviceId(e){this._deviceId=e}async uploadKeys(e,t,s){var o;const i=JSON.parse(this._account.one_time_keys()),r=Object.entries(i.curve25519);if(r.length||!this._areDeviceKeysUploaded){const a={};if(!this._areDeviceKeysUploaded){s.set("identity",!0);const h=JSON.parse(this._account.identity_keys());a.device_keys=this._deviceKeysPayload(h)}r.length&&(s.set("otks",!0),a.one_time_keys=this._oneTimeKeysPayload(r));const c=t?this._deviceId:void 0,l=await this._hsApi.uploadKeys(c,a,{log:s}).response();this._serverOTKCount=(o=l==null?void 0:l.one_time_key_counts)==null?void 0:o.signed_curve25519,s.set("serverOTKCount",this._serverOTKCount),await this._updateSessionStorage(e,h=>{r.length&&(this._account.mark_keys_as_published(),h==null||h.set(Ft,this._account.pickle(this._pickleKey)),h==null||h.set(ks,this._serverOTKCount)),this._areDeviceKeysUploaded||(this._areDeviceKeysUploaded=!0,h==null||h.set(_i,this._areDeviceKeysUploaded))})}}async generateOTKsIfNeeded(e,t){const s=this._account.max_number_of_one_time_keys(),i=Math.floor(s/2);if(this._serverOTKCount0&&await t.wrap("generate otks",l=>{l.set("max",s),l.set("server",this._serverOTKCount),l.set("unpublished",a),l.set("new",c),l.set("limit",i),this._account.generate_one_time_keys(c),this._updateSessionStorage(e,h=>{h.set(Ft,this._account.pickle(this._pickleKey))})}),!0}return!1}createInboundOlmSession(e,t){const s=new this._olm.Session;try{return s.create_inbound_from(this._account,e,t),s}catch(i){throw s.free(),i}}async createOutboundOlmSession(e,t){const s=new this._olm.Session;try{return this._olmWorker?await this._olmWorker.createOutboundOlmSession(this._account,s,e,t):s.create_outbound(this._account,e,t),s}catch(i){throw s.free(),i}}writeRemoveOneTimeKey(e,t){this._account.remove_one_time_keys(e),t.session.set(Ft,this._account.pickle(this._pickleKey))}writeSync(e,t,s){const i=e.signed_curve25519;if(Number.isSafeInteger(i)&&i!==this._serverOTKCount)return t.session.set(ks,i),s.set("otkCount",i),i}afterSync(e){Number.isSafeInteger(e)&&(this._serverOTKCount=e)}_deviceKeysPayload(e){const t={user_id:this._userId,device_id:this._deviceId,algorithms:[ki,ve],keys:{}};for(const[s,i]of Object.entries(e))t.keys[`${s}:${this._deviceId}`]=i;return this.signObject(t),t}_oneTimeKeysPayload(e){const t={};for(const[s,i]of e){const r={key:i};this.signObject(r),t[`signed_curve25519:${s}`]=r}return t}async _updateSessionStorage(e,t){if(e){const s=await e.readWriteTxn([e.storeNames.session]);try{await t(s.session)}catch(i){throw s.abort(),i}await s.complete()}else await t(void 0)}signObject(e){const t=e.signatures||{},s=e.unsigned;delete e.signatures,delete e.unsigned,t[this._userId]=t[this._userId]||{},t[this._userId]["ed25519:"+this._deviceId]=this._account.sign(On.stringify(e)),e.signatures=t,s!==void 0&&(e.unsigned=s)}pickleWithKey(e){return this._account.pickle(e)}dispose(){this._account.free(),this._account=void 0}}class Li{constructor(e,t){this._id=e,this._keyDescription=t}get id(){return this._id}get passphraseParams(){var e;return(e=this._keyDescription)==null?void 0:e.passphrase}get algorithm(){var e;return(e=this._keyDescription)==null?void 0:e.algorithm}async isCompatible(e,t){if(this.algorithm==="m.secret_storage.v1.aes-hmac-sha2"){const s=this._keyDescription;if(s.mac){const i=await _h(e.binaryKey,s.iv,t);return s.mac===i}else if(s.passphrase){const i=e.description._keyDescription;return i.passphrase?s.passphrase.algorithm===i.passphrase.algorithm&&s.passphrase.iterations===i.passphrase.iterations&&s.passphrase.salt===i.passphrase.salt:!1}}return!1}}class ts{constructor(e,t){this._keyDescription=e,this._binaryKey=t}withDescription(e){return new ts(e,this._binaryKey)}get description(){return this._keyDescription}get id(){return this._keyDescription.id}get binaryKey(){return this._binaryKey}get algorithm(){return this._keyDescription.algorithm}}async function _h(n,e,t){const{crypto:s,encoding:i}=t,{utf8:r,base64:o}=i,{derive:a,aes:c,hmac:l}=s,h=o.decode(e),d=new Uint8Array(8),u="\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0",p=r.encode(""),_=await a.hkdf(n,d,p,"SHA-256",512),f=_.slice(0,32),b=_.slice(32),S=await c.encryptCTR({key:f,iv:h,data:r.encode(u)}),k=await l.compute(b,S,"SHA-256");return o.encode(k)}const fh=5e5,gh=256;async function yh(n,e,t){const{passphraseParams:s}=n;if(!s)throw new Error("not a passphrase key");if(s.algorithm!=="m.pbkdf2")throw new Error(`Unsupported passphrase algorithm: ${s.algorithm}`);const{utf8:i}=t.encoding,r=await t.crypto.derive.pbkdf2(i.encode(e),s.iterations||fh,i.encode(s.salt),"SHA-512",s.bits||gh);return new ts(n,r)}const Dt=[139,1];function wh(n,e,t,s){const i=s.encoding.base58.decode(e.replace(/ /g,""));let r=0;for(const a of i)r^=a;if(r!==0)throw new Error("Incorrect parity");for(let a=0;a(n[n.RecoveryKey=0]="RecoveryKey",n[n.Passphrase=1]="Passphrase",n))(Qt||{});async function no(n){var r;const e=await n.readTxn([n.storeNames.accountData]),t=await e.accountData.get("m.secret_storage.default_key"),s=(r=t==null?void 0:t.content)==null?void 0:r.key;if(!s)return;const i=await e.accountData.get(`m.secret_storage.key.${s}`);if(!!i)return new Li(s,i.content)}async function vh(n,e,t){const s=await t.session.get($r);return t.session.set($r,e),t.session.set(Oi,{id:n.id,binaryKey:n.binaryKey}),s}async function bh(n){const e=await n.session.get(Oi);if(!e)return;const t=await n.accountData.get(`m.secret_storage.key.${e.id}`);if(t)return new ts(new Li(e.id,t.content),e.binaryKey)}async function Sh(n){n.session.remove(Oi)}async function Ih(n,e,t,s,i){const r=await no(t);if(!r)throw new Error("Could not find a default secret storage key in account data");return await oo(n,e,r,s,i)}async function oo(n,e,t,s,i){let r;if(n===1)r=await yh(t,e,s);else if(n===0)r=wh(t,e,i,s);else throw new Error(`Invalid type: ${n}`);return r}async function Eh(n,e,t){const s=await no(e);if(await(s==null?void 0:s.isCompatible(n,t)))return n.withDescription(s)}const ao="org.matrix.msc2697.v1.olm.libolm_pickle";async function kh(n,e,t,s){try{const i=await n.getDehydratedDevice({log:s}).response();if(i.device_data.algorithm===ao)return new Ch(i,e,t)}catch(i){i.name!=="HomeServerError"&&(s.error=i);return}}async function Rh(n,e,t,s,i){var a;const o=(await e.createDehydratedDevice({device_data:{algorithm:ao,account:n.pickleWithKey(t.binaryKey.slice()),passphrase:((a=t.description)==null?void 0:a.passphraseParams)||{}},initial_device_display_name:s}).response()).device_id;return n.setDeviceId(o),await n.uploadKeys(void 0,!0,i),o}class Ch{constructor(e,t,s){this._dehydratedDevice=e,this._olm=t,this._platform=s}async decrypt(e,t){const s=new Li("dehydrated_device",this._dehydratedDevice.device_data.passphrase),i=await oo(e,t,s,this._platform,this._olm),r=new this._olm.Account;try{const o=this._dehydratedDevice.device_data.account;return r.unpickle(i.binaryKey.slice(),o),new Th(this._dehydratedDevice,r,i)}catch(o){if(r.free(),o.message==="OLM.BAD_ACCOUNT_KEY")return;throw o}}get deviceId(){return this._dehydratedDevice.device_id}}class Th{constructor(e,t,s){this._dehydratedDevice=e,this._account=t,this._key=s}async claim(e,t){try{return(await e.claimDehydratedDevice(this.deviceId,{log:t}).response()).success}catch{return!1}}adoptUnpickledOlmAccount(){const e=this._account;return this._account=void 0,e}get deviceId(){return this._dehydratedDevice.device_id}get key(){return this._key}dispose(){var e;(e=this._account)==null||e.free(),this._account=void 0}}class Mh{tryTake(){return this._promise?!1:(this._promise=new Promise(e=>{this._resolve=e}),!0)}async take(){for(;!this.tryTake();)await this.released()}get isTaken(){return!!this._promise}release(){if(this._resolve){this._promise=void 0;const e=this._resolve;this._resolve=void 0,e()}}released(){return this._promise}}class Ah{constructor(e){this.locks=e}release(){for(const e of this.locks)e.release()}}function co(n,e,t,s){return{session:n.pickle(s),sessionId:n.session_id(),senderKey:e,lastUsed:t}}class As{constructor(e,t,s,i=!1){this.data=e,this.pickleKey=t,this.olm=s,this.isNew=i,this.isModified=i}static create(e,t,s,i,r){const o=co(t,e,r,i);return new As(o,i,s,!0)}get id(){return this.data.sessionId}load(){const e=new this.olm.Session;return e.unpickle(this.pickleKey,this.data.session),e}unload(e){e.free()}save(e){this.data.session=e.pickle(this.pickleKey),this.isModified=!0}}class lo{constructor(e,t,s){this.event=e,this.senderCurve25519Key=t,this.claimedEd25519Key=s,this.roomTracked=!0}setDevice(e){this.device=e}setRoomNotTrackedYet(){this.roomTracked=!1}get isVerified(){return this.device?this.device.ed25519Key===this.claimedEd25519Key:!1}get isUnverified(){return this.device?!this.isVerified:!this.isVerificationUnknown}get isVerificationUnknown(){return!this.device&&!this.roomTracked}}var xs=(n=>(n[n.PreKey=0]="PreKey",n[n.Normal=1]="Normal",n))(xs||{});const jr=4;function ho(n){n.sort((e,t)=>t.data.lastUsed-e.data.lastUsed)}class xh{constructor(e,t,s,i,r,o){this.account=e,this.pickleKey=t,this.now=s,this.ownUserId=i,this.olm=r,this.senderKeyLock=o}async obtainDecryptionLock(e){var i;const t=new Set;for(const r of e){const o=(i=r.content)==null?void 0:i.sender_key;o&&t.add(o)}const s=await Promise.all(Array.from(t).map(r=>this.senderKeyLock.takeLock(r)));return new Ah(s)}async decryptAll(e,t,s){try{const i=bt(e,h=>{var d;return(d=h.content)==null?void 0:d.sender_key}),r=this.now(),o=await Promise.all(Array.from(i.entries()).map(([h,d])=>this._decryptAllForSenderKey(h,d,r,s))),a=o.reduce((h,d)=>h.concat(d.results),[]),c=o.reduce((h,d)=>h.concat(d.errors),[]),l=o.map(h=>h.senderKeyDecryption);return new Dh(l,a,c,this.account,t)}catch(i){throw t.release(),i}}async _decryptAllForSenderKey(e,t,s,i){const r=await this._getSessions(e,i),o=new Nh(e,r,s),a=[],c=[];for(const l of t)try{const h=this._decryptForSenderKey(o,l,s);a.push(h)}catch(h){c.push(h)}return{results:a,errors:c,senderKeyDecryption:o}}_decryptForSenderKey(e,t,s){const i=e.senderKey,r=this._getMessageAndValidateEvent(t);let o;try{o=e.decrypt(r)}catch(a){throw new z("OLM_BAD_ENCRYPTED_MESSAGE",t,{senderKey:i,error:a.message})}if(typeof o!="string"&&r.type===xs.PreKey){let a;try{a=this._createSessionAndDecrypt(i,r,s)}catch(c){throw new z(`Could not create inbound olm session: ${c.message}`,t,{senderKey:i,error:c})}e.addNewSession(a.session),o=a.plaintext}if(typeof o=="string"){let a;try{a=JSON.parse(o)}catch(c){throw new z("PLAINTEXT_NOT_JSON",t,{plaintext:o,error:c})}return this._validatePayload(a,t),new lo(a,i,a.keys.ed25519)}else throw new z("OLM_NO_MATCHING_SESSION",t,{knownSessionIds:e.sessions.map(a=>a.id)})}_createSessionAndDecrypt(e,t,s){let i;const r=this.account.createInboundOlmSession(e,t.body);try{i=r.decrypt(t.type,t.body);const o=As.create(e,r,this.olm,this.pickleKey,s);return o.unload(r),{session:o,plaintext:i}}catch(o){throw r.free(),o}}_getMessageAndValidateEvent(e){var i;const t=(i=e.content)==null?void 0:i.ciphertext;if(!t)throw new z("OLM_MISSING_CIPHERTEXT",e);const s=t==null?void 0:t[this.account.identityKeys.curve25519];if(!s)throw new z("OLM_NOT_INCLUDED_IN_RECIPIENTS",e);return s}async _getSessions(e,t){const i=(await t.olmSessions.getAll(e)).map(r=>new As(r,this.pickleKey,this.olm));return ho(i),i}_validatePayload(e,t){var s,i,r;if(e.sender!==t.sender)throw new z("OLM_FORWARDED_MESSAGE",t,{sentBy:t.sender,encryptedBy:e.sender});if(e.recipient!==this.ownUserId)throw new z("OLM_BAD_RECIPIENT",t,{recipient:e.recipient});if(((s=e.recipient_keys)==null?void 0:s.ed25519)!==this.account.identityKeys.ed25519)throw new z("OLM_BAD_RECIPIENT_KEY",t,{key:(i=e.recipient_keys)==null?void 0:i.ed25519});if(!e.type)throw new z("missing type on payload",t,{payload:e});if(typeof((r=e.keys)==null?void 0:r.ed25519)!="string")throw new z("Missing or invalid claimed ed25519 key on payload",t,{payload:e})}}class Nh{constructor(e,t,s){this.senderKey=e,this.sessions=t,this.timestamp=s}addNewSession(e){this.sessions.unshift(e)}decrypt(e){for(const t of this.sessions){const s=this.decryptWithSession(t,e);if(typeof s=="string")return ho(this.sessions),s}}getModifiedSessions(){return this.sessions.filter(e=>e.isModified)}get hasNewSessions(){return this.sessions.some(e=>e.isNew)}decryptWithSession(e,t){if(t.type===void 0||t.body===void 0)throw new Error("Invalid message without type or body");const s=e.load();try{if(t.type===xs.PreKey&&!s.matches_inbound(t.body))return;try{const i=s.decrypt(t.type,t.body);return e.save(s),e.data.lastUsed=this.timestamp,i}catch(i){if(t.type===xs.PreKey)throw new Error(`Error decrypting prekey message with existing session id ${e.id}: ${i.message}`);return}}finally{e.unload(s)}}}class Dh{constructor(e,t,s,i,r){this.senderKeyDecryptions=e,this.results=t,this.errors=s,this.account=i,this.lock=r}get hasNewSessions(){return this.senderKeyDecryptions.some(e=>e.hasNewSessions)}write(e){try{for(const t of this.senderKeyDecryptions){for(const s of t.getModifiedSessions())if(e.olmSessions.set(s.data),s.isNew){const i=s.load();try{this.account.writeRemoveOneTimeKey(i,e)}finally{s.unload(i)}}if(t.sessions.length>jr){const{senderKey:s,sessions:i}=t;for(let r=i.length-1;r>=jr;r-=1){const o=i[r];e.olmSessions.remove(s,o.id)}}}}finally{this.lock.release()}}}function Vh(n){return n.reduce((e,t)=>!e||tthis.senderKeyLock.takeLock(a.curve25519Key)));try{const{devicesWithoutSession:a,existingEncryptionTargets:c}=await this._findExistingSessions(s),l=this.now();let h=[];try{if(a.length){const p=await r.wrap("create sessions",_=>this._createNewSessions(a,i,l,_));h=h.concat(p)}await this._loadSessions(c),h=h.concat(c);const d={l:"encrypt",targets:h.length},u=r.wrap(d,()=>h.map(p=>{const _=this._encryptForDevice(e,t,p);return new Oh(_,p.device)}));return await this._storeSessions(h,l),u}finally{for(const d of h)d.dispose()}}finally{for(const a of o)a.release()}}async _findExistingSessions(e){const t=await this.storage.readTxn([this.storage.storeNames.olmSessions]),s=await Promise.all(e.map(async o=>await t.olmSessions.getSessionIds(o.curve25519Key))),i=e.filter((o,a)=>{const c=s[a];return!(c!=null&&c.length)}),r=e.map((o,a)=>{const c=s[a];if((c==null?void 0:c.length)>0){const l=Vh(c);return Yt.fromSessionId(o,l)}}).filter(o=>!!o);return{devicesWithoutSession:i,existingEncryptionTargets:r}}_encryptForDevice(e,t,s){const{session:i,device:r}=s,o=JSON.stringify(this._buildPlainTextMessageForDevice(e,t,r)),a=i.encrypt(o);return{algorithm:ki,sender_key:this.account.identityKeys.curve25519,ciphertext:{[r.curve25519Key]:a}}}_buildPlainTextMessageForDevice(e,t,s){return{keys:{ed25519:this.account.identityKeys.ed25519},recipient_keys:{ed25519:s.ed25519Key},recipient:s.userId,sender:this.ownUserId,content:t,type:e}}async _createNewSessions(e,t,s,i){const r=await i.wrap("claim",o=>this._claimOneTimeKeys(t,e,o));try{for(const o of r){const{device:a,oneTimeKey:c}=o;o.session=await this.account.createOutboundOlmSession(a.curve25519Key,c)}await this._storeSessions(r,s)}catch(o){for(const a of r)a.dispose();throw o}return r}async _claimOneTimeKeys(e,t,s){const i=Vi(t,c=>c.userId,()=>new Map,(c,l)=>c.set(l.deviceId,l)),r=Array.from(i.entries()).reduce((c,[l,h])=>(c[l]=Array.from(h.values()).reduce((d,u)=>(d[u.deviceId]=qr,d),{}),c),{}),o=await e.claimKeys({timeout:1e4,one_time_keys:r},{log:s}).response();Object.keys(o.failures).length&&s.log({l:"failures",servers:Object.keys(o.failures)},s.level.Warn);const a=o==null?void 0:o.one_time_keys;return this._verifyAndCreateOTKTargets(a,i,s)}_verifyAndCreateOTKTargets(e,t,s){var r;const i=[];for(const[o,a]of Object.entries(e))for(const[c,l]of Object.entries(a)){const[h,d]=Object.entries(l)[0],[u]=h.split(":");if(u===qr){const p=(r=t.get(o))==null?void 0:r.get(c);if(p&&Un(this.olmUtil,o,c,p.ed25519Key,d,s)){const f=Yt.fromOTK(p,d.key);i.push(f)}}}return i}async _loadSessions(e){const t=await this.storage.readTxn([this.storage.storeNames.olmSessions]);let s=!1;try{await Promise.all(e.map(async i=>{const r=await t.olmSessions.get(i.device.curve25519Key,i.sessionId);if(r&&!s){const o=new this.olm.Session;o.unpickle(this.pickleKey,r.session),i.session=o}}))}catch(i){s=!0;for(const r of e)r.dispose();throw i}}async _storeSessions(e,t){const s=await this.storage.readWriteTxn([this.storage.storeNames.olmSessions]);try{for(const i of e){const r=co(i.session,i.device.curve25519Key,t,this.pickleKey);s.olmSessions.set(r)}}catch(i){throw s.abort(),i}await s.complete()}}class Yt{constructor(e,t,s){this.device=e,this.oneTimeKey=t,this.sessionId=s,this.session=null}static fromOTK(e,t){return new Yt(e,t,null)}static fromSessionId(e,t){return new Yt(e,null,t)}dispose(){this.session&&this.session.free()}}class Oh{constructor(e,t){this.content=e,this.device=t}}class Ph{constructor(e,t,s,i){this._roomId=e,this._results=t,this._errors=s,this._replayEntries=i}async write(e){return await Promise.all(this._replayEntries.map(async t=>{try{this._handleReplayAttack(this._roomId,t,e)}catch(s){this._errors.set(t.eventId,s)}})),{results:this._results,errors:this._errors}}async _handleReplayAttack(e,t,s){const{messageIndex:i,sessionId:r,eventId:o,timestamp:a}=t,c=await s.groupSessionDecryptions.get(e,r,i);if(c&&c.eventId!==o){const h=c.timestamp{const r=await i.decryptAll();fi(r.errors,e),fi(r.results,t),s.push(...r.replayEntries)})),new Ph(this._roomId,t,e,s)}finally{this.dispose()}}dispose(){for(const e of this._sessionDecryptions)e.dispose()}}class Fh{constructor(e,t,s){this.sessionId=e,this.messageIndex=t,this.event=s}get eventId(){return this.event.event_id}get timestamp(){return this.event.origin_server_ts}}class Bh{constructor(e,t,s,i){this.key=e,this.events=t,this.olmWorker=s,this.keyLoader=i,this.decryptionRequests=s?[]:void 0}async decryptAll(){const e=[],t=new Map;let s;return await this.keyLoader.useKey(this.key,async i=>{for(const r of this.events)try{const o=r.content.ciphertext;let a;if(this.olmWorker){const d=this.olmWorker.megolmDecrypt(i,o);this.decryptionRequests.push(d),a=await d.response()}else a=i.decrypt(o);const{plaintext:c}=a;let l;try{l=JSON.parse(c)}catch(d){throw new z("PLAINTEXT_NOT_JSON",r,{plaintext:c,err:d})}if(l.room_id!==this.key.roomId)throw new z("MEGOLM_WRONG_ROOM",r,{encryptedRoomId:l.room_id,eventRoomId:this.key.roomId});e.push(new Fh(this.key.sessionId,a.message_index,r));const h=new lo(l,this.key.senderKey,this.key.claimedEd25519Key);t.set(r.event_id,h)}catch(o){if(o.name==="AbortError")return;s||(s=new Map),s.set(r.event_id,o)}}),{results:t,errors:s,replayEntries:e}}dispose(){if(this.decryptionRequests)for(const e of this.decryptionRequests)e.abort()}}function Pi(n){var e;return(e=n.content)==null?void 0:e.sender_key}function Ui(n){var e;return(e=n.content)==null?void 0:e.session_id}function Kh(n){var e;return(e=n.content)==null?void 0:e.ciphertext}function $h(n){return typeof Pi(n)=="string"&&typeof Ui(n)=="string"&&typeof Kh(n)=="string"}class jh{constructor(){this.events=[]}get senderKey(){return Pi(this.events[0])}get sessionId(){return Ui(this.events[0])}}function gi(n){return Vi(n,e=>`${Pi(e)}|${Ui(e)}`,()=>new jh,(e,t)=>e.events.push(t))}class uo{isForSession(e,t,s){return this.roomId===e&&this.senderKey===t&&this.sessionId===s}get isBetter(){return this._isBetter}set isBetter(e){this._isBetter=e}}function mo(n,e){return n.first_known_index(){s=r.pickle(o)},t),this.isBetter===!1)return!1;s||(s=await e.useKey(this,(r,o)=>r.pickle(o)));const i={roomId:this.roomId,senderKey:this.senderKey,sessionId:this.sessionId,session:s,backup:this.backupStatus,source:this.keySource,claimedKeys:{ed25519:this.claimedEd25519Key}};return t.inboundGroupSessions.set(i),!0}get eventIds(){return this._eventIds}async _checkBetterThanKeyInStorage(e,t,s){if(this.isBetter!==void 0)return this.isBetter;let i=e.getCachedKey(this.roomId,this.senderKey,this.sessionId);if(!i){const r=await fo(this.roomId,this.senderKey,this.sessionId,s);r&&(r.hasSession?i=r:r.eventIds&&(this._eventIds=r.eventIds))}if(i){const r=i;await e.useKey(this,async o=>{await e.useKey(r,(a,c)=>{this.isBetter=mo(o,a),r.isBetter=!this.isBetter,this.isBetter&&t&&t(o,c)})})}else this.isBetter=!0;return this.isBetter}get backupStatus(){return Os.NotBackedUp}}class qh extends Fi{constructor(e){super(),this._decryptionResult=e}get roomId(){var e;return(e=this._decryptionResult.event.content)==null?void 0:e.room_id}get senderKey(){return this._decryptionResult.senderCurve25519Key}get sessionId(){var e;return(e=this._decryptionResult.event.content)==null?void 0:e.session_id}get claimedEd25519Key(){return this._decryptionResult.claimedEd25519Key}get serializationKey(){var e;return(e=this._decryptionResult.event.content)==null?void 0:e.session_key}get serializationType(){return"create"}get keySource(){return es.DeviceMessage}loadInto(e){e.create(this.serializationKey)}}class Wh extends Fi{constructor(e,t,s){super(),this._roomId=e,this.outboundSession=t,this.identityKeys=s,this.isBetter=!0,this._sessionKey=this.outboundSession.session_key()}get roomId(){return this._roomId}get senderKey(){return this.identityKeys.curve25519}get sessionId(){return this.outboundSession.session_id()}get claimedEd25519Key(){return this.identityKeys.ed25519}get serializationKey(){return this._sessionKey}get serializationType(){return"create"}get keySource(){return es.Outbound}loadInto(e){e.create(this.serializationKey)}}class Hh extends Fi{constructor(e,t,s){super(),this._roomId=e,this._sessionId=t,this._backupInfo=s}get roomId(){return this._roomId}get senderKey(){return this._backupInfo.sender_key}get sessionId(){return this._sessionId}get claimedEd25519Key(){var e;return(e=this._backupInfo.sender_claimed_keys)==null?void 0:e.ed25519}get serializationKey(){return this._backupInfo.session_key}get serializationType(){return"import_session"}get keySource(){return es.Backup}loadInto(e){e.import_session(this.serializationKey)}get backupStatus(){return Os.BackedUp}}class po extends uo{constructor(e){super(),this.isBetter=!0,this.storageEntry=e}get roomId(){return this.storageEntry.roomId}get senderKey(){return this.storageEntry.senderKey}get sessionId(){return this.storageEntry.sessionId}get claimedEd25519Key(){return this.storageEntry.claimedKeys.ed25519}get eventIds(){return this.storageEntry.eventIds}get serializationKey(){return this.storageEntry.session||""}get serializationType(){return"unpickle"}loadInto(e,t){e.unpickle(t,this.serializationKey)}get hasSession(){return!!this.serializationKey}}function zh(n){var s;const e=(s=n.event.content)==null?void 0:s.session_key,t=new qh(n);if(typeof t.roomId=="string"&&typeof t.sessionId=="string"&&typeof t.senderKey=="string"&&typeof e=="string")return t}function _o(n,e,t){var o;const s=t.session_key,i=t.sender_key,r=(o=t.sender_claimed_keys)==null?void 0:o.ed25519;if(typeof n=="string"&&typeof e=="string"&&typeof i=="string"&&typeof s=="string"&&typeof r=="string")return new Hh(n,e,t)}async function fo(n,e,t,s){const i=await s.inboundGroupSessions.get(n,e,t);if(i)return new po(i)}class Gh{constructor(e,t){this.keyLoader=e,this.olmWorker=t}async addMissingKeyEventIds(e,t,s,i,r){let o=await r.inboundGroupSessions.get(e,t,s);if(!(o!=null&&o.session)){if(o){const a=new Set(o.eventIds);for(const c of i)a.add(c);o.eventIds=Array.from(a)}else o={roomId:e,senderKey:t,sessionId:s,eventIds:i};r.inboundGroupSessions.set(o)}}async getEventIdsForMissingKey(e,t,s,i){const r=await i.inboundGroupSessions.get(e,t,s);if(r&&!r.session)return r.eventIds}async hasSession(e,t,s,i){const r=await i.inboundGroupSessions.get(e,t,s);return typeof(r==null?void 0:r.session)=="string"}async prepareDecryptAll(e,t,s,i){const r=new Map,o=[];for(const l of t)$h(l)?o.push(l):r.set(l.event_id,new z("MEGOLM_INVALID_EVENT",l));const a=gi(o),c=[];return await Promise.all(Array.from(a.values()).map(async l=>{const h=await this.getRoomKey(e,l.senderKey,l.sessionId,s,i);if(h)c.push(new Bh(h,l.events,this.olmWorker,this.keyLoader));else for(const d of l.events)r.set(d.event_id,new z("MEGOLM_NO_SESSION",d))})),new Uh(e,c,r)}async getRoomKey(e,t,s,i,r){if(i){const c=i.find(l=>l.isForSession(e,t,s));if(c&&await c.checkBetterThanKeyInStorage(this.keyLoader,r))return c}const o=this.keyLoader.getCachedKey(e,t,s);if(o)return o;const a=await fo(e,t,s,r);if(a&&a.serializationKey)return a}writeRoomKey(e,t){return e.write(this.keyLoader,t)}roomKeysFromDeviceMessages(e,t){var i,r;const s=[];for(const o of e)((i=o.event)==null?void 0:i.type)!=="m.room_key"||((r=o.event.content)==null?void 0:r.algorithm)!==ve||t.wrap("room_key",a=>{const c=zh(o);c?(a.set("roomId",c.roomId),a.set("id",c.sessionId),s.push(c)):(a.logLevel=a.level.Warn,a.set("invalid",!0))},t.level.Detail);return s}roomKeyFromBackup(e,t,s){return _o(e,t,s)}dispose(){this.keyLoader.dispose()}}class Jh extends eo{constructor(e,t,s){super(s),this.pickleKey=t,this.olm=e}getCachedKey(e,t,s){const i=this.findCachedKeyIndex(e,t,s);if(i!==-1)return this._getByIndexAndMoveUp(i).key}async useKey(e,t){const s=await this.allocateOperation(e);try{return await t(s.session,this.pickleKey)}finally{this.releaseOperation(s)}}get running(){return this._entries.some(e=>e.refCount!==0)}dispose(){for(let e=0;e{this.resolveUnusedOperation=e})),this.operationBecomesUnusedPromise}findIndexForAllocation(e){let t=this.findIndexSameKey(e);return t===-1&&(this.size{const c=i===-1?void 0:a[i];return r.isBest===!0&&r.isForSameSession(e,t,s)&&(!c||r.isBetter(c))?o:i},-1)}findIndexSameKey(e){return this._entries.findIndex(t=>t.isForSameSession(e.roomId,e.senderKey,e.sessionId)&&t.isForKey(e))}findIndexSameSessionUnused(e){return this._entries.reduce((t,s,i,r)=>{const o=t===-1?void 0:r[t];return s.refCount===0&&s.isForSameSession(e.roomId,e.senderKey,e.sessionId)&&(!o||!s.isBetter(o))?i:t},-1)}findIndexOldestUnused(){for(let e=this._entries.length-1;e>=0;e-=1)if(this._entries[e].refCount===0)return e;return-1}}class Qh{constructor(e,t){this.key=e,this.session=t,this.refCount=1}isForSameSession(e,t,s){return this.key.roomId===e&&this.key.senderKey===t&&this.key.sessionId===s}isBetter(e){return mo(this.session,e.session)}isForKey(e){return this.key.serializationKey===e.serializationKey&&this.key.serializationType===e.serializationType}dispose(){this.session.free(),this.session=void 0}get isBest(){return this.key.isBetter}}const Yh="m.megolm_backup.v1.curve25519-aes-sha2";class Bi{constructor(e,t){this.encryption=e,this.decryption=t}static fromAuthData(e,t,s){const i=e.public_key,r=new s.PkDecryption,o=new s.PkEncryption;try{const a=r.init_with_private_key(t);if(a!==i)throw new Error(`Bad backup key, public key does not match. Calculated ${a} but expected ${i}`);o.set_recipient_key(a)}catch(a){throw r.free(),a}return new Bi(o,r)}decryptRoomKey(e){const t=this.decryption.decrypt(e.ephemeral,e.mac,e.ciphertext);return JSON.parse(t)}encryptRoomKey(e,t){const s={algorithm:ve,sender_key:e.senderKey,sender_claimed_keys:{ed25519:e.claimedEd25519Key},forwarding_curve25519_key_chain:[],session_key:t};return this.encryption.encrypt(JSON.stringify(s))}dispose(){var e,t;(e=this.decryption)==null||e.free(),this.decryption=void 0,(t=this.encryption)==null||t.free(),this.encryption=void 0}}const Xh=200;class Ki{constructor(e,t,s,i,r,o,a=1e4){this.backupInfo=e,this.crypto=t,this.hsApi=s,this.keyLoader=i,this.storage=r,this.platform=o,this.maxDelay=a,this.operationInProgress=new we(void 0),this._stopped=!1,this._needsNewKey=!1,this._hasBackedUpAllKeys=!1}get hasStopped(){return this._stopped}get error(){return this._error}get version(){return this.backupInfo.version}get needsNewKey(){return this._needsNewKey}get hasBackedUpAllKeys(){return this._hasBackedUpAllKeys}async getRoomKey(e,t,s){const i=await this.hsApi.roomKeyForRoomAndSession(this.backupInfo.version,e,t,{log:s}).response();if(!i.session_data)return;const r=this.crypto.decryptRoomKey(i.session_data);if((r==null?void 0:r.algorithm)===ve)return _o(e,t,r);r!=null&&r.algorithm&&s.set("unknown algorithm",r.algorithm)}markAllForBackup(e){return e.inboundGroupSessions.markAllAsNotBackedUp()}flush(e){this.operationInProgress.get()||e.wrapDetached("flush key backup",async t=>{if(this._needsNewKey){t.set("needsNewKey",this._needsNewKey);return}this._stopped=!1,this._error=void 0,this._hasBackedUpAllKeys=!1;const s=this._runFlushOperation(t);this.operationInProgress.set(s);try{await s.result,this._hasBackedUpAllKeys=!0}catch(i){this._stopped=!0,i.name==="HomeServerError"&&(i.errcode==="M_WRONG_ROOM_KEYS_VERSION"||i.errcode==="M_NOT_FOUND")?(t.set("wrong_version",!0),this._needsNewKey=!0):(i.name!=="AbortError"||i.name==="StorageError"&&i.errcode==="AbortError")&&(this._error=i),t.catch(i)}this.operationInProgress.set(void 0)})}_runFlushOperation(e){return new Mn(async(t,s)=>{let i=0,r=0;for(;;){const o=this.platform.random()*this.maxDelay,a=this.platform.clock.createTimeout(o);t(a),await a.elapsed();const c=await this.storage.readTxn([P.inboundGroupSessions]);t(c),i=r+await c.inboundGroupSessions.countNonBackedUpSessions(),s(new Hr(i,r));const l=(await c.inboundGroupSessions.getFirstNonBackedUpSessions(Xh)).map(u=>new po(u));if(l.length===0){e.set("total",i);return}const h=await this.encodeKeysForBackup(l),d=this.hsApi.uploadRoomKeysToBackup(this.backupInfo.version,h,{log:e});t(d),await d.response(),await this.markKeysAsBackedUp(l,t),r+=l.length,s(new Hr(i,r))}})}async encodeKeysForBackup(e){const t={rooms:{}},s=t.rooms;for(const i of e){let r=s[i.roomId];r||(r=s[i.roomId]={sessions:{}}),r.sessions[i.sessionId]=await this.encodeRoomKey(i)}return t}async markKeysAsBackedUp(e,t){const s=await this.storage.readWriteTxn([P.inboundGroupSessions]);t(s);try{await Promise.all(e.map(i=>s.inboundGroupSessions.markAsBackedUp(i.roomId,i.senderKey,i.sessionId)))}catch(i){throw s.abort(),i}await s.complete()}async encodeRoomKey(e){return await this.keyLoader.useKey(e,t=>{const s=t.first_known_index(),i=t.export_session(s);return{first_message_index:s,forwarded_count:0,is_verified:!1,session_data:this.crypto.encryptRoomKey(e,i)}})}dispose(){this.crypto.dispose()}static async fromSecretStorage(e,t,s,i,r,o,a){const c=await s.readSecret("m.megolm_backup.v1",a);if(c){const l=new Uint8Array(e.encoding.base64.decode(c)),h=await i.roomKeysVersion().response();if(h.algorithm===Yh){const d=Bi.fromAuthData(h.auth_data,l,t);return new Ki(h,d,i,r,o,e)}else throw new Error(`Unknown backup algorithm: ${h.algorithm}`)}}}class Hr{constructor(e,t){this.total=e,this.finished=t}}class Zh{constructor({pickleKey:e,olm:t,account:s,keyLoader:i,storage:r,now:o,ownDeviceId:a}){this._pickleKey=e,this._olm=t,this._account=s,this._keyLoader=i,this._storage=r,this._now=o,this._ownDeviceId=a}discardOutboundSession(e,t){t.outboundGroupSessions.remove(e)}async createRoomKeyMessage(e,t){let s=await t.outboundGroupSessions.get(e);if(s){const i=new this._olm.OutboundGroupSession;try{return i.unpickle(this._pickleKey,s.session),this._createRoomKeyMessage(i,e)}finally{i.free()}}}createWithheldMessage(e,t,s){return{algorithm:e.algorithm,code:t,reason:s,room_id:e.room_id,sender_key:this._account.identityKeys.curve25519,session_id:e.session_id}}async ensureOutboundSession(e,t){let s=new this._olm.OutboundGroupSession;try{const i=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions,this._storage.storeNames.outboundGroupSessions]);let r;try{let o=await i.outboundGroupSessions.get(e);r=await this._readOrCreateSession(s,o,e,t,i),r&&this._writeSession(this._now(),s,e,i)}catch(o){throw i.abort(),o}return await i.complete(),r}finally{s.free()}}async _readOrCreateSession(e,t,s,i,r){if(t&&e.unpickle(this._pickleKey,t.session),!t||this._needsToRotate(e,t.createdAt,i)){t&&(e.free(),e=new this._olm.OutboundGroupSession),e.create();const o=this._createRoomKeyMessage(e,s);return await new Wh(s,e,this._account.identityKeys).write(this._keyLoader,r),o}}_writeSession(e,t,s,i){i.outboundGroupSessions.set({roomId:s,session:t.pickle(this._pickleKey),createdAt:e})}async encrypt(e,t,s,i){let r=new this._olm.OutboundGroupSession;try{const o=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions,this._storage.storeNames.outboundGroupSessions]);let a,c;try{let l=await o.outboundGroupSessions.get(e);a=await this._readOrCreateSession(r,l,e,i,o),c=this._encryptContent(e,r,t,s);const h=a?this._now():l.createdAt;this._writeSession(h,r,e,o)}catch(l){throw o.abort(),l}return await o.complete(),new ed(c,a)}finally{r&&r.free()}}_needsToRotate(e,t,s){let i=6048e5;Number.isSafeInteger(s==null?void 0:s.rotation_period_ms)&&(i=s==null?void 0:s.rotation_period_ms);let r=100;if(Number.isSafeInteger(s==null?void 0:s.rotation_period_msgs)&&(r=s==null?void 0:s.rotation_period_msgs),this._now()>t+i||e.message_index()>=r)return!0}_encryptContent(e,t,s,i){const r=JSON.stringify({room_id:e,type:s,content:i}),o=t.encrypt(r);return{algorithm:ve,sender_key:this._account.identityKeys.curve25519,ciphertext:o,session_id:t.session_id(),device_id:this._ownDeviceId}}_createRoomKeyMessage(e,t){return{room_id:t,session_id:e.session_id(),session_key:e.session_key(),algorithm:ve,chain_index:e.message_index()}}}class ed{constructor(e,t){this.content=e,this.roomKeyMessage=t}}class Wt{constructor(e,t,s,i){this._logger=s,this.start=s._now(),this._values=typeof e=="string"?{l:e}:e,this.logLevel=t,this._filterCreator=i}runDetached(e,t,s,i){return this._logger.runDetached(e,t,s,i)}wrapDetached(e,t,s,i){this.refDetached(this.runDetached(e,t,s,i))}refDetached(e,t){e.ensureRefId(),this.log({ref:e.values.refId},t)}ensureRefId(){this._values.refId||this.set("refId",this._logger._createRefId())}wrap(e,t,s,i){return this.child(e,s,i).run(t)}get duration(){if(this.end)return this.end-this.start}durationWithoutType(e){const t=this.durationOfType(e);if(this.duration&&t)return this.duration-t}durationOfType(e){return this._values.t===e?this.duration:this._children?this._children.reduce((t,s)=>{const i=s.durationOfType(e);return t+(i!=null?i:0)},0):0}log(e,t){const s=this.child(e,t);return s.end=s.start,s}set(e,t){if(typeof e=="object"){const s=e;Object.assign(this._values,s)}else this._values[e]=t;return this}serialize(e,t,s){if(this._filterCreator)try{e=this._filterCreator(new mi(e),this)}catch(o){console.error("Error creating log filter",o)}let i=null;if(this._children&&(i=this._children.reduce((o,a)=>{const c=a.serialize(e,this.start,!1);return c&&(o===null&&(o=[]),o.push(c)),o},null)),e&&!e.filter(this,i))return;const r={s:typeof t=="number"?this.start-t:this.start,d:this.duration,v:this._values,l:this.logLevel};return this.error&&(r.e={stack:this.error.stack,name:this.error.name,message:this.error.message.split(` +`)[0]}),s&&(r.f=!0),i&&(r.c=i),r}run(e){this.end!==void 0&&console.trace("log item is finished, additional logs will likely not be recorded");try{const t=e(this);return t instanceof Promise?t.then(s=>(this.finish(),s),s=>{throw this.catch(s)}):(this.finish(),t)}catch(t){throw this.catch(t)}}finish(){if(this.end===void 0){if(this._children)for(const e of this._children)e.finish();this.end=this._logger._now()}}get level(){return _e}catch(e){return this.error=e,this.logLevel=_e.Error,this.finish(),e}child(e,t,s){this.end&&console.trace("log item is finished, additional logs will likely not be recorded"),t||(t=this.logLevel||_e.Info);const i=new Wt(e,t,this._logger,s);return this._children||(this._children=[]),this._children.push(i),i}get logger(){return this._logger}get values(){return this._values}get children(){return this._children}}class go{constructor({platform:e,serializedTransformer:t=s=>s}){this._openItems=new Set,this._platform=e,this._serializedTransformer=t}log(e,t=_e.Info){const s=new Wt(e,t,this);s.end=s.start,this._persistItem(s,void 0,!1)}wrapOrRun(e,t,s,i,r){return e?e.wrap(t,s,i,r):this.run(t,s,i,r)}runDetached(e,t,s,i){s||(s=_e.Info);const r=new Wt(e,s,this);return this._run(r,t,s,!1,i),r}run(e,t,s,i){s===void 0&&(s=_e.Info);const r=new Wt(e,s,this);return this._run(r,t,s,!0,i)}_run(e,t,s,i,r){this._openItems.add(e);const o=()=>{let a=new mi;if(r)try{a=r(a,e)}catch(c){console.error("Error while creating log filter",c)}else a=a.minLevel(s);try{this._persistItem(e,a,!1)}catch(c){console.error("Could not persist log item",c)}this._openItems.delete(e)};try{let a=e.run(t);if(a instanceof Promise){if(a=a.then(c=>(o(),c),c=>{if(o(),i)throw c}),i)return a}else if(o(),i)return a}catch(a){if(o(),i)throw a}}_finishOpenItems(){for(const e of this._openItems){e.finish();try{this._persistItem(e,new mi,!0)}catch(t){console.error("Could not serialize log item",t)}}this._openItems.clear()}get level(){return _e}_now(){return this._platform.clock.now()}_createRefId(){return Math.round(this._platform.random()*Number.MAX_SAFE_INTEGER)}}class td extends go{_persistItem(e){yo(e)}async export(){}}const sd=["l","id"];function id(n){return Object.entries(n).filter(([e])=>!sd.includes(e)).reduce((e,[t,s])=>(e=e||{},e[t]=s,e),null)}function yo(n){const e=`${rd(n)} (${n.duration}ms)`,t=id(n.values),s=n.children||t;if(s?(n.error?console.group(e):console.groupCollapsed(e),n.error&&console.error(n.error)):n.error?console.error(n.error):console.log(e),t&&console.table(t),n.children)for(const i of n.children)yo(i);s&&console.groupEnd()}function rd(n){return n.values.t==="network"?`${n.values.method} ${n.values.url}`:n.values.l&&typeof n.values.id!="undefined"?`${n.values.l} ${n.values.id}`:n.values.l&&typeof n.values.status!="undefined"?`${n.values.l} (${n.values.status})`:n.values.l&&n.error?`${n.values.l} failed`:typeof n.values.ref!="undefined"?`ref ${n.values.ref}`:n.values.l||n.values.type}const zr="m.room.encrypted",Gr="m.room.history_visibility",nd=60*1e3;class od{constructor({room:e,deviceTracker:t,olmEncryption:s,megolmEncryption:i,megolmDecryption:r,encryptionParams:o,storage:a,keyBackup:c,notifyMissingMegolmSession:l,clock:h}){this._room=e,this._deviceTracker=t,this._olmEncryption=s,this._megolmEncryption=i,this._megolmDecryption=r,this._encryptionParams=o,this._senderDeviceCache=new Map,this._storage=a,this._keyBackup=c,this._notifyMissingMegolmSession=l,this._clock=h,this._isFlushingRoomKeyShares=!1,this._lastKeyPreShareTime=null,this._keySharePromise=null,this._historyVisibility=void 0,this._disposed=!1}enableKeyBackup(e){this._keyBackup&&!!e||(this._keyBackup=e)}async restoreMissingSessionsFromBackup(e,t){const s=e.filter(h=>h.isEncrypted&&!h.isDecrypted&&h.event).map(h=>h.event),i=gi(s),r=Array.from(i.values()),o=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]),a=await Promise.all(r.map(async h=>this._megolmDecryption.hasSession(this._room.id,h.senderKey,h.sessionId,o))),c=r.filter((h,d)=>!a[d]);if(c.length)for(var l=c.length-1;l>=0;l--){const h=c[l];await t.wrap("session",d=>this._requestMissingSessionFromBackup(h.senderKey,h.sessionId,d))}}notifyTimelineClosed(){this._senderDeviceCache=new Map}async writeSync(e,t,s,i){let r=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility,s);const o=[],a=[];if(await ja(e,l=>{var h;if(l.state_key===""&&l.type===Gr){const d=(h=l==null?void 0:l.content)==null?void 0:h.history_visibility;if(d!==r)return i.wrap({l:"history_visibility changed",from:r,to:d},async u=>{r=d;const p=await this._deviceTracker.writeHistoryVisibility(this._room,r,s,u);o.push(...p.added),a.push(...p.removed)})}}),t.size){const l=await this._deviceTracker.writeMemberChanges(this._room,t,r,s);o.push(...l.added),a.push(...l.removed)}a.length&&(i.log({l:"discardOutboundSession",leftUsers:a}),this._megolmEncryption.discardOutboundSession(this._room.id,s));let c=!1;return o.length&&(c=await this._addShareRoomKeyOperationForMembers(o,s,i)),{shouldFlush:c,historyVisibility:r}}afterSync({historyVisibility:e}){this._historyVisibility=e}async _loadHistoryVisibilityIfNeeded(e,t=void 0){var s,i;if(!e){t||(t=await this._storage.readTxn([this._storage.storeNames.roomState]));const r=await t.roomState.get(this._room.id,Gr,"");if(r)return(i=(s=r.event)==null?void 0:s.content)==null?void 0:i.history_visibility}return e}async prepareDecryptAll(e,t,s,i){var c,l,h;const r=new Map,o=[];for(const d of e)d.redacted_because||((c=d.unsigned)==null?void 0:c.redacted_because)||(((l=d.content)==null?void 0:l.algorithm)!==ve&&r.set(d.event_id,new Error("Unsupported algorithm: "+((h=d.content)==null?void 0:h.algorithm))),o.push(d));const a=await this._megolmDecryption.prepareDecryptAll(this._room.id,o,t,i);return new ad(a,r,s,this,e)}async _processDecryptionResults(e,t,s,i,r,o){const a=e.filter(l=>{const h=s.get(l.event_id);return(h==null?void 0:h.code)==="MEGOLM_NO_SESSION"});if(!a.length)return;const c=gi(a);i===st.Sync&&await Promise.all(Array.from(c.values()).map(async l=>{const h=l.events.map(d=>d.event_id);return this._megolmDecryption.addMissingKeyEventIds(this._room.id,l.senderKey,l.sessionId,h,r)})),this._keyBackup&&o.wrapDetached("check key backup",async l=>{if(l.set("source",i),l.set("events",a.length),l.set("sessions",c.size),i===st.Sync){if(await this._clock.createTimeout(1e4).elapsed(),this._disposed)return;const h=await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);await Promise.all(Array.from(c).map(async([d,u])=>{await this._megolmDecryption.hasSession(this._room.id,u.senderKey,u.sessionId,h)&&c.delete(d)}))}await Promise.all(Array.from(c.values()).map(h=>l.wrap("session",d=>this._requestMissingSessionFromBackup(h.senderKey,h.sessionId,d))))})}async _verifyDecryptionResult(e,t){let s=this._senderDeviceCache.get(e.senderCurve25519Key);s||(s=await this._deviceTracker.getDeviceByCurve25519Key(e.senderCurve25519Key,t),this._senderDeviceCache.set(e.senderCurve25519Key,s)),s?e.setDevice(s):this._room.isTrackingMembers||e.setRoomNotTrackedYet()}async _requestMissingSessionFromBackup(e,t,s){if(!this._keyBackup){s.set("enabled",!1),this._notifyMissingMegolmSession();return}s.set("id",t),s.set("senderKey",e);try{const i=await this._keyBackup.getRoomKey(this._room.id,t,s);if(i){if(i.senderKey!==e){s.set("wrong_sender_key",i.senderKey),s.logLevel=s.level.Warn;return}let r=!1,o;const a=await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions]);try{r=await this._megolmDecryption.writeRoomKey(i,a),s.set("isBetter",r),r&&(o=i.eventIds)}catch(c){throw a.abort(),c}await a.complete(),r&&await s.wrap("retryDecryption",c=>this._room.notifyRoomKey(i,o||[],c))}}catch(i){i.name==="HomeServerError"&&i.errcode==="M_NOT_FOUND"?(s.error=i,s.logLevel=s.level.Error):s.set("not_found",!0)}}getEventIdsForMissingKey(e,t){return this._megolmDecryption.getEventIdsForMissingKey(this._room.id,e.senderKey,e.sessionId,t)}async ensureMessageKeyIsShared(e,t){var s;if(!(((s=this._lastKeyPreShareTime)==null?void 0:s.measure()){var r;const i=await this._megolmEncryption.ensureOutboundSession(this._room.id,this._encryptionParams);i&&((r=this._keyBackup)==null||r.flush(t),await t.wrap("share key",o=>this._shareNewRoomKey(i,e,o)))})(),await this._keySharePromise}finally{this._keySharePromise=null}}}async encrypt(e,t,s,i){var o;this._keySharePromise&&(i.set("waitForRunningKeyShare",!0),await this._keySharePromise);const r=await i.wrap("megolm encrypt",()=>this._megolmEncryption.encrypt(this._room.id,e,t,this._encryptionParams));return r.roomKeyMessage&&((o=this._keyBackup)==null||o.flush(i),await i.wrap("share key",a=>this._shareNewRoomKey(r.roomKeyMessage,s,a))),{type:zr,content:r.content}}needsToShareKeys(e){for(const t of e.values())if(t.hasJoined)return!0;return!1}async _shareNewRoomKey(e,t,s){this._historyVisibility=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility),await this._deviceTracker.trackRoom(this._room,this._historyVisibility,s);const i=await this._deviceTracker.devicesForTrackedRoom(this._room.id,t,s),r=Array.from(i.reduce((c,l)=>c.add(l.userId),new Set));let o=await this._storage.readWriteTxn([this._storage.storeNames.operations]),a;try{a=this._writeRoomKeyShareOperation(e,r,o)}catch(c){throw o.abort(),c}await this._processShareRoomKeyOperation(a,t,s)}async _addShareRoomKeyOperationForMembers(e,t,s){const i=await this._megolmEncryption.createRoomKeyMessage(this._room.id,t);return i?(s.log({l:"share key for new members",userIds:e,id:i.session_id,chain_index:i.chain_index}),this._writeRoomKeyShareOperation(i,e,t),!0):!1}async flushPendingRoomKeyShares(e,t,s){if(!this._isFlushingRoomKeyShares){this._isFlushingRoomKeyShares=!0;try{t||(t=await(await this._storage.readTxn([this._storage.storeNames.operations])).operations.getAllByTypeAndScope("share_room_key",this._room.id));for(const i of t)i.type==="share_room_key"&&await s.wrap("operation",r=>this._processShareRoomKeyOperation(i,e,r))}finally{this._isFlushingRoomKeyShares=!1}}}_writeRoomKeyShareOperation(e,t,s){const r={id:Math.floor(Math.random()*Number.MAX_SAFE_INTEGER).toString(),type:"share_room_key",scope:this._room.id,userIds:t,roomKeyMessage:e};return s.operations.add(r),r}async _processShareRoomKeyOperation(e,t,s){s.set("id",e.id),this._historyVisibility=await this._loadHistoryVisibilityIfNeeded(this._historyVisibility),await this._deviceTracker.trackRoom(this._room,this._historyVisibility,s);const i=await this._deviceTracker.devicesForRoomMembers(this._room.id,e.userIds,t,s),r=await s.wrap("olm encrypt",a=>this._olmEncryption.encrypt("m.room_key",e.roomKeyMessage,i,t,a)),o=i.filter(a=>!r.some(c=>c.device===a));await s.wrap("send",a=>this._sendMessagesToDevices(zr,r,t,a)),o.length&&await s.wrap("missingDevices",async a=>{a.set("devices",o.map(h=>h.deviceId));const c=e.userIds.filter(h=>o.some(d=>d.userId===h));a.set("unsentUserIds",c),e.userIds=c,await this._updateOperationsStore(h=>h.update(e));const l=this._megolmEncryption.createWithheldMessage(e.roomKeyMessage,"m.no_olm","OTKs exhausted");await this._sendSharedMessageToDevices("org.matrix.room_key.withheld",l,o,t,a)}),await this._updateOperationsStore(a=>a.remove(e.id))}async _updateOperationsStore(e){const t=await this._storage.readWriteTxn([this._storage.storeNames.operations]);try{e(t.operations)}catch(s){throw t.abort(),s}await t.complete()}async _sendSharedMessageToDevices(e,t,s,i,r){const o=bt(s,l=>l.userId),a={messages:Array.from(o.entries()).reduce((l,[h,d])=>(l[h]=d.reduce((u,p)=>(u[p.deviceId]=t,u),{}),l),{})},c=Ms();await i.sendToDevice(e,a,c,{log:r}).response()}async _sendMessagesToDevices(e,t,s,i){i.set("messages",t.length);const r=bt(t,c=>c.device.userId),o={messages:Array.from(r.entries()).reduce((c,[l,h])=>(c[l]=h.reduce((d,u)=>(d[u.device.deviceId]=u.content,d),{}),c),{})},a=Ms();await s.sendToDevice(e,o,a,{log:i}).response()}filterUndecryptedEventEntriesForKeys(e,t){return e.filter(s=>{var i,r;if(s.isEncrypted&&!s.isDecrypted){const{event:o}=s;if(o){const a=(i=o.content)==null?void 0:i.sender_key,c=(r=o.content)==null?void 0:r.session_id;return t.some(l=>a===l.senderKey&&c===l.sessionId)}}return!1})}dispose(){this._disposed=!0}}class ad{constructor(e,t,s,i,r){this._megolmDecryptionPreparation=e,this._extraErrors=t,this._source=s,this._roomEncryption=i,this._events=r}async decrypt(){return new cd(await this._megolmDecryptionPreparation.decrypt(),this._extraErrors,this._source,this._roomEncryption,this._events)}dispose(){this._megolmDecryptionPreparation.dispose()}}class cd{constructor(e,t,s,i,r){this._megolmDecryptionChanges=e,this._extraErrors=t,this._source=s,this._roomEncryption=i,this._events=r}async write(e,t){const{results:s,errors:i}=await this._megolmDecryptionChanges.write(e);return fi(this._extraErrors,i),await this._roomEncryption._processDecryptionResults(this._events,s,i,this._source,e,t),new ld(s,i,this._roomEncryption)}}class ld{constructor(e,t,s){this.results=e,this.errors=t,this._roomEncryption=s}applyToEntries(e){for(const t of e){const s=this.results.get(t.id);if(s)t.setDecryptionResult(s);else{const i=this.errors.get(t.id);i&&t.setDecryptionError(i)}}}verifySenders(e){return Promise.all(Array.from(this.results.values()).map(t=>this._roomEncryption._verifyDecryptionResult(t,e)))}}const yi=0,Jr=1;function hd(n,e,t){if(n){if(!n.roomIds.includes(t))return n.roomIds.push(t),n}else return n={userId:e,roomIds:[t],deviceTrackingStatus:yi},n}function dd(n){var s;const e=n.device_id;return{userId:n.user_id,deviceId:e,ed25519Key:n.keys[`ed25519:${e}`],curve25519Key:n.keys[`curve25519:${e}`],algorithms:n.algorithms,displayName:(s=n.unsigned)==null?void 0:s.device_display_name}}class ud{constructor({storage:e,getSyncToken:t,olmUtil:s,ownUserId:i,ownDeviceId:r}){this._storage=e,this._getSyncToken=t,this._identityChangedForRoom=null,this._olmUtil=s,this._ownUserId=i,this._ownDeviceId=r}async writeDeviceChanges(e,t,s){const{userIdentities:i}=t;s.set("changed",e.length),await Promise.all(e.map(async r=>{const o=await i.get(r);o&&(s.log({l:"outdated",id:r}),o.deviceTrackingStatus=yi,i.set(o))}))}async writeMemberChanges(e,t,s,i){const r=[],o=[];return await Promise.all(Array.from(t.values()).map(async a=>{if(us(a.membership,s))await this._addRoomToUserIdentity(a.roomId,a.userId,i)&&r.push(a.userId);else if(us(a.previousMembership,s)){const{roomId:c}=a;if(a.userId===this._ownUserId){const l=await i.roomMembers.getAllUserIds(c);await Promise.all(l.map(h=>this._removeRoomFromUserIdentity(c,h,i)))}else await this._removeRoomFromUserIdentity(c,a.userId,i);o.push(a.userId)}})),{added:r,removed:o}}async trackRoom(e,t,s){if(e.isTrackingMembers||!e.isEncrypted)return;const i=await e.loadMemberList(void 0,s),r=await this._storage.readWriteTxn([this._storage.storeNames.roomSummary,this._storage.storeNames.userIdentities]);try{let o;try{o=e.writeIsTrackingMembers(!0,r);const a=Array.from(i.members.values());s.set("members",a.length),await Promise.all(a.map(async c=>{us(c.membership,t)&&await this._addRoomToUserIdentity(c.roomId,c.userId,r)}))}catch(a){throw r.abort(),a}await r.complete(),e.applyIsTrackingMembersChanges(o)}finally{i.release()}}async writeHistoryVisibility(e,t,s,i){const r=[],o=[];return e.isTrackingMembers&&e.isEncrypted&&await i.wrap("rewriting userIdentities",async a=>{const c=await e.loadMemberList(s,a);try{const l=Array.from(c.members.values());a.set("members",l.length),await Promise.all(l.map(async h=>{us(h.membership,t)?await this._addRoomToUserIdentity(h.roomId,h.userId,s)&&r.push(h.userId):await this._removeRoomFromUserIdentity(h.roomId,h.userId,s)&&o.push(h.userId)}))}finally{c.release()}}),{added:r,removed:o}}async _addRoomToUserIdentity(e,t,s){const{userIdentities:i}=s,r=await i.get(t),o=hd(r,t,e);return o?(i.set(o),!0):!1}async _removeRoomFromUserIdentity(e,t,s){const{userIdentities:i,deviceIdentities:r}=s,o=await i.get(t);return o?(o.roomIds=o.roomIds.filter(a=>a!==e),o.roomIds.length===0?(i.remove(t),r.removeAllForUser(t)):i.set(o),!0):!1}async _queryKeys(e,t,s){const i=await t.queryKeys({timeout:1e4,device_keys:e.reduce((c,l)=>(c[l]=[],c),{}),token:this._getSyncToken()},{log:s}).response(),r=s.wrap("verify",c=>this._filterVerifiedDeviceKeys(i.device_keys,c)),o=await this._storage.readWriteTxn([this._storage.storeNames.userIdentities,this._storage.storeNames.deviceIdentities]);let a;try{a=(await Promise.all(r.map(async({userId:l,verifiedKeys:h})=>{const d=h.map(dd);return await this._storeQueriedDevicesForUserId(l,d,o)}))).reduce((l,h)=>l.concat(h),[]),s.set("devices",a.length)}catch(c){throw o.abort(),c}return await o.complete(),a}async _storeQueriedDevicesForUserId(e,t,s){const i=await s.deviceIdentities.getAllDeviceIds(e);for(const c of i)t.every(l=>l.deviceId!==c)&&s.deviceIdentities.remove(e,c);const r=[],o=[];await Promise.all(t.map(async c=>{if(i.includes(c.deviceId)){const l=await s.deviceIdentities.get(c.userId,c.deviceId);if(l.ed25519Key!==c.ed25519Key){r.push(l);return}}r.push(c),o.push(c)}));for(const c of o)s.deviceIdentities.set(c);const a=await s.userIdentities.get(e);return a.deviceTrackingStatus=Jr,s.userIdentities.set(a),r}_filterVerifiedDeviceKeys(e,t){const s=new Set;return Object.entries(e).map(([r,o])=>{const c=Object.entries(o).filter(([l,h])=>{var b,S;const d=h.device_id;if(h.user_id!==r||d!==l)return!1;const p=(b=h.keys)==null?void 0:b[`ed25519:${l}`],_=(S=h.keys)==null?void 0:S[`curve25519:${l}`];if(typeof p!="string"||typeof _!="string")return!1;if(s.has(_))return t.log({l:"ignore device with duplicate curve25519 key",keys:h},t.level.Warn),!1;s.add(_);const f=this._hasValidSignature(h,t);return f||t.log({l:"ignore device with invalid signature",keys:h},t.level.Warn),f}).map(([,l])=>l);return{userId:r,verifiedKeys:c}})}_hasValidSignature(e,t){var o;const s=e.device_id,i=e.user_id,r=(o=e==null?void 0:e.keys)==null?void 0:o[`${Pn}:${s}`];return Un(this._olmUtil,i,s,r,e,t)}async devicesForTrackedRoom(e,t,s){const i=await this._storage.readTxn([this._storage.storeNames.roomMembers,this._storage.storeNames.userIdentities]),r=await i.roomMembers.getAllUserIds(e);return await this._devicesForUserIds(e,r,i,t,s)}async devicesForRoomMembers(e,t,s,i){const r=await this._storage.readTxn([this._storage.storeNames.userIdentities]);return await this._devicesForUserIds(e,t,r,s,i)}async _devicesForUserIds(e,t,s,i,r){const a=(await Promise.all(t.map(f=>s.userIdentities.get(f)))).filter(f=>f&&f.roomIds.includes(e)),c=a.filter(f=>f.deviceTrackingStatus===Jr),l=a.filter(f=>f.deviceTrackingStatus===yi);r.set("uptodate",c.length),r.set("outdated",l.length);let h;l.length&&(h=await this._queryKeys(l.map(f=>f.userId),i,r));const d=await this._storage.readTxn([this._storage.storeNames.deviceIdentities]);let p=(await Promise.all(c.map(f=>d.deviceIdentities.getAllForUserId(f.userId)))).reduce((f,b)=>f.concat(b),[]);return h&&h.length&&(p=p.concat(h)),p.filter(f=>!(f.userId===this._ownUserId&&f.deviceId===this._ownDeviceId))}async getDeviceByCurve25519Key(e,t){return await t.deviceIdentities.getByCurve25519Key(e)}}class md{constructor(){this._map=new Map}async takeLock(e){let t=this._map.get(e);return t?await t.take():(t=new Mh,t.tryTake(),this._map.set(e,t)),t.released().then(()=>{Promise.resolve().then(()=>{t.isTaken||this._map.delete(e)})}),t}}class pd{constructor({key:e,platform:t}){this._key=e,this._platform=t}async readSecret(e,t){var r,o;const s=await t.accountData.get(e);if(!s)return;const i=(o=(r=s==null?void 0:s.content)==null?void 0:r.encrypted)==null?void 0:o[this._key.id];if(!i)throw new Error(`Secret ${s.type} is not encrypted for key ${this._key.id}`);if(this._key.algorithm==="m.secret_storage.v1.aes-hmac-sha2")return await this._decryptAESSecret(s.type,i);throw new Error(`Unsupported algorithm for key ${this._key.id}: ${this._key.algorithm}`)}async _decryptAESSecret(e,t){const{base64:s,utf8:i}=this._platform.encoding,r=await this._platform.crypto.derive.hkdf(this._key.binaryKey,new Uint8Array(8).buffer,i.encode(e),"SHA-256",512),o=r.slice(0,32),a=r.slice(32),c=s.decode(t.ciphertext);if(!await this._platform.crypto.hmac.verify(a,s.decode(t.mac),c,"SHA-256"))throw new Error("Bad MAC");const h=await this._platform.crypto.aes.decryptCTR({key:o,iv:s.decode(t.iv),data:c});return i.decode(h)}}const Xe="DEFAULT_KEY",Vt="pusher";class _d{constructor({storage:e,hsApi:t,sessionInfo:s,olm:i,olmWorker:r,platform:o,mediaRepository:a}){this._platform=o,this._storage=e,this._hsApi=t,this._mediaRepository=a,this._syncInfo=null,this._sessionInfo=s,this._rooms=new qt,this._roomUpdateCallback=(c,l)=>this._rooms.update(c.id,l),this._activeArchivedRooms=new Map,this._invites=new qt,this._inviteUpdateCallback=(c,l)=>this._invites.update(c.id,l),this._roomsBeingCreatedUpdateCallback=(c,l)=>{c.isCancelled?this._roomsBeingCreated.remove(c.id):this._roomsBeingCreated.update(c.id,l)},this._roomsBeingCreated=new qt,this._user=new Bl(s.userId),this._deviceMessageHandler=new mh({storage:e}),this._olm=i,this._olmUtil=null,this._e2eeAccount=null,this._deviceTracker=null,this._olmEncryption=null,this._keyLoader=null,this._megolmEncryption=null,this._megolmDecryption=null,this._getSyncToken=()=>this.syncToken,this._olmWorker=r,this._keyBackup=new we(void 0),this._observedRoomStatus=new Map,i&&(this._olmUtil=new i.Utility,this._deviceTracker=new ud({storage:e,getSyncToken:this._getSyncToken,olmUtil:this._olmUtil,ownUserId:s.userId,ownDeviceId:s.deviceId})),this._createRoomEncryption=this._createRoomEncryption.bind(this),this._forgetArchivedRoom=this._forgetArchivedRoom.bind(this),this.needsKeyBackup=new we(!1)}get fingerprintKey(){var e;return(e=this._e2eeAccount)==null?void 0:e.identityKeys.ed25519}get hasSecretStorageKey(){return this._hasSecretStorageKey}get deviceId(){return this._sessionInfo.deviceId}get userId(){return this._sessionInfo.userId}_setupEncryption(){const e=new md,t=new xh(this._e2eeAccount,Xe,this._platform.clock.now,this._user.id,this._olm,e);this._olmEncryption=new Lh(this._e2eeAccount,Xe,this._olm,this._storage,this._platform.clock.now,this._user.id,this._olmUtil,e),this._keyLoader=new Jh(this._olm,Xe,20),this._megolmEncryption=new Zh({account:this._e2eeAccount,pickleKey:Xe,olm:this._olm,storage:this._storage,keyLoader:this._keyLoader,now:this._platform.clock.now,ownDeviceId:this._sessionInfo.deviceId}),this._megolmDecryption=new Gh(this._keyLoader,this._olmWorker),this._deviceMessageHandler.enableEncryption({olmDecryption:t,megolmDecryption:this._megolmDecryption})}_createRoomEncryption(e,t){var s;if(!this._olmEncryption)throw new Error("creating room encryption before encryption got globally enabled");return t.algorithm!==ve?null:new od({room:e,deviceTracker:this._deviceTracker,olmEncryption:this._olmEncryption,megolmEncryption:this._megolmEncryption,megolmDecryption:this._megolmDecryption,storage:this._storage,keyBackup:(s=this._keyBackup)==null?void 0:s.get(),encryptionParams:t,notifyMissingMegolmSession:()=>{this._keyBackup.get()||this.needsKeyBackup.set(!0)},clock:this._platform.clock})}enableSecretStorage(e,t,s=void 0){return this._platform.logger.wrapOrRun(s,"enable secret storage",async i=>{if(!this._olm)throw new Error("olm required");this._keyBackup.get()&&(this._keyBackup.get().dispose(),this._keyBackup.set(null));const r=await Ih(e,t,this._storage,this._platform,this._olm),o=await this._storage.readTxn([this._storage.storeNames.accountData]);if(await this._createKeyBackup(r,o,i))return await this._writeSSSSKey(r,i),this._keyBackup.get().flush(i),r;throw new Error("Could not read key backup with the given key")})}async _writeSSSSKey(e,t){const s=this._keyBackup.get();if(!s)return;const i=s.version,r=await this._storage.readWriteTxn([this._storage.storeNames.session,this._storage.storeNames.inboundGroupSessions]);try{const o=await vh(e,i,r);if(t.set("previousBackupVersion",o),t.set("backupVersion",i),!!o&&o!==i){const a=await s.markAllForBackup(r);t.set("amountMarkedForBackup",a)}}catch(o){throw r.abort(),o}await r.complete()}async disableSecretStorage(){const e=await this._storage.readWriteTxn([this._storage.storeNames.session]);try{Sh(e)}catch(t){throw e.abort(),t}if(await e.complete(),this._keyBackup.get()){for(const t of this._rooms.values())t.isEncrypted&&t.enableKeyBackup(void 0);this._keyBackup.get().dispose(),this._keyBackup.set(null)}}_createKeyBackup(e,t,s){return s.wrap("enable key backup",async i=>{try{const r=new pd({key:e,platform:this._platform}),o=await Ki.fromSecretStorage(this._platform,this._olm,r,this._hsApi,this._keyLoader,this._storage,t);if(o){for(const a of this._rooms.values())a.isEncrypted&&a.enableKeyBackup(o);return this._keyBackup.set(o),!0}}catch(r){i.catch(r)}return!1})}get keyBackup(){return this._keyBackup}get hasIdentity(){return!!this._e2eeAccount}async createIdentity(e){this._olm&&(this._e2eeAccount||(this._e2eeAccount=await this._createNewAccount(this._sessionInfo.deviceId,this._storage),e.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption()),await this._e2eeAccount.generateOTKsIfNeeded(this._storage,e),await e.wrap("uploadKeys",t=>this._e2eeAccount.uploadKeys(this._storage,!1,t)))}async dehydrateIdentity(e,t){return t.set("deviceId",e.deviceId),this._olm?e.deviceId!==this.deviceId?(t.set("wrong_device",!0),!1):this._e2eeAccount?(t.set("account_already_setup",!0),!1):await e.claim(this._hsApi,t)?(this._e2eeAccount=await rt.adoptDehydratedDevice({dehydratedDevice:e,hsApi:this._hsApi,olm:this._olm,pickleKey:Xe,userId:this._sessionInfo.userId,olmWorker:this._olmWorker,deviceId:this.deviceId,storage:this._storage}),t.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption(),!0):(t.set("already_claimed",!0),!1):(t.set("no_olm",!0),!1)}_createNewAccount(e,t=void 0){return rt.create({hsApi:this._hsApi,olm:this._olm,pickleKey:Xe,userId:this._sessionInfo.userId,olmWorker:this._olmWorker,deviceId:e,storage:t})}setupDehydratedDevice(e,t=null){return this._platform.logger.wrapOrRun(t,"setupDehydratedDevice",async s=>{const i=await this._createNewAccount("temp-device-id");try{const r=await Rh(i,this._hsApi,e,"Dehydrated device",s);return s.set("deviceId",r),r}finally{i.dispose()}})}async load(e){const t=await this._storage.readTxn([this._storage.storeNames.session,this._storage.storeNames.roomSummary,this._storage.storeNames.invites,this._storage.storeNames.roomMembers,this._storage.storeNames.timelineEvents,this._storage.storeNames.timelineFragments,this._storage.storeNames.pendingEvents]);this._syncInfo=await t.session.get("sync"),this._olm&&(this._e2eeAccount=await rt.load({hsApi:this._hsApi,olm:this._olm,pickleKey:Xe,userId:this._sessionInfo.userId,deviceId:this._sessionInfo.deviceId,olmWorker:this._olmWorker,txn:t}),this._e2eeAccount&&(e.set("keys",this._e2eeAccount.identityKeys),this._setupEncryption()));const s=await this._getPendingEventsByRoom(t),i=await t.invites.getAll(),r=Promise.all(i.map(async c=>{const l=this.createInvite(c.roomId);e.wrap("invite",h=>l.load(c,h)),this._invites.add(l.id,l)})),o=await t.roomSummary.getAll(),a=Promise.all(o.map(async c=>{const l=this.createJoinedRoom(c.roomId,s.get(c.roomId));await e.wrap("room",h=>l.load(c,t,h)),this._rooms.add(l.id,l)}));await Promise.all([r,a]);for(const[c,l]of this.invites){const h=this.rooms.get(c);h&&h.setInvite(l)}}dispose(){var e,t,s,i;(e=this._olmWorker)==null||e.dispose(),this._olmWorker=void 0,(t=this._keyBackup.get())==null||t.dispose(),this._keyBackup.set(void 0),(s=this._megolmDecryption)==null||s.dispose(),this._megolmDecryption=void 0,(i=this._e2eeAccount)==null||i.dispose(),this._e2eeAccount=void 0;for(const r of this._rooms.values())r.dispose();this._rooms=void 0}async start(e,t,s){var a;if(e){const c=await this._storage.readWriteTxn([this._storage.storeNames.session]);c.session.set("serverVersions",e),await c.complete()}if(!this._keyBackup.get()){t&&await s.wrap("SSSSKeyFromDehydratedDeviceKey",async h=>{const d=await Eh(t.key,this._storage,this._platform);d&&(h.set("success",!0),await this._writeSSSSKey(d))});const c=await this._storage.readTxn([this._storage.storeNames.session,this._storage.storeNames.accountData]),l=await bh(c);l&&await this._createKeyBackup(l,c,s)&&((a=this._keyBackup.get())==null||a.flush(s)),this._keyBackup.get()||this._keyBackup.set(null)}const r=await(await this._storage.readWriteTxn([this._storage.storeNames.operations])).operations.getAll(),o=bt(r,c=>c.scope);for(const c of this._rooms.values()){let l;const h=o.get(c.id);h&&(l=bt(h,d=>d.type)),c.start(l,s)}}async _getPendingEventsByRoom(e){return(await e.pendingEvents.getAll()).reduce((s,i)=>{const r=s.get(i.roomId);return r?r.push(i):s.set(i.roomId,[i]),s},new Map)}get rooms(){return this._rooms}findDirectMessageForUserId(e){for(const[,t]of this._rooms)if(t.isDirectMessageForUserId(e))return t;for(const[,t]of this._invites)if(t.isDirectMessageForUserId(e))return t}createJoinedRoom(e,t){return new ih({roomId:e,getSyncToken:this._getSyncToken,storage:this._storage,emitCollectionChange:this._roomUpdateCallback,hsApi:this._hsApi,mediaRepository:this._mediaRepository,pendingEvents:t,user:this._user,createRoomEncryption:this._createRoomEncryption,platform:this._platform})}_createArchivedRoom(e){const t=new rh({roomId:e,getSyncToken:this._getSyncToken,storage:this._storage,emitCollectionChange:()=>{},releaseCallback:()=>this._activeArchivedRooms.delete(e),forgetCallback:this._forgetArchivedRoom,hsApi:this._hsApi,mediaRepository:this._mediaRepository,user:this._user,createRoomEncryption:this._createRoomEncryption,platform:this._platform});return this._activeArchivedRooms.set(e,t),t}get invites(){return this._invites}createInvite(e){return new uh({roomId:e,hsApi:this._hsApi,emitCollectionUpdate:this._inviteUpdateCallback,mediaRepository:this._mediaRepository,user:this._user,platform:this._platform})}get roomsBeingCreated(){return this._roomsBeingCreated}createRoom(e){let t;return this._platform.logger.runDetached("create room",async s=>{const i=`local-${Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER)}`;t=new dh(i,e,this._roomsBeingCreatedUpdateCallback,this._mediaRepository,this._platform,s),this._roomsBeingCreated.set(i,t);const r=[t.create(this._hsApi,s)];e.loadProfiles!==!1&&r.push(t.loadProfiles(this._hsApi,s)),await Promise.all(r),t.roomId&&(this.rooms.get(t.roomId)&&this._tryReplaceRoomBeingCreated(t.roomId,s),await t.adjustDirectMessageMapIfNeeded(this._user,this._storage,this._hsApi,s))}),t}async obtainSyncLock(e){var s;const t=(s=e.to_device)==null?void 0:s.events;if(Array.isArray(t)&&t.length)return await this._deviceMessageHandler.obtainSyncLock(t)}async prepareSync(e,t,s,i){var o;const r=(o=e.to_device)==null?void 0:o.events;if(Array.isArray(r)&&r.length)return await i.wrap("deviceMsgs",a=>this._deviceMessageHandler.prepareSync(r,t,s,a))}async writeSync(e,t,s,i,r){const o={syncInfo:null,e2eeAccountChanges:null},a=e.next_batch;if(a!==this.syncToken){const d={token:a,filterId:t};i.session.set("sync",d),o.syncInfo=d}const c=e.device_one_time_keys_count;this._e2eeAccount&&c&&(o.e2eeAccountChanges=this._e2eeAccount.writeSync(c,i,r));const l=e.device_lists;this._deviceTracker&&Array.isArray(l==null?void 0:l.changed)&&l.changed.length&&await r.wrap("deviceLists",d=>this._deviceTracker.writeDeviceChanges(l.changed,i,d)),s&&(o.hasNewRoomKeys=await r.wrap("deviceMsgs",d=>this._deviceMessageHandler.writeSync(s,i,d)));const h=e.account_data;if(Array.isArray(h==null?void 0:h.events))for(const d of h.events)typeof d.type=="string"&&i.accountData.set(d);return o}afterSync({syncInfo:e,e2eeAccountChanges:t}){e&&(this._syncInfo=e),this._e2eeAccount&&this._e2eeAccount.afterSync(t)}async afterSyncCompleted(e,t,s){var i;t||await this._e2eeAccount.generateOTKsIfNeeded(this._storage,s)&&await s.wrap("uploadKeys",o=>this._e2eeAccount.uploadKeys(this._storage,!1,o)),e.hasNewRoomKeys&&((i=this._keyBackup.get())==null||i.flush(s))}_tryReplaceRoomBeingCreated(e,t){for(const[,s]of this._roomsBeingCreated)if(s.roomId===e){const i=this._observedRoomStatus.get(s.id);i&&(t.log("replacing room being created").set("localId",s.id).set("roomId",s.roomId),i.set(i.get()|U.Replaced)),s.dispose(),this._roomsBeingCreated.remove(s.id);return}}applyRoomCollectionChangesAfterSync(e,t,s,i){var r,o;for(const a of t)a.shouldAdd?(this._rooms.add(a.id,a.room),this._tryReplaceRoomBeingCreated(a.id,i)):a.shouldRemove&&this._rooms.remove(a.id);for(const a of e)a.shouldAdd?this._invites.add(a.id,a.invite):a.shouldRemove&&this._invites.remove(a.id);if(this._observedRoomStatus.size!==0){for(const a of s)a.shouldAdd&&((r=this._observedRoomStatus.get(a.id))==null||r.set(U.Archived));for(const a of t)a.shouldAdd&&((o=this._observedRoomStatus.get(a.id))==null||o.set(U.Joined));for(const a of e){const c=this._observedRoomStatus.get(a.id);if(c){const l=c.get()|U.Invited;if(a.shouldAdd)c.set(l);else if(a.shouldRemove){const h=l^U.Invited;c.set(h)}}}}}_forgetArchivedRoom(e){const t=this._observedRoomStatus.get(e);t&&t.set((t.get()|U.Archived)^U.Archived)}get syncToken(){var e;return(e=this._syncInfo)==null?void 0:e.token}get syncFilterId(){var e;return(e=this._syncInfo)==null?void 0:e.filterId}get user(){return this._user}get mediaRepository(){return this._mediaRepository}enablePushNotifications(e){return e?this._enablePush():this._disablePush()}async _enablePush(){return this._platform.logger.run("enablePush",async e=>{const t=tt.createDefaultPayload(this._sessionInfo.id),s=await this._platform.notificationService.enablePush(tt,t);if(!s)return e.set("no_pusher",!0),!1;await s.enable(this._hsApi,e);const i=await this._storage.readWriteTxn([this._storage.storeNames.session]);return i.session.set(Vt,s.serialize()),await i.complete(),!0})}async _disablePush(){return this._platform.logger.run("disablePush",async e=>{await this._platform.notificationService.disablePush();const s=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(Vt);if(!s)return!0;await new tt(s).disable(this._hsApi,e);const r=await this._storage.readWriteTxn([this._storage.storeNames.session]);return r.session.remove(Vt),await r.complete(),!0})}async arePushNotificationsEnabled(){return await this._platform.notificationService.isPushEnabled()?!!await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(Vt):!1}async checkPusherEnabledOnHomeserver(){const t=await(await this._storage.readTxn([this._storage.storeNames.session])).session.get(Vt);if(!t)return!1;const s=new tt(t),i=await this._hsApi.getPushers().response();return((i==null?void 0:i.pushers)||[]).map(o=>new tt(o)).some(o=>o.equals(s))}async getRoomStatus(e){if(!!this._roomsBeingCreated.get(e))return U.BeingCreated;if(!!this._rooms.get(e))return U.Joined;{const i=!!this._invites.get(e),o=await(await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary])).archivedRoomSummary.has(e);return i&&o?U.Invited|U.Archived:i?U.Invited:o?U.Archived:U.None}}async observeRoomStatus(e){let t=this._observedRoomStatus.get(e);if(!t){const s=await this.getRoomStatus(e);t=new ci(s,()=>{this._observedRoomStatus.delete(e)}),this._observedRoomStatus.set(e,t)}return t}createOrGetArchivedRoomForSync(e){let t=this._activeArchivedRooms.get(e);return t?t.retain():t=this._createArchivedRoom(e),t}loadArchivedRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"loadArchivedRoom",async s=>{s.set("id",e);const i=this._activeArchivedRooms.get(e);if(i)return i.retain(),i;const r=await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary,this._storage.storeNames.roomMembers]),o=await r.archivedRoomSummary.get(e);if(o){const a=this._createArchivedRoom(e);return await a.load(o,r,s),a}})}joinRoom(e,t=null){return this._platform.logger.wrapOrRun(t,"joinRoom",async s=>(await this._hsApi.joinIdOrAlias(e,{log:s}).response()).room_id)}}class fd{constructor({username:e,password:t,homeserver:s}){this._username=e,this._password=t,this.homeserver=s}async login(e,t,s){return await e.passwordLogin(this._username,this._password,t,{log:s}).response()}}class gd{constructor({homeserver:e,loginToken:t}){this.homeserver=e,this._loginToken=t}async login(e,t,s){return await e.tokenLogin(this._loginToken,Ms(),t,{log:s}).response()}}class yd{constructor(e){this._homeserver=e}get homeserver(){return this._homeserver}createSSORedirectURL(e){return`${this._homeserver}/_matrix/client/r0/login/sso/redirect?redirectUrl=${e}`}}class $i{constructor(e,t){this._session=e,this._params=t}setNextStage(e){this._nextStage=e}get nextStage(){return this._nextStage}}class wd extends $i{generateAuthenticationData(){return{session:this._session,type:this.type}}get type(){return"m.login.dummy"}}class vd extends $i{generateAuthenticationData(){return{session:this._session,type:this.type}}get type(){return"m.login.terms"}get privacyPolicy(){var e;return(e=this._params)==null?void 0:e.policies.privacy_policy}get termsOfService(){var e;return(e=this._params)==null?void 0:e.policies.terms_of_service}}class bd extends $i{constructor(e,t,s){super(e,t),this._type=s}generateAuthenticationData(){if(!this._token)throw new Error("No token provided for TokenAuth");return{session:this._session,type:this._type,token:this._token}}setToken(e){this._token=e}get type(){return this._type}}class Sd{constructor(e,t,s){this._hsApi=e,this._accountDetails=t,this._flowSelector=s!=null?s:i=>i[0]}async start(){const e=await this._hsApi.register(this._accountDetails.username,this._accountDetails.password,this._accountDetails.initialDeviceDisplayName,void 0,this._accountDetails.inhibitLogin).response();return this.parseStagesFromResponse(e)}async submitStage(e){const t=e.generateAuthenticationData(),{username:s,password:i,initialDeviceDisplayName:r,inhibitLogin:o}=this._accountDetails,a=this._hsApi.register(s,i,r,t,o),c=await a.response(),l=await a.responseCode(),h=yr(ft({},c),{status:l});return this.parseRegistrationResponse(h,e)}parseStagesFromResponse(e){const{session:t,params:s}=e,i=this._flowSelector(e.flows);if(!i)throw new Error("flowSelector did not return any flow!");let r,o;for(const a of i.stages){const c=this._createRegistrationStage(a,t,s);r?(o.setNextStage(c),o=c):(r=c,o=c)}return r}async parseRegistrationResponse(e,t){var s;switch(e.status){case 200:this._sessionInfo=e;return;case 401:if((s=e.completed)!=null&&s.includes(t.type))return t.nextStage;throw new Error("This stage could not be completed!")}}_createRegistrationStage(e,t,s){switch(e){case"m.login.dummy":return new wd(t,s==null?void 0:s[e]);case"m.login.terms":return new vd(t,s==null?void 0:s[e]);case"org.matrix.msc3231.login.registration_token":case"m.login.registration_token":return new bd(t,s==null?void 0:s[e],e);default:throw new Error(`Unknown stage: ${e}`)}}get sessionInfo(){return this._sessionInfo}}const M=xe("NotLoading","Login","LoginFailed","QueryAccount","AccountSetup","Loading","SessionSetup","Migrating","FirstSync","Error","Ready"),Ce=xe("Connection","Credentials","Unknown");class ji{constructor(e){this._platform=e,this._sessionStartedByReconnector=!1,this._status=new we(M.NotLoading),this._error=null,this._loginFailure=null,this._reconnector=null,this._session=null,this._sync=null,this._sessionId=null,this._storage=null,this._requestScheduler=null,this._olmPromise=e.loadOlm(),this._workerPromise=e.loadOlmWorker(),this._accountSetup=void 0}createNewSessionId(){return Math.floor(this._platform.random()*Number.MAX_SAFE_INTEGER).toString()}get sessionId(){return this._sessionId}async startWithExistingSession(e){this._status.get()===M.NotLoading&&(this._status.set(M.Loading),await this._platform.logger.run("load session",async t=>{t.set("id",e);try{const s=await this._platform.sessionInfoStorage.get(e);if(!s)throw new Error("Invalid session id: "+e);await this._loadSessionInfo(s,null,t),t.set("status",this._status.get())}catch(s){t.catch(s),this._error=s,this._status.set(M.Error)}}))}_parseLoginOptions(e,t){const s=e.flows,i={homeserver:t};for(const r of s)r.type==="m.login.password"?i.password=(o,a)=>new fd({homeserver:t,username:o,password:a}):r.type==="m.login.sso"&&s.find(o=>o.type==="m.login.token")?i.sso=new yd(t):r.type==="m.login.token"&&(i.token=o=>new gd({homeserver:t,loginToken:o}));return i}queryLogin(e){return new Mn(async t=>{e=await ma(e,(r,o)=>t(this._platform.request(r,o)));const s=new Ze({homeserver:e,request:this._platform.request}),i=await t(s.getLoginFlows()).response();return this._parseLoginOptions(i,e)})}async startRegistration(e,t,s,i,r){const o=this._platform.request,a=new Ze({homeserver:e,request:o});return new Sd(a,{username:t,password:s,initialDeviceDisplayName:i},r)}async startWithLogin(e,{inspectAccountSetup:t}={}){const s=this._status.get();s!==M.LoginFailed&&s!==M.NotLoading&&s!==M.Error||(this._resetStatus(),await this._platform.logger.run("login",async i=>{this._status.set(M.Login);const r=this._platform.clock;let o;try{const c=this._platform.request,l=new Ze({homeserver:e.homeserver,request:c}),h=await e.login(l,"Hydrogen",i),d=this.createNewSessionId();o={id:d,deviceId:h.device_id,userId:h.user_id,homeServer:e.homeserver,homeserver:e.homeserver,accessToken:h.access_token,lastUsed:r.now()},i.set("id",d)}catch(c){this._error=c,c.name==="HomeServerError"?(c.errcode==="M_FORBIDDEN"?this._loginFailure=Ce.Credentials:this._loginFailure=Ce.Unknown,i.set("loginFailure",this._loginFailure),this._status.set(M.LoginFailed)):c.name==="ConnectionError"?(this._loginFailure=Ce.Connection,this._status.set(M.LoginFailed)):this._status.set(M.Error);return}let a;t&&(a=await this._inspectAccountAfterLogin(o,i),a&&(o.deviceId=a.deviceId)),await this._platform.sessionInfoStorage.add(o);try{await this._loadSessionInfo(o,a,i),i.set("status",this._status.get())}catch(c){i.catch(c),a==null||a.dispose(),this._error=c,this._status.set(M.Error)}}))}async _loadSessionInfo(e,t,s){s.set("appVersion",this._platform.version);const i=this._platform.clock;this._sessionStartedByReconnector=!1,this._status.set(M.Loading),this._reconnector=new ba({onlineStatus:this._platform.onlineStatus,retryDelay:new Dn(i.createTimeout),createMeasure:i.createMeasure});const r=new Ze({homeserver:e.homeServer,accessToken:e.accessToken,request:this._platform.request,reconnector:this._reconnector});this._sessionId=e.id,this._storage=await this._platform.storageFactory.create(e.id,s);const o={id:e.id,deviceId:e.deviceId,userId:e.userId,homeserver:e.homeServer},a=await this._olmPromise;let c=null;this._workerPromise&&(c=await this._workerPromise),this._requestScheduler=new Ra({hsApi:r,clock:i}),this._requestScheduler.start();const l=new Ea({homeserver:e.homeServer,platform:this._platform});if(this._session=new _d({storage:this._storage,sessionInfo:o,hsApi:this._requestScheduler.hsApi,olm:a,olmWorker:c,mediaRepository:l,platform:this._platform}),await this._session.load(s),t?(await s.wrap("dehydrateIdentity",h=>this._session.dehydrateIdentity(t,h)),await this._session.setupDehydratedDevice(t.key,s)):this._session.hasIdentity||(this._status.set(M.SessionSetup),await s.wrap("createIdentity",h=>this._session.createIdentity(h))),this._sync=new Ma({hsApi:this._requestScheduler.hsApi,storage:this._storage,session:this._session,logger:this._platform.logger}),this._reconnectSubscription=this._reconnector.connectionStatus.subscribe(h=>{h===$t.Online&&this._platform.logger.runDetached("reconnect",async d=>{this._requestScheduler.start(),this._sync.start(),this._sessionStartedByReconnector=!0;const u=t;t=void 0,await d.wrap("session start",p=>this._session.start(this._reconnector.lastVersionsResponse,u,p))})}),await s.wrap("wait first sync",()=>this._waitForFirstSync()),!this._isDisposed&&(this._status.set(M.Ready),!this._sessionStartedByReconnector)){const h=await r.versions({timeout:1e4,log:s}).response();if(this._isDisposed)return;const d=t;t=void 0,await s.wrap("session start",u=>this._session.start(h,d,u))}}async _waitForFirstSync(){this._sync.start(),this._status.set(M.FirstSync),this._waitForFirstSyncHandle=this._sync.status.waitFor(e=>{var t;return e===L.Stopped?((t=this._sync.error)==null?void 0:t.name)!=="ConnectionError":e===L.Syncing});try{if(await this._waitForFirstSyncHandle.promise,this._sync.status.get()===L.Stopped&&this._sync.error)throw this._sync.error}catch(e){if(e.name==="AbortError")return;throw e}finally{this._waitForFirstSyncHandle=null}}_inspectAccountAfterLogin(e,t){return t.wrap("inspectAccount",async s=>{var a;this._status.set(M.QueryAccount);const i=new Ze({homeserver:e.homeServer,accessToken:e.accessToken,request:this._platform.request}),r=await this._olmPromise;let o;try{o=await kh(i,r,this._platform,s)}catch(c){if(c.name==="HomeServerError")s.set("not_supported",!0);else throw c}if(o){let c;const l=new Promise(d=>c=d);this._accountSetup=new Id(o,c),this._status.set(M.AccountSetup),await l;const h=(a=this._accountSetup)==null?void 0:a._dehydratedDevice;return this._accountSetup=null,h}})}get accountSetup(){return this._accountSetup}get loadStatus(){return this._status}get loadError(){return this._error}get loginFailure(){return this._loginFailure}get sync(){return this._sync}get session(){return this._session}get reconnector(){return this._reconnector}get _isDisposed(){return!this._reconnector}startLogout(e){return this._platform.logger.run("logout",async t=>{this._sessionId=e,t.set("id",this._sessionId);const s=await this._platform.sessionInfoStorage.get(this._sessionId);if(!s)throw new Error(`Could not find session for id ${this._sessionId}`);try{await new Ze({homeserver:s.homeServer,accessToken:s.accessToken,request:this._platform.request}).logout({log:t}).response()}catch{}await this.deleteSession(t)})}dispose(){this._reconnectSubscription&&(this._reconnectSubscription(),this._reconnectSubscription=null),this._reconnector=null,this._requestScheduler&&(this._requestScheduler.stop(),this._requestScheduler=null),this._sync&&(this._sync.stop(),this._sync=null),this._session&&(this._session.dispose(),this._session=null),this._waitForFirstSyncHandle&&(this._waitForFirstSyncHandle.dispose(),this._waitForFirstSyncHandle=null),this._storage&&(this._storage.close(),this._storage=null)}async deleteSession(e){this._sessionId&&(this.dispose(),await Promise.all([e.wrap("storageFactory",()=>this._platform.storageFactory.delete(this._sessionId)),e.wrap("sessionInfoStorage",()=>this._platform.sessionInfoStorage.delete(this._sessionId))]),this._sessionId=null)}_resetStatus(){this._status.set(M.NotLoading),this._error=null,this._loginFailure=null}}class Id{constructor(e,t){this._encryptedDehydratedDevice=e,this._dehydratedDevice=void 0,this._finishStage=t}get encryptedDehydratedDevice(){return this._encryptedDehydratedDevice}finish(e){this._dehydratedDevice=e,this._finishStage()}}class A extends Ls{constructor(e){super(),this._isDisposed=!1,this._options=e}childOptions(e){return Object.assign({},this._options,e)}get options(){return this._options}getOption(e){return this._options[e]}observeNavigation(e,t){const i=this.navigation.observe(e).subscribe(r=>{t(r,e)});this.track(i)}track(e){return this.disposables||(this.disposables=new Ni),this.disposables.track(e)}untrack(e){if(this.disposables)return this.disposables.untrack(e)}dispose(){this.disposables&&this.disposables.dispose(),this._isDisposed=!0}get isDisposed(){return this._isDisposed}disposeTracked(e){if(this.disposables)return this.disposables.disposeTracked(e)}i18n(e,...t){let s="";for(let i=0;it.toLowerCase().trim())}matches(e){const t=e.name.toLowerCase();return this._parts.every(s=>t.includes(s))}}class Md extends Ct{constructor(e,t){super(),this._source=e,this._apply=t,this._subscription=null}hasApply(){return!!this._apply}setApply(e){this._apply=e,e&&this.applyOnce(this._apply)}applyOnce(e){for(const[t,s]of this._source)e(t,s)}onAdd(e,t){this._apply&&this._apply(e,t),this.emitAdd(e,t)}onRemove(e,t){this.emitRemove(e,t)}onUpdate(e,t,s){this._apply&&this._apply(e,t,s),this.emitUpdate(e,t,s)}onSubscribeFirst(){this._subscription=this._source.subscribe(this),this._apply&&this.applyOnce(this._apply),super.onSubscribeFirst()}onUnsubscribeLast(){super.onUnsubscribeLast(),this._subscription=this._subscription()}onReset(){this._apply&&this.applyOnce(this._apply),this.emitReset()}[Symbol.iterator](){return this._source[Symbol.iterator]()}get size(){return this._source.size}get(e){return this._source.get(e)}}class Ad{constructor(e){this._observables=new Map,this._allowsChild=e,this._path=new ke([],e),this._pathObservable=new we(this._path)}get pathObservable(){return this._pathObservable}get path(){return this._path}push(e,...t){const s=this.path.with(new se(e,...t));s&&this.applyPath(s)}applyPath(e){const t=this._path;this._path=e;for(let s=t.segments.length-1;s>=0;s-=1){const i=t.segments[s];if(!this._path.get(i.type)){const r=this._observables.get(i.type);r==null||r.emitIfChanged()}}for(const s of this._path.segments){const i=this._observables.get(s.type);i==null||i.emitIfChanged()}this._pathObservable.set(this._path)}observe(e){let t=this._observables.get(e);return t||(t=new Nd(this,e),this._observables.set(e,t)),t}pathFrom(e){let t,s;for(s=0;s=-1)}until(e){const t=this._segments.findIndex(s=>s.type===e);return t!==-1?new ke(this._segments.slice(0,t+1),this._allowsChild):new ke([],this._allowsChild)}get(e){return this._segments.find(t=>t.type===e)}replace(e){const t=this._segments.findIndex(s=>s.type===e.type);if(t!==-1){const s=this._segments[t-1];if(this._allowsChild(s,e)){const i=this._segments[t+1];if(!i||this._allowsChild(e,i)){const r=this._segments.slice();return r[t]=e,new ke(r,this._allowsChild)}}}}get segments(){return this._segments}}class Nd extends kt{constructor(e,t){var s;super(),this._navigation=e,this._type=t,this._lastSetValue=(s=e.path.get(t))==null?void 0:s.value}get(){const t=this._navigation.path.get(this._type);return t==null?void 0:t.value}emitIfChanged(){const e=this.get();xd(e,this._lastSetValue)||(this._lastSetValue=e,this.emit(e))}}class Dd{constructor(e,t,s,i){this._isApplyingUrl=!1,this._history=e,this._navigation=t,this._parseUrlPath=s,this._stringifyPath=i,this._defaultSessionId=this._getLastSessionId()}_getLastSessionId(){var s;const t=(s=this._urlAsNavPath(this._history.getLastSessionUrl()||"").get("session"))==null?void 0:s.value;if(typeof t=="string")return t}attach(){this._subscription=this._history.subscribe(e=>this._applyUrl(e)),this._pathSubscription=this._navigation.pathObservable.subscribe(e=>this._applyNavPathToHistory(e)),this._applyUrl(this._history.get())}dispose(){this._subscription&&(this._subscription=this._subscription()),this._pathSubscription&&(this._pathSubscription=this._pathSubscription())}_applyNavPathToHistory(e){const t=this.urlForPath(e);t!==this._history.get()&&(this._isApplyingUrl?this._history.replaceUrlSilently(t):this._history.pushUrlSilently(t))}_applyNavPathToNavigation(e){this._isApplyingUrl=!0,this._navigation.applyPath(e),this._isApplyingUrl=!1}_urlAsNavPath(e){const t=this._history.urlAsPath(e);return this._navigation.pathFrom(this._parseUrlPath(t,this._navigation.path,this._defaultSessionId))}_applyUrl(e){const t=this._urlAsNavPath(e);this._applyNavPathToNavigation(t)}pushUrl(e){this._history.pushUrl(e)}tryRestoreLastUrl(){const e=this._urlAsNavPath(this._history.getLastSessionUrl()||"");return e.segments.length!==0?(this._applyNavPathToNavigation(e),!0):!1}urlForSegments(e){let t=this._navigation.path;for(const s of e)if(t=t.with(s),!t)return;return this.urlForPath(t)}urlForSegment(e,...t){return this.urlForSegments([this._navigation.segment(e,...t)])}urlUntilSegment(e){return this.urlForPath(this._navigation.path.until(e))}urlForPath(e){return this._history.pathAsUrl(this._stringifyPath(e))}openRoomActionUrl(e){const t=`${this._stringifyPath(this._navigation.path.until("session"))}/open-room/${e}`;return this._history.pathAsUrl(t)}createSSOCallbackURL(){return window.location.origin}normalizeUrl(){this._history.replaceUrlSilently(`${window.location.origin}/${window.location.hash}`)}}function Vd(){return new Ad(Od)}function Ld({history:n,navigation:e}){return new Dd(n,e,Ud,Fd)}function Od(n,e){const{type:t}=e;switch(n==null?void 0:n.type){case void 0:return t==="login"||t==="session"||t==="sso"||t==="logout";case"session":return t==="room"||t==="rooms"||t==="settings"||t==="create-room";case"rooms":return t==="room"||t==="empty-grid-tile";case"room":return t==="lightbox"||t==="right-panel";case"right-panel":return t==="details"||t==="members"||t==="member";default:return!1}}function Pd(n,e,t){if(n.value.includes(e))return n;{const s=t.get("empty-grid-tile"),i=t.get("room");let r=0;s?r=s.value:i&&(r=n.value.indexOf(i.value));const o=n.value.slice();return o[r]=e,new se("rooms",o)}}function Yr(n,e,...t){n.push(new se("right-panel")),n.push(new se(e,...t))}function vi(n,e){const t=n.path.segments,s=t.findIndex(r=>r.type==="right-panel");let i=e;return s!==-1&&(i=e.until("room"),i=i.with(t[s]),i=i.with(t[s+1])),i}function Ud(n,e,t){const s=n.substring(1).split("/"),i=s[Symbol.iterator](),r=[];let o;for(;!(o=i.next()).done;){const a=o.value;if(a==="rooms"){const c=i.next().value;if(c===void 0)break;const l=c.split(",");r.push(new se(a,l));const h=parseInt(i.next().value||"0",10),d=l[h];d?r.push(new se("room",d)):r.push(new se("empty-grid-tile",h))}else if(a==="open-room"){const c=i.next().value;if(!c)break;const l=e.get("rooms");if(l&&r.push(Pd(l,c,e)),r.push(new se("room",c)),s.findIndex(u=>u==="open-room")>=s.length-2){const u=e.segments,p=u.findIndex(_=>_.type==="right-panel");p!==-1&&r.push(...u.slice(p))}}else if(a==="last-session"){let c=e.get("session");typeof(c==null?void 0:c.value)!="string"&&t&&(c=new se("session",t)),c&&r.push(c)}else if(a==="details"||a==="members")Yr(r,a);else if(a==="member"){const c=i.next().value;if(!c)break;Yr(r,a,c)}else if(a.includes("loginToken")){const c=a.split("=").pop();r.push(new se("sso",c))}else{const c=i.next().value;r.push(new se(a,c))}}return r}function Fd(n){let e="",t;for(const s of n.segments){switch(s.type){case"rooms":e+=`/rooms/${s.value.join(",")}`;break;case"empty-grid-tile":e+=`/${s.value}`;break;case"room":(t==null?void 0:t.type)==="rooms"?e+=`/${t.value.indexOf(s.value)}`:e+=`/${s.type}/${s.value}`;break;case"right-panel":case"sso":continue;default:e+=`/${s.type}`,s.value&&s.value!==!0&&(e+=`/${s.value}`)}t=s}return e}class Bd extends A{constructor(e){super(e);const{session:t}=e;this._tileViewModelsMap=this._mapTileViewModels(t.roomsBeingCreated,t.invites,t.rooms),this._tileViewModelsFilterMap=new Md(this._tileViewModelsMap),this._tileViewModels=this._tileViewModelsFilterMap.sortValues((s,i)=>s.compare(i)),this._currentTileVM=null,this._setupNavigation(),this._closeUrl=this.urlCreator.urlForSegment("session"),this._settingsUrl=this.urlCreator.urlForSegment("settings"),this._createRoomUrl=this.urlCreator.urlForSegment("create-room")}_mapTileViewModels(e,t,s){return t.join(e,s).mapValues((r,o)=>{var l;let a;return r.isBeingCreated?a=new Cd(this.childOptions({roomBeingCreated:r,emitChange:o})):r.isInvite?a=new Rd(this.childOptions({invite:r,emitChange:o})):a=new kd(this.childOptions({room:r,emitChange:o})),((l=this.navigation.path.get("room"))==null?void 0:l.value)===r.id&&(a.open(),this._updateCurrentVM(a)),a})}_updateCurrentVM(e){var t;(t=this._currentTileVM)==null||t.close(),this._currentTileVM=e}get closeUrl(){return this._closeUrl}get settingsUrl(){return this._settingsUrl}get createRoomUrl(){return this._createRoomUrl}_setupNavigation(){const e=this.navigation.observe("room");this.track(e.subscribe(s=>this._open(s)));const t=this.navigation.observe("rooms");this.gridEnabled=!!t.get(),this.track(t.subscribe(s=>{const i=this.gridEnabled^!!s;this.gridEnabled=!!s,i&&this.emitChange("gridEnabled")}))}_open(e){var t,s;(t=this._currentTileVM)==null||t.close(),this._currentTileVM=null,e&&(this._currentTileVM=this._tileViewModelsMap.get(e),(s=this._currentTileVM)==null||s.open())}toggleGrid(){const e=this.navigation.path.get("room");let t=this.navigation.path.until("session");this.gridEnabled?e&&(t=t.with(e),t=vi(this.navigation,t)):e?(t=t.with(this.navigation.segment("rooms",[e.value])),t=t.with(e),t=vi(this.navigation,t)):(t=t.with(this.navigation.segment("rooms",[])),t=t.with(this.navigation.segment("empty-grid-tile",0))),this.navigation.applyPath(t)}get tileViewModels(){return this._tileViewModels}clearFilter(){this._tileViewModelsFilterMap.setApply(null),this._tileViewModelsFilterMap.applyOnce((e,t)=>t.hidden=!1)}setFilter(e){if(e=e.trim(),e.length===0)return this.clearFilter(),!1;{const t=!this._tileViewModelsFilterMap.hasApply(),s=new Td(e);return this._tileViewModelsFilterMap.setApply((i,r)=>{r.hidden=!s.matches(r)}),t}}}class fe{constructor(e,t,s,i){this._remove=e,this._update=t,this._replace=s,this._updateParams=i}get shouldReplace(){return this._replace}get shouldRemove(){return this._remove}get shouldUpdate(){return this._update}get updateParams(){return this._updateParams}static Remove(){return new fe(!0,!1,!1,null)}static Update(e){return new fe(!1,!0,!1,e)}static Nothing(){return new fe(!1,!1,!1,null)}static Replace(e){return new fe(!1,!1,!0,e)}}class Kd extends Rt{constructor(e,t){super(),this._entries=e,this._tiles=null,this._entrySubscription=null,this._tileOptions=t,this._emitSpontanousUpdate=this._emitSpontanousUpdate.bind(this)}_createTile(e){const t=this._tileOptions.tileClassForEntry(e);if(t)return new t(e,this._tileOptions)}_emitSpontanousUpdate(e,t){const s=e.lowerEntry,i=this._findTileIdx(s);this.emitUpdate(i,e,t)}onSubscribeFirst(){this._entrySubscription=this._entries.subscribe(this),this._populateTiles()}_populateTiles(){this._tiles=[];let e=null;for(let s of this._entries)(!e||!e.tryIncludeEntry(s))&&(e=this._createTile(s),e&&this._tiles.push(e));let t=null;for(let s of this._tiles)t&&t.updateNextSibling(s),s.updatePreviousSibling(t),t=s;t&&t.updateNextSibling(null);for(const s of this._tiles)s.setUpdateEmit(this._emitSpontanousUpdate)}_findTileIdx(e){return He(this._tiles,e,(t,s)=>-s.compareEntry(t))}_findTileAtIdx(e,t){const s=this._getTileAtIdx(t);if(s&&s.compareEntry(e)===0)return s}_getTileAtIdx(e){return e>=0&&ei.compare(r)),s=this._tiles[t];return(s==null?void 0:s.compare(e))===0?t:-1}sliceIterator(e,t){return this._tiles.slice(e,t)[Symbol.iterator]()}}class $d extends A{constructor(e){super(e);const{timeline:t,tileOptions:s}=e;this._timeline=this.track(t),this._tiles=new Kd(t.entries,s),this._startTile=null,this._endTile=null,this._topLoadingPromise=null,this._requestedStartTile=null,this._requestedEndTile=null,this._requestScheduled=!1,this._showJumpDown=!1}setVisibleTileRange(e,t){this._requestedStartTile=e,this._requestedEndTile=t,this._requestScheduled||(Promise.resolve().then(()=>{this._setVisibleTileRange(this._requestedStartTile,this._requestedEndTile),this._requestScheduled=!1}),this._requestScheduled=!0)}_setVisibleTileRange(e,t){let s;if(e&&t){this._startTile=e,this._endTile=t;const i=this._tiles.getTileIndex(this._startTile),r=this._tiles.getTileIndex(this._endTile);for(const o of this._tiles.sliceIterator(i,r+1))o.notifyVisible();s=i<10,this._setShowJumpDown(r{this._topLoadingPromise=null,i||this.setVisibleTileRange(this._requestedStartTile,this._requestedEndTile)}))}get tiles(){return this._tiles}_setShowJumpDown(e){this._showJumpDown!==e&&(this._showJumpDown=e,this.emitChange("showJumpDown"))}get showJumpDown(){return this._showJumpDown}}class jd extends A{constructor(e){super(e.options),this._roomVM=e,this._isEmpty=!0,this._replyVM=null}setReplyingTo(e){var s;(new Boolean(e)!==new Boolean(this._replyVM)||!((s=this._replyVM)!=null&&s.id.equals(e.asEventKey())))&&(this._replyVM=this.disposeTracked(this._replyVM),e&&(this._replyVM=this.track(this._roomVM._createTile(e)),this._replyVM.notifyVisible()),this.emitChange("replyViewModel"),this.emit("focus"))}clearReplyingTo(){this.setReplyingTo(null)}get replyViewModel(){return this._replyVM}get isEncrypted(){return this._roomVM.isEncrypted}async sendMessage(e){const t=await this._roomVM._sendMessage(e,this._replyVM);return t&&(this._isEmpty=!0,this.emitChange("canSend"),this.clearReplyingTo()),t}sendPicture(){this._roomVM._pickAndSendPicture()}sendFile(){this._roomVM._pickAndSendFile()}sendVideo(){this._roomVM._pickAndSendVideo()}get canSend(){return!this._isEmpty}async setInput(e){const t=this._isEmpty;this._isEmpty=e.length===0,t&&!this._isEmpty&&this._roomVM._room.ensureMessageKeyIsShared(),t!==this._isEmpty&&this.emitChange("canSend")}get kind(){return"composer"}}function Ht(n){return{w:n.width,h:n.height,mimetype:n.blob.mimeType,size:n.blob.size}}class ss extends A{constructor(e,t){super(t),this._entry=e,this._emitUpdate=void 0}get shape(){return null}get isContinuation(){return!1}get hasDateSeparator(){return!1}get id(){return this._entry.asEventKey()}get eventId(){return this._entry.id}get isPending(){return this._entry.isPending}get isUnsent(){return this._entry.isPending&&this._entry.pendingEvent.status!==V.Sent}get canAbortSending(){return this._entry.isPending&&!this._entry.pendingEvent.hasStartedSending}abortSending(){var e;(e=this._entry.pendingEvent)==null||e.abort()}setUpdateEmit(e){this._emitUpdate=e}emitChange(e){this._emitUpdate&&this._emitUpdate(this,e),super.emitChange(e)}get upperEntry(){return this._entry}get lowerEntry(){return this._entry}compare(e){return this.upperEntry.compare(e.upperEntry)}compareEntry(e){return this._entry.compare(e)}updateEntry(e,t){const s=this.shape==="redacted";return!e.isGap&&e.isRedacted!==s?fe.Replace("shape"):(this._entry=e,fe.Update(t))}removeEntry(){return!0}tryIncludeEntry(){return!1}updatePreviousSibling(){}updateNextSibling(){}notifyVisible(){}dispose(){this.setUpdateEmit(null),super.dispose()}get _room(){return this._roomVM.room}get _roomVM(){return this._options.roomVM}get _timeline(){return this._options.timeline}get _powerLevels(){return this._timeline.powerLevels}get _ownMember(){return this._options.timeline.me}}class qd extends ss{constructor(e,t){super(e,t),this._loading=!1,this._error=null,this._isAtTop=!0,this._siblingChanged=!1}async fill(){if(!this._loading&&!this._entry.edgeReached){this._loading=!0,this.emitChange("isLoading");try{await this._room.fillGap(this._entry,10)}catch(e){throw console.error(`room.fillGap(): ${e.message}: +${e.stack}`),this._error=e,this.emitChange("error"),e}finally{this._loading=!1,this.emitChange("isLoading")}return!0}return!1}async notifyVisible(){let e=0,t;this._siblingChanged=!1;do t=await this.fill(),e=e+1;while(e<10&&!this._siblingChanged&&t&&!this.isDisposed)}get isAtTop(){return this._isAtTop}updatePreviousSibling(e){super.updatePreviousSibling(e);const t=!e;this._isAtTop!==t&&(this._isAtTop=t,this.emitChange("isAtTop")),this._siblingChanged=!0}updateNextSibling(){this._siblingChanged=!0}updateEntry(e,t){return super.updateEntry(e,t),e.isGap?fe.Nothing():fe.Remove()}get shape(){return"gap"}get isLoading(){return this._loading}get error(){return this._error?`Could not load ${this._entry.prev_batch?"previous":"next"} messages: ${this._error.message}`:null}}class Wd{constructor(e){this._parentTile=e,this._map=new qt,this._reactions=this._map.sortValues((t,s)=>t._compare(s))}update(e,t){if(e){for(const s in e)if(e.hasOwnProperty(s)){const i=e[s],r=this._map.get(s);r?r._tryUpdate(i)&&this._map.update(s):this._map.add(s,new Xr(s,i,null,this._parentTile))}}if(t)for(const[s,i]of t.entries()){const r=this._map.get(s);r?(r._tryUpdatePending(i),this._map.update(s)):this._map.add(s,new Xr(s,null,i,this._parentTile))}for(const s of this._map.keys()){const i=t==null?void 0:t.has(s),r=e==null?void 0:e.hasOwnProperty(s);!r&&!i?this._map.remove(s):r?i||this._map.get(s)._tryUpdatePending(null)&&this._map.update(s):this._map.get(s)._tryUpdate(null)&&this._map.update(s)}}get reactions(){return this._reactions}getReaction(e){return this._map.get(e)}}class Xr{constructor(e,t,s,i){this._key=e,this._annotation=t,this._pending=s,this._parentTile=i,this._isToggling=!1}_tryUpdate(e){const t=!!this._annotation!=!!e,i=this._annotation&&e&&(e.me!==this._annotation.me||e.count!==this._annotation.count||e.firstTimestamp!==this._annotation.firstTimestamp);return t||i?(this._annotation=e,!0):!1}_tryUpdatePending(e){return!e&&!this._pending?!1:(this._pending=e,!0)}get key(){return this._key}get count(){var e,t;return(((e=this._pending)==null?void 0:e.count)||0)+(((t=this._annotation)==null?void 0:t.count)||0)}get isPending(){return this._pending!==null}get isActive(){var e;return((e=this._annotation)==null?void 0:e.me)||this.isPending}get firstTimestamp(){let e=Number.MAX_SAFE_INTEGER;return this._annotation&&(e=Math.min(e,this._annotation.firstTimestamp)),this._pending&&(e=Math.min(e,this._pending.firstTimestamp)),e}_compare(e){if(e===this)return 0;if(this.count!==e.count)return e.count-this.count;{const t=this.firstTimestamp-e.firstTimestamp;return t===0?this.key{var r,o;if(!this.canReact){s.set("powerlevel_lacking",!0);return}if(this._entry.haveAnnotation(e)){s.set("already_reacted",!0);return}const i=(o=(r=this._entry.pendingAnnotations)==null?void 0:r.get(e))==null?void 0:o.redactionEntry;i&&!i.pendingEvent.hasStartedSending?(s.set("abort_redaction",!0),await i.pendingEvent.abort()):await this._room.sendEvent("m.reaction",this._entry.annotate(e),null,s)})}redactReaction(e,t=null){return this.logger.wrapOrRun(t,"redactReaction",async s=>{var r,o;if(!this._powerLevels.canRedactFromSender(this._ownMember.userId)){s.set("powerlevel_lacking",!0);return}if(!this._entry.haveAnnotation(e)){s.set("not_yet_reacted",!0);return}let i=(o=(r=this._entry.pendingAnnotations)==null?void 0:r.get(e))==null?void 0:o.annotationEntry;i||(i=await this._timeline.getOwnAnnotationEntry(this._entry.id,e)),i?await this._room.sendRedaction(i.id,null,s):s.set("no_reaction",!0)})}toggleReaction(e,t=null){return this.logger.wrapOrRun(t,"toggleReaction",async s=>{this._entry.haveAnnotation(e)?await this.redactReaction(e,s):await this.react(e,s)})}_updateReactions(){const{annotations:e,pendingAnnotations:t}=this._entry;!e&&!t?this._reactions&&(this._reactions=null):(this._reactions||(this._reactions=new Wd(this)),this._reactions.update(e,t))}get replyTile(){return this._entry.contextEventId?this._replyTile:null}}const Hd="(?:https|http|ftp):\\/\\/",wo="[^\\s.,?!)]",Zr="[a-zA-Z0-9:.\\[\\]-]",zd=`${Zr}*(?=${Zr})${wo}`,Gd=`(?:[\\/#](?:[^\\s]*${wo})?)`,Jd=`${Hd}${zd}${Gd}?`,Qd=new RegExp(Jd,"gi");function vo(n,e){const t=n.matchAll(Qd);let s=0;for(let r of t){const o=n.slice(s,r.index);e(o,!1),e(r[0],!0);const a=r[0].length;s=r.index+a}const i=n.slice(s);e(i,!1)}function Yd(n){const e=[],t=n.split(` +`),s=(i,r)=>{r?e.push(new bi(i,[new St(i)])):e.push(new St(i))};for(let i=0;i=t.length-1||e.push(new bo)}return new Wi(n,e)}function Xd(n){return new Wi(n,[new St(n)])}class Zd{constructor(e,t){this.level=e,this.inlines=t}get type(){return"header"}}class en{constructor(e,t){this.language=e,this.text=t}get type(){return"codeblock"}}class eu{constructor(e,t){this.items=t,this.startOffset=e}get type(){return"list"}}class tu{constructor(e,t){this.head=e,this.body=t}get type(){return"table"}}class su{get type(){return"rule"}}class bo{get type(){return"newline"}}class ws{constructor(e,t){this.format=e.toLowerCase(),this.children=t}get type(){return"format"}}class iu{constructor(e,t,s,i,r){this.src=e,this.width=t,this.height=s,this.alt=i,this.title=r}get type(){return"image"}}class ru{constructor(e,t,s){this.id=e,this.href=t,this.children=s}get type(){return"pill"}get avatarColorNumber(){return de(this.id)}get avatarInitials(){return he(this.id)}}class bi{constructor(e,t){this.url=e,this.inlines=t}get type(){return"link"}}class St{constructor(e){this.text=e}get type(){return"text"}}function nu(n){return n.type==="format"&&n.format==="blockquote"}class Wi{constructor(e,t){this.sourceString=e,this.parts=t}insertEmote(e){let t=0;for(;t`${n}://`),lu="https://matrix.to",tn=`${lu}/#/`;class hu{constructor(e,t){this.result=e,this.mediaRepository=t}parsePillLink(e){if(!e.startsWith(tn))return null;const t=e.substring(tn.length);return t[0]==="@"?t:null}parseLink(e,t){const s=this.result.getAttributeValue(e,"href"),i=s==null?void 0:s.toLowerCase();if(!i||!cu.some(o=>i.startsWith(o)))return new ws("span",t);const r=this.parsePillLink(s);return r?new ru(r,s,t):new bi(s,t)}parseList(e){const t=this.result;let s=null;t.getNodeElementName(e)==="OL"&&(s=parseInt(t.getAttributeValue(e,"start"))||1);const i=[];for(const r of t.getChildNodes(e)){if(t.getNodeElementName(r)!=="LI")continue;const o=this.parseAnyNodes(t.getChildNodes(r));i.push(o)}return new eu(s,i)}_ensureElement(e,t){return e&&this.result.isElementNode(e)&&this.result.getNodeElementName(e)===t}parseCodeBlock(e){const t=this.result;let s;for(const o of t.getChildNodes(e)){s=o;break}let i=null;if(!this._ensureElement(s,"CODE"))return new en(i,this.result.getNodeText(e));const r=t.getAttributeValue(s,"class")||"";for(const o of r.split(" "))if(o.startsWith("language-")&&!o.startsWith("language-_")){i=o.substring(9);break}return new en(i,this.result.getNodeText(s))}parseImage(e){const t=this.result,s=t.getAttributeValue(e,"src")||"",i=this.mediaRepository.mxcUrl(s);if(!i)return null;const r=parseInt(t.getAttributeValue(e,"width"))||null,o=parseInt(t.getAttributeValue(e,"height"))||null,a=t.getAttributeValue(e,"alt"),c=t.getAttributeValue(e,"title");return new iu(i,r,o,a,c)}parseTableRow(e,t){const s=[];for(const i of this.result.getChildNodes(e)){if(!this._ensureElement(i,t))continue;const r=this.result.getChildNodes(i),o=this.parseInlineNodes(r);s.push(o)}return s}parseTableHead(e){let t=null;for(const s of this.result.getChildNodes(e)){t=s;break}return this._ensureElement(t,"TR")?this.parseTableRow(t,"TH"):null}parseTableBody(e){const t=[];for(const s of this.result.getChildNodes(e))!this._ensureElement(s,"TR")||t.push(this.parseTableRow(s,"TD"));return t}parseTable(e){const t=Array.from(this.result.getChildNodes(e));let s,i;return this._ensureElement(t[0],"THEAD")&&this._ensureElement(t[1],"TBODY")?(s=this.parseTableHead(t[0]),i=this.parseTableBody(t[1])):this._ensureElement(t[0],"TBODY")&&(s=null,i=this.parseTableBody(t[0])),new tu(s,i)}parseInlineElement(e){const t=this.result,s=t.getNodeElementName(e),i=t.getChildNodes(e);switch(s){case"A":{const r=this.parseInlineNodes(i);return this.parseLink(e,r)}case"BR":return new bo;default:{if(!ou.includes(s))return null;const r=this.parseInlineNodes(i);return new ws(s,r)}}}parseInlineNode(e){return this.result.isElementNode(e)?this.parseInlineElement(e):null}parseBlockElement(e){const t=this.result,s=t.getNodeElementName(e),i=t.getChildNodes(e);switch(s){case"H1":case"H2":case"H3":case"H4":case"H5":case"H6":{const r=this.parseInlineNodes(i);return new Zd(parseInt(s[1]),r)}case"UL":case"OL":return this.parseList(e);case"PRE":return this.parseCodeBlock(e);case"HR":return new su;case"IMG":return this.parseImage(e);case"P":{const r=this.parseInlineNodes(i);return new ws(s,r)}case"TABLE":return this.parseTable(e);default:{if(!au.includes(s))return null;const r=this.parseAnyNodes(i);return new ws(s,r)}}}parseBlockNode(e){return this.result.isElementNode(e)?this.parseBlockElement(e):null}_parseTextParts(e,t){if(!this.result.isTextNode(e))return!1;const s=(i,r)=>{r?t.push(new bi(i,[new St(i)])):t.push(new St(i))};return vo(this.result.getNodeText(e),s),!0}_isAllowedNode(e){return!this._ensureElement(e,"MX-REPLY")}_parseInlineNodes(e,t){for(const s of e){if(this._parseTextParts(s,t))continue;const i=this.parseInlineNode(s);if(i){t.push(i);continue}this._isAllowedNode(s)&&this._parseInlineNodes(this.result.getChildNodes(s),t)}}parseInlineNodes(e){const t=[];return this._parseInlineNodes(e,t),t}_parseAnyNodes(e,t){for(const s of e){if(this._parseTextParts(s,t))continue;const i=this.parseInlineNode(s)||this.parseBlockNode(s);if(i){t.push(i);continue}this._isAllowedNode(s)&&this._parseAnyNodes(this.result.getChildNodes(s),t)}}parseAnyNodes(e){const t=[];return this._parseAnyNodes(e,t),t}}function du(n,e,t){const s=n.parseHTML(t),r=new hu(s,e).parseAnyNodes(s.rootNodes);return new Wi(t,r)}class uu extends So{_getContentString(e){var t;return((t=this._getContent())==null?void 0:t[e])||""}_getPlainBody(){return this._getContentString("body")}_getFormattedBody(){return this._getContentString("formatted_body")}_getBody(){return this._getBodyFormat()===Bt.Html?this._getFormattedBody():this._getPlainBody()}_getBodyFormat(){var e;return((e=this._getContent())==null?void 0:e.format)==="org.matrix.custom.html"?Bt.Html:Bt.Plain}_parseBody(e,t){var i;let s;return t===Bt.Html?s=du(this.platform,this._mediaRepository,e):s=Yd(e),((i=this._getContent())==null?void 0:i.msgtype)==="m.emote"&&s.insertEmote(`* ${this.displayName} `),s}}class sn extends Je{get shape(){return"redacted"}get description(){const{redactionReason:e}=this._entry;return this.isRedacting?e?this.i18n`This message is being deleted (${e})…`:this.i18n`This message is being deleted…`:e?this.i18n`This message has been deleted (${e}).`:this.i18n`This message has been deleted.`}get isRedacting(){return this._entry.isRedacting}get canRedact(){return!1}abortPendingRedaction(){return this._entry.abortPendingRedaction()}}const mu=300,pu=400;class Io extends Je{constructor(e,t){super(e,t),this._decryptedThumbnail=null,this._decryptedFile=null,this._isVisible=!1,this._error=null,this._downloading=!1,this._downloadError=null}async downloadMedia(){if(this._downloading||this.isPending)return;const e=this._getContent(),t=e.body;this._downloading=!0,this.emitChange("status");let s;try{s=await this._mediaRepository.downloadAttachment(e),this.platform.saveFileAs(s,t)}catch(i){this._downloadError=i}finally{s==null||s.dispose(),this._downloading=!1}this.emitChange("status")}get isUploading(){return this.isPending&&this._entry.pendingEvent.status===V.UploadingAttachments}get uploadPercentage(){const{pendingEvent:e}=this._entry;return e&&Math.round(e.attachmentsSentBytes/e.attachmentsTotalBytes*100)}get status(){const{pendingEvent:e}=this._entry;switch(e==null?void 0:e.status){case V.Waiting:return this.i18n`Waiting…`;case V.EncryptingAttachments:case V.Encrypting:return this.i18n`Encrypting…`;case V.UploadingAttachments:return this.i18n`Uploading…`;case V.Sending:return this.i18n`Sending…`;case V.Error:return this.i18n`Error: ${e.error.message}`;default:return this._downloadError?"Download failed":this._downloading?this.i18n`Downloading…`:""}}get thumbnailUrl(){var e,t;if(!this._isVisible)return"";if(this._decryptedThumbnail)return this._decryptedThumbnail.url;{const s=(e=this._getContent().info)==null?void 0:e.thumbnail_url;if(s)return this._mediaRepository.mxcUrlThumbnail(s,this.width,this.height,"scale")}if(this._entry.isPending){const s=this._entry.pendingEvent.getAttachment("info.thumbnail_url");return s&&s.localPreview.url}if(this._isMainResourceImage()){if(this._decryptedFile)return this._decryptedFile.url;{const s=(t=this._getContent())==null?void 0:t.url;if(typeof s=="string")return this._mediaRepository.mxcUrlThumbnail(s,this.width,this.height,"scale")}}return""}notifyVisible(){super.notifyVisible(),this._isVisible=!0,this.emitChange("thumbnailUrl"),this.isPending||this._tryLoadEncryptedThumbnail()}get width(){var t;const e=(t=this._getContent())==null?void 0:t.info;return Math.round((e==null?void 0:e.w)*this._scaleFactor())}get height(){var t;const e=(t=this._getContent())==null?void 0:t.info;return Math.round((e==null?void 0:e.h)*this._scaleFactor())}get mimeType(){var t;const e=(t=this._getContent())==null?void 0:t.info;return e==null?void 0:e.mimetype}get label(){return this._getContent().body}get error(){return this._error?`Could not load media: ${this._error.message}`:null}setViewError(e){this._error=e,this.emitChange("error")}async _loadEncryptedFile(e){const t=await this._mediaRepository.downloadEncryptedFile(e,!0);if(this.isDisposed){t.dispose();return}return this.track(t)}async _tryLoadEncryptedThumbnail(){var e;try{const t=(e=this._getContent().info)==null?void 0:e.thumbnail_file,s=this._getContent().file;t?(this._decryptedThumbnail=await this._loadEncryptedFile(t),this.emitChange("thumbnailUrl")):s&&this._isMainResourceImage()&&(this._decryptedFile=await this._loadEncryptedFile(s),this.emitChange("thumbnailUrl"))}catch(t){this._error=t,this.emitChange("error")}}_scaleFactor(){var i;const e=(i=this._getContent())==null?void 0:i.info,t=mu/(e==null?void 0:e.h),s=pu/(e==null?void 0:e.w);return Math.min(s,t,1)}_isMainResourceImage(){return!0}}class _u extends Io{constructor(e,t){super(e,t),this._lightboxUrl=this.urlCreator.urlForSegments([this.navigation.segment("room",this._room.id),this.navigation.segment("lightbox",this._entry.id)])}get lightboxUrl(){return this.isPending?"":this._lightboxUrl}get shape(){return"image"}}class fu extends Io{async loadVideo(){const e=this._getContent().file;e&&!this._decryptedFile&&(this._decryptedFile=await this._loadEncryptedFile(e),this.emitChange("videoUrl"))}get videoUrl(){var t;if(this._decryptedFile)return this._decryptedFile.url;const e=(t=this._getContent())==null?void 0:t.url;return typeof e=="string"?this._mediaRepository.mxcUrl(e):""}get shape(){return"video"}_isMainResourceImage(){return!1}}function gu(n,e=2){if(Number.isSafeInteger(n)){const t=Math.min(3,Math.floor(Math.log(n)/Math.log(1024))),s=Math.round(n/Math.pow(1024,t)).toFixed(e);switch(t){case 0:return`${s} bytes`;case 1:return`${s} KB`;case 2:return`${s} MB`;case 3:return`${s} GB`}}return""}class yu extends Je{constructor(e,t){super(e,t),this._downloadError=null,this._downloading=!1}async download(){if(this._downloading||this.isPending)return;const e=this._getContent(),t=e.body;this._downloading=!0,this.emitChange("label");let s;try{s=await this._mediaRepository.downloadAttachment(e),this.platform.saveFileAs(s,t)}catch(i){this._downloadError=i}finally{s==null||s.dispose(),this._downloading=!1}this.emitChange("label")}get label(){var s;if(this._downloadError)return`Could not download file: ${this._downloadError.message}`;const t=this._getContent().body;if(this._entry.isPending){const{pendingEvent:i}=this._entry;switch(i==null?void 0:i.status){case V.Waiting:return this.i18n`Waiting to send ${t}…`;case V.EncryptingAttachments:case V.Encrypting:return this.i18n`Encrypting ${t}…`;case V.UploadingAttachments:{const r=Math.round(i.attachmentsSentBytes/i.attachmentsTotalBytes*100);return this.i18n`Uploading ${t}: ${r}%`}case V.Sending:case V.Sent:return this.i18n`Sending ${t}…`;case V.Error:return this.i18n`Error: could not send ${t}: ${i.error.message}`;default:return`Unknown send status for ${t}`}}else{const i=gu((s=this._getContent().info)==null?void 0:s.size);return this._downloading?this.i18n`Downloading ${t} (${i})…`:this.i18n`Download ${t} (${i})`}}get shape(){return"file"}}class wu extends Je{get shape(){return"location"}get mapsLink(){try{const e=new URL(this._getContent().geo_uri);if(e.protocol!=="geo:")return"";const[t,...s]=e.pathname.split(";"),[i,r]=t.split(","),o=parseFloat(i),a=parseFloat(r);let c;for(const l of s){const[h,d]=l.split("=");h==="u"&&(c=parseFloat(d))}if(this.platform.isIOS)return`http://maps.apple.com/?ll=${o},${a}`;{let l=`geo:${o},${a}`;return c&&(l=l+`;u=${c}`),l}}catch{return""}}get label(){return this.i18n`${this.displayName} sent their location`}}class vu extends ss{get shape(){return"announcement"}get announcement(){const e=this._entry.content;return`${this._entry.displayName||this._entry.sender} named the room "${e==null?void 0:e.name}"`}}class bu extends ss{get shape(){return"announcement"}get announcement(){var l,h;const{sender:e,content:t,prevContent:s,stateKey:i}=this._entry,r=this._entry.displayName||e,o=e===i?r:((l=this._entry.content)==null?void 0:l.displayname)||i,a=t&&t.membership,c=s&&s.membership;if(c==="join"&&a==="join"){if(t.avatar_url!==s.avatar_url)return`${r} changed their avatar`;if(t.displayname!==s.displayname)return t.displayname?`${(h=s.displayname)!=null?h:i} changed their name to ${t.displayname}`:`${i} removed their name (${s.displayname})`}else{if(a==="join")return`${o} joined the room`;if(a==="invite")return`${o} was invited to the room by ${r}`;if(c==="invite"){if(a==="join")return`${o} accepted the invitation to join the room`;if(a==="leave")return`${o} declined the invitation to join the room`}else if(a==="leave"){if(i===e)return`${o} left the room`;{const d=t.reason;return`${o} was kicked from the room by ${r}${d?`: ${d}`:""}`}}else if(a==="ban")return`${o} was banned from the room by ${r}`}return`${e} membership changed to ${t.membership}`}}class Su extends So{updateEntry(e,t){const s=super.updateEntry(e,t);return e.eventType!=="m.room.encrypted"?fe.Replace("shape"):s}get shape(){return"message-status"}_getBody(){const e=this._entry.decryptionError,t=e==null?void 0:e.code;let s;return t==="MEGOLM_NO_SESSION"?s=this.i18n`The sender hasn't sent us the key for this message yet.`:s=(e==null?void 0:e.message)||this.i18n`Could not decrypt message because of unknown reason.`,s}}class Iu extends ss{get shape(){return"announcement"}get announcement(){const e=this._entry.displayName||this._entry.sender;return this.i18n`${e} has enabled end-to-end encryption`}}class Eu extends Je{get shape(){return"missing-attachment"}get label(){const e=this._getContent().body;return this._getContent().msgtype==="m.image"?this.i18n`The image ${e} wasn't fully sent previously and could not be recovered.`:this.i18n`The file ${e} wasn't fully sent previously and could not be recovered.`}}function ku(n){if(n.isGap)return qd;if(n.isPending&&n.pendingEvent.isMissingAttachments)return Eu;if(n.eventType)switch(n.eventType){case"m.room.message":{if(n.isRedacted)return sn;const e=n.content;switch(e&&e.msgtype){case"m.text":case"m.notice":case"m.emote":return uu;case"m.image":return _u;case"m.video":return fu;case"m.file":return yu;case"m.location":return wu;default:return}}case"m.room.name":return vu;case"m.room.member":return bu;case"m.room.encrypted":return n.isRedacted?sn:Su;case"m.room.encryption":return Iu;default:return}}class rn extends A{constructor(e){super(e);const{room:t,tileClassForEntry:s}=e;this._room=t,this._timelineVM=null,this._tileClassForEntry=s!=null?s:ku,this._tileOptions=void 0,this._onRoomChange=this._onRoomChange.bind(this),this._timelineError=null,this._sendError=null,this._composerVM=null,t.isArchived?this._composerVM=this.track(new Cu(this.childOptions({archivedRoom:t}))):this._recreateComposerOnPowerLevelChange(),this._clearUnreadTimout=null,this._closeUrl=this.urlCreator.urlUntilSegment("session")}async load(){this._room.on("change",this._onRoomChange);try{const e=await this._room.openTimeline();this._tileOptions=this.childOptions({roomVM:this,timeline:e,tileClassForEntry:this._tileClassForEntry}),this._timelineVM=this.track(new $d(this.childOptions({tileOptions:this._tileOptions,timeline:e}))),this.emitChange("timelineViewModel")}catch(e){console.error(`room.openTimeline(): ${e.message}: +${e.stack}`),this._timelineError=e,this.emitChange("error")}this._clearUnreadAfterDelay()}async _recreateComposerOnPowerLevelChange(){const e=await this._room.observePowerLevels(),t=()=>e.get().canSendType("m.room.message");let s=t();const i=r=>{this._composerVM=this.disposeTracked(this._composerVM),r?this._composerVM=this.track(new jd(this)):this._composerVM=this.track(new Tu(this.childOptions())),this.emitChange("powerLevelObservable")};this.track(e.subscribe(()=>{const r=t();s!==r&&(i(r),s=r)})),i(s)}async _clearUnreadAfterDelay(){if(!(this._room.isArchived||this._clearUnreadTimout)){this._clearUnreadTimout=this.clock.createTimeout(2e3);try{await this._clearUnreadTimout.elapsed(),await this._room.clearUnread(),this._clearUnreadTimout=null}catch(e){if(e.name!=="AbortError")throw e}}}focus(){this._clearUnreadAfterDelay()}dispose(){super.dispose(),this._room.off("change",this._onRoomChange),this._room.isArchived&&this._room.release(),this._clearUnreadTimout&&(this._clearUnreadTimout.abort(),this._clearUnreadTimout=null)}_onRoomChange(){this._composerVM.emitChange(),this.emitChange()}get kind(){return"room"}get closeUrl(){return this._closeUrl}get name(){return this._room.name||this.i18n`Empty Room`}get id(){return this._room.id}get timelineViewModel(){return this._timelineVM}get isEncrypted(){return this._room.isEncrypted}get error(){return this._timelineError?`Something went wrong loading the timeline: ${this._timelineError.message}`:this._sendError?`Something went wrong sending your message: ${this._sendError.message}`:""}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._room.avatarColorId)}avatarUrl(e){return De(this._room.avatarUrl,e,this.platform,this._room.mediaRepository)}get avatarTitle(){return this.name}get canLeave(){return this._room.isJoined}leaveRoom(){this._room.leave()}get canForget(){return this._room.isArchived}forgetRoom(){this._room.forget()}get canRejoin(){return this._room.isArchived}rejoinRoom(){this._room.join()}_createTile(e){if(this._tileOptions){const t=this._tileOptions.tileClassForEntry(e);if(t)return new t(e,this._tileOptions)}}async _processCommandJoin(e){var t,s,i,r;try{const o=await this._options.client.session.joinRoom(e);await(await this._options.client.session.observeRoomStatus(o)).waitFor(c=>c===U.Joined),this.navigation.push("room",o)}catch(o){let a;((t=o.statusCode)!=null?t:o.status)===400?a=new Error(`/join : '${e}' was not legal room ID or room alias`):((s=o.statusCode)!=null?s:o.status)===404||((i=o.statusCode)!=null?i:o.status)===502||o.message=="Internal Server Error"?a=new Error(`/join : room '${e}' not found`):((r=o.statusCode)!=null?r:o.status)===403?a=new Error(`/join : you're not invited to join '${e}'`):a=o,this._sendError=a,this._timelineError=null,this.emitChange("error")}}async _processCommand(e){let t;const[s,...i]=e.substring(1).split(" ");switch(s){case"me":e=i.join(" "),t="m.emote";break;case"join":if(i.length===1){const r=i[0];await this._processCommandJoin(r)}else this._sendError=new Error("join syntax: /join "),this._timelineError=null,this.emitChange("error");break;case"shrug":e="\xAF\\_(\u30C4)_/\xAF "+i.join(" "),t="m.text";break;case"tableflip":e="(\u256F\xB0\u25A1\xB0\uFF09\u256F\uFE35 \u253B\u2501\u253B "+i.join(" "),t="m.text";break;case"unflip":e="\u252C\u2500\u2500\u252C \u30CE( \u309C-\u309C\u30CE) "+i.join(" "),t="m.text";break;case"lenny":e="( \u0361\xB0 \u035C\u0296 \u0361\xB0) "+i.join(" "),t="m.text";break;default:this._sendError=new Error(`no command name "${s}". To send the message instead of executing, please type "/${e}"`),this._timelineError=null,this.emitChange("error"),e=void 0}return{type:t,message:e}}async _sendMessage(e,t){if(!this._room.isArchived&&e){let s={type:"m.text",message:e};e.startsWith("//")?s.message=e.substring(1).trim():e.startsWith("/")&&(s=await this._processCommand(e));try{const i=s.type,r=s.message;i&&r&&(t?await t.reply(i,r):await this._room.sendEvent("m.room.message",{msgtype:i,body:r}))}catch(i){return console.error(`room.sendMessage(): ${i.message}: +${i.stack}`),this._sendError=i,this._timelineError=null,this.emitChange("error"),!1}return!0}return!1}async _pickAndSendFile(){try{const e=await this.platform.openFile();return e?this._sendFile(e):void 0}catch(e){console.error(e)}}async _sendFile(e){const t={body:e.name,msgtype:"m.file"};await this._room.sendEvent("m.room.message",t,{url:this._room.createAttachment(e.blob,e.name)})}async _pickAndSendVideo(){try{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const e=await this.platform.openFile("video/*");if(!e)return;if(!e.blob.mimeType.startsWith("video/"))return this._sendFile(e);let t;try{t=await this.platform.loadVideo(e.blob)}catch(c){throw c instanceof window.MediaError&&c.code===4?new Error(`this browser does not support videos of type ${e==null?void 0:e.blob.mimeType}.`):c}const s={body:e.name,msgtype:"m.video",info:Ru(t)},i={url:this._room.createAttachment(t.blob,e.name)},o=await this.platform.settingsStorage.getInt("sentImageSizeLimit")||Math.min(t.maxDimension,800),a=await t.scale(o);s.info.thumbnail_info=Ht(a),i["info.thumbnail_url"]=this._room.createAttachment(a.blob,e.name),await this._room.sendEvent("m.room.message",s,i)}catch(e){this._sendError=e,this.emitChange("error"),console.error(e.stack)}}async _pickAndSendPicture(){try{if(!this.platform.hasReadPixelPermission()){alert("Please allow canvas image data access, so we can scale your images down.");return}const e=await this.platform.openFile("image/*");if(!e)return;if(!e.blob.mimeType.startsWith("image/"))return this._sendFile(e);let t=await this.platform.loadImage(e.blob);const s=await this.platform.settingsStorage.getInt("sentImageSizeLimit");if(s&&t.maxDimension>s){const o=await t.scale(s);t.dispose(),t=o}const i={body:e.name,msgtype:"m.image",info:Ht(t)},r={url:this._room.createAttachment(t.blob,e.name)};if(t.maxDimension>600){const o=await t.scale(400);i.info.thumbnail_info=Ht(o),r["info.thumbnail_url"]=this._room.createAttachment(o.blob,e.name)}await this._room.sendEvent("m.room.message",i,r)}catch(e){this._sendError=e,this.emitChange("error"),console.error(e.stack)}}get room(){return this._room}get composerViewModel(){return this._composerVM}openDetailsPanel(){let e=this.navigation.path.until("room");e=e.with(this.navigation.segment("right-panel",!0)),e=e.with(this.navigation.segment("details",!0)),this.navigation.applyPath(e)}startReply(e){this._room.isArchived||this._composerVM.setReplyingTo(e)}dismissError(){this._sendError=null,this.emitChange("error")}}function Ru(n){const e=Ht(n);return e.duration=n.duration,e}class Cu extends A{constructor(e){super(e),this._archivedRoom=e.archivedRoom}get description(){return this._archivedRoom.isKicked?this._archivedRoom.kickReason?this.i18n`You were kicked from the room by ${this._archivedRoom.kickedBy.name} because: ${this._archivedRoom.kickReason}`:this.i18n`You were kicked from the room by ${this._archivedRoom.kickedBy.name}.`:this._archivedRoom.isBanned?this._archivedRoom.kickReason?this.i18n`You were banned from the room by ${this._archivedRoom.kickedBy.name} because: ${this._archivedRoom.kickReason}`:this.i18n`You were banned from the room by ${this._archivedRoom.kickedBy.name}.`:this.i18n`You left this room`}get kind(){return"disabled"}}class Tu extends A{get description(){return this.i18n`You do not have the powerlevel necessary to send messages`}get kind(){return"disabled"}}class Mu extends A{constructor(e){super(e);const{roomIdOrAlias:t,session:s}=e;this._session=s,this.roomIdOrAlias=t,this._error=null,this._busy=!1}get error(){var e;return(e=this._error)==null?void 0:e.message}async join(){this._busy=!0,this.emitChange("busy");try{const e=await this._session.joinRoom(this.roomIdOrAlias);this.navigation.push("room",e)}catch(e){this._error=e,this._busy=!1,this.emitChange("error")}}get busy(){return this._busy}get kind(){return"unknown"}}class Au extends A{constructor(e){super(e);const{invite:t,mediaRepository:s}=e;this._invite=t,this._mediaRepository=s,this._onInviteChange=this._onInviteChange.bind(this),this._error=null,this._closeUrl=this.urlCreator.urlUntilSegment("session"),this._invite.on("change",this._onInviteChange),this._inviter=null,this._invite.inviter&&(this._inviter=new xu(this._invite.inviter,s,this.platform)),this._roomDescription=this._createRoomDescription()}get kind(){return"invite"}get closeUrl(){return this._closeUrl}get name(){return this._invite.name}get id(){return this._invite.id}get isEncrypted(){return this._invite.isEncrypted}get isDirectMessage(){return this._invite.isDirectMessage}get inviter(){return this._inviter}get busy(){return this._invite.accepting||this._invite.rejecting}get error(){return this._error?`Something went wrong: ${this._error.message}`:""}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._invite.avatarColorId)}avatarUrl(e){return De(this._invite.avatarUrl,e,this.platform,this._mediaRepository)}_createRoomDescription(){const e=[];return this._invite.isPublic?e.push("Public room"):e.push("Private room"),this._invite.canonicalAlias&&e.push(this._invite.canonicalAlias),e.join(" \u2022 ")}get roomDescription(){return this._roomDescription}get avatarTitle(){return this.name}focus(){}async accept(){try{await this._invite.accept()}catch(e){this._error=e,this.emitChange("error")}}async reject(){try{await this._invite.reject()}catch(e){this._error=e,this.emitChange("error")}}_onInviteChange(){this.emitChange()}dispose(){super.dispose(),this._invite.off("change",this._onInviteChange)}}class xu{constructor(e,t,s){this._member=e,this._mediaRepository=t,this._platform=s}get id(){return this._member.userId}get name(){return this._member.name}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._member.userId)}avatarUrl(e){return De(this._member.avatarUrl,e,this._platform,this._mediaRepository)}get avatarTitle(){return this.name}}class Nu extends A{constructor(e){super(e);const{roomBeingCreated:t,mediaRepository:s}=e;this._roomBeingCreated=t,this._mediaRepository=s,this._onRoomChange=this._onRoomChange.bind(this),this._closeUrl=this.urlCreator.urlUntilSegment("session"),this._roomBeingCreated.on("change",this._onRoomChange)}get kind(){return"roomBeingCreated"}get closeUrl(){return this._closeUrl}get name(){return this._roomBeingCreated.name}get id(){return this._roomBeingCreated.id}get isEncrypted(){return this._roomBeingCreated.isEncrypted}get error(){const{error:e}=this._roomBeingCreated;return e?e.name==="ConnectionError"?this.i18n`You seem to be offline`:e.message:""}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._roomBeingCreated.avatarColorId)}get avatarTitle(){return this.name}avatarUrl(e){var t;return(t=this._roomBeingCreated.avatarBlobUrl)!=null?t:De(this._roomBeingCreated.avatarUrl,e,this.platform,this._mediaRepository)}focus(){}_onRoomChange(){this.emitChange()}cancel(){this._roomBeingCreated.cancel(),this.navigation.applyPath(this.navigation.path.until("session"))}dispose(){super.dispose(),this._roomBeingCreated.off("change",this._onRoomChange)}}class Du extends A{constructor(e){super(e),this._eventId=e.eventId,this._unencryptedImageUrl=null,this._decryptedImage=null,this._closeUrl=this.urlCreator.urlUntilSegment("room"),this._eventEntry=null,this._date=null,this._subscribeToEvent(e.room,e.eventId)}_subscribeToEvent(e,t){const s=e.observeEvent(t);this.track(s.subscribe(i=>{this._loadEvent(e,i)})),this._loadEvent(e,s.get())}async _loadEvent(e,t){if(!t)return;const{mediaRepository:s}=e;this._eventEntry=t;const{content:i}=this._eventEntry;this._date=this._eventEntry.timestamp?new Date(this._eventEntry.timestamp):null,i.url?(this._unencryptedImageUrl=s.mxcUrl(i.url),this.emitChange("imageUrl")):i.file&&(this._decryptedImage=this.track(await s.downloadEncryptedFile(i.file)),this.emitChange("imageUrl"))}get imageWidth(){var e,t,s;return(s=(t=(e=this._eventEntry)==null?void 0:e.content)==null?void 0:t.info)==null?void 0:s.w}get imageHeight(){var e,t,s;return(s=(t=(e=this._eventEntry)==null?void 0:e.content)==null?void 0:t.info)==null?void 0:s.h}get name(){var e,t;return(t=(e=this._eventEntry)==null?void 0:e.content)==null?void 0:t.body}get sender(){var e;return(e=this._eventEntry)==null?void 0:e.displayName}get imageUrl(){return this._decryptedImage?this._decryptedImage.url:this._unencryptedImageUrl?this._unencryptedImageUrl:""}get date(){return this._date&&this._date.toLocaleDateString({},{weekday:"long",year:"numeric",month:"long",day:"numeric"})}get time(){return this._date&&this._date.toLocaleTimeString({},{hour:"numeric",minute:"2-digit"})}get closeUrl(){return this._closeUrl}close(){this.platform.history.pushUrl(this.closeUrl)}}const J=xe("Disconnected","Connecting","FirstSync","Sending","Syncing","SyncError");class Vu extends A{constructor(e){super(e);const{sync:t,reconnector:s,session:i}=e;this._sync=t,this._reconnector=s,this._status=this._calculateState(s.connectionStatus.get(),t.status.get()),this._session=i,this._setupKeyBackupUrl=this.urlCreator.urlForSegment("settings"),this._dismissSecretStorage=!1}start(){const e=()=>this._updateStatus();this.track(this._sync.status.subscribe(e)),this.track(this._reconnector.connectionStatus.subscribe(e)),this.track(this._session.needsKeyBackup.subscribe(()=>{this.emitChange()}))}get setupKeyBackupUrl(){return this._setupKeyBackupUrl}get isShown(){return this._session.needsKeyBackup.get()&&!this._dismissSecretStorage||this._status!==J.Syncing}get statusLabel(){switch(this._status){case J.Disconnected:{const e=Math.round(this._reconnector.retryIn/1e3);return this.i18n`Disconnected, trying to reconnect in ${e}s…`}case J.Connecting:return this.i18n`Trying to reconnect now…`;case J.FirstSync:return this.i18n`Catching up with your conversations…`;case J.SyncError:return this.i18n`Sync failed because of ${this._sync.error}`}return this._session.needsKeyBackup.get()?this.i18n`Set up session backup to decrypt older messages.`:""}get isWaiting(){switch(this._status){case J.Connecting:case J.FirstSync:return!0;default:return!1}}_updateStatus(){const e=this._calculateState(this._reconnector.connectionStatus.get(),this._sync.status.get());e!==this._status&&(e===J.Disconnected?this._retryTimer=this.track(this.clock.createInterval(()=>{this.emitChange("statusLabel")},1e3)):this._retryTimer=this.disposeTracked(this._retryTimer),this._status=e,this.emitChange())}_calculateState(e,t){if(e!==$t.Online)switch(e){case $t.Reconnecting:return J.Connecting;case $t.Waiting:return J.Disconnected}else if(t!==L.Syncing)switch(t){case L.InitialSync:case L.CatchupSync:return J.FirstSync;case L.Stopped:return J.SyncError}else return J.Syncing}get isConnectNowShown(){return this._status===J.Disconnected}get isSecretStorageShown(){return this._status===J.Syncing&&this._session.needsKeyBackup.get()&&!this._dismissSecretStorage}get canDismiss(){return this.isSecretStorageShown}dismiss(){this.isSecretStorageShown&&(this._dismissSecretStorage=!0,this.emitChange())}connectNow(){this.isConnectNowShown&&this._reconnector.tryNow()}}function nn(n){return n.map((e,t)=>{if(!n.slice(0,t).includes(e))return e})}class Lu extends A{constructor(e){super(e),this._width=e.width,this._height=e.height,this._createRoomViewModelObservable=e.createRoomViewModelObservable,this._selectedIndex=0,this._viewModelsObservables=[],this._setupNavigation()}_setupNavigation(){const e=this.navigation.observe("empty-grid-tile");this.track(e.subscribe(s=>{typeof s=="number"&&this._setFocusIndex(s)})),typeof e.get()=="number"&&(this._selectedIndex=e.get());const t=this.navigation.observe("room");this.track(t.subscribe(s=>{s&&this._setFocusRoom(s)}))}roomViewModelAt(e){var t;return(t=this._viewModelsObservables[e])==null?void 0:t.get()}get focusIndex(){return this._selectedIndex}get width(){return this._width}get height(){return this._height}_switchToRoom(e){let t=this.navigation.path.until("rooms");t=t.with(this.navigation.segment("room",e)),t=vi(this.navigation,t),this.navigation.applyPath(t)}focusTile(e){if(e===this._selectedIndex)return;const t=this._viewModelsObservables[e];t?this._switchToRoom(t.id):this.navigation.push("empty-grid-tile",e)}initializeRoomIdsAndTransferVM(e,t){e=nn(e);let s=!1;if(t){const r=e.indexOf(t.id);r!==-1&&(this._viewModelsObservables[r]=this.track(t),t.subscribe(o=>this._refreshRoomViewModel(o)),s=!0)}this.setRoomIds(e);const i=this.navigation.path.get("room");if(i){const r=this._viewModelsObservables.findIndex(o=>o&&o.id===i.value);r!==-1&&(this._selectedIndex=r)}return s}setRoomIds(e){e=nn(e);let t=!1;const s=this._height*this._width;for(let i=0;ithis._refreshRoomViewModel(c)),a.initialize()}t=!0}}return t&&this.emitChange(),t}_refreshRoomViewModel(e){this.emitChange(),e==null||e.focus()}releaseRoomViewModel(e){const t=this._viewModelsObservables.findIndex(s=>s&&s.id===e);if(t!==-1){const s=this._viewModelsObservables[t];return this.untrack(s),s.unsubscribeAll(),this._viewModelsObservables[t]=null,s}}_setFocusIndex(e){var s;if(e===this._selectedIndex||e>=this._width*this._height)return;this._selectedIndex=e;const t=this._viewModelsObservables[this._selectedIndex];(s=t==null?void 0:t.get())==null||s.focus(),this.emitChange("focusIndex")}_setFocusRoom(e){const t=this._viewModelsObservables.findIndex(s=>(s==null?void 0:s.id)===e);t>=0&&this._setFocusIndex(t)}}const ee=xe("Enabled","SetupKey","SetupPhrase","Pending","NewVersionAvailable"),Lt=xe("Writing","Stopped","Done","Pending");class Ou extends A{constructor(e){super(e),this._session=e.session,this._error=null,this._isBusy=!1,this._dehydratedDeviceId=void 0,this._status=void 0,this._backupOperation=this._session.keyBackup.flatMap(t=>t.operationInProgress),this._progress=this._backupOperation.flatMap(t=>t.progress),this.track(this._backupOperation.subscribe(()=>{this._reevaluateStatus(),this.emitChange("isBackingUp")})),this.track(this._progress.subscribe(()=>this.emitChange("backupPercentage"))),this._reevaluateStatus(),this.track(this._session.keyBackup.subscribe(()=>{this._reevaluateStatus()&&this.emitChange("status")}))}_reevaluateStatus(){if(this._isBusy)return!1;let e;const t=this._session.keyBackup.get();t?e=t.needsNewKey?ee.NewVersionAvailable:ee.Enabled:t===null?e=this.showPhraseSetup()?ee.SetupPhrase:ee.SetupKey:e=ee.Pending;const s=e!==this._status;return this._status=e,s}get decryptAction(){return this.i18n`Set up`}get purpose(){return this.i18n`set up key backup`}offerDehydratedDeviceSetup(){return!0}get dehydratedDeviceId(){return this._dehydratedDeviceId}get isBusy(){return this._isBusy}get backupVersion(){var e;return(e=this._session.keyBackup.get())==null?void 0:e.version}get backupWriteStatus(){const e=this._session.keyBackup.get();if(e){if(e.hasStopped)return Lt.Stopped}else return Lt.Pending;return e.operationInProgress.get()?Lt.Writing:e.hasBackedUpAllKeys?Lt.Done:Lt.Pending}get backupError(){var e,t;return(t=(e=this._session.keyBackup.get())==null?void 0:e.error)==null?void 0:t.message}get status(){return this._status}get error(){var e;return(e=this._error)==null?void 0:e.message}showPhraseSetup(){this._status===ee.SetupKey&&(this._status=ee.SetupPhrase,this.emitChange("status"))}showKeySetup(){this._status===ee.SetupPhrase&&(this._status=ee.SetupKey,this.emitChange("status"))}async _enterCredentials(e,t,s){if(t)try{this._isBusy=!0,this.emitChange("isBusy");const i=await this._session.enableSecretStorage(e,t);s&&(this._dehydratedDeviceId=await this._session.setupDehydratedDevice(i))}catch(i){console.error(i),this._error=i,this.emitChange("error")}finally{this._isBusy=!1,this._reevaluateStatus(),this.emitChange("")}}enterSecurityPhrase(e,t){this._enterCredentials(Qt.Passphrase,e,t)}enterSecurityKey(e,t){this._enterCredentials(Qt.RecoveryKey,e,t)}async disable(){try{this._isBusy=!0,this.emitChange("isBusy"),await this._session.disableSecretStorage()}catch(e){console.error(e),this._error=e,this.emitChange("error")}finally{this._isBusy=!1,this._reevaluateStatus(),this.emitChange("")}}get isBackingUp(){return!!this._backupOperation.get()}get backupPercentage(){const e=this._progress.get();return e?Math.round(e.finished/e.total*100):0}get backupInProgressLabel(){const e=this._progress.get();return e?this.i18n`${e.finished} of ${e.total}`:this.i18n`…`}cancelBackup(){var e;(e=this._backupOperation.get())==null||e.abort()}startBackup(){var e;(e=this._session.keyBackup.get())==null||e.flush()}}async function Pu(n,e,t,s){const i=new Map;n.text&&i.set("text",n.text),i.set("user_agent",n.userAgent),i.set("app",n.app),i.set("version",n.version),n.label&&i.set("label",n.label),i.set("file",{name:"logs.json",blob:e});const r=new Map;r.set("Accept","application/json");const o=s(t,{method:"POST",body:i,headers:r});let a;try{a=await o.response()}catch(h){throw new Error(`Could not submit logs to ${t}, got error ${h.message}`)}const{status:c,body:l}=a;if(c<200||c>=300)throw new Error(`Could not submit logs to ${t}, got status code ${c} with body ${l}`)}class Uu{constructor(){this.supported=null,this.enabled=!1,this.updating=!1,this.enabledOnServer=null,this.serverError=null}}function Fu(n){const t=Math.ceil(n.length/4);let s="";for(let i=0;ithis.maxSentImageSizeLimit||es){const i=await t.scale(s);t.dispose(),t=i}this._avatarScaledBlob=t.blob,this._avatarInfo=Ht(t),this._avatarFileName=e.name,this.emitChange("hasAvatar")}}function $u(n){n.startsWith("#")&&(n=n.substr(1));const e=n.indexOf(":");return e!==-1&&(n=n.substr(0,e)),n}class on extends we{constructor(e,t){super(null),this._statusSubscription=null,this._sessionViewModel=e,this.id=t}async initialize(){const{session:e}=this._sessionViewModel._client,t=await e.observeRoomStatus(this.id);this.set(await this._statusToViewModel(t.get())),this._statusSubscription=t.subscribe(async s=>{var i;(i=this.get())==null||i.dispose(),this.set(await this._statusToViewModel(s))})}async _statusToViewModel(e){if(e&U.Replaced)if(e&U.BeingCreated){const{session:t}=this._sessionViewModel._client,s=t.roomsBeingCreated.get(this.id);this._sessionViewModel.notifyRoomReplaced(s.id,s.roomId)}else throw new Error("Don't know how to replace a room with this status: "+(e^U.Replaced));else return e&U.BeingCreated?this._sessionViewModel._createRoomBeingCreatedViewModel(this.id):e&U.Invited?this._sessionViewModel._createInviteViewModel(this.id):e&U.Joined?this._sessionViewModel._createRoomViewModelInstance(this.id):e&U.Archived?await this._sessionViewModel._createArchivedRoomViewModel(this.id):this._sessionViewModel._createUnknownRoomViewModel(this.id)}dispose(){var e;this._statusSubscription&&(this._statusSubscription=this._statusSubscription()),this.unsubscribeAll(),(e=this.get())==null||e.dispose()}}class ju extends A{constructor(e){super(e),this._room=e.room,this._onRoomChange=this._onRoomChange.bind(this),this._room.on("change",this._onRoomChange)}get type(){return"room-details"}get shouldShowBackButton(){return!1}get previousSegmentName(){return!1}get roomId(){return this._room.id}get canonicalAlias(){return this._room.canonicalAlias}get name(){return this._room.name}get isEncrypted(){return!!this._room.isEncrypted}get memberCount(){return this._room.joinedMemberCount}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this._room.avatarColorId)}avatarUrl(e){return De(this._room.avatarUrl,e,this.platform,this._room.mediaRepository)}get avatarTitle(){return this.name}_onRoomChange(){this.emitChange()}dispose(){super.dispose(),this._room.off("change",this._onRoomChange)}openPanel(e){let t=this.navigation.path.until("room");t=t.with(this.navigation.segment("right-panel",!0)),t=t.with(this.navigation.segment(e,!0)),this.navigation.applyPath(t)}}class qu extends A{constructor(e){super(e),this._member=this._options.member,this._mediaRepository=e.mediaRepository,this._previousName=null,this._nameChanged=!0}get name(){return`${this._member.name}${this._disambiguationPart}`}get _disambiguationPart(){return this._disambiguate?` (${this.userId})`:""}get userId(){return this._member.userId}get previousName(){return this._previousName}get nameChanged(){return this._nameChanged}get detailsUrl(){const e=this.navigation.path.get("room").value;return`${this.urlCreator.openRoomActionUrl(e)}/member/${this._member.userId}`}_updatePreviousName(e){const t=this._member.name;t!==e?(this._previousName=t,this._nameChanged=!0):this._nameChanged=!1}setDisambiguation(e){this._disambiguate=e,this.emitChange()}updateFrom(e){this._updatePreviousName(e.name),this._member=e}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this.userId)}avatarUrl(e){return De(this._member.avatarUrl,e,this.platform,this._mediaRepository)}get avatarTitle(){return this.name}}function Wu(n){const e=new Intl.Collator,t=s=>s.charAt(0)==="@"?s.slice(1):s;return function(i,r){const o=n.getUserLevel(i.userId),a=n.getUserLevel(r.userId);if(o!==a)return a-o;const c=t(i.name),l=t(r.name);return e.compare(c,l)}}class Hu{constructor(){this._map=new Map}_unDisambiguate(e,t){const s=t.indexOf(e);if(s!==-1){const[i]=t.splice(s,1);i.setDisambiguation(!1)}}_handlePreviousName(e){const t=e.previousName;if(typeof t!="string")return;const s=this._map.get(t);if(Array.isArray(s)){if(this._unDisambiguate(e,s),s.length===1){const i=s[0];i.setDisambiguation(!1),this._map.set(t,i)}}else this._map.delete(t)}_updateMap(e){const t=e.name,s=this._map.get(t);if(s){if(Array.isArray(s))return s.findIndex(i=>i.userId===e.userId)!==-1?void 0:(s.push(e),s);if(e.userId!==s.userId){const i=[s,e];return this._map.set(t,i),i}}else this._map.set(t,e)}disambiguate(e){if(!e.nameChanged)return;this._handlePreviousName(e);const t=this._updateMap(e);t==null||t.forEach(s=>s.setDisambiguation(!0))}}class zu extends A{constructor(e){super(e);const t=e.members,s=e.powerLevelsObservable;this.track(s.subscribe(()=>{}));const i=s.get();this.memberTileViewModels=this._mapTileViewModels(t.members.filterValues(r=>r.membership==="join")).sortValues(Wu(i)),this.nameDisambiguator=new Hu,this.mediaRepository=e.mediaRepository}get type(){return"member-list"}get shouldShowBackButton(){return!0}get previousSegmentName(){return"details"}_mapTileViewModels(e){const t=(i,r)=>{const o=this.mediaRepository,a=new qu(this.childOptions({member:i,emitChange:r,mediaRepository:o}));return this.nameDisambiguator.disambiguate(a),a},s=(i,r,o)=>{i.updateFrom(o),this.nameDisambiguator.disambiguate(i)};return e.mapValues(t,s)}}class Gu extends A{constructor(e){super(e),this._observableMember=e.observableMember,this._mediaRepository=e.mediaRepository,this._member=this._observableMember.get(),this._isEncrypted=e.isEncrypted,this._powerLevelsObservable=e.powerLevelsObservable,this._session=e.session,this.track(this._powerLevelsObservable.subscribe(()=>this._onPowerLevelsChange())),this.track(this._observableMember.subscribe(()=>this._onMemberChange()))}get name(){return this._member.name}get userId(){return this._member.userId}get type(){return"member-details"}get shouldShowBackButton(){return!0}get previousSegmentName(){return"members"}get role(){return this.powerLevel>=100?this.i18n`Admin`:this.powerLevel>=50?this.i18n`Moderator`:this.powerLevel===0?this.i18n`Default`:this.i18n`Custom (${this.powerLevel})`}_onMemberChange(){this._member=this._observableMember.get(),this.emitChange("member")}_onPowerLevelsChange(){this.emitChange("role")}get avatarLetter(){return he(this.name)}get avatarColorNumber(){return de(this.userId)}avatarUrl(e){return De(this._member.avatarUrl,e,this.platform,this._mediaRepository)}get avatarTitle(){return this.name}get isEncrypted(){return this._isEncrypted}get powerLevel(){var e;return(e=this._powerLevelsObservable.get())==null?void 0:e.getUserLevel(this._member.userId)}get linkToUser(){return`https://matrix.to/#/${encodeURIComponent(this._member.userId)}`}async openDirectMessage(){const e=this._session.findDirectMessageForUserId(this.userId);let t=e==null?void 0:e.id;t||(t=(await this._session.createRoom({type:re.DirectMessage,invites:[this.userId]})).id),this.navigation.push("room",t)}}class Ju extends A{constructor(e){super(e),this._room=e.room,this._session=e.session,this._members=null,this._setupNavigation()}get activeViewModel(){return this._activeViewModel}async _getMemberListArguments(){this._members||(this._members=await this._room.loadMemberList(),this.track(()=>this._members.release()));const e=this._room,t=await this._room.observePowerLevels();return{members:this._members,powerLevelsObservable:t,mediaRepository:e.mediaRepository}}async _getMemberDetailsArguments(){const t=this.navigation.path.get("member").value,s=await this._room.observeMember(t);if(!s)return!1;const i=this._room.isEncrypted,r=await this._room.observePowerLevels();return{observableMember:s,isEncrypted:i,powerLevelsObservable:r,mediaRepository:this._room.mediaRepository,session:this._session}}_setupNavigation(){this._hookUpdaterToSegment("details",ju,()=>({room:this._room})),this._hookUpdaterToSegment("members",zu,()=>this._getMemberListArguments()),this._hookUpdaterToSegment("member",Gu,()=>this._getMemberDetailsArguments(),()=>{const e=`${this.urlCreator.urlUntilSegment("room")}/members`;this.urlCreator.pushUrl(e)})}_hookUpdaterToSegment(e,t,s,i){const r=this.navigation.observe(e),o=this._setupUpdater(e,t,s,i);this.track(r.subscribe(o))}_setupUpdater(e,t,s,i){const r=async(o=!1)=>{var c;if(o||(this._activeViewModel=this.disposeTracked(this._activeViewModel)),!!((c=this.navigation.path.get(e))!=null&&c.value)){const l=await s();if(!l&&i){i();return}this._activeViewModel=this.track(new t(this.childOptions(l)))}this.emitChange("activeViewModel")};return r(!0),r}closePanel(){const e=this.navigation.path.until("room");this.navigation.applyPath(e)}showPreviousPanel(){const e=this.activeViewModel.previousSegmentName;if(e){let t=this.navigation.path.until("room");t=t.with(this.navigation.segment("right-panel",!0)),t=t.with(this.navigation.segment(e,!0)),this.navigation.applyPath(t)}}}class Qu extends A{constructor(e){super(e);const{client:t}=e;this._client=this.track(t),this._sessionStatusViewModel=this.track(new Vu(this.childOptions({sync:t.sync,reconnector:t.reconnector,session:t.session}))),this._leftPanelViewModel=this.track(new Bd(this.childOptions({session:this._client.session}))),this._settingsViewModel=null,this._roomViewModelObservable=null,this._gridViewModel=null,this._createRoomViewModel=null,this._setupNavigation()}_setupNavigation(){const e=this.navigation.observe("rooms");this.track(e.subscribe(a=>{this._updateGrid(a)})),e.get()&&this._updateGrid(e.get());const t=this.navigation.observe("room");this.track(t.subscribe(a=>{this._gridViewModel||this._updateRoom(a),this._updateRightPanel()})),this._gridViewModel||this._updateRoom(t.get());const s=this.navigation.observe("settings");this.track(s.subscribe(a=>{this._updateSettings(a)})),this._updateSettings(s.get());const i=this.navigation.observe("create-room");this.track(i.subscribe(a=>{this._updateCreateRoom(a)})),this._updateCreateRoom(i.get());const r=this.navigation.observe("lightbox");this.track(r.subscribe(a=>{this._updateLightbox(a)})),this._updateLightbox(r.get());const o=this.navigation.observe("right-panel");this.track(o.subscribe(()=>this._updateRightPanel())),this._updateRightPanel()}get id(){return this._client.sessionId}start(){this._sessionStatusViewModel.start()}get activeMiddleViewModel(){var e;return((e=this._roomViewModelObservable)==null?void 0:e.get())||this._gridViewModel||this._settingsViewModel||this._createRoomViewModel}get roomGridViewModel(){return this._gridViewModel}get leftPanelViewModel(){return this._leftPanelViewModel}get sessionStatusViewModel(){return this._sessionStatusViewModel}get settingsViewModel(){return this._settingsViewModel}get currentRoomViewModel(){var e;return(e=this._roomViewModelObservable)==null?void 0:e.get()}get rightPanelViewModel(){return this._rightPanelViewModel}get createRoomViewModel(){return this._createRoomViewModel}_updateGrid(e){var i;const t=!(this._gridViewModel&&e),s=this.navigation.path.get("room");if(e)this._gridViewModel?this._gridViewModel.setRoomIds(e):(this._gridViewModel=this.track(new Lu(this.childOptions({width:3,height:2,createRoomViewModelObservable:r=>new on(this,r)}))),(i=this._roomViewModelObservable)==null||i.unsubscribeAll(),this._gridViewModel.initializeRoomIdsAndTransferVM(e,this._roomViewModelObservable)?this._roomViewModelObservable=this.untrack(this._roomViewModelObservable):this._roomViewModelObservable&&(this._roomViewModelObservable=this.disposeTracked(this._roomViewModelObservable)));else if(this._gridViewModel&&!e){if(s){const r=this._gridViewModel.releaseRoomViewModel(s.value);r&&(this._roomViewModelObservable=this.track(r),this._roomViewModelObservable.subscribe(()=>{this.emitChange("activeMiddleViewModel")}))}this._gridViewModel=this.disposeTracked(this._gridViewModel)}t&&this.emitChange("activeMiddleViewModel")}_createRoomViewModelInstance(e){const t=this._client.session.rooms.get(e);if(t){const s=new rn(this.childOptions({room:t}));return s.load(),s}return null}_createUnknownRoomViewModel(e){return new Mu(this.childOptions({roomIdOrAlias:e,session:this._client.session}))}async _createArchivedRoomViewModel(e){const t=await this._client.session.loadArchivedRoom(e);if(t){const s=new rn(this.childOptions({room:t}));return s.load(),s}return null}_createInviteViewModel(e){const t=this._client.session.invites.get(e);return t?new Au(this.childOptions({invite:t,mediaRepository:this._client.session.mediaRepository})):null}_createRoomBeingCreatedViewModel(e){const t=this._client.session.roomsBeingCreated.get(e);return t?new Nu(this.childOptions({roomBeingCreated:t,mediaRepository:this._client.session.mediaRepository})):null}_updateRoom(e){var s;if(((s=this._roomViewModelObservable)==null?void 0:s.id)===e)return;if(this._roomViewModelObservable&&(this._roomViewModelObservable=this.disposeTracked(this._roomViewModelObservable)),!e){this.emitChange("activeMiddleViewModel");return}const t=new on(this,e);this._roomViewModelObservable=this.track(t),this._roomViewModelObservable.subscribe(()=>{this.emitChange("activeMiddleViewModel")}),t.initialize()}_updateSettings(e){this._settingsViewModel&&(this._settingsViewModel=this.disposeTracked(this._settingsViewModel)),e&&(this._settingsViewModel=this.track(new Bu(this.childOptions({client:this._client}))),this._settingsViewModel.load()),this.emitChange("activeMiddleViewModel")}_updateCreateRoom(e){this._createRoomViewModel&&(this._createRoomViewModel=this.disposeTracked(this._createRoomViewModel)),e&&(this._createRoomViewModel=this.track(new Ku(this.childOptions({session:this._client.session})))),this.emitChange("activeMiddleViewModel")}_updateLightbox(e){if(this._lightboxViewModel&&(this._lightboxViewModel=this.disposeTracked(this._lightboxViewModel)),e){const t=this._roomFromNavigation();this._lightboxViewModel=this.track(new Du(this.childOptions({eventId:e,room:t})))}this.emitChange("lightboxViewModel")}get lightboxViewModel(){return this._lightboxViewModel}_roomFromNavigation(){var s;const e=(s=this.navigation.path.get("room"))==null?void 0:s.value;return this._client.session.rooms.get(e)}_updateRightPanel(){var t;if(this._rightPanelViewModel=this.disposeTracked(this._rightPanelViewModel),!!((t=this.navigation.path.get("right-panel"))!=null&&t.value)){const s=this._roomFromNavigation();this._rightPanelViewModel=this.track(new Ju(this.childOptions({room:s,session:this._client.session})))}this.emitChange("rightPanelViewModel")}notifyRoomReplaced(e,t){this.navigation.push("room",t)}}class Yu extends A{constructor(e){super(e),this._accountSetup=e.accountSetup,this._dehydratedDevice=void 0,this._decryptDehydratedDeviceViewModel=void 0,this._accountSetup.encryptedDehydratedDevice&&(this._decryptDehydratedDeviceViewModel=new Xu(this,t=>{this._dehydratedDevice=t,this._decryptDehydratedDeviceViewModel=void 0,this.emitChange("deviceDecrypted")}))}get decryptDehydratedDeviceViewModel(){return this._decryptDehydratedDeviceViewModel}get deviceDecrypted(){return!!this._dehydratedDevice}get dehydratedDeviceId(){return this._accountSetup.encryptedDehydratedDevice.deviceId}finish(){this._accountSetup.finish(this._dehydratedDevice)}}class Xu extends A{constructor(e,t){super(e.options),this._accountSetupViewModel=e,this._isBusy=!1,this._status=ee.SetupKey,this._error=void 0,this._decryptedCallback=t}get decryptAction(){return this.i18n`Restore`}get purpose(){return this.i18n`claim your dehydrated device`}get offerDehydratedDeviceSetup(){return!1}get dehydratedDeviceId(){var e;return(e=this._accountSetupViewModel._dehydratedDevice)==null?void 0:e.deviceId}get isBusy(){return this._isBusy}get backupVersion(){return 0}get status(){return this._status}get error(){var e;return(e=this._error)==null?void 0:e.message}showPhraseSetup(){this._status===ee.SetupKey&&(this._status=ee.SetupPhrase,this.emitChange("status"))}showKeySetup(){this._status===ee.SetupPhrase&&(this._status=ee.SetupKey,this.emitChange("status"))}async _enterCredentials(e,t){if(t)try{this._isBusy=!0,this.emitChange("isBusy");const{encryptedDehydratedDevice:s}=this._accountSetupViewModel._accountSetup,i=await s.decrypt(e,t);this._decryptedCallback(i)}catch(s){console.error(s),this._error=s,this.emitChange("error")}finally{this._isBusy=!1,this.emitChange("")}}enterSecurityPhrase(e){this._enterCredentials(Qt.Passphrase,e)}enterSecurityKey(e){this._enterCredentials(Qt.RecoveryKey,e)}disable(){}}class Eo extends A{constructor(e){super(e);const{client:t,ready:s,homeserver:i,deleteSessionOnCancel:r}=e;this._client=t,this._ready=s,this._homeserver=i,this._deleteSessionOnCancel=r,this._loading=!1,this._error=null,this.backUrl=this.urlCreator.urlForSegment("session",!0),this._accountSetupViewModel=void 0}async start(){if(!this._loading)try{this._loading=!0,this.emitChange("loading"),this._waitHandle=this._client.loadStatus.waitFor(s=>(s===M.AccountSetup?this._accountSetupViewModel=new Yu(this.childOptions({accountSetup:this._client.accountSetup})):this._accountSetupViewModel=void 0,this.emitChange("loadLabel"),s===M.FirstSync&&this._client.sync.status.get()===L.CatchupSync||s===M.LoginFailed||s===M.Error||s===M.Ready));try{await this._waitHandle.promise}catch{return}const e=this._client.loadStatus.get(),t=this._client.loadError;if(e===M.FirstSync||e===M.Ready){const s=this._client;this._client=null,this._ready(s)}t&&console.error("session load error",t)}catch(e){this._error=e,console.error("error thrown during session load",e.stack)}finally{this._loading=!1,this.emitChange("loading")}}dispose(){this._client&&(this._client.dispose(),this._client=null),this._waitHandle&&(this._waitHandle.dispose(),this._waitHandle=null)}get loading(){const e=this._client;return e&&e.loadStatus.get()===M.AccountSetup?!1:this._loading}get loadLabel(){const e=this._client,t=this._getError();if(t||e&&e.loadStatus.get()===M.Error)return`Something went wrong: ${t&&t.message}.`;if(e)switch(e.loadStatus.get()){case M.QueryAccount:return"Querying account encryption setup\u2026";case M.AccountSetup:return"";case M.SessionSetup:return"Setting up your encryption keys\u2026";case M.Loading:return"Loading your conversations\u2026";case M.FirstSync:return"Getting your conversations from the server\u2026";default:return this._client.loadStatus.get()}return"Preparing\u2026"}_getError(){var e;return this._error||((e=this._client)==null?void 0:e.loadError)}get hasError(){return!!this._getError()}async exportLogs(){const e=await this.logger.export();this.platform.saveFileAs(e.asBlob(),`hydrogen-logs-${this.platform.clock.now()}.json`)}async logout(){await this._client.logout(),this.navigation.push("session",!0)}get accountSetupViewModel(){return this._accountSetupViewModel}}class Zu extends A{constructor(e){super(e);const{loginOptions:t,attemptLogin:s}=e;this._loginOptions=t,this._attemptLogin=s,this._isBusy=!1,this._errorMessage=""}get isBusy(){return this._isBusy}get errorMessage(){return this._errorMessage}setBusy(e){this._isBusy=e,this.emitChange("isBusy")}_showError(e){this._errorMessage=e,this.emitChange("errorMessage")}async login(e,t){this._errorMessage="",this.emitChange("errorMessage");const s=await this._attemptLogin(this._loginOptions.password(e,t));let i="";switch(s){case Ce.Credentials:i=this.i18n`Your username and/or password don't seem to be correct.`;break;case Ce.Connection:i=this.i18n`Can't connect to ${this._loginOptions.homeserver}.`;break;case Ce.Unknown:i=this.i18n`Something went wrong while checking your login and password.`;break}i&&this._showError(i)}}class em extends A{constructor(e){super(e),this._sso=e.loginOptions.sso,this._isBusy=!1}get isBusy(){return this._isBusy}setBusy(e){this._isBusy=e,this.emitChange("isBusy")}async startSSOLogin(){await this.platform.settingsStorage.setString("sso_ongoing_login_homeserver",this._sso.homeserver);const e=this._sso.createSSORedirectURL(this.urlCreator.createSSOCallbackURL());this.platform.openUrl(e)}}class tm extends A{constructor(e){super(e);const{loginToken:t,client:s,attemptLogin:i}=e;this._loginToken=t,this._client=s,this._attemptLogin=i,this._errorMessage="",this.performSSOLoginCompletion()}get errorMessage(){return this._errorMessage}_showError(e){this._errorMessage=e,this.emitChange("errorMessage")}async performSSOLoginCompletion(){if(!this._loginToken)return;const e=await this.platform.settingsStorage.getString("sso_ongoing_login_homeserver");let t;try{t=await this._client.queryLogin(e).result}catch(r){this._showError(r.message);return}if(!t.token){this.navigation.push("session");return}const s=await this._attemptLogin(t.token(this._loginToken));let i="";switch(s){case Ce.Credentials:i=this.i18n`Your login token is invalid.`;break;case Ce.Connection:i=this.i18n`Can't connect to ${e}.`;break;case Ce.Unknown:i=this.i18n`Something went wrong while checking your login token.`;break}i&&this._showError(i)}}class sm extends A{constructor(e){super(e),this._hideHomeserver=!1,this._isBusy=!1,this._errorMessage="";const{ready:t,defaultHomeserver:s,loginToken:i}=e;this._ready=t,this._loginToken=i,this._client=new ji(this.platform),this._homeserver=s,this._initViewModels()}get passwordLoginViewModel(){return this._passwordLoginViewModel}get startSSOLoginViewModel(){return this._startSSOLoginViewModel}get completeSSOLoginViewModel(){return this._completeSSOLoginViewModel}get homeserver(){return this._homeserver}get resolvedHomeserver(){var e;return(e=this._loginOptions)==null?void 0:e.homeserver}get errorMessage(){return this._errorMessage}get showHomeserver(){return!this._hideHomeserver}get loadViewModel(){return this._loadViewModel}get isBusy(){return this._isBusy}get isFetchingLoginOptions(){return!!this._abortQueryOperation}goBack(){this.navigation.push("session")}_initViewModels(){this._loginToken?(this._hideHomeserver=!0,this._completeSSOLoginViewModel=this.track(new tm(this.childOptions({client:this._client,attemptLogin:e=>this.attemptLogin(e),loginToken:this._loginToken}))),this.emitChange("completeSSOLoginViewModel")):this.queryHomeserver()}_showPasswordLogin(){this._passwordLoginViewModel=this.track(new Zu(this.childOptions({loginOptions:this._loginOptions,attemptLogin:e=>this.attemptLogin(e)}))),this.emitChange("passwordLoginViewModel")}_showSSOLogin(){this._startSSOLoginViewModel=this.track(new em(this.childOptions({loginOptions:this._loginOptions}))),this.emitChange("startSSOLoginViewModel")}_showError(e){this._errorMessage=e,this.emitChange("errorMessage")}_setBusy(e){var t,s;this._isBusy=e,(t=this._passwordLoginViewModel)==null||t.setBusy(e),(s=this._startSSOLoginViewModel)==null||s.setBusy(e),this.emitChange("isBusy")}async attemptLogin(e){this._setBusy(!0),this._client.startWithLogin(e,{inspectAccountSetup:!0});const t=this._client.loadStatus;return await t.waitFor(r=>r!==M.Login).promise,this._setBusy(!1),t.get()===M.LoginFailed?this._client.loginFailure:(this._hideHomeserver=!0,this.emitChange("hideHomeserver"),this._disposeViewModels(),this._createLoadViewModel(),null)}_createLoadViewModel(){this._loadViewModelSubscription=this.disposeTracked(this._loadViewModelSubscription),this._loadViewModel=this.disposeTracked(this._loadViewModel),this._loadViewModel=this.track(new Eo(this.childOptions({ready:e=>{this._client=null,this._ready(e)},client:this._client,homeserver:this._homeserver}))),this._loadViewModel.start(),this.emitChange("loadViewModel"),this._loadViewModelSubscription=this.track(this._loadViewModel.disposableOn("change",()=>{this._loadViewModel.loading||(this._loadViewModelSubscription=this.disposeTracked(this._loadViewModelSubscription)),this._setBusy(!1)}))}_disposeViewModels(){this._startSSOLoginViewModel=this.disposeTracked(this._startSSOLoginViewModel),this._passwordLoginViewModel=this.disposeTracked(this._passwordLoginViewModel),this._completeSSOLoginViewModel=this.disposeTracked(this._completeSSOLoginViewModel),this.emitChange("disposeViewModels")}async setHomeserver(e){this._homeserver=e,this._loginOptions=void 0,this._queriedHomeserver=void 0,this._showError(""),this._disposeViewModels(),this._abortQueryOperation=this.disposeTracked(this._abortQueryOperation),this.emitChange("loginViewModels"),this.disposeTracked(this._abortHomeserverQueryTimeout);const t=this.clock.createTimeout(1e3);this._abortHomeserverQueryTimeout=this.track(()=>t.abort());try{await t.elapsed()}catch(s){if(s.name==="AbortError")return;throw s}this._abortHomeserverQueryTimeout=this.disposeTracked(this._abortHomeserverQueryTimeout),this.queryHomeserver()}async queryHomeserver(){if(!(this._homeserver===this._queriedHomeserver||this._homeserver==="")){this._queriedHomeserver=this._homeserver,this._abortHomeserverQueryTimeout=this.disposeTracked(this._abortHomeserverQueryTimeout),this._abortQueryOperation=this.disposeTracked(this._abortQueryOperation);try{const e=this._client.queryLogin(this._homeserver);this._abortQueryOperation=this.track(()=>e.abort()),this.emitChange("isFetchingLoginOptions"),this._loginOptions=await e.result,this.emitChange("resolvedHomeserver")}catch(e){if(e.name==="AbortError")return;this._loginOptions=void 0}finally{this._abortQueryOperation=this.disposeTracked(this._abortQueryOperation),this.emitChange("isFetchingLoginOptions")}this._loginOptions?(this._loginOptions.sso&&this._showSSOLogin(),this._loginOptions.password&&this._showPasswordLogin(),!this._loginOptions.sso&&!this._loginOptions.password&&this._showError("This homeserver supports neither SSO nor password based login flows")):this._showError(`Could not query login methods supported by ${this.homeserver}`)}}dispose(){super.dispose(),this._client&&this._client.deleteSession()}}class im extends A{constructor(e){super(e),this._sessionId=e.sessionId,this._busy=!1,this._showConfirm=!0,this._error=void 0}get showConfirm(){return this._showConfirm}get busy(){return this._busy}get cancelUrl(){return this.urlCreator.urlForSegment("session",!0)}async logout(){this._busy=!0,this._showConfirm=!1,this.emitChange("busy");try{await new ji(this.platform).startLogout(this._sessionId),this.navigation.push("session",!0)}catch(e){this._error=e,this._busy=!1,this.emitChange("busy")}}get status(){return this._error?this.i18n`Could not log out of device: ${this._error.message}`:this.i18n`Logging out… Please don't close the app.`}}class rm extends A{constructor(e,t){super(e),this._pickerVM=t,this._sessionInfo=e.sessionInfo,this._isDeleting=!1,this._isClearing=!1,this._error=null,this._exportDataUrl=null}get error(){return this._error&&this._error.message}get id(){return this._sessionInfo.id}get openUrl(){return this.urlCreator.urlForSegment("session",this.id)}get label(){const{userId:e,comment:t}=this._sessionInfo;return t?`${e} (${t})`:e}get sessionInfo(){return this._sessionInfo}get exportDataUrl(){return this._exportDataUrl}get avatarColorNumber(){return de(this._sessionInfo.userId)}get avatarInitials(){return he(this._sessionInfo.userId)}}class nm extends A{constructor(e){super(e),this._sessions=new xi((t,s)=>t.id.localeCompare(s.id)),this._loadViewModel=null,this._error=null}async load(){const e=await this.platform.sessionInfoStorage.getAll();this._sessions.setManyUnsorted(e.map(t=>new rm(this.childOptions({sessionInfo:t}),this)))}get loadViewModel(){return this._loadViewModel}get sessions(){return this._sessions}get cancelUrl(){return this.urlCreator.urlForSegment("login")}}class om extends A{constructor(e){super(e),this._error=null,this._sessionPickerViewModel=null,this._sessionLoadViewModel=null,this._loginViewModel=null,this._logoutViewModel=null,this._sessionViewModel=null,this._pendingClient=null}async load(){this.track(this.navigation.observe("login").subscribe(()=>this._applyNavigation())),this.track(this.navigation.observe("session").subscribe(()=>this._applyNavigation())),this.track(this.navigation.observe("sso").subscribe(()=>this._applyNavigation())),this._applyNavigation(!0)}async _applyNavigation(e){var o,a,c;const t=this.navigation.path.get("login"),s=(o=this.navigation.path.get("logout"))==null?void 0:o.value,i=(a=this.navigation.path.get("session"))==null?void 0:a.value,r=(c=this.navigation.path.get("sso"))==null?void 0:c.value;if(t)this.activeSection!=="login"&&this._showLogin();else if(s)this.activeSection!=="logout"&&this._showLogout(s);else if(i===!0)this.activeSection!=="picker"&&this._showPicker();else if(i){if(!this._sessionViewModel||this._sessionViewModel.id!==i)if(this._pendingClient&&this._pendingClient.sessionId===i){const l=this._pendingClient;this._pendingClient=null,this._showSession(l)}else this._pendingClient&&(this._pendingClient.dispose(),this._pendingClient=null),this._showSessionLoader(i)}else if(r)this.urlCreator.normalizeUrl(),this.activeSection!=="login"&&this._showLogin(r);else try{if(!(e&&this.urlCreator.tryRestoreLastUrl())){const l=await this.platform.sessionInfoStorage.getAll();l.length===0?this.navigation.push("login"):l.length===1?this.navigation.push("session",l[0].id):this.navigation.push("session")}}catch(l){this._setSection(()=>this._error=l)}}async _showPicker(){this._setSection(()=>{this._sessionPickerViewModel=new nm(this.childOptions())});try{await this._sessionPickerViewModel.load()}catch(e){this._setSection(()=>this._error=e)}}_showLogin(e){this._setSection(()=>{this._loginViewModel=new sm(this.childOptions({defaultHomeserver:this.platform.config.defaultHomeServer,ready:t=>{this._pendingClient=t,this.navigation.push("session",t.sessionId)},loginToken:e}))})}_showLogout(e){this._setSection(()=>{this._logoutViewModel=new im(this.childOptions({sessionId:e}))})}_showSession(e){this._setSection(()=>{this._sessionViewModel=new Qu(this.childOptions({client:e})),this._sessionViewModel.start()})}_showSessionLoader(e){const t=new ji(this.platform);t.startWithExistingSession(e),this._setSection(()=>{this._sessionLoadViewModel=new Eo(this.childOptions({client:t,ready:s=>this._showSession(s)})),this._sessionLoadViewModel.start()})}get activeSection(){return this._error?"error":this._sessionViewModel?"session":this._loginViewModel?"login":this._logoutViewModel?"logout":this._sessionPickerViewModel?"picker":this._sessionLoadViewModel?"loading":"redirecting"}_setSection(e){this._error=null,this._sessionPickerViewModel=this.disposeTracked(this._sessionPickerViewModel),this._sessionLoadViewModel=this.disposeTracked(this._sessionLoadViewModel),this._loginViewModel=this.disposeTracked(this._loginViewModel),this._logoutViewModel=this.disposeTracked(this._logoutViewModel),this._sessionViewModel=this.disposeTracked(this._sessionViewModel),e(),this._sessionPickerViewModel&&this.track(this._sessionPickerViewModel),this._sessionLoadViewModel&&this.track(this._sessionLoadViewModel),this._loginViewModel&&this.track(this._loginViewModel),this._logoutViewModel&&this.track(this._logoutViewModel),this._sessionViewModel&&this.track(this._sessionViewModel),this.emitChange("activeSection")}get error(){return this._error}get sessionViewModel(){return this._sessionViewModel}get loginViewModel(){return this._loginViewModel}get logoutViewModel(){return this._logoutViewModel}get sessionPickerViewModel(){return this._sessionPickerViewModel}get sessionLoadViewModel(){return this._sessionLoadViewModel}}async function am(n){try{await n.init();const e=Vd();n.setNavigation(e);const t=Ld({navigation:e,history:n.history});t.attach();const s=new om({platform:n,urlCreator:t,navigation:e});await s.load(),n.createAndMountRootView(s)}catch(e){console.error(`${e.message}: +${e.stack}`)}}function cm(n,e,t,s){const i=n(e);let r=!1;return i.elapsed().then(()=>{r=!0,t.abort()},()=>{}),s.then(o=>(i.abort(),o),o=>{throw i.abort(),o.name==="AbortError"&&r?new qe(`Request timed out after ${e}ms`,!0):o})}function ko(n,e=Math.random){return n.includes("?")?n=n+"&":n=n+"?",n+`_cacheBuster=${Math.ceil(e()*Number.MAX_SAFE_INTEGER)}`}function Ro(n){var t;const e=new FormData;for(const[s,i]of n)((t=i.blob)==null?void 0:t.nativeBlob)&&i.name?e.set(s,i.blob.nativeBlob,i.name):e.set(s,i);return e}class lm{constructor(e,t){this._promise=e,this._xhr=t}abort(){this._xhr.abort()}response(){return this._promise}}function hm(n,{method:e,headers:t,timeout:s,format:i,uploadProgress:r}){const o=new XMLHttpRequest;if(r&&o.upload.addEventListener("progress",a=>r(a.loaded)),o.open(e,n),i==="buffer"&&(o.responseType="arraybuffer"),t)for(const[a,c]of t.entries())try{o.setRequestHeader(a,c)}catch(l){console.info(`Could not set ${a} header: ${l.message}`)}return s&&(o.timeout=s),o}function dm(n,e,t){return new Promise((s,i)=>{n.addEventListener("load",()=>s(n)),n.addEventListener("abort",()=>i(new ye)),n.addEventListener("error",()=>i(new qe(`Error ${e} ${t}`))),n.addEventListener("timeout",()=>i(new qe(`Timeout ${e} ${t}`,!0)))})}function Co(n,e){let{cache:t,format:s,body:i,method:r}=e;t||(n=ko(n));const o=hm(n,e),a=dm(o,r,n).then(c=>{const{status:l}=c;let h=null;return s==="buffer"?h=c.response:c.getResponseHeader("Content-Type")==="application/json"&&(h=JSON.parse(c.responseText)),{status:l,body:h}});return i!=null&&i.nativeBlob&&(i=i.nativeBlob),i instanceof Map&&(i=Ro(i)),o.send(i||null),new lm(a,o)}class an{constructor(e,t){if(t)this.promise=e,this._controller=t;else{const s=new Promise((i,r)=>{this._controller={abort(){const o=new Error("fetch request aborted");o.name="AbortError",r(o)}}});this.promise=Promise.race([e,s])}}abort(){this._controller.abort()}response(){return this.promise}}function um(n,e){return function(s,i){if(e!=null&&e.haltRequests)return new an(new Promise(()=>{}),{});if(i!=null&&i.uploadProgress)return Co(s,i);let{method:r,headers:o,body:a,timeout:c,format:l,cache:h=!1}=i;const d=typeof AbortController=="function"?new AbortController:null;a!=null&&a.nativeBlob&&(a=a.nativeBlob),a instanceof Map&&(a=Ro(a));let u={method:r,body:a};if(d&&(u=Object.assign(u,{signal:d.signal})),h||(s=ko(s)),u=Object.assign(u,{mode:"cors",credentials:"omit",referrer:"no-referrer",cache:"default"}),o){const f=new Headers;for(const[b,S]of o.entries())f.append(b,S);u.headers=f}const p=fetch(s,u).then(async f=>{const{status:b}=f;let S;try{l==="json"?S=await f.json():l==="buffer"?S=await f.arrayBuffer():l==="text"&&(S=await f.text())}catch(k){if(!(k.name==="SyntaxError"&&b>=400))throw k}return{status:b,body:S}},f=>{throw f.name==="AbortError"?new ye:f instanceof TypeError?new qe(`${r} ${s}: ${f.message}`):f}),_=new an(p,d);return c&&(_.promise=cm(n,c,_,_.promise)),_}}class mm{constructor(e){this._name=e}getAll(){const e=localStorage.getItem(this._name);if(e){const t=JSON.parse(e);if(Array.isArray(t))return Promise.resolve(t)}return Promise.resolve([])}async updateLastUsed(e,t){const s=await this.getAll();if(s){const i=s.find(r=>r.id===e);i&&(i.lastUsed=t,localStorage.setItem(this._name,JSON.stringify(s)))}}async get(e){const t=await this.getAll();if(t)return t.find(s=>s.id===e)}async add(e){const t=await this.getAll();t.push(e),localStorage.setItem(this._name,JSON.stringify(t))}async delete(e){let t=await this.getAll();t=t.filter(s=>s.id!==e),localStorage.setItem(this._name,JSON.stringify(t))}}class pm{constructor(e){this._prefix=e}async setInt(e,t){this._set(e,t)}async getInt(e,t=0){const s=window.localStorage.getItem(`${this._prefix}${e}`);return typeof s=="string"?parseInt(s,10):t}async setBool(e,t){this._set(e,t)}async getBool(e,t=!1){const s=window.localStorage.getItem(`${this._prefix}${e}`);return typeof s=="string"?s==="true":t}async setString(e,t){this._set(e,t)}async getString(e){return window.localStorage.getItem(`${this._prefix}${e}`)}async remove(e){window.localStorage.removeItem(`${this._prefix}${e}`)}async _set(e,t){window.localStorage.setItem(`${this._prefix}${e}`,t)}}class _m{constructor(){this._encoder=null,this._decoder=null}encode(e){return this._encoder||(this._encoder=new TextEncoder),this._encoder.encode(e)}decode(e){return this._decoder||(this._decoder=new TextDecoder),this._decoder.decode(e)}}var nt={};(function(){for(var n="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",e=new Uint8Array(256),t=0;t>2],a+=n[(i[r]&3)<<4|i[r+1]>>4],a+=n[(i[r+1]&15)<<2|i[r+2]>>6],a+=n[i[r+2]&63];return o%3===2?a=a.substring(0,a.length-1)+"=":o%3===1&&(a=a.substring(0,a.length-2)+"=="),a},nt.decode=function(s){var i=s.length*.75,r=s.length,o,a=0,c,l,h,d;s[s.length-1]==="="&&(i--,s[s.length-2]==="="&&i--);var u=new ArrayBuffer(i),p=new Uint8Array(u);for(o=0;o>4,p[a++]=(l&15)<<4|h>>2,p[a++]=(h&3)<<6|d&63;return u}})();class fm{encodeUnpadded(e){const t=nt.encode(e),s=t.indexOf("=");return s!==-1?t.substr(0,s):t}encode(e){return nt.encode(e)}decode(e){return nt.decode(e)}}var To={isBuffer:function(n){return n instanceof Uint8Array},from:function(n){return n},allocUnsafe:function(n){return To.alloc(n)},alloc:function(n){return new Uint8Array(n)}},gm=Object.freeze(Object.defineProperty({__proto__:null,Buffer:To},Symbol.toStringTag,{value:"Module"})),ym=Na(gm),vs=ym.Buffer;function wm(n){if(n.length>=255)throw new TypeError("Alphabet too long");for(var e=new Uint8Array(256),t=0;t>>0,R=new Uint8Array(k);b!==S;){for(var w=p[b],I=0,x=k-1;(w!==0||I>>0,R[x]=w%o>>>0,w=w/o>>>0;if(w!==0)throw new Error("Non-zero carry");f=I,b++}for(var D=k-f;D!==k&&R[D]===0;)D++;for(var Le=a.repeat(_);D>>0,k=new Uint8Array(S);p[_];){var R=e[p.charCodeAt(_)];if(R===255)return;for(var w=0,I=S-1;(R!==0||w>>0,k[I]=R%256>>>0,R=R/256>>>0;if(R!==0)throw new Error("Non-zero carry");b=w,_++}if(p[_]!==" "){for(var x=S-b;x!==S&&k[x]===0;)x++;var D=vs.allocUnsafe(f+(S-x));D.fill(0,0,f);for(var Le=f;x!==S;)D[Le++]=k[x++];return D}}}function u(p){var _=d(p);if(_)return _;throw new Error("Non-base"+o+" character")}return{encode:h,decodeUnsafe:d,decode:u}}var vm=wm,bm=vm,Sm="123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz",cn=bm(Sm);class Im{encode(e){return cn.encode(e)}decode(e){return cn.decode(e)}}class Em{constructor(){this.utf8=new _m,this.base64=new fm,this.base58=new Im}}class km{constructor(e){this._workerPool=e}megolmDecrypt(e,t){const s=e.export_session(e.first_known_index());return this._workerPool.send({type:"megolm_decrypt",ciphertext:t,sessionKey:s})}async createAccountAndOTKs(e,t){let s;window.msCrypto&&(s=[window.msCrypto.getRandomValues(new Uint8Array(64)),window.msCrypto.getRandomValues(new Uint8Array(t*32))]);const i=await this._workerPool.send({type:"olm_create_account_otks",randomValues:s,otkAmount:t}).response();e.unpickle("",i)}async createOutboundOlmSession(e,t,s,i){const r=e.pickle("");let o;window.msCrypto&&(o=[window.msCrypto.getRandomValues(new Uint8Array(64))]);const a=await this._workerPool.send({type:"olm_create_outbound",accountPickle:r,theirIdentityKey:s,theirOneTimeKey:i,randomValues:o}).response();t.unpickle("",a)}dispose(){this._workerPool.dispose()}}class Rm extends go{constructor(e){super(e);const{name:t,flushInterval:s=60*1e3,limit:i=3e3}=e;this._name=t,this._limit=i,this._queuedItems=this._loadQueuedItems(),window.addEventListener("pagehide",this,!1),this._flushInterval=this._platform.clock.createInterval(()=>this._tryFlush(),s)}dispose(){window.removeEventListener("pagehide",this,!1),this._flushInterval.dispose()}handleEvent(e){e.type==="pagehide"&&this._finishAllAndFlush()}async _tryFlush(){const e=await this._openDB();try{const t=e.transaction(["logs"],"readwrite"),s=t.objectStore("logs"),i=this._queuedItems.length;for(const o of this._queuedItems)s.add(o);const r=await X(s.count());if(r>this._limit){let o=r-this._limit+Math.round(.1*this._limit);await K(s.openCursor(),(a,c,l)=>(l.delete(),o-=1,{done:o===0}))}await Jt(t),this._queuedItems.splice(0,i)}catch(t){console.error("Could not flush logs",t)}finally{try{e.close()}catch{}}}_finishAllAndFlush(){this._finishOpenItems(),this.log({l:"pagehide, closing logs",t:"navigation"}),this._persistQueuedItems(this._queuedItems)}_loadQueuedItems(){const e=`${this._name}_queuedItems`;try{const t=window.localStorage.getItem(e);if(t)return window.localStorage.removeItem(e),JSON.parse(t)}catch(t){console.error("Could not load queued log items",t)}return[]}_openDB(){return Mi(this._name,e=>e.createObjectStore("logs",{keyPath:"id",autoIncrement:!0}),1)}_persistItem(e,t,s){const i=e.serialize(t,void 0,s);if(i){const r=this._serializedTransformer(i);this._queuedItems.push({json:JSON.stringify(r)})}}_persistQueuedItems(e){try{window.localStorage.setItem(`${this._name}_queuedItems`,JSON.stringify(e))}catch(t){console.error("Could not persist queued log items in localStorage, they will likely be lost",t)}}async export(){const e=await this._openDB();try{const s=e.transaction(["logs"],"readonly").objectStore("logs"),r=(await dc(s.openCursor(),()=>!1)).concat(this._queuedItems);return new Cm(r,this,this._platform)}finally{try{e.close()}catch{}}}async _removeItems(e){const t=await this._openDB();try{const s=t.transaction(["logs"],"readwrite"),i=s.objectStore("logs");for(const r of e)if(typeof r.id=="number")i.delete(r.id);else{const o=this._queuedItems.indexOf(r);o===-1&&this._queuedItems.splice(o,1)}await Jt(s)}finally{try{t.close()}catch{}}}}class Cm{constructor(e,t,s){this._items=e,this._logger=t,this._platform=s}get count(){return this._items.length}removeFromStore(){return this._logger._removeItems(this._items)}asBlob(){var r;const e={formatVersion:1,appVersion:(r=this._platform.updateService)==null?void 0:r.version,items:this._items.map(o=>JSON.parse(o.json))},t=JSON.stringify(e),s=this._platform.encoding.utf8.encode(t);return this._platform.createBlob(s,"application/json")}}function Mo(n){return typeof n!="object"||"nodeType"in n||Array.isArray(n)}function It(n,e){return Object.entries(n).reduce((t,[s,i])=>(typeof i=="function"&&(i=i(e)),i?t+(t.length?" ":"")+s:t),"")}function vt(n,e,t){e==="className"&&(e="class"),t===!1?n.removeAttribute(e):(t===!0&&(t=e),n.setAttribute(e,t))}function Tm(n,e,t){return Ao(Hi,n,e,t)}function Ao(n,e,t,s){t&&Mo(t)&&(s=t,t=void 0);const i=document.createElementNS(n,e);if(t)for(let[r,o]of Object.entries(t))typeof o=="object"&&(o=o!==null&&r==="className"?It(o,void 0):!1),vt(i,r,o);if(s){Array.isArray(s)||(s=[s]);for(let r of s)typeof r=="string"&&(r=Te(r)),i.appendChild(r)}return i}function Te(n){return document.createTextNode(n)}const Hi="http://www.w3.org/1999/xhtml",Mm="http://www.w3.org/2000/svg",xo={[Hi]:["br","a","ol","ul","li","div","h1","h2","h3","h4","h5","h6","p","strong","em","span","img","section","main","article","aside","del","blockquote","table","thead","tbody","tr","th","td","hr","pre","code","button","time","input","textarea","select","option","label","form","progress","output","video"],[Mm]:["svg","g","path","circle","ellipse","rect","use"]},T={};for(const[n,e]of Object.entries(xo))for(const t of e)T[t]=function(s,i){return Ao(n,t,s,i)};function Xt(n,e){let t;try{t=n.mount(e)}catch(s){t=Am(s)}return t}function Am(n){const e=new Error().stack;let t=null;return e&&(t=e.split(` +`)[1]),T.div([T.h2("Something went wrong\u2026"),T.h3(n.message),T.p(`This occurred while running ${t}.`),T.pre(n.stack)])}function ln(n,e,t){if(e===n.childElementCount)n.appendChild(t);else{const i=n.children[e];n.insertBefore(t,i)}}function xm(n){n.innerHTML=""}function Nm(n){return async e=>{var t,s;(t=e.target)==null||t.setAttribute("disabled","disabled"),await n(e),(s=e.target)==null||s.removeAttribute("disabled")}}class is{constructor({list:e,onItemClick:t,className:s,tagName:i="ul",parentProvidesUpdates:r=!0},o){this._onItemClick=t,this._list=e,this._className=s,this._tagName=i,this._root=void 0,this._subscription=void 0,this._childCreator=o,this._childInstances=void 0,this._mountArgs={parentProvidesUpdates:r}}root(){return this._root}update(e){if(e.list){if(this._subscription)for(this._unloadList();this._root.lastChild;)this._root.lastChild.remove();this._list=e.list,this.loadList()}}mount(){const e={};this._className&&(e.className=this._className);const t=this._root=Tm(this._tagName,e);return this.loadList(),this._onItemClick&&t.addEventListener("click",this),t}handleEvent(e){e.type==="click"&&this._handleClick(e)}unmount(){this._list&&this._unloadList()}_handleClick(e){if(e.target===this._root||!this._onItemClick)return;let t=e.target;for(;t.parentNode!==this._root;)t=t.parentNode;const s=Array.prototype.indexOf.call(this._root.childNodes,t),i=this._childInstances[s];i&&this._onItemClick(i,e)}_unloadList(){this._subscription=this._subscription();for(let e of this._childInstances)e.unmount();this._childInstances=void 0}loadList(){if(!this._list)return;this._subscription=this._list.subscribe(this),this._childInstances=[];const e=document.createDocumentFragment();for(let t of this._list){const s=this._childCreator(t);this._childInstances.push(s),e.appendChild(Xt(s,this._mountArgs))}this._root.appendChild(e)}onReset(){for(const e of this._childInstances)e.root().remove(),e.unmount();this._childInstances.length=0}onAdd(e,t){this.addChild(e,t)}onRemove(e,t){this.removeChild(e)}onMove(e,t,s){this.moveChild(e,t)}onUpdate(e,t,s){this.updateChild(e,t,s)}addChild(e,t){const s=this._childCreator(t);this._childInstances.splice(e,0,s),ln(this._root,e,Xt(s,this._mountArgs))}removeChild(e){const[t]=this._childInstances.splice(e,1);t.root().remove(),t.unmount()}moveChild(e,t){const[s]=this._childInstances.splice(e,1);this._childInstances.splice(t,0,s),s.root().remove(),ln(this._root,t,s.root())}updateChild(e,t,s){if(this._childInstances){const i=this._childInstances[e];i&&i.update(t,s)}}recreateItem(e,t){if(this._childInstances){const s=this._childCreator(t);if(!s)this.onRemove(e,t);else{const[i]=this._childInstances.splice(e,1,s);this._root.replaceChild(s.mount(this._mountArgs),i.root()),i.unmount()}}}getChildInstanceByIndex(e){var t;return(t=this._childInstances)==null?void 0:t[e]}}class No{constructor(e){this._value=e,this._boundUpdateFromValue=null}subscribeOnMount(e){e&&e.parentProvidesUpdates||this._subscribe()}unmount(){this._unsubscribe()}get value(){return this._value}_updateFromValue(e){this.update(this._value,e)}_subscribe(){var e;typeof((e=this._value)==null?void 0:e.on)=="function"&&(this._boundUpdateFromValue=this._updateFromValue.bind(this),this._value.on("change",this._boundUpdateFromValue))}_unsubscribe(){this._boundUpdateFromValue&&(typeof this._value.off=="function"&&this._value.off("change",this._boundUpdateFromValue),this._boundUpdateFromValue=null)}}function Dm(n){for(const e of Object.values(n))if(typeof e=="function")return!0;return!1}class E extends No{constructor(){super(...arguments),this._eventListeners=void 0,this._bindings=void 0,this._root=void 0,this._subViews=void 0}_attach(){if(this._eventListeners)for(let{node:e,name:t,fn:s,useCapture:i}of this._eventListeners)e.addEventListener(t,s,i)}_detach(){if(this._eventListeners)for(let{node:e,name:t,fn:s,useCapture:i}of this._eventListeners)e.removeEventListener(t,s,i)}mount(e){const t=new Do(this);try{this._root=this.render(t,this._value)}finally{t.close()}return this.subscribeOnMount(e),this._attach(),this._root}unmount(){if(this._detach(),super.unmount(),this._subViews)for(const e of this._subViews)e.unmount()}root(){return this._root}update(e,t){if(this._value=e,this._bindings)for(const s of this._bindings)s()}_addEventListener(e,t,s,i=!1){this._eventListeners||(this._eventListeners=[]),this._eventListeners.push({node:e,name:t,fn:s,useCapture:i})}_addBinding(e){this._bindings||(this._bindings=[]),this._bindings.push(e)}addSubView(e){this._subViews||(this._subViews=[]),this._subViews.push(e)}removeSubView(e){if(!this._subViews)return;const t=this._subViews.indexOf(e);t!==-1&&this._subViews.splice(t,1)}updateSubViews(e,t){if(this._subViews)for(const s of this._subViews)s.update(e,t)}}class Do{constructor(e){this._closed=!1,this._templateView=e}close(){this._closed=!0}_addBinding(e){this._closed&&console.trace("Adding a binding after render will likely cause memory leaks"),this._templateView._addBinding(e)}get _value(){return this._templateView.value}addEventListener(e,t,s,i=!1){this._templateView._addEventListener(e,t,s,i)}_addAttributeBinding(e,t,s){let i;const r=()=>{const o=s(this._value);i!==o&&(i=o,vt(e,t,o))};this._addBinding(r),r()}_addClassNamesBinding(e,t){this._addAttributeBinding(e,"className",s=>It(t,s))}_addTextBinding(e){const t=e(this._value)+"",s=Te(t);let i=t;const r=()=>{const o=e(this._value)+"";i!==o&&(i=o,s.textContent=o)};return this._addBinding(r),s}_isEventHandler(e,t){return e.startsWith("on")&&e.length>2&&typeof t=="function"}_setNodeAttributes(e,t){for(let[s,i]of Object.entries(t))if(typeof i=="object"){if(s!=="className"||i===null)continue;Dm(i)?this._addClassNamesBinding(e,i):vt(e,s,It(i,this._value))}else if(this._isEventHandler(s,i)){const r=s.substr(2,1).toLowerCase()+s.substr(3),o=i;this._templateView._addEventListener(e,r,o)}else typeof i=="function"?this._addAttributeBinding(e,s,i):vt(e,s,i)}_setNodeChildren(e,t){Array.isArray(t)||(t=[t]);for(let s of t)typeof s=="function"?s=this._addTextBinding(s):typeof s=="string"&&(s=Te(s)),e.appendChild(s)}_addReplaceNodeBinding(e,t){let s=e(this._value),i=t(null);const r=()=>{const o=e(this._value);if(s!==o){s=o;const a=t(i);i.parentNode&&i.parentNode.replaceChild(a,i),i=a}};return this._addBinding(r),i}el(e,t,s){return this.elNS(Hi,e,t,s)}elNS(e,t,s,i){let r;s&&(Mo(s)?i=s:r=s);const o=document.createElementNS(e,t);return r&&this._setNodeAttributes(o,r),i&&this._setNodeChildren(o,i),o}view(e,t){return this._templateView.addSubView(e),Xt(e,t)}mapView(e,t){return this._addReplaceNodeBinding(e,s=>{if(s&&s.nodeType!==Node.COMMENT_NODE){const r=this._templateView._subViews;if(r){const o=r.findIndex(a=>a.root()===s);if(o!==-1){const[a]=r.splice(o,1);a.unmount()}}}const i=t(e(this._value));return i?this.view(i):document.createComment("node binding placeholder")})}map(e,t){return this.mapView(e,s=>new Ns(this._value,(i,r)=>{const o=t(s,i,r);return o||document.createComment("map placeholder")}))}ifView(e,t){return this.mapView(s=>!!e(s),s=>s?t(this._value):null)}if(e,t){return this.ifView(e,s=>new Ns(s,t))}mapSideEffect(e,t){let s=e(this._value);const i=()=>{const r=e(this._value);s!==r&&(t(r,s),s=r)};this._addBinding(i),t(s,void 0)}}for(const[n,e]of Object.entries(xo))for(const t of e)Do.prototype[t]=function(s,i){return this.elNS(n,t,s,i)};class Ns extends E{constructor(e,t){super(e),this._render=t}render(e,t){return this._render(e,t)}}function it(n,e,t=void 0){const s=!!n.avatarUrl(e);let i=It({avatar:!0,[`size-${e}`]:!0,[`usercolor${n.avatarColorNumber}`]:!s});t&&(i+=` ${t}`);const r=s?Vo(n,e):Te(n.avatarLetter),o=T.div({className:i,"data-testid":"avatar"},[r]);return s&&(vt(o,"data-avatar-letter",n.avatarLetter),vt(o,"data-avatar-color",n.avatarColorNumber)),o}function Vo(n,e){const t=e.toString();return T.img({src:n.avatarUrl(e),width:t,height:t,title:n.avatarTitle})}function Vm(n){const e=n.target,t=e.parentElement;return e.tagName==="IMG"&&t.classList.contains("avatar")}function hn(n){if(!Vm(n))return;const e=n.target.parentElement,t=e.getAttribute("data-avatar-color");e.classList.add(`usercolor${t}`);const s=e.getAttribute("data-avatar-letter");e.textContent=s}class ht extends No{constructor(e,t){super(e),this._root=null,this._avatarUrl=null,this._avatarTitle=null,this._avatarLetter=null,this._size=t}_avatarUrlChanged(){return this.value.avatarUrl(this._size)!==this._avatarUrl?(this._avatarUrl=this.value.avatarUrl(this._size),!0):!1}_avatarTitleChanged(){return this.value.avatarTitle!==this._avatarTitle?(this._avatarTitle=this.value.avatarTitle,!0):!1}_avatarLetterChanged(){return this.value.avatarLetter!==this._avatarLetter?(this._avatarLetter=this.value.avatarLetter,!0):!1}mount(e){return this._avatarUrlChanged(),this._avatarLetterChanged(),this._avatarTitleChanged(),this._root=it(this.value,this._size),this.subscribeOnMount(e),this._root}root(){return this._root}update(e){if(this._avatarUrlChanged()){const s=`usercolor${e.avatarColorNumber}`;e.avatarUrl(this._size)?(this._root.replaceChild(Vo(e,this._size),this._root.firstChild),this._root.classList.remove(s)):(this._root.textContent=e.avatarLetter,this._root.classList.add(s))}const t=!!e.avatarUrl(this._size);if(this._avatarTitleChanged()&&t){const s=this._root.firstChild;s.tagName==="IMG"&&s.setAttribute("title",e.avatarTitle)}this._avatarLetterChanged()&&!t&&(this._root.textContent=e.avatarLetter)}}let Ot;function Ve(n,e=void 0){Ot===void 0&&(Ot=document.querySelector(".hydrogen"));const t=Object.assign({spinner:!0},e);return Ot!=null&&Ot.classList.contains("legacy")?n.div({className:t},[n.div(),n.div(),n.div(),n.div()]):n.svg({className:t,viewBox:"0 0 100 100"},n.circle({cx:"50%",cy:"50%",r:"45%",pathLength:"100"}))}class Lm extends E{render(e,t){const s={active:i=>i.isOpen,hidden:i=>i.hidden};return e.li({className:s},[e.a({href:t.url},[e.view(new ht(t,32),{parentProvidesUpdates:!0}),e.div({className:"description"},[e.div({className:{name:!0,unread:i=>i.isUnread}},i=>i.name),e.map(i=>i.busy,i=>i?Ve(e):e.div({className:{badge:!0,highlighted:r=>r.isHighlighted,hidden:r=>!r.badgeCount}},r=>r.badgeCount))])])])}update(e,t){super.update(e),this.updateSubViews(e,t)}}class Om extends E{render(e,t){const s=()=>{i.value="",i.blur(),r.blur(),t.clear()},i=e.input({type:"text",placeholder:t==null?void 0:t.label,"aria-label":t==null?void 0:t.label,autocomplete:t==null?void 0:t.autocomplete,enterkeyhint:"search",name:t==null?void 0:t.name,onInput:o=>t.set(o.target.value),onKeydown:o=>{(o.key==="Escape"||o.key==="Esc")&&s()},onFocus:()=>i.select()}),r=e.button({onClick:s,title:t.i18n`Clear`,"aria-label":t.i18n`Clear`});return e.div({className:"FilterField"},[i,r])}}class Pm extends E{render(e,t){const s=o=>o.gridEnabled?o.i18n`Show single room`:o.i18n`Enable grid layout`,i=e.view(new is({className:"RoomList",list:t.tileViewModels},o=>new Lm(o))),r=e.div({className:"utilities"},[e.a({className:"button-utility close-session",href:t.closeUrl,"aria-label":t.i18n`Back to account list`,title:t.i18n`Back to account list`}),e.view(new Om({i18n:t.i18n,label:t.i18n`Filter rooms…`,name:"room-filter",autocomplete:!0,set:o=>{t.setFilter(o)&&(i.scrollTop=0)},clear:()=>t.clearFilter()})),e.button({onClick:()=>t.toggleGrid(),className:{"button-utility":!0,grid:!0,on:o=>o.gridEnabled},title:s,"aria-label":s}),e.a({className:"button-utility settings",href:t.settingsUrl,"aria-label":t.i18n`Settings`,title:t.i18n`Settings`}),e.a({className:"button-utility create",href:t.createRoomUrl,"aria-label":t.i18n`Create room`,title:t.i18n`Create room`})]);return e.div({className:"LeftPanel"},[r,i])}}class zi{constructor(e,t=null){this._view=e,this._target=null,this._arrangement=null,this._scroller=null,this._fakeRoot=null,this._trackingTemplateView=null,this._closeCallback=t}_getPopupContainer(){const e=this._target.closest(".hydrogen");let t=e.querySelector(".popupContainer");return t||(t=T.div({className:"popupContainer"}),e.appendChild(t)),t}trackInTemplateView(e){this._trackingTemplateView=e,this._trackingTemplateView.addSubView(this)}showRelativeTo(e,t=0){this._target=e,this._verticalPadding=t,this._scroller=Um(this._target),this._view.mount(),this._getPopupContainer().appendChild(this._popup),this._position(),this._scroller&&document.body.addEventListener("scroll",this,!0),setTimeout(()=>{document.body.addEventListener("click",this,!1)},10)}get isOpen(){return!!this._view}close(){this._view&&(this._view.unmount(),this._trackingTemplateView.removeSubView(this),this._scroller&&document.body.removeEventListener("scroll",this,!0),document.body.removeEventListener("click",this,!1),this._popup.remove(),this._view=null,this._closeCallback&&this._closeCallback())}get _popup(){return this._view.root()}handleEvent(e){e.type==="scroll"?this._position()||this.close():e.type==="click"&&this._onClick(e)}_onClick(){this.close()}_position(){const e=this._target.getBoundingClientRect(),t=this._popup.clientWidth,s=this._popup.clientHeight,i=(this._scroller?this._scroller:document.documentElement).getBoundingClientRect();if(e.top>i.bottom||e.left>i.right||e.bottom=e.bottom+s)this._popup.style.top=`${e.bottom+this._verticalPadding}px`;else if(i.top<=e.top-s)this._popup.style.top=`${e.top-s-this._verticalPadding}px`;else return!1;if(i.right>=e.right+t)this._popup.style.left=`${e.left}px`;else if(i.left<=e.left-t)this._popup.style.left=`${e.right-t}px`;else return!1;return!0}root(){return this._fakeRoot}mount(){return this._fakeRoot=document.createComment("popup"),this._fakeRoot}unmount(){this.close()}update(){}}function Um(n){let e=n;do if(e=e.parentElement,e.scrollHeight>e.clientHeight){const s=window.getComputedStyle(e).getPropertyValue("overflow-y");if(s==="auto"||s==="scroll")return e}while(e!==document.body)}class Y extends E{static option(e,t){return new Fm(e,t)}constructor(e){super(),this._options=e}render(e){return e.ul({className:"menu",role:"menu"},this._options.map(t=>t.toDOM(e)))}}class Fm{constructor(e,t){this.label=e,this.callback=t,this.icon=null,this.destructive=!1}setIcon(e){return this.icon=e,this}setDestructive(){return this.destructive=!0,this}toDOM(e){const t={destructive:this.destructive};return this.icon&&(t.icon=!0,t[this.icon]=!0),e.li({className:t},e.button({className:"menu-item",onClick:this.callback},this.label))}}function dn(n){return n.offsetTop+n.clientHeight}function un(n,e,t=n.children.length-1){for(var s=t;s>=0;s--)if(n.children[s].offsetTop{this.restoreScrollPosition()}),this.tilesView=new Km(t.tiles,()=>this.restoreScrollPosition(),this.viewClassForTile);const s=e.div({className:"Timeline"},[e.div({className:"Timeline_scroller bottom-aligned-scroll",onScroll:()=>this.onScroll()},e.view(this.tilesView)),e.button({className:{Timeline_jumpDown:!0,hidden:i=>!i.showJumpDown},title:"Jump down",onClick:()=>this.jumpDown()})]);return typeof ResizeObserver=="function"&&(this.resizeObserver=new ResizeObserver(()=>{this.restoreScrollPosition()}),this.resizeObserver.observe(s)),s}get scrollNode(){return this.root().firstElementChild}get tilesNode(){return this.tilesView.root()}jumpDown(){const{scrollNode:e}=this;this.stickToBottom=!0,e.scrollTop=e.scrollHeight}unmount(){super.unmount(),this.resizeObserver&&(this.resizeObserver.unobserve(this.root()),this.resizeObserver=void 0)}restoreScrollPosition(){const{scrollNode:e,tilesNode:t}=this,s=e.clientHeight-t.clientHeight;if(s>0){t.style.setProperty("margin-top",`${s}px`);const i=this.value.tiles.length;this.updateVisibleRange(0,i-1)}else if(t.style.removeProperty("margin-top"),this.stickToBottom)e.scrollTop=e.scrollHeight;else if(this.anchoredNode){const i=dn(this.anchoredNode);if(i!==this.anchoredBottom){const r=i-this.anchoredBottom;typeof e.scrollBy=="function"?e.scrollBy(0,r):e.scrollTop=e.scrollTop+r,this.anchoredBottom=i}}}onScroll(){const{scrollNode:e,tilesNode:t}=this,{scrollHeight:s,scrollTop:i,clientHeight:r}=e;let o;if(this.stickToBottom=Math.abs(s-(i+r))<1,this.stickToBottom)o=this.value.tiles.length-1;else{const c=i+r,l=un(t,c);this.anchoredNode=t.childNodes[l],this.anchoredBottom=dn(this.anchoredNode),o=l}let a=un(t,i,o);this.updateVisibleRange(a,o)}updateVisibleRange(e,t){const s=this.tilesView.getChildInstanceByIndex(e),i=this.tilesView.getChildInstanceByIndex(t);this.value.setVisibleTileRange(s==null?void 0:s.value,i==null?void 0:i.value)}}class Km extends is{constructor(e,t,s){super({list:e,onItemClick:(i,r)=>i.onClick(r)},i=>{const r=s(i);return new r(i,s)}),this.viewClassForTile=s,this.onChanged=t}onReset(){super.onReset(),this.onChanged()}onUpdate(e,t,s){if(s==="shape"){const i=this.viewClassForTile(t),r=this.getChildInstanceByIndex(e);if(!i||!(r instanceof i)){super.recreateItem(e,t);return}}super.onUpdate(e,t,s),this.onChanged()}onAdd(e,t){super.onAdd(e,t),this.onChanged()}onRemove(e,t){super.onRemove(e,t),this.onChanged()}onMove(e,t,s){super.onMove(e,t,s),this.onChanged()}}class $m extends E{render(e,t){return e.div({className:"TimelineLoadingView"},[Ve(e),e.div(t.isEncrypted?t.i18n`Loading encrypted messages…`:t.i18n`Loading messages…`)])}}class jm extends E{constructor(e,t){super(e),this._viewClassForTile=t,this._input=null,this._attachmentPopup=null,this._focusInput=null,this._rafResizeHandle=void 0}render(e,t){this._input=e.textarea({onKeydown:r=>this._onKeyDown(r),onInput:()=>{t.setInput(this._input.value),this._input.value?this._adjustHeight():this._clearHeight()},placeholder:r=>r.isEncrypted?"Send an encrypted message\u2026":"Send a message\u2026",rows:"1"}),this._focusInput=()=>this._input.focus(),this.value.on("focus",this._focusInput);const s=e.map(r=>r.replyViewModel,(r,o)=>{const a=r&&this._viewClassForTile(r);return a?o.div({className:"MessageComposer_replyPreview"},[o.span({className:"replying"},"Replying"),o.button({className:"cancel",onClick:()=>this._clearReplyingTo()},"Close"),o.view(new a(r,this._viewClassForTile,{interactive:!1},"div"))]):null}),i=e.div({className:"MessageComposer_input"},[this._input,e.button({className:"sendFile",title:t.i18n`Pick attachment`,onClick:r=>this._toggleAttachmentMenu(r)},t.i18n`Send file`),e.button({className:"send",title:t.i18n`Send`,onClick:()=>this._trySend()},t.i18n`Send`)]);return e.div({className:{MessageComposer:!0,MessageComposer_canSend:r=>r.canSend}},[s,i])}unmount(){this._focusInput&&this.value.off("focus",this._focusInput),super.unmount()}_clearReplyingTo(){this.value.clearReplyingTo()}async _trySend(){this._input.focus();const{value:e}=this._input,t=()=>{this._input.value=e,this._adjustHeight()};this._input.value="",this._clearHeight();try{await this.value.sendMessage(e)||t()}catch(s){t(),console.error(s)}}_onKeyDown(e){e.key==="Enter"&&!e.shiftKey&&(e.preventDefault(),this._trySend())}_toggleAttachmentMenu(e){if(this._attachmentPopup&&this._attachmentPopup.isOpen)this._attachmentPopup.close();else{const t=this.value;this._attachmentPopup=new zi(new Y([Y.option(t.i18n`Send video`,()=>t.sendVideo()).setIcon("video"),Y.option(t.i18n`Send picture`,()=>t.sendPicture()).setIcon("picture"),Y.option(t.i18n`Send file`,()=>t.sendFile()).setIcon("file")])),this._attachmentPopup.trackInTemplateView(this),this._attachmentPopup.showRelativeTo(e.target,12)}}_adjustHeight(){this._rafResizeHandle||(this._rafResizeHandle=window.requestAnimationFrame(()=>{const e=this._input.scrollHeight;this._input.style.height=`${e}px`,this._rafResizeHandle=void 0}))}_clearHeight(){this._input.style.removeProperty("height")}}class qm extends E{render(e){return e.div({className:"DisabledComposerView"},e.h3(t=>t.description))}}class Lo extends E{constructor(e,t){super(e),this._viewClassForTile=t,this._optionsPopup=null}render(e,t){return e.main({className:"RoomView middle"},[e.div({className:"RoomHeader middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close room`}),e.view(new ht(t,32)),e.div({className:"room-description"},[e.h2(s=>s.name)]),e.button({className:"button-utility room-options","aria-label":t.i18n`Room options`,onClick:s=>this._toggleOptionsMenu(s)})]),e.div({className:"RoomView_body"},[e.div({className:"RoomView_error"},[e.if(s=>s.error,s=>s.div([s.p({},i=>i.error),s.button({className:"RoomView_error_closerButton",onClick:i=>t.dismissError(i)})]))]),e.mapView(s=>s.timelineViewModel,s=>s?new Bm(s,this._viewClassForTile):new $m(t)),e.mapView(s=>s.composerViewModel,s=>{switch(s==null?void 0:s.kind){case"composer":return new jm(t.composerViewModel,this._viewClassForTile);case"disabled":return new qm(t.composerViewModel)}})])])}_toggleOptionsMenu(e){if(this._optionsPopup&&this._optionsPopup.isOpen)this._optionsPopup.close();else{const t=this.value,s=[];if(s.push(Y.option(t.i18n`Room details`,()=>t.openDetailsPanel())),t.canLeave&&s.push(Y.option(t.i18n`Leave room`,()=>this._confirmToLeaveRoom()).setDestructive()),t.canForget&&s.push(Y.option(t.i18n`Forget room`,()=>t.forgetRoom()).setDestructive()),t.canRejoin&&s.push(Y.option(t.i18n`Rejoin room`,()=>t.rejoinRoom())),!s.length)return;this._optionsPopup=new zi(new Y(s)),this._optionsPopup.trackInTemplateView(this),this._optionsPopup.showRelativeTo(e.target,10)}}_confirmToLeaveRoom(){confirm(this.value.i18n`Are you sure you want to leave "${this.value.name}"?`)&&this.value.leaveRoom()}}class Wm extends E{render(e,t){return e.main({className:"UnknownRoomView middle"},e.div([e.h2([t.i18n`You are currently not in ${t.roomIdOrAlias}.`,e.br(),t.i18n`Want to join it?`]),e.button({className:"button-action primary",onClick:()=>t.join(),disabled:s=>s.busy},t.i18n`Join room`),e.if(s=>s.error,s=>s.p({className:"error"},t.error))]))}}class Et{constructor(e,t=void 0){typeof e=="function"&&!t&&(t=e,e=null),this._root=t?t(T,e):this.render(T,e)}mount(){return this._root}root(){return this._root}unmount(){}update(){}}class Oo extends Et{constructor(e="Loading"){super(e,(t,s)=>t.div({className:"LoadingView"},[Ve(t),s]))}}class Po extends E{render(e,t){return e.main({className:"RoomView middle"},[e.div({className:"RoomHeader middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close room`}),e.view(new ht(t,32)),e.div({className:"room-description"},[e.h2(s=>s.name)])]),e.div({className:"RoomView_body"},[e.mapView(s=>s.error,s=>s?new Hm(t):new Oo(t.i18n`Setting up the room…`))])])}}class Hm extends E{render(e,t){return e.div({className:"RoomBeingCreated_error centered-column"},[e.h3(t.i18n`Could not create the room, something went wrong:`),e.div({className:"RoomView_error form-group"},t.error),e.div({className:"button-row"},e.button({className:"button-action primary destructive",onClick:()=>t.cancel()},t.i18n`Cancel`))])}}class Uo extends E{render(e,t){var r;let s=[];t.isDirectMessage&&s.push(it(t,128,"InviteView_dmAvatar"));let i;return t.isDirectMessage?i=[e.strong(t.name),` (${(r=t.inviter)==null?void 0:r.id}) wants to chat with you.`]:t.inviter?i=[it(t.inviter,24),e.strong(t.inviter.name),` (${t.inviter.id}) invited you.`]:i="You were invited to join.",s.push(e.p({className:"InviteView_inviter"},i)),t.isDirectMessage||s.push(e.div({className:"InviteView_roomProfile"},[it(t,64,"InviteView_roomAvatar"),e.h3(t.name),e.p({className:"InviteView_roomDescription"},t.roomDescription)])),e.main({className:"InviteView middle"},[e.div({className:"RoomHeader middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close invite`}),it(t,32),e.div({className:"room-description"},[e.h2(o=>o.name)])]),e.if(o=>o.error,o=>o.div({className:"RoomView_error"},a=>a.error)),e.div({className:"InviteView_body"},[e.div({className:"InviteView_invite"},[...s,e.div({className:"InviteView_buttonRow"},e.button({className:"button-action primary",disabled:o=>o.busy,onClick:()=>t.accept()},t.i18n`Accept`)),e.div({className:"InviteView_buttonRow"},e.button({className:"button-action primary destructive",disabled:o=>o.busy,onClick:()=>t.reject()},t.i18n`Reject`))])])])}}class zm extends E{render(e,t){const s=e.a({href:t.closeUrl,title:t.i18n`Close`,className:"close"}),i=e.div({role:"img","aria-label":c=>c.name,title:c=>c.name,className:{picture:!0,hidden:c=>!c.imageUrl},style:c=>`background-image: url('${c.imageUrl}'); max-width: ${c.imageWidth}px; max-height: ${c.imageHeight}px;`}),r=e.div({className:{loading:!0,hidden:c=>!!c.imageUrl}},[Ve(e),e.div(t.i18n`Loading image…`)]),o=e.div({className:"details"},[e.strong(c=>c.name),e.br(),"uploaded by ",e.strong(c=>c.sender),c=>` at ${c.time} on ${c.date}.`]),a=e.div({role:"dialog",className:"lightbox",onClick:c=>this.clickToClose(c),onKeydown:c=>this.closeOnEscKey(c)},[i,r,o,s]);return Gm(e,a),a}clickToClose(e){e.target===this.root()&&this.value.close()}closeOnEscKey(e){(e.key==="Escape"||e.key==="Esc")&&this.value.close()}}function Gm(n,e){const t=Jm(e),s=t[0],i=t[t.length-1];n.addEventListener(e,"keydown",r=>{r.key==="Tab"&&(r.shiftKey?document.activeElement===s&&(i.focus(),r.preventDefault()):document.activeElement===i&&(s.focus(),r.preventDefault()))},!0),Promise.resolve().then(()=>{s.focus()})}function Jm(n){return n.querySelectorAll("a[href], button, textarea, input, select")}class Qm extends E{render(e,t){return e.div({className:{SessionStatusView:!0,hidden:s=>!s.isShown}},[Ve(e,{hidden:s=>!s.isWaiting}),e.p(s=>s.statusLabel),e.if(s=>s.isConnectNowShown,s=>s.button({className:"link",onClick:()=>t.connectNow()},"Retry now")),e.if(s=>s.isSecretStorageShown,s=>s.a({href:t.setupKeyBackupUrl},"Go to settings")),e.if(s=>s.canDismiss,s=>s.div({className:"end"},s.button({className:"dismiss",onClick:()=>t.dismiss()})))])}}class Ym extends E{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const s=[];for(let i=0;it.focusTile(i),onFocusin:()=>t.focusTile(i),className:{container:!0,[`tile${i}`]:!0,focused:r=>r.focusIndex===i}},e.mapView(r=>r.roomViewModelAt(i),r=>r?r.kind==="roomBeingCreated"?new Po(r):r.kind==="invite"?new Uo(r):new Lo(r,this._viewClassForTile):new Et(o=>o.div({className:"room-placeholder"},[o.h2({className:"focused"},t.i18n`Select a room on the left`),o.h2({className:"unfocused"},t.i18n`Click to select this tile`)])))));return s.push(e.div({className:i=>`focus-ring tile${i.focusIndex}`})),e.div({className:"RoomGridView middle layout3x2"},s)}}class Fo extends E{render(e){return e.div([e.map(t=>t.status,(t,s,i)=>{switch(t){case"Enabled":return Xm(s,i);case"NewVersionAvailable":return Zm(s,i);case"SetupKey":return ep(s,i);case"SetupPhrase":return tp(s,i);case"Pending":return s.p(i.i18n`Waiting to go online…`)}}),e.map(t=>t.backupWriteStatus,(t,s,i)=>{switch(t){case"Writing":{const r=s.progress({min:0,max:100,value:o=>o.backupPercentage});return s.div(["Backup in progress ",r," ",o=>o.backupInProgressLabel])}case"Stopped":{let r;return i.backupError?r=`Backup has stopped because of an error: ${i.backupError}`:r="Backup has stopped",s.p(r," ",s.button({onClick:()=>i.startBackup()},"Backup now"))}case"Done":return s.p("All keys are backed up.");default:return null}})])}}function Xm(n,e){const t=[n.p([e.i18n`Key backup is enabled, using backup version ${e.backupVersion}. `,n.button({onClick:()=>e.disable()},e.i18n`Disable`)])];return e.dehydratedDeviceId&&t.push(n.p(e.i18n`A dehydrated device id was set up with id ${e.dehydratedDeviceId} which you can use during your next login with your secret storage key.`)),n.div(t)}function Zm(n,e){const t=[n.p([e.i18n`A new backup version has been created from another device. Disable key backup and enable it again with the new key.`,n.button({onClick:()=>e.disable()},e.i18n`Disable`)])];return n.div(t)}function ep(n,e){const t=n.button({className:"link",onClick:()=>e.showPhraseSetup()},e.i18n`use a security phrase`);return n.div([n.p(e.i18n`Enter your secret storage security key below to ${e.purpose}, which will enable you to decrypt messages received before you logged into this session. The security key is a code of 12 groups of 4 characters separated by a space that Element created for you when setting up security.`),Ko(n),Bo(n,e,e.i18n`Security key`,(s,i)=>e.enterSecurityKey(s,i)),n.p([e.i18n`Alternatively, you can `,t,e.i18n` if you have one.`])])}function tp(n,e){const t=n.button({className:"link",onClick:()=>e.showKeySetup()},e.i18n`use your security key`);return n.div([n.p(e.i18n`Enter your secret storage security phrase below to ${e.purpose}, which will enable you to decrypt messages received before you logged into this session. The security phrase is a freeform secret phrase you optionally chose when setting up security in Element. It is different from your password to login, unless you chose to set them to the same value.`),Ko(n),Bo(n,e,e.i18n`Security phrase`,(s,i)=>e.enterSecurityPhrase(s,i)),n.p([e.i18n`You can also `,t,e.i18n`.`])])}function Bo(n,e,t,s){let i;const r=()=>s(o.value,(i==null?void 0:i.checked)||!1),o=n.input({type:"password",disabled:c=>c.isBusy,placeholder:t}),a=[n.p([o,n.button({disabled:c=>c.isBusy,onClick:r},e.decryptAction)])];if(e.offerDehydratedDeviceSetup){i=n.input({type:"checkbox",id:"enable-dehydrated-device"});const c=n.a({href:"https://github.com/uhoreg/matrix-doc/blob/dehydration/proposals/2697-device-dehydration.md",target:"_blank",rel:"noopener"},"more info");a.push(n.p([i,n.label({for:i.id},[e.i18n`Back up my device as well (`,c,")"])]))}return n.div({className:"row"},[n.div({className:"label"},t),n.div({className:"content"},a)])}function Ko(n){return n.if(e=>e.error,(e,t)=>e.div([e.p({className:"error"},s=>s.i18n`Could not enable key backup: ${s.error}.`),e.p(t.i18n`Try double checking that you did not mix up your security key, security phrase and login password as explained above.`)]))}class sp extends E{render(e,t){let s=t.version;t.showUpdateButton&&(s=e.span([t.version,e.button({onClick:()=>t.checkForUpdate()},t.i18n`Check for updates`)]));const i=(a,c,l,h="")=>a.div({className:`row ${h}`},[a.div({className:"label"},c),a.div({className:"content"},l)]),r=[];r.push(e.h3("Session"),i(e,t.i18n`User ID`,t.userId),i(e,t.i18n`Session ID`,t.deviceId,"code"),i(e,t.i18n`Session key`,t.fingerprintKey,"code"),i(e,"",e.button({onClick:()=>t.logout(),disabled:a=>a.isLoggingOut},t.i18n`Log out`))),r.push(e.h3("Key backup"),e.view(new Fo(t.keyBackupViewModel))),r.push(e.h3("Notifications"),e.map(a=>a.pushNotifications.supported,(a,c)=>{if(a===null)return c.p(t.i18n`Loading…`);if(a){const l=d=>d.pushNotifications.enabled?d.i18n`Push notifications are enabled`:d.i18n`Push notifications are disabled`,h=d=>d.pushNotifications.enabled?d.i18n`Disable`:d.i18n`Enable`;return i(c,l,c.button({onClick:()=>t.togglePushNotifications(),disabled:d=>d.pushNotifications.updating},h))}else return c.p(t.i18n`Push notifications are not supported on this browser`)}),e.if(a=>a.pushNotifications.supported&&a.pushNotifications.enabled,a=>a.div([a.p(["If you think push notifications are not being delivered, ",a.button({className:"link",onClick:()=>t.checkPushEnabledOnServer()},"check")," if they got disabled on the server"]),a.map(c=>c.pushNotifications.enabledOnServer,(c,l)=>{if(c===!0)return l.p("Push notifications are still enabled on the server, so everything should be working. Sometimes notifications can get dropped if they can't be delivered within a given time.");if(c===!1)return l.p("Push notifications have been disabled on the server, likely due to a bug. Please re-enable them by clicking Disable and then Enable again above.")}),a.map(c=>c.pushNotifications.serverError,(c,l)=>{if(c)return l.p("Couldn't not check on server: "+c.message)})]))),r.push(e.h3("Preferences"),i(e,t.i18n`Scale down images when sending`,this._imageCompressionRange(e,t)),e.if(a=>a.activeTheme,(a,c)=>i(a,c.i18n`Use the following theme`,this._themeOptions(a,c))));const o=[];return t.canSendLogsToServer&&o.push(e.button({onClick:Nm(()=>t.sendLogsToServer())},`Submit logs to ${t.logsServer}`)),o.push(e.button({onClick:()=>t.exportLogs()},"Download logs")),r.push(e.h3("Application"),i(e,t.i18n`Version`,s),i(e,t.i18n`Storage usage`,a=>`${a.storageUsage} / ${a.storageQuota}`),i(e,t.i18n`Debug logs`,o),e.p({className:{hidden:a=>!a.logsFeedbackMessage}},a=>a.logsFeedbackMessage),e.p(["Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited, the usernames of other users and the names of files you send. They do not contain messages. For more information, review our ",e.a({href:"https://element.io/privacy",target:"_blank",rel:"noopener"},"privacy policy"),"."])),e.main({className:"Settings middle"},[e.div({className:"middle-header"},[e.a({className:"button-utility close-middle",href:t.closeUrl,title:t.i18n`Close settings`}),e.h2("Settings")]),e.div({className:"SettingsBody"},r)])}_imageCompressionRange(e,t){const i=Math.ceil(t.minSentImageSizeLimit/32)*32,r=(Math.floor(t.maxSentImageSizeLimit/32)+1)*32,o=a=>t.setSentImageSizeLimit(parseInt(a.target.value,10));return[e.input({type:"range",step:32,min:i,max:r,value:a=>a.sentImageSizeLimit||r,onInput:o,onChange:o})," ",e.output(a=>a.sentImageSizeLimit?a.i18n`resize to ${a.sentImageSizeLimit}px`:a.i18n`no resizing`)]}_themeOptions(e,t){const{themeName:s,themeVariant:i}=t.activeTheme,r=[];for(const _ of Object.keys(t.themeMapping))r.push(e.option({value:_,selected:_===s},_));const o=e.select({onChange:_=>{const f=_.target.value;if(!("id"in t.themeMapping[f])){const b=h.checked?"dark":u.checked?"light":"default";a(b);return}t.changeThemeOption(f)}},r),a=_=>{const f=o.options[o.selectedIndex].value;t.changeThemeOption(f,_)},c=i==="dark",l=i==="light",h=e.input({type:"radio",name:"radio-chooser",value:"dark",id:"dark",checked:c}),d=e.input({type:"radio",name:"radio-chooser",value:"default",id:"default",checked:!(c||l)}),u=e.input({type:"radio",name:"radio-chooser",value:"light",id:"light",checked:l}),p=e.form({className:{hidden:()=>{const _=o.options[o.selectedIndex].value;return"id"in t.themeMapping[_]}},onChange:_=>a(_.target.value)},[d,e.label({for:"default"},"Match system theme"),h,e.label({for:"dark"},"dark"),u,e.label({for:"light"},"light")]);return e.div({className:"theme-chooser"},[o,p])}}class ip extends E{render(e,t){return e.main({className:"middle"},e.div({className:"CreateRoomView centered-column"},[e.h2("Create room"),e.form({className:"CreateRoomView_detailsForm form",onChange:s=>this.onFormChange(s),onSubmit:s=>this.onSubmit(s)},[e.div({className:"vertical-layout"},[e.button({type:"button",className:"CreateRoomView_selectAvatar",onClick:()=>t.selectAvatar()},e.mapView(s=>s.hasAvatar,s=>s?new ht(t,64):new Et(void 0,i=>i.div({className:"CreateRoomView_selectAvatarPlaceholder"})))),e.div({className:"stretch form-row text"},[e.label({for:"name"},t.i18n`Room name`),e.input({onInput:s=>t.setName(s.target.value),type:"text",name:"name",id:"name",placeholder:t.i18n`Enter a room name`})])]),e.div({className:"form-row text"},[e.label({for:"topic"},t.i18n`Topic (optional)`),e.textarea({onInput:s=>t.setTopic(s.target.value),name:"topic",id:"topic",placeholder:t.i18n`Topic`})]),e.div({className:"form-group"},[e.div({className:"form-row check"},[e.input({type:"radio",name:"isPublic",id:"isPrivate",value:"false",checked:!t.isPublic}),e.label({for:"isPrivate"},t.i18n`Private room, only upon invitation.`)]),e.div({className:"form-row check"},[e.input({type:"radio",name:"isPublic",id:"isPublic",value:"true",checked:t.isPublic}),e.label({for:"isPublic"},t.i18n`Public room, anyone can join`)])]),e.div({className:{"form-row check":!0,hidden:s=>s.isPublic}},[e.input({type:"checkbox",name:"isEncrypted",id:"isEncrypted",checked:t.isEncrypted}),e.label({for:"isEncrypted"},t.i18n`Enable end-to-end encryption`)]),e.div({className:{"form-row text":!0,hidden:s=>!s.isPublic}},[e.label({for:"roomAlias"},t.i18n`Room alias`),e.input({onInput:s=>t.setRoomAlias(s.target.value),type:"text",name:"roomAlias",id:"roomAlias",placeholder:t.i18n`Room alias (, or # or #:hs.tld`})]),e.div({className:"form-group"},[e.div(e.button({className:"link",type:"button",onClick:()=>t.toggleAdvancedShown()},s=>s.isAdvancedShown?s.i18n`Hide advanced settings`:s.i18n`Show advanced settings`)),e.div({className:{"form-row check":!0,hidden:s=>!s.isAdvancedShown}},[e.input({type:"checkbox",name:"isFederationDisabled",id:"isFederationDisabled",checked:t.isFederationDisabled}),e.label({for:"isFederationDisabled"},[t.i18n`Disable federation`,e.p({className:"form-row-description"},t.i18n`Can't be changed later. This will prevent people on other homeservers from joining the room. This is typically used when only people from your own organisation (if applicable) should be allowed in the room, and is otherwise not needed.`)])])]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:s=>!s.canCreate},t.i18n`Create room`)])])]))}onFormChange(e){switch(e.target.name){case"isEncrypted":this.value.setEncrypted(e.target.checked);break;case"isPublic":this.value.setPublic(e.currentTarget.isPublic.value==="true");break;case"isFederationDisabled":this.value.setFederationDisabled(e.target.checked);break}}onSubmit(e){e.preventDefault(),this.value.create()}}class rp extends E{render(e,t){const s=()=>t.isEncrypted?t.i18n`On`:t.i18n`Off`;return e.div({className:"RoomDetailsView"},[e.div({className:"RoomDetailsView_avatar"},[e.view(new ht(t,52)),e.mapView(i=>i.isEncrypted,i=>new np(i))]),e.div({className:"RoomDetailsView_name"},[e.h2(i=>i.name)]),this._createRoomAliasDisplay(t),e.div({className:"RoomDetailsView_rows"},[this._createRightPanelButtonRow(e,t.i18n`People`,{MemberCount:!0},i=>i.memberCount,()=>t.openPanel("members")),this._createRightPanelRow(e,t.i18n`Encryption`,{EncryptionStatus:!0},s)])])}_createRoomAliasDisplay(e){return e.canonicalAlias?T.div({className:"RoomDetailsView_id"},[e.canonicalAlias]):""}_createRightPanelRow(e,t,s,i){const r=It(ft({RoomDetailsView_label:!0},s));return e.div({className:"RoomDetailsView_row"},[e.div({className:r},[t]),e.div({className:"RoomDetailsView_value"},i)])}_createRightPanelButtonRow(e,t,s,i,r){const o=It(ft({RoomDetailsView_label:!0},s));return e.button({className:"RoomDetailsView_row",onClick:r},[e.div({className:o},[t]),e.div({className:"RoomDetailsView_value"},i)])}}class np extends E{render(e,t){return e.div({className:"EncryptionIconView"},[e.div({className:t?"EncryptionIconView_encrypted":"EncryptionIconView_unencrypted"})])}}class op{constructor(e,t){this.start=e,this.end=t}get length(){return this.end-this.start}contains(e){return e.start>=this.start&&e.end<=this.end}containsIndex(e){return e>=this.start&&e(n[n.Before=1]="Before",n[n.Inside=2]="Inside",n[n.After=3]="After",n))(ot||{});class ap{constructor(e){this.range=e,this.idx=e.start-1}next(){return this.idxthis.range.start?(this.idx-=1,{value:this.idx,done:!1}):{value:void 0,done:!0}}}function lp(n,e){let t=0;for(;t(n[n.Move=0]="Move",n[n.Add=1]="Add",n[n.Remove=2]="Remove",n[n.RemoveAndAdd=3]="RemoveAndAdd",n[n.UpdateRange=4]="UpdateRange",n))(wt||{});class zt extends op{constructor(e,t,s,i=t-e){super(e,t),this._totalLength=s,this._viewportItemCount=i}expand(e){if(this.length===0)return this;const t=Math.max(0,this.start-e),s=Math.min(this.totalLength,this.end+e);return new zt(t,s,this.totalLength,this._viewportItemCount)}get totalLength(){return this._totalLength}get viewportItemCount(){return this._viewportItemCount}static fromViewport(e,t,s,i){const r=Math.min(Math.max(0,Math.floor(i/t)),e),o=e-r,a=s!==0?Math.ceil(s/t):0,c=Math.min(a,o);return new zt(r,r+c,e,a)}queryAdd(e,t,s){const i=this.viewportItemCount>this.length?this.end:this.end-1;if(e<=i){const r=this.clampIndex(e,i),o=r===e?t:bs(s[Symbol.iterator](),r);return this.createAddResult(r,o)}else return{type:4,newRange:this.deriveRange(1,0)}}queryRemove(e,t){if(ethis.length)return{type:1,addIdx:e,value:t,newRange:this.deriveRange(1,1)};{const s=this.clampIndex(Number.MAX_SAFE_INTEGER);return{type:3,removeIdx:s,addIdx:e,value:t,newRange:this.deriveRange(1,0)}}}createRemoveResult(e,t){if(this.endrequestAnimationFrame(t)),await new Promise(t=>requestAnimationFrame(t)),!this._list)return;this._subscription=this._list.subscribe(this);const e=this._getVisibleRange();this.renderRange=e.expand(this.overflowItems),this._childInstances=[],this.reRenderFullRange(this.renderRange)}_getVisibleRange(){const{clientHeight:e,scrollTop:t}=this.root();if(e===0)throw new Error("LazyListView height is 0");return zt.fromViewport(this._list.length,this.itemHeight,e,t)}reRenderFullRange(e){xm(this._listElement);const t=document.createDocumentFragment(),s=this._list[Symbol.iterator]();this._childInstances.length=0,e.forEachInIterator(s,i=>{const r=this._childCreator(i);this._childInstances.push(r),t.appendChild(Xt(r,this._mountArgs))}),this._listElement.appendChild(t),this.adjustPadding(e)}renderUpdate(e,t){if(t.intersects(e)){for(const s of e.reverseIterable())if(!t.containsIndex(s)){const i=s-e.start;this.removeChild(i)}t.forEachInIterator(this._list[Symbol.iterator](),(s,i)=>{if(!e.containsIndex(i)){const r=i-t.start;this.addChild(r,s)}}),this.adjustPadding(t)}else this.reRenderFullRange(t)}adjustPadding(e){const t=e.start*this.itemHeight,s=(e.totalLength-e.end)*this.itemHeight,i=this._listElement.style;i.paddingTop=`${t}px`,i.paddingBottom=`${s}px`}mount(){const e=super.mount();return this.scrollContainer=T.div({className:"LazyListParent"},e),this.scrollContainer.addEventListener("scroll",this),this.scrollContainer}unmount(){this.root().removeEventListener("scroll",this),this.scrollContainer=void 0,super.unmount()}root(){return this.scrollContainer}get _listElement(){return super.root()}onAdd(e,t){const s=this.renderRange.queryAdd(e,t,this._list);this.applyRemoveAddResult(s)}onRemove(e,t){const s=this.renderRange.queryRemove(e,this._list);this.applyRemoveAddResult(s)}onMove(e,t,s){const i=this.renderRange.queryMove(e,t,s,this._list);i&&(i.type===wt.Move?this.moveChild(this.renderRange.toLocalIndex(i.fromIdx),this.renderRange.toLocalIndex(i.toIdx)):this.applyRemoveAddResult(i))}onUpdate(e,t,s){this.renderRange.containsIndex(e)&&this.updateChild(this.renderRange.toLocalIndex(e),t,s)}applyRemoveAddResult(e){(e.type===wt.Remove||e.type===wt.RemoveAndAdd)&&this.removeChild(this.renderRange.toLocalIndex(e.removeIdx)),e.newRange&&(this.renderRange=e.newRange,this.adjustPadding(this.renderRange)),(e.type===wt.Add||e.type===wt.RemoveAndAdd)&&this.addChild(this.renderRange.toLocalIndex(e.addIdx),e.value)}}class dp extends E{render(e,t){return e.li({className:"MemberTileView"},e.a({href:t.detailsUrl},[e.view(new ht(t,32)),e.div({className:"MemberTileView_name"},s=>s.name)]))}}class up extends hp{constructor(e){super({list:e.memberTileViewModels,className:"MemberListView",itemHeight:40},t=>new dp(t))}}class mp extends E{render(e,t){return e.div({className:"MemberDetailsView"},[e.view(new ht(t,128)),e.div({className:"MemberDetailsView_name"},e.h2(s=>s.name)),e.div({className:"MemberDetailsView_id"},t.userId),this._createSection(e,t.i18n`Role`,s=>s.role),this._createSection(e,t.i18n`Security`,t.isEncrypted?t.i18n`Messages in this room are end-to-end encrypted.`:t.i18n`Messages in this room are not end-to-end encrypted.`),this._createOptions(e,t)])}_createSection(e,t,s){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t),e.div({className:"MemberDetailsView_value"},s)])}_createOptions(e,t){return e.div({className:"MemberDetailsView_section"},[e.div({className:"MemberDetailsView_label"},t.i18n`Options`),e.div({className:"MemberDetailsView_options"},[e.a({href:t.linkToUser,target:"_blank",rel:"noopener"},t.i18n`Open Link to User`),e.button({className:"text",onClick:()=>t.openDirectMessage()},t.i18n`Open direct message`)])])}}class pp extends E{render(e){return e.div({className:"RightPanelView"},[e.ifView(t=>t.activeViewModel,t=>new _p(t)),e.mapView(t=>t.activeViewModel,t=>this._viewFromType(t))])}_viewFromType(e){switch(e==null?void 0:e.type){case"room-details":return new rp(e);case"member-list":return new up(e);case"member-details":return new mp(e);default:return new Oo}}}class _p extends E{render(e,t){return e.div({className:"RightPanelView_buttons"},[e.button({className:{back:!0,"button-utility":!0,hide:!t.activeViewModel.shouldShowBackButton},onClick:()=>t.showPreviousPanel()}),e.button({className:"close button-utility",onClick:()=>t.closePanel()})])}}class fp extends is{constructor(e){const t={className:"Timeline_messageReactions",tagName:"div",list:e.reactions,onItemClick:s=>s.onClick()};super(t,s=>new gp(s))}}class gp extends E{render(e,t){return e.button({className:{active:s=>s.isActive,pending:s=>s.isPending}},[t.key," ",s=>`${s.count}`])}onClick(){this.value.toggle()}}class Tt extends E{constructor(e,t,s,i="li"){super(e),this._menuPopup=null,this._tagName=i,this._viewClassForTile=t,this._renderFlags=s}get _interactive(){var e,t;return(t=(e=this._renderFlags)==null?void 0:e.interactive)!=null?t:!0}get _isReplyPreview(){var e;return(e=this._renderFlags)==null?void 0:e.reply}render(e,t){const s=[this.renderMessageBody(e,t)];this._interactive&&s.push(e.button({className:"Timeline_messageOptions"},"\u22EF"));const i=e.el(this._tagName,{className:{Timeline_message:!0,own:t.isOwn,unsent:t.isUnsent,unverified:t.isUnverified,disabled:!this._interactive,continuation:o=>o.isContinuation},"data-event-id":t.eventId},s);e.mapSideEffect(o=>o.isContinuation,(o,a)=>{if(o&&a===!1)i.removeChild(i.querySelector(".Timeline_messageAvatar")),i.removeChild(i.querySelector(".Timeline_messageSender"));else if(!o&&!this._isReplyPreview){const c=T.a({href:t.memberPanelLink,className:"Timeline_messageAvatar"},[it(t,30)]),l=T.div({className:`Timeline_messageSender usercolor${t.avatarColorNumber}`},t.displayName);i.insertBefore(c,i.firstChild),i.insertBefore(l,i.firstChild)}});let r=null;return e.mapSideEffect(o=>o.reactions,o=>{o&&this._interactive&&!r?(r=new fp(o),this.addSubView(r),i.appendChild(Xt(r))):!o&&r&&(i.removeChild(r.root()),r.unmount(),this.removeSubView(r),r=null)}),i}onClick(e){e.target.className==="Timeline_messageOptions"&&this._toggleMenu(e.target)}_toggleMenu(e){if(this._menuPopup&&this._menuPopup.isOpen)this._menuPopup.close();else{const t=this.createMenuOptions(this.value);if(!t.length)return;this.root().classList.add("menuOpen");const s=()=>this.root().classList.remove("menuOpen");this._menuPopup=new zi(new Y(t),s),this._menuPopup.trackInTemplateView(this),this._menuPopup.showRelativeTo(e,2)}}createMenuOptions(e){const t=[];return e.canReact&&e.shape!=="redacted"&&!e.isPending&&(t.push(new yp(e)),t.push(Y.option(e.i18n`Reply`,()=>e.startReply()))),e.canAbortSending?t.push(Y.option(e.i18n`Cancel`,()=>e.abortSending())):e.canRedact&&t.push(Y.option(e.i18n`Delete`,()=>e.redact()).setDestructive()),t}renderMessageBody(){}}class yp{constructor(e){this._vm=e}toDOM(e){const t=["\u{1F44D}","\u{1F44E}","\u{1F604}","\u{1F389}","\u{1F615}","\u2764\uFE0F","\u{1F680}","\u{1F440}"].map(i=>e.button({onClick:()=>this._vm.react(i)},i)),s=e.button({onClick:()=>{const i=prompt("Enter your reaction (emoji)");i&&this._vm.react(i)}},"\u2026");return e.li({className:"quick-reactions"},[...t,s])}}class wp extends E{constructor(e,t){super(e),this._viewClassForTile=t}render(e,t){const s=this._viewClassForTile(t);if(!s)throw new Error(`Shape ${t.shape} is unrecognized.`);const i=new s(t,this._viewClassForTile,{reply:!0,interactive:!1});return e.div({className:"ReplyPreviewView"},e.blockquote([e.a({className:"link",href:t.permaLink},"In reply to"),e.a({className:"pill",href:t.senderProfileLink},[it(t,12,void 0),t.displayName]),e.br(),e.view(i)]))}}class vp extends E{render(e){return e.blockquote({className:"ReplyPreviewView"},[e.div({className:"Timeline_messageBody statusMessage"},"This reply could not be found.")])}}class bp extends Tt{renderMessageBody(e,t){const s=e.time({className:{hidden:!t.date}},t.date+" "+t.time),i=e.div({className:{Timeline_messageBody:!0,statusMessage:o=>o.shape==="message-status"}},e.mapView(o=>o.replyTile,o=>this._isReplyPreview?null:t.isReply&&!o?new vp:o?new wp(o,this._viewClassForTile):null)),r=o=>(o==null?void 0:o.nodeType)!==Node.COMMENT_NODE&&o.className!=="ReplyPreviewView";return e.mapSideEffect(o=>o.body,o=>{for(;r(i.lastChild);)i.removeChild(i.lastChild);for(const a of o.parts)i.appendChild($o(a));i.appendChild(s)}),i}}function Sp(n){const e=n.items.map(s=>T.li(at(s))),t=n.startOffset;return t?T.ol({start:t},e):T.ul(e)}function Ip(n){const e={src:n.src};return n.width&&(e.width=n.width),n.height&&(e.height=n.height),n.alt&&(e.alt=n.alt),n.title&&(e.title=n.title),T.img(e)}function Ep(n){const e=`avatar size-12 usercolor${n.avatarColorNumber}`,t=T.div({class:e},Te(n.avatarInitials)),s=at(n.children);return s.unshift(t),T.a({class:"pill",href:n.href,rel:"noopener",target:"_blank"},s)}function kp(n){const e=[];if(n.head){const s=n.head.map(i=>T.th(at(i)));e.push(T.thead(T.tr(s)))}const t=[];for(const s of n.body){const i=s.map(r=>T.td(at(r)));t.push(T.tr(i))}return e.push(T.tbody(t)),T.table(e)}const Rp={header:n=>T["h"+Math.min(6,n.level)](at(n.inlines)),codeblock:n=>T.pre(T.code(Te(n.text))),table:n=>kp(n),code:n=>T.code(Te(n.text)),text:n=>Te(n.text),link:n=>T.a({href:n.url,className:"link",target:"_blank",rel:"noopener"},at(n.inlines)),pill:Ep,format:n=>T[n.format](at(n.children)),rule:()=>T.hr(),list:Sp,image:Ip,newline:()=>T.br()};function $o(n){const e=Rp[n.type];return e?e(n):Te(`[unknown part type ${n.type}]`)}function at(n){return Array.from(n,$o)}class jo extends Tt{renderMessageBody(e,t){let i=`padding-top: ${t.height/t.width*100}%;`;t.platform.isIE11&&(i=`height: ${t.height}px`);const r=[e.div({className:"spacer",style:i}),this.renderMedia(e,t),e.time(t.date+" "+t.time)],o=e.div({className:{status:!0,hidden:a=>!a.status}},a=>a.status);if(r.push(o),t.isPending){const a=e.progress({min:0,max:100,value:c=>c.uploadPercentage,className:{hidden:c=>!c.isUploading}});r.push(a)}return e.div({className:"Timeline_messageBody"},[e.div({className:"media",style:`max-width: ${t.width}px`,"data-testid":"media"},r),e.if(a=>a.error,a=>a.p({className:"error"},t.error))])}createMenuOptions(e){const t=super.createMenuOptions(e);if(!e.isPending){let s;switch(e.shape){case"image":s=e.i18n`Download image`;break;case"video":s=e.i18n`Download video`;break;default:s=e.i18n`Download media`;break}t.push(Y.option(s,()=>e.downloadMedia()))}return t}}class Cp extends jo{renderMedia(e,t){const s=e.img({src:i=>i.thumbnailUrl,alt:i=>i.label,title:i=>i.label,style:`max-width: ${t.width}px; max-height: ${t.height}px;`});return t.isPending||!t.lightboxUrl?s:e.a({href:t.lightboxUrl},s)}}function Ds(n,e){return new Promise((t,s)=>{let i;const r=a=>{i(),s(a.target.error)},o=()=>{i(),t()};i=()=>{n.removeEventListener(e,o),n.removeEventListener("error",r)},n.addEventListener(e,o),n.addEventListener("error",r)})}class Tp extends jo{renderMedia(e){const t=e.video({src:s=>s.videoUrl||`data:${s.mimeType},`,title:s=>s.label,controls:!0,preload:"none",poster:s=>s.thumbnailUrl,onPlay:this._onPlay.bind(this),style:s=>`max-width: ${s.width}px; max-height: ${s.height}px;${s.isPending?"z-index: -1":""}`});return t.addEventListener("error",this._onError.bind(this)),t}async _onPlay(e){const t=this.value;if(!t.videoUrl)try{const s=e.target;await t.loadVideo();const i=Ds(s,"loadeddata");s.load(),await i,s.play()}catch{}}_onError(e){const t=this.value,s=e.target,i=s.error;if(i instanceof window.MediaError&&i.code===4)if(!s.src.startsWith("data:"))t.setViewError(new Error(`this browser does not support videos of type ${t.mimeType}.`));else return;else t.setViewError(i)}}class Mp extends Tt{renderMessageBody(e,t){const s=[];return t.isPending?s.push(i=>i.label):s.push(e.button({className:"link",onClick:()=>t.download()},i=>i.label),e.time(t.date+" "+t.time)),e.p({className:"Timeline_messageBody statusMessage"},s)}}class Ap extends Tt{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},[e.span(t.label),e.a({className:"Timeline_locationLink",href:t.mapsLink,target:"_blank",rel:"noopener"},t.i18n`Open in maps`),e.time(t.date+" "+t.time)])}}class xp extends Tt{renderMessageBody(e,t){return e.p({className:"Timeline_messageBody statusMessage"},t.label)}}class Np extends E{constructor(e){super(e)}render(e){return e.li({className:"AnnouncementView"},e.div(t=>t.announcement))}onClick(){}}class Dp extends Tt{renderMessageBody(e){return e.p({className:"Timeline_messageBody statusMessage"},t=>t.description)}createMenuOptions(e){const t=super.createMenuOptions(e);return e.isRedacting&&t.push(Y.option(e.i18n`Cancel`,()=>e.abortPendingRedaction())),t}}class Vp extends E{constructor(e){super(e)}render(e){const t={GapView:!0,isLoading:s=>s.isLoading,isAtTop:s=>s.isAtTop};return e.li({className:t},[Ve(e),e.div(s=>s.isLoading?s.i18n`Loading more messages …`:s.i18n`Not loading!`),e.if(s=>s.error,s=>s.strong(i=>i.error))])}onClick(){}}function mn(n){switch(n.shape){case"gap":return Vp;case"announcement":return Np;case"message":case"message-status":return bp;case"image":return Cp;case"video":return Tp;case"file":return Mp;case"location":return Ap;case"missing-attachment":return xp;case"redacted":return Dp;default:throw new Error(`Tiles of shape "${n.shape}" are not supported, check the tileClassForEntry function in the view model`)}}class Lp extends E{render(e,t){return e.div({className:{SessionView:!0,"middle-shown":s=>!!s.activeMiddleViewModel,"right-shown":s=>!!s.rightPanelViewModel}},[e.view(new Qm(t.sessionStatusViewModel)),e.view(new Pm(t.leftPanelViewModel)),e.mapView(s=>s.activeMiddleViewModel,()=>t.roomGridViewModel?new Ym(t.roomGridViewModel,mn):t.settingsViewModel?new sp(t.settingsViewModel):t.createRoomViewModel?new ip(t.createRoomViewModel):t.currentRoomViewModel?t.currentRoomViewModel.kind==="invite"?new Uo(t.currentRoomViewModel):t.currentRoomViewModel.kind==="room"?new Lo(t.currentRoomViewModel,mn):t.currentRoomViewModel.kind==="roomBeingCreated"?new Po(t.currentRoomViewModel):new Wm(t.currentRoomViewModel):new Et(s=>s.div({className:"room-placeholder"},s.h2(t.i18n`Choose a room on the left side.`)))),e.mapView(s=>s.lightboxViewModel,s=>s?new zm(s):null),e.mapView(s=>s.rightPanelViewModel,s=>s?new pp(s):null)])}}function qo(n){return "2832467534"?n.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web/releases/tag/v0.3.1"},`Hydrogen v0.3.1 (${"2832467534"}) on Github`):n.a({target:"_blank",href:"https://github.com/vector-im/hydrogen-web"},"Hydrogen on Github")}class Op extends E{render(e,t){const s=o=>!!o.isBusy,i=e.input({id:"username",type:"text",placeholder:t.i18n`Username`,disabled:s}),r=e.input({id:"password",type:"password",placeholder:t.i18n`Password`,disabled:s});return e.div({className:"PasswordLoginView form"},[e.if(o=>o.error,o=>o.div({className:"error"},a=>a.error)),e.form({onSubmit:o=>{o.preventDefault(),t.login(i.value,r.value)}},[e.if(o=>o.errorMessage,(o,a)=>o.p({className:"error"},a.i18n(a.errorMessage))),e.div({className:"form-row text"},[e.label({for:"username"},t.i18n`Username`),i]),e.div({className:"form-row text"},[e.label({for:"password"},t.i18n`Password`),r]),e.div({className:"button-row"},[e.button({className:"button-action primary",type:"submit",disabled:s},t.i18n`Log In`)])])])}}class Pp extends E{render(e,t){return e.div({className:"Settings"},[e.h3(t.i18n`Restore your encrypted history?`),e.ifView(s=>s.decryptDehydratedDeviceViewModel,s=>new Fo(s.decryptDehydratedDeviceViewModel)),e.map(s=>s.deviceDecrypted,(s,i)=>s?i.p(t.i18n`That worked out, you're good to go!`):i.p(t.i18n`This will claim the dehydrated device ${t.dehydratedDeviceId}, and will set up a new one.`)),e.div({className:"button-row"},[e.button({className:"button-action primary",onClick:()=>{t.finish()},type:"button"},s=>s.deviceDecrypted?s.i18n`Continue`:s.i18n`Continue without restoring`)])])}}class Ps extends E{render(e){const t=e.if(i=>i.hasError,(i,r)=>i.button({onClick:()=>r.exportLogs()},r.i18n`Export logs`)),s=e.if(i=>i.hasError,(i,r)=>i.button({onClick:()=>r.logout()},r.i18n`Log out`));return e.div({className:"SessionLoadStatusView"},[e.p({className:"status"},[Ve(e,{hidden:i=>!i.loading}),e.p(i=>i.loadLabel),t,s]),e.ifView(i=>i.accountSetupViewModel,i=>new Pp(i.accountSetupViewModel))])}}class Up extends E{render(e){return e.div({className:"CompleteSSOView"},[e.p({className:"CompleteSSOView_title"},"Finishing up your SSO Login"),e.if(t=>t.errorMessage,(t,s)=>t.p({className:"error"},s.i18n(s.errorMessage))),e.mapView(t=>t.loadViewModel,t=>t?new Ps(t):null)])}}class Fp extends E{render(e,t){const s=i=>i.isBusy;return e.div({className:"PreSessionScreen"},[e.button({className:"button-utility LoginView_back",onClick:()=>t.goBack(),disabled:s}),e.div({className:"logo"}),e.h1([t.i18n`Sign In`]),e.mapView(i=>i.completeSSOLoginViewModel,i=>i?new Up(i):null),e.if(i=>i.showHomeserver,(i,r)=>i.div({className:"LoginView_sso form-row text"},[i.label({for:"homeserver"},r.i18n`Homeserver`),i.input({id:"homeserver",type:"text",placeholder:r.i18n`Your matrix homeserver`,value:r.homeserver,disabled:s,onInput:o=>r.setHomeserver(o.target.value),onChange:()=>r.queryHomeserver()}),i.p({className:{LoginView_forwardInfo:!0,hidden:o=>!o.resolvedHomeserver}},o=>o.i18n`You will connect to ${o.resolvedHomeserver}.`),i.if(o=>o.errorMessage,(o,a)=>o.p({className:"error"},a.i18n(a.errorMessage)))])),e.if(i=>i.isFetchingLoginOptions,i=>i.div({className:"LoginView_query-spinner"},[Ve(i),i.p("Fetching available login options...")])),e.mapView(i=>i.passwordLoginViewModel,i=>i?new Op(i):null),e.if(i=>i.passwordLoginViewModel&&i.startSSOLoginViewModel,i=>i.p({className:"LoginView_separator"},t.i18n`or`)),e.mapView(i=>i.startSSOLoginViewModel,i=>i?new Bp(i):null),e.mapView(i=>i.loadViewModel,i=>i?new Ps(i):null),e.p(qo(e))])}}class Bp extends E{render(e,t){return e.div({className:"StartSSOLoginView"},e.button({className:"StartSSOLoginView_button button-action secondary",type:"button",onClick:()=>t.startSSOLogin(),disabled:s=>s.isBusy},t.i18n`Log in with SSO`))}}class Kp extends E{render(e,t){const s=new Ns(t,r=>r.div([r.p("Are you sure you want to log out?"),r.div({className:"button-row"},[r.a({className:"button-action",type:"submit",href:t.cancelUrl},["Cancel"]),r.button({className:"button-action primary destructive",type:"submit",onClick:()=>t.logout()},t.i18n`Log out`)])])),i=new Ns(t,r=>r.p({className:"status",hidden:o=>!o.showStatus},[Ve(r,{hidden:o=>!o.busy}),r.span(o=>o.status)]));return e.div({className:"LogoutScreen"},[e.div({className:"content"},[e.mapView(r=>r.showConfirm,r=>r?s:i)])])}}class $p extends E{render(e,t){return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionLoadView"},[e.view(new Ps(t))]),e.div({className:{"button-row":!0,hidden:s=>s.loading}},e.a({className:"button-action primary",href:t.backUrl},t.i18n`Go back`))])}}class jp extends E{_onDeleteClick(){confirm("Are you sure?")&&this.value.delete()}_onClearClick(){confirm("Are you sure?")&&this.value.clear()}render(e,t){return e.li([e.a({className:"session-info",href:t.openUrl},[e.div({className:`avatar usercolor${t.avatarColorNumber}`},s=>s.avatarInitials),e.div({className:"user-id"},s=>s.label)])])}}class qp extends E{render(e,t){const s=new is({list:t.sessions,parentProvidesUpdates:!1},i=>new jp(i));return e.div({className:"PreSessionScreen"},[e.div({className:"logo"}),e.div({className:"SessionPickerView"},[e.h1(["Continue as \u2026"]),e.view(s),e.div({className:"button-row"},[e.a({className:"button-action primary",href:t.cancelUrl},t.i18n`Sign In`)]),e.ifView(i=>i.loadViewModel,()=>new Ps(t.loadViewModel)),e.p(qo(e))])])}}class Wp extends E{render(e,t){return e.mapView(s=>s.activeSection,s=>{switch(s){case"error":return new Et(i=>i.div({className:"StatusView"},[i.h1("Something went wrong"),i.p(t.errorText)]));case"session":return new Lp(t.sessionViewModel);case"login":return new Fp(t.loginViewModel);case"logout":return new Kp(t.logoutViewModel);case"picker":return new qp(t.sessionPickerViewModel);case"redirecting":return new Et(i=>i.p("Redirecting..."));case"loading":return new $p(t.sessionLoadViewModel);default:throw new Error(`Unknown section: ${t.activeSection}`)}})}}class Hp{constructor(e){this._reject=null,this._handle=null,this._promise=new Promise((t,s)=>{this._reject=s,this._handle=setTimeout(()=>{this._reject=null,t()},e)})}elapsed(){return this._promise}abort(){this._reject&&(this._reject(new ye),clearTimeout(this._handle),this._handle=null,this._reject=null)}dispose(){this.abort()}}class zp{constructor(e,t){this._handle=setInterval(t,e)}dispose(){this._handle&&(clearInterval(this._handle),this._handle=null)}}class Gp{constructor(){this._start=window.performance.now()}measure(){return window.performance.now()-this._start}}class Jp{createMeasure(){return new Gp}createTimeout(e){return new Hp(e)}createInterval(e,t){return new zp(t,e)}now(){return Date.now()}}class Qp{constructor(){this._waitingForReply=new Map,this._messageIdCounter=0,this._navigation=null,this._registration=null,this._registrationPromise=null,this._currentController=null,this.haltRequests=!1}setNavigation(e){this._navigation=e}registerAndStart(e){this._registrationPromise=(async()=>{navigator.serviceWorker.addEventListener("message",this),navigator.serviceWorker.addEventListener("controllerchange",this),this._registration=await navigator.serviceWorker.register(e),await navigator.serviceWorker.ready,this._currentController=navigator.serviceWorker.controller,this._registration.addEventListener("updatefound",this),this._registrationPromise=null,this._registration.waiting&&this._registration.active&&this._proposeUpdate(),console.log("Service Worker registered")})()}_onMessage(e){const{data:t}=e,s=t.replyTo;if(s){const i=this._waitingForReply.get(s);i&&(this._waitingForReply.delete(s),i(t.payload))}if(t.type==="hasSessionOpen"){const i=this._navigation.observe("session").get()===t.payload.sessionId;e.source.postMessage({replyTo:t.id,payload:i})}else if(t.type==="hasRoomOpen"){const i=this._navigation.observe("session").get()===t.payload.sessionId,r=this._navigation.observe("room").get()===t.payload.roomId;e.source.postMessage({replyTo:t.id,payload:i&&r})}else if(t.type==="closeSession"){const{sessionId:i}=t.payload;this._closeSessionIfNeeded(i).finally(()=>{e.source.postMessage({replyTo:t.id})})}else t.type==="haltRequests"?(this.haltRequests=!0,e.source.postMessage({replyTo:t.id})):t.type==="openRoom"&&this._navigation.push("room",t.payload.roomId)}_closeSessionIfNeeded(e){var s;const t=(s=this._navigation)==null?void 0:s.path.get("session");return e&&(t==null?void 0:t.value)===e?new Promise(i=>{const r=this._navigation.pathObservable.subscribe(o=>{const a=o.get("session");(!a||a.value!==e)&&(r(),i())});this._navigation.push("session")}):Promise.resolve()}async _proposeUpdate(){if(document.hidden)return;const e=await this._sendAndWaitForReply("version",null,this._registration.waiting);confirm(`Version ${e.version} (${e.buildHash}) is available. Reload to apply?`)&&(await this._sendAndWaitForReply("haltRequests"),this._send("skipWaiting",null,this._registration.waiting))}handleEvent(e){switch(e.type){case"message":this._onMessage(e);break;case"updatefound":this._registration.installing.addEventListener("statechange",this);break;case"statechange":{e.target.state==="installed"&&(this._proposeUpdate(),e.target.removeEventListener("statechange",this));break}case"controllerchange":this._currentController?document.location.reload():this._currentController=navigator.serviceWorker.controller;break}}async _send(e,t,s=void 0){this._registrationPromise&&await this._registrationPromise,s||(s=this._registration.active),s.postMessage({type:e,payload:t})}async _sendAndWaitForReply(e,t,s=void 0){this._registrationPromise&&await this._registrationPromise,s||(s=this._registration.active),this._messageIdCounter+=1;const i=this._messageIdCounter,r=new Promise(o=>{this._waitingForReply.set(i,o)});return s.postMessage({type:e,id:i,payload:t}),await r}async checkForUpdate(){this._registrationPromise&&await this._registrationPromise,this._registration.update()}get version(){return"0.3.1"}get buildHash(){return "2832467534"}async preventConcurrentSessionAccess(e){return this._sendAndWaitForReply("closeSession",{sessionId:e})}async getRegistration(){return this._registrationPromise&&await this._registrationPromise,this._registration}}class Yp{constructor(e,t){this._serviceWorkerHandler=e,this._pushConfig=t}async enablePush(e,t){var i;const s=await((i=this._serviceWorkerHandler)==null?void 0:i.getRegistration());if(s!=null&&s.pushManager){const o=(await s.pushManager.subscribe({userVisibleOnly:!0,applicationServerKey:this._pushConfig.applicationServerKey})).toJSON(),a=o.keys.p256dh,c={endpoint:o.endpoint,auth:o.keys.auth,events_only:!0,default_payload:t};return e.httpPusher(this._pushConfig.gatewayUrl,this._pushConfig.appId,a,c)}}async disablePush(){var t;const e=await((t=this._serviceWorkerHandler)==null?void 0:t.getRegistration());if(e!=null&&e.pushManager){const s=await e.pushManager.getSubscription();s&&await s.unsubscribe()}}async isPushEnabled(){var t;const e=await((t=this._serviceWorkerHandler)==null?void 0:t.getRegistration());return e!=null&&e.pushManager?!!await e.pushManager.getSubscription():!1}async supportsPush(){var t;if(!this._pushConfig)return!1;const e=await((t=this._serviceWorkerHandler)==null?void 0:t.getRegistration());return e&&"pushManager"in e}async enableNotifications(){return"Notification"in window?await Notification.requestPermission()==="granted":!1}async supportsNotifications(){return"Notification"in window}async areNotificationsEnabled(){return"Notification"in window?Notification.permission==="granted":!1}async showNotification(e,t=void 0){var i;if("Notification"in window){new Notification(e,{body:t});return}const s=await((i=this._serviceWorkerHandler)==null?void 0:i.getRegistration());s==null||s.showNotification(e,{body:t})}}class Xp extends kt{constructor(){super(),this._lastSessionHash=void 0}handleEvent(e){e.type==="hashchange"&&(this.emit(this.get()),this._storeHash(this.get()))}get(){return document.location.search.includes("loginToken")?document.location.search:document.location.hash}replaceUrlSilently(e){window.history.replaceState(null,null,e),this._storeHash(e)}pushUrlSilently(e){window.history.pushState(null,null,e),this._storeHash(e)}pushUrl(e){document.location.hash=e}urlAsPath(e){return e.startsWith("#")?e.substr(1):e}pathAsUrl(e){return`#${e}`}onSubscribeFirst(){var e;this._lastSessionHash=(e=window.localStorage)==null?void 0:e.getItem("hydrogen_last_url_hash"),window.addEventListener("hashchange",this)}onUnsubscribeLast(){window.removeEventListener("hashchange",this)}_storeHash(e){var t;(t=window.localStorage)==null||t.setItem("hydrogen_last_url_hash",e)}getLastSessionUrl(){return this._lastSessionHash}}class Zp extends kt{constructor(){super(),this._onOffline=this._onOffline.bind(this),this._onOnline=this._onOnline.bind(this)}_onOffline(){this.emit(!1)}_onOnline(){this.emit(!0)}get(){return navigator.onLine}onSubscribeFirst(){window.addEventListener("offline",this._onOffline),window.addEventListener("online",this._onOnline)}onUnsubscribeLast(){window.removeEventListener("offline",this._onOffline),window.removeEventListener("online",this._onOnline)}}function Q(n,e){return n instanceof Promise?n:new Promise((t,s)=>{n.oncomplete=i=>t(i.target.result),n.onerror=()=>s(new Error("Crypto error on "+e))})}class e_{constructor(e){this._subtleCrypto=e}async verify(e,t,s,i){const r={name:"HMAC",hash:{name:ct(i)}},o=await Q(this._subtleCrypto.importKey("raw",e,r,!1,["verify"]),"importKey");return await Q(this._subtleCrypto.verify(r,o,t,s),"verify")}async compute(e,t,s){const i={name:"HMAC",hash:{name:ct(s)}},r=await Q(this._subtleCrypto.importKey("raw",e,i,!1,["sign"]),"importKey"),o=await Q(this._subtleCrypto.sign(i,r,t),"sign");return new Uint8Array(o)}}class t_{constructor(e,t,s){this._subtleCrypto=e,this._crypto=t,this._cryptoExtras=s}async pbkdf2(e,t,s,i,r){if(!this._subtleCrypto.deriveBits)throw new Error("PBKDF2 is not supported");const o=await Q(this._subtleCrypto.importKey("raw",e,{name:"PBKDF2"},!1,["deriveBits"]),"importKey"),a=await Q(this._subtleCrypto.deriveBits({name:"PBKDF2",salt:s,iterations:t,hash:ct(i)},o,r),"deriveBits");return new Uint8Array(a)}async hkdf(e,t,s,i,r){if(!this._subtleCrypto.deriveBits)return this._cryptoExtras.hkdf(this._crypto,e,t,s,i,r);const o=await Q(this._subtleCrypto.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),"importKey"),a=await Q(this._subtleCrypto.deriveBits({name:"HKDF",salt:t,info:s,hash:ct(i)},o,r),"deriveBits");return new Uint8Array(a)}}class s_{constructor(e,t){this._subtleCrypto=e,this._crypto=t}async decryptCTR({key:e,jwkKey:t,iv:s,data:i,counterLength:r=64}){const o={name:"AES-CTR",counter:s,length:r};let a;try{const c=e||t,l=t?"jwk":"raw";a=await Q(this._subtleCrypto.importKey(l,c,o,!1,["decrypt"]),"importKey")}catch(c){throw new Error(`Could not import key for AES-CTR decryption: ${c.message}`)}try{const c=await Q(this._subtleCrypto.decrypt(o,a,i),"decrypt");return new Uint8Array(c)}catch(c){throw new Error(`Could not decrypt with AES-CTR: ${c.message}`)}}async encryptCTR({key:e,jwkKey:t,iv:s,data:i}){const r={name:"AES-CTR",counter:s,length:64};let o;const a=e||t,c=t?"jwk":"raw";try{o=await Q(this._subtleCrypto.importKey(c,a,r,!1,["encrypt"]),"importKey")}catch(l){throw new Error(`Could not import key for AES-CTR encryption: ${l.message}`)}try{const l=await Q(this._subtleCrypto.encrypt(r,o,i),"encrypt");return new Uint8Array(l)}catch(l){throw new Error(`Could not encrypt with AES-CTR: ${l.message}`)}}async generateKey(e,t=256){const s=await Q(this._subtleCrypto.generateKey({name:"AES-CTR",length:t},!0,["encrypt","decrypt"]));return Q(this._subtleCrypto.exportKey(e,s))}async generateIV(){return Wo(this._crypto)}}function Wo(n){const e=n.getRandomValues(new Uint8Array(8)),t=new Uint8Array(16);for(let s=0;s{this._resolve=s,this._reject=i}),this._message=e,this._pool=t,this._worker=null}abort(){this._isNotDisposed&&(this._pool._abortRequest(this),this._dispose())}response(){return this._promise}_dispose(){this._reject=null,this._resolve=null}get _isNotDisposed(){return this._resolve&&this._reject}}class d_{constructor(e,t){this._workers=[];for(let s=0;s{this._init={resolve:t,reject:s}});return this.sendAll({type:"ping"}).then(this._init.resolve,this._init.reject).finally(()=>{this._init=null}),e}handleEvent(e){if(e.type==="message"){const t=e.data,s=this._requests.get(t.replyToId);if(s){if(s._worker.busy=!1,s._isNotDisposed){if(t.type==="success")s._resolve(t.payload);else if(t.type==="error"){const i=new Error(t.message);i.stack=t.stack,s._reject(i)}s._dispose()}this._requests.delete(t.replyToId)}this._sendPending()}else e.type==="error"&&(this._init&&this._init.reject(new Error("worker error during init")),console.error("worker error",e))}_getPendingRequest(){for(const e of this._requests.values())if(!e._worker)return e}_getFreeWorker(){for(const e of this._workers)if(!e.busy)return e}_sendPending(){this._pendingFlag=!1;let e;do{e=!1;const t=this._getPendingRequest();if(t){const s=this._getFreeWorker();s&&(this._sendWith(t,s),e=!0)}}while(e)}_sendWith(e,t){e._worker=t,t.busy=!0,t.worker.postMessage(e._message)}_enqueueRequest(e){this._counter+=1,e.id=this._counter;const t=new h_(e,this);return this._requests.set(e.id,t),t}send(e){const t=this._enqueueRequest(e),s=this._getFreeWorker();return s&&this._sendWith(t,s),t}sendAll(e){const t=this._workers.map(s=>{const i=this._enqueueRequest(Object.assign({},e));return this._sendWith(i,s),i.response()});return Promise.all(t)}dispose(){for(const e of this._workers)e.detach(this),e.worker.terminate()}_trySendPendingInNextTick(){this._pendingFlag||(this._pendingFlag=!0,Promise.resolve().then(()=>{this._sendPending()}))}_abortRequest(e){e._reject(new ye),e._worker&&(e._worker.busy=!1),this._requests.delete(e._message.id),this._trySendPendingInNextTick()}}class Zt{static async fromBlob(e){const t=await _n(e),{width:s,height:i}=t;return new Zt(e,s,i,t)}constructor(e,t,s,i){this.blob=e,this.width=t,this.height=s,this._domElement=i}get maxDimension(){return Math.max(this.width,this.height)}async _getDomElement(){return this._domElement||(this._domElement=await _n(this.blob)),this._domElement}async scale(e){const t=this.width/this.height,s=Math.min(1,e/(t>=1?this.width:this.height)),i=Math.round(this.width*s),r=Math.round(this.height*s),o=document.createElement("canvas");o.width=i,o.height=r;const a=o.getContext("2d"),c=await this._getDomElement();a.drawImage(c,0,0,i,r);let l=this.blob.mimeType==="image/jpeg"?"image/jpeg":"image/png",h;if(o.toBlob)h=await new Promise(u=>o.toBlob(u,l));else if(o.msToBlob)l="image/png",h=o.msToBlob();else throw new Error("canvas can't be turned into blob");const d=lt.fromBlob(h);return new Zt(d,i,r,null)}dispose(){this.blob.dispose()}}class Gi extends Zt{get duration(){if(typeof this._domElement.duration=="number")return Math.round(this._domElement.duration*1e3)}static async fromBlob(e){const t=await m_(e),{videoWidth:s,videoHeight:i}=t;return new Gi(e,s,i,t)}}function u_(){const n=document.createElement("canvas");n.width=1,n.height=1;const e=n.getContext("2d"),t=[Math.round(Math.random()*255),Math.round(Math.random()*255),Math.round(Math.random()*255)];e.fillStyle=`rgb(${t[0]}, ${t[1]}, ${t[2]})`,e.fillRect(0,0,1,1);const s=e.getImageData(0,0,1,1).data;return s[0]===t[0]&&s[1]===t[1]&&s[2]===t[2]}async function _n(n){const e=document.createElement("img"),t=Ds(e,"load");return e.src=n.url,await t,e}async function m_(n){const e=document.createElement("video");e.muted=!0;const t=Ds(e,"loadedmetadata");e.src=n.url,e.load(),await t;const s=Ds(e,"seeked");return await new Promise(i=>setTimeout(i,200)),e.currentTime=.1,await s,e}async function p_(n,e,t,s,i){let r=n.querySelector("iframe.downloadSandbox");if(!r){r=document.createElement("iframe"),r.setAttribute("sandbox","allow-scripts allow-downloads allow-downloads-without-user-activation"),r.setAttribute("src",e),r.className="hidden downloadSandbox",n.appendChild(r);let o;await new Promise((a,c)=>{o=()=>{r.removeEventListener("load",a),r.removeEventListener("error",c)},r.addEventListener("load",a),r.addEventListener("error",c)}),o()}if(i){const o=await t.readAsBuffer();r.contentWindow.postMessage({type:"downloadBuffer",buffer:o,mimeType:t.mimeType,filename:s},"*")}else r.contentWindow.postMessage({type:"downloadBlob",blob:t.nativeBlob,filename:s},"*")}/*! @license DOMPurify 2.3.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.0/LICENSE */function __(n){if(Array.isArray(n)){for(var e=0,t=Array(n.length);e1?t-1:0),i=1;i/gm),M_=Ae(/^data-[\-\w.\u00B7-\uFFFF]/),A_=Ae(/^aria-[\-\w]+$/),x_=Ae(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),N_=Ae(/^(?:\w+script|data):/i),D_=Ae(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),Kt=typeof Symbol=="function"&&typeof Symbol.iterator=="symbol"?function(n){return typeof n}:function(n){return n&&typeof Symbol=="function"&&n.constructor===Symbol&&n!==Symbol.prototype?"symbol":typeof n};function pe(n){if(Array.isArray(n)){for(var e=0,t=Array(n.length);e0&&arguments[0]!==void 0?arguments[0]:V_(),e=function(m){return zo(m)};if(e.version="2.3.0",e.removed=[],!n||!n.document||n.document.nodeType!==9)return e.isSupported=!1,e;var t=n.document,s=n.document,i=n.DocumentFragment,r=n.HTMLTemplateElement,o=n.Node,a=n.Element,c=n.NodeFilter,l=n.NamedNodeMap,h=l===void 0?n.NamedNodeMap||n.MozNamedAttrMap:l,d=n.Text,u=n.Comment,p=n.DOMParser,_=n.trustedTypes,f=a.prototype,b=Ss(f,"cloneNode"),S=Ss(f,"nextSibling"),k=Ss(f,"childNodes"),R=Ss(f,"parentNode");if(typeof r=="function"){var w=s.createElement("template");w.content&&w.content.ownerDocument&&(s=w.content.ownerDocument)}var I=L_(_,t),x=I&&ns?I.createHTML(""):"",D=s,Le=D.implementation,Qo=D.createNodeIterator,Yo=D.createDocumentFragment,Xo=D.getElementsByTagName,Zo=t.importNode,Ji={};try{Ji=yt(s).documentMode?s.documentMode:{}}catch{}var ue={};e.isSupported=typeof R=="function"&&Le&&typeof Le.createHTMLDocument!="undefined"&&Ji!==9;var Fs=C_,Bs=T_,ea=M_,ta=A_,sa=N_,Qi=D_,Ks=x_,$=null,Yi=C({},[].concat(pe(vn),pe(ri),pe(ni),pe(oi),pe(bn))),j=null,Xi=C({},[].concat(pe(Sn),pe(ai),pe(In),pe(Is))),$s=null,js=null,Zi=!0,qs=!0,er=!1,dt=!1,ut=!1,Ws=!1,Hs=!1,mt=!1,rs=!1,tr=!0,ns=!1,sr=!0,zs=!0,Mt=!1,pt={},ia=C({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]),ir=null,rr=C({},["audio","video","img","source","image","track"]),Gs=null,nr=C({},["alt","class","for","id","label","name","pattern","placeholder","summary","title","value","style","xmlns"]),Js="http://www.w3.org/1998/Math/MathML",Qs="http://www.w3.org/2000/svg",Oe="http://www.w3.org/1999/xhtml",os=Oe,Ys=!1,_t=null,ra=s.createElement("form"),Xs=function(m){_t&&_t===m||((!m||(typeof m=="undefined"?"undefined":Kt(m))!=="object")&&(m={}),m=yt(m),$="ALLOWED_TAGS"in m?C({},m.ALLOWED_TAGS):Yi,j="ALLOWED_ATTR"in m?C({},m.ALLOWED_ATTR):Xi,Gs="ADD_URI_SAFE_ATTR"in m?C(yt(nr),m.ADD_URI_SAFE_ATTR):nr,ir="ADD_DATA_URI_TAGS"in m?C(yt(rr),m.ADD_DATA_URI_TAGS):rr,$s="FORBID_TAGS"in m?C({},m.FORBID_TAGS):{},js="FORBID_ATTR"in m?C({},m.FORBID_ATTR):{},pt="USE_PROFILES"in m?m.USE_PROFILES:!1,Zi=m.ALLOW_ARIA_ATTR!==!1,qs=m.ALLOW_DATA_ATTR!==!1,er=m.ALLOW_UNKNOWN_PROTOCOLS||!1,dt=m.SAFE_FOR_TEMPLATES||!1,ut=m.WHOLE_DOCUMENT||!1,mt=m.RETURN_DOM||!1,rs=m.RETURN_DOM_FRAGMENT||!1,tr=m.RETURN_DOM_IMPORT!==!1,ns=m.RETURN_TRUSTED_TYPE||!1,Hs=m.FORCE_BODY||!1,sr=m.SANITIZE_DOM!==!1,zs=m.KEEP_CONTENT!==!1,Mt=m.IN_PLACE||!1,Ks=m.ALLOWED_URI_REGEXP||Ks,os=m.NAMESPACE||Oe,dt&&(qs=!1),rs&&(mt=!0),pt&&($=C({},[].concat(pe(bn))),j=[],pt.html===!0&&(C($,vn),C(j,Sn)),pt.svg===!0&&(C($,ri),C(j,ai),C(j,Is)),pt.svgFilters===!0&&(C($,ni),C(j,ai),C(j,Is)),pt.mathMl===!0&&(C($,oi),C(j,In),C(j,Is))),m.ADD_TAGS&&($===Yi&&($=yt($)),C($,m.ADD_TAGS)),m.ADD_ATTR&&(j===Xi&&(j=yt(j)),C(j,m.ADD_ATTR)),m.ADD_URI_SAFE_ATTR&&C(Gs,m.ADD_URI_SAFE_ATTR),zs&&($["#text"]=!0),ut&&C($,["html","head","body"]),$.table&&(C($,["tbody"]),delete $s.tbody),Z&&Z(m),_t=m)},or=C({},["mi","mo","mn","ms","mtext"]),ar=C({},["foreignobject","desc","title","annotation-xml"]),as=C({},ri);C(as,ni),C(as,k_);var Zs=C({},oi);C(Zs,R_);var na=function(m){var g=R(m);(!g||!g.tagName)&&(g={namespaceURI:Oe,tagName:"template"});var y=et(m.tagName),N=et(g.tagName);if(m.namespaceURI===Qs)return g.namespaceURI===Oe?y==="svg":g.namespaceURI===Js?y==="svg"&&(N==="annotation-xml"||or[N]):Boolean(as[y]);if(m.namespaceURI===Js)return g.namespaceURI===Oe?y==="math":g.namespaceURI===Qs?y==="math"&&ar[N]:Boolean(Zs[y]);if(m.namespaceURI===Oe){if(g.namespaceURI===Qs&&!ar[N]||g.namespaceURI===Js&&!or[N])return!1;var q=C({},["title","style","font","a","script"]);return!Zs[y]&&(q[y]||!as[y])}return!1},Pe=function(m){Pt(e.removed,{element:m});try{m.parentNode.removeChild(m)}catch{try{m.outerHTML=x}catch{m.remove()}}},cr=function(m,g){try{Pt(e.removed,{attribute:g.getAttributeNode(m),from:g})}catch{Pt(e.removed,{attribute:null,from:g})}if(g.removeAttribute(m),m==="is"&&!j[m])if(mt||rs)try{Pe(g)}catch{}else try{g.setAttribute(m,"")}catch{}},lr=function(m){var g=void 0,y=void 0;if(Hs)m=""+m;else{var N=yn(m,/^[\r\n\t ]+/);y=N&&N[0]}var q=I?I.createHTML(m):m;if(os===Oe)try{g=new p().parseFromString(q,"text/html")}catch{}if(!g||!g.documentElement){g=Le.createDocument(os,"template",null);try{g.documentElement.innerHTML=Ys?"":q}catch{}}var W=g.body||g.documentElement;return m&&y&&W.insertBefore(s.createTextNode(y),W.childNodes[0]||null),os===Oe?Xo.call(g,ut?"html":"body")[0]:ut?g.documentElement:W},hr=function(m){return Qo.call(m.ownerDocument||m,m,c.SHOW_ELEMENT|c.SHOW_COMMENT|c.SHOW_TEXT,null,!1)},oa=function(m){return m instanceof d||m instanceof u?!1:typeof m.nodeName!="string"||typeof m.textContent!="string"||typeof m.removeChild!="function"||!(m.attributes instanceof h)||typeof m.removeAttribute!="function"||typeof m.setAttribute!="function"||typeof m.namespaceURI!="string"||typeof m.insertBefore!="function"},At=function(m){return(typeof o=="undefined"?"undefined":Kt(o))==="object"?m instanceof o:m&&(typeof m=="undefined"?"undefined":Kt(m))==="object"&&typeof m.nodeType=="number"&&typeof m.nodeName=="string"},be=function(m,g,y){!ue[m]||b_(ue[m],function(N){N.call(e,g,y,_t)})},dr=function(m){var g=void 0;if(be("beforeSanitizeElements",m,null),oa(m)||yn(m.nodeName,/[\u0080-\uFFFF]/))return Pe(m),!0;var y=et(m.nodeName);if(be("uponSanitizeElement",m,{tagName:y,allowedTags:$}),!At(m.firstElementChild)&&(!At(m.content)||!At(m.content.firstElementChild))&&Ke(/<[/\w]/g,m.innerHTML)&&Ke(/<[/\w]/g,m.textContent))return Pe(m),!0;if(!$[y]||$s[y]){if(zs&&!ia[y]){var N=R(m)||m.parentNode,q=k(m)||m.childNodes;if(q&&N)for(var W=q.length,H=W-1;H>=0;--H)N.insertBefore(b(q[H],!0),S(m))}return Pe(m),!0}return m instanceof a&&!na(m)||(y==="noscript"||y==="noembed")&&Ke(/<\/no(script|embed)/i,m.innerHTML)?(Pe(m),!0):(dt&&m.nodeType===3&&(g=m.textContent,g=Be(g,Fs," "),g=Be(g,Bs," "),m.textContent!==g&&(Pt(e.removed,{element:m.cloneNode()}),m.textContent=g)),be("afterSanitizeElements",m,null),!1)},ur=function(m,g,y){if(sr&&(g==="id"||g==="name")&&(y in s||y in ra))return!1;if(!(qs&&!js[g]&&Ke(ea,g))){if(!(Zi&&Ke(ta,g))){if(!j[g]||js[g])return!1;if(!Gs[g]){if(!Ke(Ks,Be(y,Qi,""))){if(!((g==="src"||g==="xlink:href"||g==="href")&&m!=="script"&&S_(y,"data:")===0&&ir[m])){if(!(er&&!Ke(sa,Be(y,Qi,"")))){if(y)return!1}}}}}}return!0},mr=function(m){var g=void 0,y=void 0,N=void 0,q=void 0;be("beforeSanitizeAttributes",m,null);var W=m.attributes;if(!!W){var H={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:j};for(q=W.length;q--;){g=W[q];var Se=g,xt=Se.name,pr=Se.namespaceURI;if(y=I_(g.value),N=et(xt),H.attrName=N,H.attrValue=y,H.keepAttr=!0,H.forceKeepAttr=void 0,be("uponSanitizeAttribute",m,H),y=H.attrValue,!H.forceKeepAttr&&(cr(xt,m),!!H.keepAttr)){if(Ke(/\/>/i,y)){cr(xt,m);continue}dt&&(y=Be(y,Fs," "),y=Be(y,Bs," "));var ca=m.nodeName.toLowerCase();if(!!ur(ca,N,y))try{pr?m.setAttributeNS(pr,xt,y):m.setAttribute(xt,y),gn(e.removed)}catch{}}}be("afterSanitizeAttributes",m,null)}},aa=function v(m){var g=void 0,y=hr(m);for(be("beforeSanitizeShadowDOM",m,null);g=y.nextNode();)be("uponSanitizeShadowNode",g,null),!dr(g)&&(g.content instanceof i&&v(g.content),mr(g));be("afterSanitizeShadowDOM",m,null)};return e.sanitize=function(v,m){var g=void 0,y=void 0,N=void 0,q=void 0,W=void 0;if(Ys=!v,Ys&&(v=""),typeof v!="string"&&!At(v)){if(typeof v.toString!="function")throw wn("toString is not a function");if(v=v.toString(),typeof v!="string")throw wn("dirty is not a string, aborting")}if(!e.isSupported){if(Kt(n.toStaticHTML)==="object"||typeof n.toStaticHTML=="function"){if(typeof v=="string")return n.toStaticHTML(v);if(At(v))return n.toStaticHTML(v.outerHTML)}return v}if(Ws||Xs(m),e.removed=[],typeof v=="string"&&(Mt=!1),!Mt)if(v instanceof o)g=lr(""),y=g.ownerDocument.importNode(v,!0),y.nodeType===1&&y.nodeName==="BODY"||y.nodeName==="HTML"?g=y:g.appendChild(y);else{if(!mt&&!dt&&!ut&&v.indexOf("<")===-1)return I&&ns?I.createHTML(v):v;if(g=lr(v),!g)return mt?null:x}g&&Hs&&Pe(g.firstChild);for(var H=hr(Mt?v:g);N=H.nextNode();)N.nodeType===3&&N===q||dr(N)||(N.content instanceof i&&aa(N.content),mr(N),q=N);if(q=null,Mt)return v;if(mt){if(rs)for(W=Yo.call(g.ownerDocument);g.firstChild;)W.appendChild(g.firstChild);else W=g;return tr&&(W=Zo.call(t,W,!0)),W}var Se=ut?g.outerHTML:g.innerHTML;return dt&&(Se=Be(Se,Fs," "),Se=Be(Se,Bs," ")),I&&ns?I.createHTML(Se):Se},e.setConfig=function(v){Xs(v),Ws=!0},e.clearConfig=function(){_t=null,Ws=!1},e.isValidAttribute=function(v,m,g){_t||Xs({});var y=et(v),N=et(m);return ur(y,N,g)},e.addHook=function(v,m){typeof m=="function"&&(ue[v]=ue[v]||[],Pt(ue[v],m))},e.removeHook=function(v){ue[v]&&gn(ue[v])},e.removeHooks=function(v){ue[v]&&(ue[v]=[])},e.removeAllHooks=function(){ue={}},e}var O_=zo();class P_{constructor(e){this._bodyNode=e}get rootNodes(){return Array.from(this._bodyNode.childNodes)}getChildNodes(e){return Array.from(e.childNodes)}getAttributeNames(e){return Array.from(e.getAttributeNames())}getAttributeValue(e,t){return e.getAttribute(t)}isTextNode(e){return e.nodeType===Node.TEXT_NODE}getNodeText(e){return e.textContent}isElementNode(e){return e.nodeType===Node.ELEMENT_NODE}getNodeElementName(e){return e.tagName}}const U_={ALLOWED_URI_REGEXP:/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|xxx|mxc):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i,FORBID_TAGS:["mx-reply"],KEEP_CONTENT:!1};function F_(n){const e=O_.sanitize(n,U_),t=new DOMParser().parseFromString(`${e}`,"text/html").body;return new P_(t)}var je=(n=>(n[n.Dark=0]="Dark",n[n.Light=1]="Light",n))(je||{});function B_(n,e,t){let s=n.replaceAll("#ff00ff",e);if(s=s.replaceAll("#00ffff",t),n===s)throw new Error("svg-colorizer made no color replacements! The input svg should only contain colors #ff00ff (primary, case-sensitive) and #00ffff (secondary, case-sensitive).");return s}class K_{constructor(e,t,s,i){this._platform=e,this._iconVariables=t,this._resolvedVariables=s,this._manifestLocation=i}async toVariables(){const{parsedStructure:e,promises:t}=await this._fetchAndParseIcons();return await Promise.all(t),this._produceColoredIconVariables(e)}async _fetchAndParseIcons(){const e=[],t={};for(const[s,i]of Object.entries(this._iconVariables)){const r=new URL(`https://${i}`),o=r.hostname,a=new URL(o,new URL(this._manifestLocation,window.location.origin)),c=this._platform.request(a,{method:"GET",format:"text",cache:!0}).response();e.push(c);const l=r.searchParams;t[s]={svg:c,primary:l.get("primary"),secondary:l.get("secondary")}}return{parsedStructure:t,promises:e}}async _produceColoredIconVariables(e){let t={};for(const[s,{svg:i,primary:r,secondary:o}]of Object.entries(e)){const{body:a}=await i;if(!r)throw new Error(`Primary color variable ${r} not in list of variables!`);const c=this._resolvedVariables[r],l=this._resolvedVariables[o],h=B_(a,c,l),d=`url('data:image/svg+xml;utf8,${encodeURIComponent(h)}')`;t[s]=d}return t}}var Us={exports:{}},$_=function(n){var e={};function t(s){if(e[s])return e[s].exports;var i=e[s]={i:s,l:!1,exports:{}};return n[s].call(i.exports,i,i.exports,t),i.l=!0,i.exports}return t.m=n,t.c=e,t.d=function(s,i,r){t.o(s,i)||Object.defineProperty(s,i,{enumerable:!0,get:r})},t.r=function(s){typeof Symbol!="undefined"&&Symbol.toStringTag&&Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(s,"__esModule",{value:!0})},t.t=function(s,i){if(1&i&&(s=t(s)),8&i||4&i&&typeof s=="object"&&s&&s.__esModule)return s;var r=Object.create(null);if(t.r(r),Object.defineProperty(r,"default",{enumerable:!0,value:s}),2&i&&typeof s!="string")for(var o in s)t.d(r,o,function(a){return s[a]}.bind(null,o));return r},t.n=function(s){var i=s&&s.__esModule?function(){return s.default}:function(){return s};return t.d(i,"a",i),i},t.o=function(s,i){return Object.prototype.hasOwnProperty.call(s,i)},t.p="",t(t.s=0)}([function(n,e,t){function s(l){let h,d;const u={light:function(){return!_()},dark:_,lighten:S,darken:b,saturate:k,desaturate:function(w=0){return k(w*=-1)},increaseContrast:function(w=0){return R(w*=-1)},decreaseContrast:R,active:function(){return R(.123)},highlight:function(){return R(.1)},selected:function(){return R(.066)},text:function(){return d=f()?i("#333333"):i("#FFFFFF"),u},shadow:function(){return d=f()?i("#000000"):i("#FFFFFF"),u},hex:function(){const w=d;return d=h,"#"+w.map(I=>parseInt(I+"",10).toString(16).padStart(2,"0")).join("")},rgb:function(){const w=d;return d=h,`rgb(${w.join()})`},rgba:function(w=1){const I=d;return d=h,`rgba(${I.join()}, ${w})`},setHex:p,setRgb:function(w=[0,0,0]){let[I,x,D]=w;return I=c(I,0,255),x=c(x,0,255),D=c(D,0,255),h=[I,x,D],d=[I,x,D],u}};function p(w="#000000"){return h=i(w),d=h,u}function _(){const[w,I,x]=d;return d=h,(299*w+587*I+114*x)/1e3<128}function f(){const[w,I,x]=d;return(299*w+587*I+114*x)/1e3>=128}function b(w=0){return S(w*=-1)}function S(w=0){let[I,x,D]=a(d);return D=c(D+w,0,1),d=r([I,x,D]),u}function k(w=0){let[I,x,D]=a(d);return x=c(x+w,0,1),d=r([I,x,D]),u}function R(w=0){return f()?b(w):S(w)}return p(l),u}function i(l){if(typeof l!="string")throw new TypeError("Expected a string");(l=l.replace(/^#/,"")).length===3&&(l=l[0]+l[0]+l[1]+l[1]+l[2]+l[2]);var h=parseInt(l,16);return[h>>16,h>>8&255,255&h]}function r(l){const[h,d,u]=l;let p,_,f;if(d===0)p=_=f=u;else{const b=function(R,w,I){return I<0&&(I+=1),I>1&&(I-=1),I<.16666666666666666?R+6*(w-R)*I:I<.5?w:I<.6666666666666666?R+(w-R)*(.6666666666666666-I)*6:R},S=u<.5?u*(1+d):u+d-u*d,k=2*u-S;p=c(b(k,S,h+1/3),0,1),_=c(b(k,S,h),0,1),f=c(b(k,S,h-1/3),0,1)}return[Math.round(255*p),Math.round(255*_),Math.round(255*f)]}t.r(e),t.d(e,"offColor",function(){return s}),t.d(e,"hexRgb",function(){return i}),t.d(e,"hslToRgb",function(){return r}),t.d(e,"color",function(){return o}),t.d(e,"rgbToHsl",function(){return a});const o=s;function a(l){const h=l[0]/255,d=l[1]/255,u=l[2]/255,p=Math.max(h,d,u),_=Math.min(h,d,u);let f=(p+_)/2,b=(p+_)/2;const S=(p+_)/2;if(p===_)f=b=0;else{const k=p-_;switch(b=S>.5?k/(2-p-_):k/(p+_),p){case h:f=(d-u)/k+(d=h?l:h}}]);Us.exports=$_;var Go=Us.exports,Cn;const En=(Cn=Us.exports.offColor)!=null?Cn:Go.offColor;function kn(n,e,t,s){const i=parseInt(t);switch(s&&(e==="darker"?e="lighter":e==="lighter"&&(e="darker")),e){case"darker":return En(n).darken(i/100).hex();case"lighter":return En(n).lighten(i/100).hex()}}class j_{constructor(e,t,s){this._aliases={},this._derivedAliases=[],this._baseVariables=e,this._variablesToDerive=t,this._isDark=s}toVariables(){var t;const e={};this._detectAliases();for(const s of this._variablesToDerive){const i=this._derive(s);i&&(e[s]=i)}for(const[s,i]of Object.entries(this._aliases))e[s]=(t=this._baseVariables[i])!=null?t:e[i];for(const s of this._derivedAliases){const i=this._deriveAlias(s,e);i&&(e[s]=i)}return e}_detectAliases(){const e=[];for(const t of this._variablesToDerive){const[s,i]=t.split("=");i?this._aliases[s]=i:e.push(t)}this._variablesToDerive=e}_derive(e){const t=/(.+)--(.+)-(.+)/,s=e.match(t);if(s){const[,i,r,o]=s,a=this._baseVariables[i];if(!a)if(this._aliases[i]){this._derivedAliases.push(e);return}else throw new Error(`Cannot find value for base variable "${i}"!`);return kn(a,r,o,this._isDark)}}_deriveAlias(e,t){const s=/(.+)--(.+)-(.+)/,i=e.match(s);if(i){const[,r,o,a]=i,c=t[r];if(!c)throw new Error(`Cannot find value for alias "${r}" when trying to derive ${e}!`);return kn(c,o,a,this._isDark)}}}var Tn;(Tn=Us.exports.offColor)!=null||Go.offColor;class q_{constructor(e,t){this._themeMapping={},this._preferredColorScheme=t,this._platform=e}async parse(e,t,s,i){await i.wrap("RuntimeThemeParser.parse",async()=>{var d;const{cssLocation:r,derivedVariables:o,icons:a}=this._getSourceData(t,s,i),c=e.name;if(!c)throw new Error("Theme name not found in manifest!");let l={},h={};for(const[u,p]of Object.entries((d=e.values)==null?void 0:d.variants))try{const _=`${e.id}-${u}`,{name:f,default:b,dark:S,variables:k}=p,R=new j_(k,o,S).toVariables();Object.assign(k,R);const w=await new K_(this._platform,a,k,s).toVariables();Object.assign(k,R,w);const I=`${c} ${f}`;if(b){Object.assign(S?l:h,{variantName:f,id:_,cssLocation:r,variables:k});continue}this._themeMapping[I]={cssLocation:r,id:_,variables:k}}catch(_){console.error(_);continue}if(l.id&&h.id){const u=this._preferredColorScheme===je.Dark?l:h;this._themeMapping[c]={dark:l,light:h,default:u}}else{const u=l.id?l:h;this._themeMapping[`${c} ${u.variantName}`]={id:u.id,cssLocation:u.cssLocation}}})}_getSourceData(e,t,s){return s.wrap("getSourceData",()=>{var c,l,h;const i=(c=e.source)==null?void 0:c["runtime-asset"];if(!i)throw new Error(`Run-time asset not found in source section for theme at ${t}`);const r=new URL(i,new URL(t,window.location.origin)).href,o=(l=e.source)==null?void 0:l["derived-variables"];if(!o)throw new Error(`Derived variables not found in source section for theme at ${t}`);const a=(h=e.source)==null?void 0:h.icon;if(!a)throw new Error(`Icon mapping not found in source section for theme at ${t}`);return{cssLocation:r,derivedVariables:o,icons:a}})}get themeMapping(){return this._themeMapping}}class W_{constructor(e){this._themeMapping={},this._preferredColorScheme=e}parse(e,t,s){s.wrap("BuiltThemeParser.parse",()=>{var c,l,h;const i=(c=e.source)==null?void 0:c["built-assets"],r=e.name;if(!r)throw new Error(`Theme name not found in manifest at ${t}`);let o={},a={};for(let[d,u]of Object.entries(i)){try{u=new URL(u,new URL(t,window.location.origin)).href}catch{continue}const p=(l=d.match(/.+-(.+)/))==null?void 0:l[1],_=(h=e.values)==null?void 0:h.variants[p];if(!_)throw new Error(`Variant ${p} is missing in manifest at ${t}`);const{name:f,default:b,dark:S}=_,k=`${r} ${f}`;if(b){const R=S?o:a;R.variantName=f,R.id=d,R.cssLocation=u;continue}this._themeMapping[k]={cssLocation:u,id:d}}if(o.id&&a.id){const d=this._preferredColorScheme===je.Dark?o:a;this._themeMapping[r]={dark:o,light:a,default:d}}else{const d=o.id?o:a;this._themeMapping[`${r} ${d.variantName}`]={id:d.id,cssLocation:d.cssLocation}}})}get themeMapping(){return this._themeMapping}}class H_{constructor(e){this._platform=e}async init(e,t){await this._platform.logger.wrapOrRun(t,"ThemeLoader.init",async s=>{const i=await Promise.all(e.map(c=>this._platform.request(c,{method:"GET",format:"json",cache:!0}).response())),r=new q_(this._platform,this.preferredColorScheme),o=new W_(this.preferredColorScheme),a=[];for(let c=0;c_.body.id===l.extends);if(h===-1)throw new Error(`Base manifest for derived theme at ${e[c]} not found!`);const{body:d}=i[h],u=e[h],p=r.parse(l,d,u,s);a.push(p)}else o.parse(l,e[c],s)}catch(h){console.error(h)}}await Promise.all(a),this._themeMapping=ft(ft({},o.themeMapping),r.themeMapping),Object.assign(this._themeMapping,o.themeMapping,r.themeMapping),this._addDefaultThemeToMapping(s),s.log({l:"Preferred colorscheme",scheme:this.preferredColorScheme===je.Dark?"dark":"light"}),s.log({l:"Result",themeMapping:this._themeMapping})})}setTheme(e,t,s){this._platform.logger.wrapOrRun(s,{l:"change theme",name:e,variant:t},()=>{let i,r,o=this._themeMapping[e];if("id"in o)i=o.cssLocation,r=o.variables;else{if(!t)throw new Error("themeVariant is undefined!");i=o[t].cssLocation,r=o[t].variables}this._platform.replaceStylesheet(i),r?(s==null||s.log({l:"Derived Theme",variables:r}),this._injectCSSVariables(r)):this._removePreviousCSSVariables(),this._platform.settingsStorage.setString("theme-name",e),t?this._platform.settingsStorage.setString("theme-variant",t):this._platform.settingsStorage.remove("theme-variant")})}_injectCSSVariables(e){const t=document.documentElement;for(const[s,i]of Object.entries(e))t.style.setProperty(`--${s}`,i);this._injectedVariables=e}_removePreviousCSSVariables(){if(!this._injectedVariables)return;const e=document.documentElement;for(const t of Object.keys(this._injectedVariables))e.style.removeProperty(`--${t}`);this._injectedVariables=void 0}get themeMapping(){return this._themeMapping}async getActiveTheme(){let e=await this._platform.settingsStorage.getString("theme-name"),t=await this._platform.settingsStorage.getString("theme-variant");return(!e||!this._themeMapping[e])&&(e="Default"in this._themeMapping?"Default":Object.keys(this._themeMapping)[0],this._themeMapping[e][t]||(t="default"in this._themeMapping[e]?"default":void 0)),{themeName:e,themeVariant:t}}getDefaultTheme(){var e,t;switch(this.preferredColorScheme){case je.Dark:return(e=this._platform.config.defaultTheme)==null?void 0:e.dark;case je.Light:return(t=this._platform.config.defaultTheme)==null?void 0:t.light}}_findThemeDetailsFromId(e){var t,s;for(const[i,r]of Object.entries(this._themeMapping)){if("id"in r&&r.id===e)return{themeName:i,themeData:r};if("light"in r&&((t=r.light)==null?void 0:t.id)===e)return{themeName:i,themeData:r.light};if("dark"in r&&((s=r.dark)==null?void 0:s.id)===e)return{themeName:i,themeData:r.dark}}}_addDefaultThemeToMapping(e){e.wrap("addDefaultThemeToMapping",t=>{const s=this.getDefaultTheme();if(s){const i=this._findThemeDetailsFromId(s);if(i){this._themeMapping.Default={id:"default",cssLocation:i.themeData.cssLocation};const r=i.themeData.variables;r&&(this._themeMapping.Default.variables=r)}}t.log({l:"Default Theme",theme:s})})}get preferredColorScheme(){if(window.matchMedia("(prefers-color-scheme: dark)").matches)return je.Dark;if(window.matchMedia("(prefers-color-scheme: light)").matches)return je.Light}}function Rn(n){return new Promise(function(e,t){var s=document.createElement("script");s.setAttribute("src",n),s.onload=e,s.onerror=t,document.body.appendChild(s)})}async function z_(n){return window.msCrypto&&!window.crypto&&(window.crypto=window.msCrypto),n?(window.WebAssembly?(await Rn(n.wasmBundle),await window.Olm.init({locateFile:()=>n.wasm})):(await Rn(n.legacyBundle),await window.Olm.init()),window.Olm):null}function G_(n){return n.startsWith("/")?n:new URL(n,document.location.href).pathname}async function J_(n){const e=new d_(n.worker,4);return await e.init(),await e.sendAll({type:"load_olm",path:G_(n.olm.legacyBundle)}),new km(e)}function Q_(n){if(!window.visualViewport)return;const e=()=>{const t=n.querySelector(".SessionView");if(!t)return;const s=n.querySelector(".bottom-aligned-scroll");let i,r,o;s&&(i=s.scrollTop,r=s.offsetHeight);const a=t.offsetTop+t.offsetHeight-window.visualViewport.height;n.style.setProperty("--ios-viewport-height",window.visualViewport.height.toString()+"px"),n.style.setProperty("--ios-viewport-top",a.toString()+"px"),s&&(o=s.offsetHeight,s.scrollTop=i+r-o)};return window.visualViewport.addEventListener("resize",e),()=>{window.visualViewport.removeEventListener("resize",e)}}class Y_{constructor({container:e,assetPaths:t,config:s,configURL:i,options:r=null,cryptoExtras:o=null}){this._container=e,this._assetPaths=t,this._config=s,this._configURL=i,this.settingsStorage=new pm("hydrogen_setting_v1_"),this.clock=new Jp,this.encoding=new Em,this.random=Math.random,this._createLogger(r==null?void 0:r.development),this.history=new Xp,this.onlineStatus=new Zp,this._serviceWorkerHandler=null,t.serviceWorker&&"serviceWorker"in navigator&&(this._serviceWorkerHandler=new Qp,this._serviceWorkerHandler.registerAndStart(t.serviceWorker)),this.notificationService=void 0,this._assetPaths.olm&&(this.crypto=new a_(o)),this.storageFactory=new nl(this._serviceWorkerHandler),this.sessionInfoStorage=new mm("hydrogen_sessions_v1"),this.estimateStorageUsage=c_,typeof fetch=="function"?this.request=um(this.clock.createTimeout,this._serviceWorkerHandler):this.request=Co;const a=!!window.MSInputMethodContext&&!!document.documentMode;this.isIE11=a;const c=/iPad|iPhone|iPod/.test(navigator.platform)||navigator.platform==="MacIntel"&&navigator.maxTouchPoints>1&&!window.MSStream;this.isIOS=c,this._disposables=new Ni,this._olmPromise=void 0,this._workerPromise=void 0,this._themeLoader=new H_(this)}async init(){try{await this.logger.run("Platform init",async e=>{var t;if(!this._config){if(!this._configURL)throw new Error("Neither config nor configURL was provided!");const{status:s,body:i}=await this.request(this._configURL,{method:"GET",format:"json",cache:!0}).response();if(s===404)throw new Error(`Could not find ${this._configURL}. Did you copy over config.sample.json?`);if(s>=400)throw new Error(`Got status ${s} while trying to fetch ${this._configURL}`);this._config=i}if(this.notificationService=new Yp(this._serviceWorkerHandler,this._config.push),this._themeLoader){const s=this.config.themeManifests;await((t=this._themeLoader)==null?void 0:t.init(s,e));const{themeName:i,themeVariant:r}=await this._themeLoader.getActiveTheme();e.log({l:"Active theme",name:i,variant:r}),this._themeLoader.setTheme(i,r,e)}})}catch(e){throw this._container.innerText=e.message,e}}_createLogger(e){const t=s=>{var i;return(i=s.e)!=null&&i.stack&&(s.e.stack=s.e.stack.replace(/\/\?loginToken=(.+)/,"?loginToken=")),s};e?this.logger=new td({platform:this}):this.logger=new Rm({name:"hydrogen_logs",platform:this,serializedTransformer:t})}get updateService(){return this._serviceWorkerHandler}loadOlm(){return this._olmPromise||(this._olmPromise=z_(this._assetPaths.olm)),this._olmPromise}get config(){return this._config}async loadOlmWorker(){if(!window.WebAssembly)return this._workerPromise||(this._workerPromise=J_(this._assetPaths)),this._workerPromise}createAndMountRootView(e){if(this.isIE11&&(this._container.className+=" legacy"),this.isIOS){this._container.className+=" ios";const s=Q_(this._container);s&&this._disposables.track(s)}this._container.addEventListener("error",hn,!0),this._disposables.track(()=>this._container.removeEventListener("error",hn,!0)),window.__hydrogenViewModel=e;const t=new Wp(e);this._container.appendChild(t.mount())}setNavigation(e){var t;(t=this._serviceWorkerHandler)==null||t.setNavigation(e)}createBlob(e,t){return lt.fromBuffer(e,t)}saveFileAs(e,t){navigator.msSaveBlob?navigator.msSaveBlob(e.nativeBlob,t):p_(this._container,this._assetPaths.downloadSandbox,e,t,this.isIOS)}openFile(e=null){const t=document.createElement("input");t.setAttribute("type","file"),t.className="hidden",e&&t.setAttribute("accept",e);const s=new Promise(i=>{const r=()=>{t.removeEventListener("change",r,!0);const o=t.files[0];this._container.removeChild(t),o?i({name:o.name,blob:lt.fromBlob(o)}):i()};t.addEventListener("change",r,!0)});return this._container.appendChild(t),t.click(),s}openUrl(e){location.href=e}parseHTML(e){return F_(e)}async loadImage(e){return Zt.fromBlob(e)}async loadVideo(e){return Gi.fromBlob(e)}hasReadPixelPermission(){return u_()}get devicePixelRatio(){return window.devicePixelRatio||1}get version(){return"0.3.1"}get themeLoader(){return this._themeLoader}replaceStylesheet(e){const t=document.querySelector("head");document.querySelectorAll(".theme").forEach(i=>i.remove());const s=document.createElement("link");s.href=e,s.rel="stylesheet",s.type="text/css",s.className="theme",t.appendChild(s)}get description(){var e;return(e=navigator.userAgent)!=null?e:""}dispose(){this._disposables.dispose()}}var X_="./config.json",Z_="./assets/download-sandbox.48a866e9.html",ef="./assets/main.bdb9a925.js",tf="./assets/olm.b3e0f9b4.wasm",sf="./assets/olm.92f1ccd0.js",rf="./assets/olm_legacy.9dc48f49.js",Jo={downloadSandbox:Z_,worker:ef,olm:{wasm:tf,legacyBundle:rf,wasmBundle:sf}};Jo.serviceWorker="sw.js";const nf=new Y_({container:document.body,assetPaths:Jo,configURL:X_,options:{development:!1}});am(nf); +//# sourceMappingURL=index.ca5690cf.js.map diff --git a/assets/index.ca5690cf.js.map b/assets/index.ca5690cf.js.map new file mode 100644 index 00000000..8718e8b6 --- /dev/null +++ b/assets/index.ca5690cf.js.map @@ -0,0 +1 @@ +{"version":3,"file":"index.ca5690cf.js","sources":["../../src/utils/enum.ts","../../src/matrix/well-known.js","../../src/utils/error.ts","../../src/observable/BaseObservable.ts","../../src/observable/ObservableValue.ts","../../src/utils/AbortableOperation.ts","../../src/platform/web/dom/BlobHandle.js","../../src/matrix/net/common.ts","../../src/matrix/error.js","../../src/matrix/net/HomeServerRequest.ts","../../src/matrix/net/HomeServerApi.ts","../../src/matrix/net/ExponentialRetryDelay.ts","../../src/matrix/net/Reconnector.ts","../../src/matrix/e2ee/attachment.js","../../src/matrix/net/MediaRepository.ts","../../src/matrix/net/RequestScheduler.ts","../../src/matrix/Sync.js","../../src/utils/EventEmitter.ts","../../node_modules/another-json/another-json.js","../../src/matrix/e2ee/common.js","../../src/matrix/room/RoomSummary.js","../../src/matrix/storage/common.ts","../../src/matrix/room/timeline/EventKey.ts","../../src/matrix/room/timeline/entries/BaseEntry.ts","../../src/matrix/room/common.ts","../../src/matrix/room/timeline/relations.js","../../src/matrix/room/timeline/PendingAnnotation.js","../../src/matrix/room/timeline/entries/reply.js","../../src/matrix/room/timeline/entries/BaseEventEntry.js","../../src/matrix/room/timeline/entries/PendingEventEntry.js","../../src/matrix/room/sending/PendingEvent.js","../../src/matrix/room/timeline/entries/EventEntry.js","../../src/matrix/room/timeline/persistence/common.js","../../src/matrix/room/members/RoomMember.js","../../src/matrix/room/timeline/common.js","../../src/matrix/room/timeline/FragmentIdComparer.js","../../vite/preload-helper","../../src/matrix/storage/idb/error.ts","../../src/matrix/storage/idb/utils.ts","../../src/matrix/storage/idb/QueryTarget.ts","../../src/matrix/storage/idb/Store.ts","../../src/utils/typedJSON.ts","../../src/matrix/storage/idb/stores/SessionStore.ts","../../src/matrix/storage/idb/stores/RoomSummaryStore.ts","../../src/matrix/storage/idb/stores/InviteStore.ts","../../src/logging/LogFilter.ts","../../src/logging/NullLogger.ts","../../src/matrix/storage/idb/stores/TimelineEventStore.ts","../../src/matrix/storage/idb/stores/common.ts","../../src/matrix/storage/idb/stores/TimelineRelationStore.ts","../../src/matrix/storage/idb/stores/RoomStateStore.ts","../../src/matrix/storage/idb/stores/RoomMemberStore.ts","../../src/matrix/storage/idb/stores/TimelineFragmentStore.ts","../../src/matrix/storage/idb/stores/PendingEventStore.ts","../../src/matrix/storage/idb/stores/UserIdentityStore.ts","../../src/matrix/storage/idb/stores/DeviceIdentityStore.ts","../../src/matrix/storage/idb/stores/OlmSessionStore.ts","../../src/matrix/storage/idb/stores/InboundGroupSessionStore.ts","../../src/matrix/storage/idb/stores/OutboundGroupSessionStore.ts","../../src/matrix/storage/idb/stores/GroupSessionDecryptionStore.ts","../../src/matrix/storage/idb/stores/OperationStore.ts","../../src/matrix/storage/idb/stores/AccountDataStore.ts","../../src/matrix/storage/idb/Transaction.ts","../../src/matrix/storage/idb/Storage.ts","../../src/matrix/storage/idb/export.ts","../../src/matrix/storage/idb/schema.ts","../../src/matrix/storage/idb/quirks.ts","../../src/matrix/storage/idb/StorageFactory.ts","../../src/matrix/room/timeline/persistence/RelationWriter.js","../../src/matrix/room/timeline/Direction.ts","../../src/matrix/room/timeline/entries/FragmentBoundaryEntry.js","../../src/matrix/room/timeline/persistence/SyncWriter.js","../../src/utils/LRUCache.ts","../../src/matrix/room/timeline/persistence/MemberWriter.js","../../src/matrix/room/timeline/persistence/GapWriter.js","../../src/observable/list/BaseObservableList.ts","../../src/utils/sortedIndex.ts","../../src/observable/map/BaseObservableMap.ts","../../src/observable/map/ObservableMap.ts","../../src/observable/list/SortedMapList.js","../../src/observable/map/FilteredMap.js","../../src/observable/map/MappedMap.js","../../src/observable/map/JoinedMap.js","../../src/observable/list/ObservableArray.ts","../../src/observable/list/common.ts","../../src/observable/list/SortedArray.ts","../../src/observable/list/BaseMappedList.ts","../../src/observable/list/AsyncMappedList.ts","../../src/observable/list/ConcatList.ts","../../src/observable/index.js","../../src/utils/Disposables.ts","../../src/matrix/room/timeline/persistence/TimelineReader.js","../../src/matrix/room/timeline/entries/NonPersistedEventEntry.js","../../src/matrix/User.js","../../src/matrix/room/timeline/Timeline.js","../../src/matrix/room/members/load.js","../../src/utils/RetainedValue.ts","../../src/matrix/room/members/MemberList.js","../../src/matrix/room/members/Heroes.js","../../src/matrix/room/ObservedEventMap.js","../../src/logging/utils.ts","../../src/matrix/room/PowerLevels.js","../../src/matrix/room/BaseRoom.js","../../src/matrix/common.js","../../src/matrix/room/sending/SendQueue.js","../../src/matrix/room/AttachmentUpload.js","../../src/matrix/room/Room.js","../../src/matrix/room/ArchivedRoom.js","../../src/matrix/profile.ts","../../src/matrix/room/RoomBeingCreated.ts","../../src/matrix/room/Invite.js","../../src/matrix/push/Pusher.ts","../../src/utils/groupBy.ts","../../src/matrix/DeviceMessageHandler.js","../../src/matrix/e2ee/Account.js","../../src/matrix/ssss/common.ts","../../src/matrix/ssss/passphrase.ts","../../src/matrix/ssss/recoveryKey.ts","../../src/matrix/ssss/index.ts","../../src/matrix/e2ee/Dehydration.js","../../src/utils/Lock.ts","../../src/matrix/e2ee/olm/Session.ts","../../src/matrix/e2ee/DecryptionResult.ts","../../src/matrix/e2ee/olm/types.ts","../../src/matrix/e2ee/olm/Decryption.ts","../../src/matrix/e2ee/olm/Encryption.ts","../../src/matrix/e2ee/megolm/decryption/DecryptionChanges.js","../../src/utils/mergeMap.ts","../../src/matrix/e2ee/megolm/decryption/DecryptionPreparation.js","../../src/matrix/e2ee/megolm/decryption/ReplayDetectionEntry.ts","../../src/matrix/e2ee/megolm/decryption/SessionDecryption.ts","../../src/matrix/e2ee/megolm/decryption/utils.ts","../../src/matrix/e2ee/megolm/decryption/RoomKey.ts","../../src/matrix/e2ee/megolm/Decryption.ts","../../src/matrix/e2ee/megolm/decryption/KeyLoader.ts","../../src/matrix/e2ee/megolm/keybackup/Curve25519.ts","../../src/matrix/e2ee/megolm/keybackup/KeyBackup.ts","../../src/matrix/e2ee/megolm/Encryption.js","../../src/logging/LogItem.ts","../../src/logging/BaseLogger.ts","../../src/logging/ConsoleLogger.ts","../../src/matrix/e2ee/RoomEncryption.js","../../src/matrix/e2ee/DeviceTracker.js","../../src/utils/LockMap.ts","../../src/matrix/ssss/SecretStorage.ts","../../src/matrix/Session.js","../../src/matrix/login/PasswordLoginMethod.ts","../../src/matrix/login/TokenLoginMethod.ts","../../src/matrix/login/SSOLoginHelper.ts","../../src/matrix/registration/stages/BaseRegistrationStage.ts","../../src/matrix/registration/stages/DummyAuth.ts","../../src/matrix/registration/stages/TermsAuth.ts","../../src/matrix/registration/stages/TokenAuth.ts","../../src/matrix/registration/Registration.ts","../../src/matrix/Client.js","../../src/domain/ViewModel.ts","../../src/domain/avatar.ts","../../src/domain/session/leftpanel/BaseTileViewModel.js","../../src/domain/session/leftpanel/RoomTileViewModel.js","../../src/domain/session/leftpanel/common.js","../../src/domain/session/leftpanel/InviteTileViewModel.js","../../src/domain/session/leftpanel/RoomBeingCreatedTileViewModel.js","../../src/domain/session/leftpanel/RoomFilter.js","../../src/observable/map/ApplyMap.js","../../src/domain/navigation/Navigation.ts","../../src/domain/navigation/URLRouter.ts","../../src/domain/navigation/index.ts","../../src/domain/session/leftpanel/LeftPanelViewModel.js","../../src/domain/session/room/timeline/UpdateAction.js","../../src/domain/session/room/timeline/TilesCollection.js","../../src/domain/session/room/timeline/TimelineViewModel.js","../../src/domain/session/room/ComposerViewModel.js","../../src/domain/session/common.js","../../src/domain/session/room/timeline/tiles/SimpleTile.js","../../src/domain/session/room/timeline/tiles/GapTile.js","../../src/domain/session/room/timeline/ReactionsViewModel.js","../../src/domain/session/room/timeline/tiles/BaseMessageTile.js","../../src/domain/session/room/timeline/linkify/regex.js","../../src/domain/session/room/timeline/linkify/linkify.js","../../src/domain/session/room/timeline/MessageBody.js","../../src/domain/session/room/timeline/tiles/BaseTextTile.js","../../src/domain/session/room/timeline/deserialize.js","../../src/domain/session/room/timeline/tiles/TextTile.js","../../src/domain/session/room/timeline/tiles/RedactedTile.js","../../src/domain/session/room/timeline/tiles/BaseMediaTile.js","../../src/domain/session/room/timeline/tiles/ImageTile.js","../../src/domain/session/room/timeline/tiles/VideoTile.js","../../src/utils/formatSize.ts","../../src/domain/session/room/timeline/tiles/FileTile.js","../../src/domain/session/room/timeline/tiles/LocationTile.js","../../src/domain/session/room/timeline/tiles/RoomNameTile.js","../../src/domain/session/room/timeline/tiles/RoomMemberTile.js","../../src/domain/session/room/timeline/tiles/EncryptedEventTile.js","../../src/domain/session/room/timeline/tiles/EncryptionEnabledTile.js","../../src/domain/session/room/timeline/tiles/MissingAttachmentTile.js","../../src/domain/session/room/timeline/tiles/index.ts","../../src/domain/session/room/RoomViewModel.js","../../src/domain/session/room/UnknownRoomViewModel.js","../../src/domain/session/room/InviteViewModel.js","../../src/domain/session/room/RoomBeingCreatedViewModel.js","../../src/domain/session/room/LightboxViewModel.js","../../src/domain/session/SessionStatusViewModel.js","../../src/domain/session/RoomGridViewModel.js","../../src/domain/session/settings/KeyBackupViewModel.js","../../src/domain/rageshake.ts","../../src/domain/session/settings/SettingsViewModel.js","../../src/domain/session/CreateRoomViewModel.js","../../src/domain/session/RoomViewModelObservable.js","../../src/domain/session/rightpanel/RoomDetailsViewModel.js","../../src/domain/session/rightpanel/MemberTileViewModel.js","../../src/domain/session/rightpanel/members/comparator.js","../../src/domain/session/rightpanel/members/disambiguator.js","../../src/domain/session/rightpanel/MemberListViewModel.js","../../src/domain/session/rightpanel/MemberDetailsViewModel.js","../../src/domain/session/rightpanel/RightPanelViewModel.js","../../src/domain/session/SessionViewModel.js","../../src/domain/AccountSetupViewModel.js","../../src/domain/SessionLoadViewModel.js","../../src/domain/login/PasswordLoginViewModel.js","../../src/domain/login/StartSSOLoginViewModel.js","../../src/domain/login/CompleteSSOLoginViewModel.js","../../src/domain/login/LoginViewModel.ts","../../src/domain/LogoutViewModel.ts","../../src/domain/SessionPickerViewModel.js","../../src/domain/RootViewModel.js","../../src/platform/web/main.js","../../src/utils/timeout.ts","../../src/platform/web/dom/request/common.js","../../src/platform/web/dom/request/xhr.js","../../src/platform/web/dom/request/fetch.js","../../src/matrix/sessioninfo/localstorage/SessionInfoStorage.ts","../../src/platform/web/dom/SettingsStorage.js","../../src/platform/web/dom/UTF8.js","../../node_modules/base64-arraybuffer/lib/base64-arraybuffer.js","../../src/platform/web/utils/Base64.js","../../scripts/package-overrides/buffer/index.js","../../node_modules/base-x/src/index.js","../../node_modules/bs58/index.js","../../src/platform/web/utils/Base58.js","../../src/platform/web/utils/Encoding.js","../../src/matrix/e2ee/OlmWorker.js","../../src/logging/IDBLogger.ts","../../src/platform/web/ui/general/html.ts","../../src/platform/web/ui/general/utils.ts","../../src/platform/web/ui/general/ListView.ts","../../src/platform/web/ui/general/BaseUpdateView.ts","../../src/platform/web/ui/general/TemplateView.ts","../../src/platform/web/ui/avatar.js","../../src/platform/web/ui/AvatarView.js","../../src/platform/web/ui/common.js","../../src/platform/web/ui/session/leftpanel/RoomTileView.js","../../src/platform/web/ui/session/leftpanel/LeftPanelView.js","../../src/platform/web/ui/general/Popup.js","../../src/platform/web/ui/general/Menu.js","../../src/platform/web/ui/session/room/TimelineView.ts","../../src/platform/web/ui/session/room/TimelineLoadingView.js","../../src/platform/web/ui/session/room/MessageComposer.js","../../src/platform/web/ui/session/room/DisabledComposerView.js","../../src/platform/web/ui/session/room/RoomView.js","../../src/platform/web/ui/session/room/UnknownRoomView.js","../../src/platform/web/ui/general/StaticView.js","../../src/platform/web/ui/general/LoadingView.js","../../src/platform/web/ui/session/room/RoomBeingCreatedView.js","../../src/platform/web/ui/session/room/InviteView.js","../../src/platform/web/ui/session/room/LightboxView.js","../../src/platform/web/ui/session/SessionStatusView.js","../../src/platform/web/ui/session/RoomGridView.js","../../src/platform/web/ui/session/settings/KeyBackupSettingsView.js","../../src/platform/web/ui/session/settings/SettingsView.js","../../src/platform/web/ui/session/CreateRoomView.js","../../src/platform/web/ui/session/rightpanel/RoomDetailsView.js","../../src/platform/web/ui/general/Range.ts","../../src/platform/web/ui/general/ListRange.ts","../../src/platform/web/ui/general/LazyListView.ts","../../src/platform/web/ui/session/rightpanel/MemberTileView.js","../../src/platform/web/ui/session/rightpanel/MemberListView.js","../../src/platform/web/ui/session/rightpanel/MemberDetailsView.js","../../src/platform/web/ui/session/rightpanel/RightPanelView.js","../../src/platform/web/ui/session/room/timeline/ReactionsView.js","../../src/platform/web/ui/session/room/timeline/BaseMessageView.js","../../src/platform/web/ui/session/room/timeline/ReplyPreviewView.js","../../src/platform/web/ui/session/room/timeline/TextMessageView.js","../../src/platform/web/ui/session/room/timeline/BaseMediaView.js","../../src/platform/web/ui/session/room/timeline/ImageView.js","../../src/platform/web/dom/utils.js","../../src/platform/web/ui/session/room/timeline/VideoView.js","../../src/platform/web/ui/session/room/timeline/FileView.js","../../src/platform/web/ui/session/room/timeline/LocationView.js","../../src/platform/web/ui/session/room/timeline/MissingAttachmentView.js","../../src/platform/web/ui/session/room/timeline/AnnouncementView.js","../../src/platform/web/ui/session/room/timeline/RedactedView.js","../../src/platform/web/ui/session/room/timeline/GapView.js","../../src/platform/web/ui/session/room/common.ts","../../src/platform/web/ui/session/SessionView.js","../../src/platform/web/ui/login/common.js","../../src/platform/web/ui/login/PasswordLoginView.js","../../src/platform/web/ui/login/AccountSetupView.js","../../src/platform/web/ui/login/SessionLoadStatusView.js","../../src/platform/web/ui/login/CompleteSSOView.js","../../src/platform/web/ui/login/LoginView.js","../../src/platform/web/ui/LogoutView.js","../../src/platform/web/ui/login/SessionLoadView.js","../../src/platform/web/ui/login/SessionPickerView.js","../../src/platform/web/ui/RootView.js","../../src/platform/web/dom/Clock.js","../../src/platform/web/dom/ServiceWorkerHandler.js","../../src/platform/web/dom/NotificationService.js","../../src/platform/web/dom/History.js","../../src/platform/web/dom/OnlineStatus.js","../../src/platform/web/dom/Crypto.js","../../src/platform/web/dom/StorageEstimate.js","../../src/platform/web/dom/WorkerPool.js","../../src/platform/web/dom/ImageHandle.js","../../src/platform/web/dom/download.js","../../node_modules/dompurify/dist/purify.es.js","../../src/platform/web/parsehtml.js","../../src/platform/web/theming/parsers/types.ts","../../src/platform/web/theming/shared/svg-colorizer.mjs","../../src/platform/web/theming/IconColorizer.ts","../../node_modules/off-color/cjs/index.min.js","../../node_modules/off-color/index.js","../../src/platform/web/theming/shared/color.mjs","../../src/platform/web/theming/DerivedVariables.ts","../../src/platform/web/theming/parsers/RuntimeThemeParser.ts","../../src/platform/web/theming/parsers/BuiltThemeParser.ts","../../src/platform/web/theming/ThemeLoader.ts","../../src/platform/web/Platform.js","../../src/platform/web/assets/config.json?url","../../src/platform/web/assets/download-sandbox.html?url","../../src/platform/web/worker/main.js?url","../../node_modules/@matrix-org/olm/olm.wasm?url","../../node_modules/@matrix-org/olm/olm.js?url","../../node_modules/@matrix-org/olm/olm_legacy.js?url","../../src/platform/web/sdk/paths/vite.js","../../src/platform/web/index.html?html-proxy&index=0.js"],"sourcesContent":["/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function createEnum(...values: string[]): Readonly<{}> {\n const obj = {};\n for (const value of values) {\n obj[value] = value;\n }\n return Object.freeze(obj);\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction normalizeHomeserver(homeserver) {\n try {\n return new URL(homeserver).origin;\n } catch (err) {\n return new URL(`https://${homeserver}`).origin;\n }\n}\n\nasync function getWellKnownResponse(homeserver, request) {\n const requestOptions = {format: \"json\", timeout: 30000, method: \"GET\"};\n try {\n const wellKnownUrl = `${homeserver}/.well-known/matrix/client`;\n return await request(wellKnownUrl, requestOptions).response();\n } catch (err) {\n if (err.name === \"ConnectionError\") {\n // don't fail lookup on a ConnectionError,\n // there might be a missing CORS header on a 404 response or something,\n // which won't be a problem necessarily with homeserver requests later on ...\n return null;\n } else {\n throw err;\n }\n }\n}\n\nexport async function lookupHomeserver(homeserver, request) {\n homeserver = normalizeHomeserver(homeserver);\n const wellKnownResponse = await getWellKnownResponse(homeserver, request);\n if (wellKnownResponse && wellKnownResponse.status === 200) {\n const {body} = wellKnownResponse;\n const wellKnownHomeserver = body[\"m.homeserver\"]?.[\"base_url\"];\n if (typeof wellKnownHomeserver === \"string\") {\n homeserver = normalizeHomeserver(wellKnownHomeserver);\n }\n }\n return homeserver;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class AbortError extends Error {\n get name(): string {\n return \"AbortError\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// we return undefined so you can reassign any member\n// that uses `member?: T` syntax in one statement.\nexport type SubscriptionHandle = () => undefined;\n\nexport abstract class BaseObservable {\n protected _handlers: Set = new Set();\n\n onSubscribeFirst(): void {\n\n }\n\n onUnsubscribeLast(): void {\n\n }\n\n subscribe(handler: T): SubscriptionHandle {\n this._handlers.add(handler);\n if (this._handlers.size === 1) {\n this.onSubscribeFirst();\n }\n return () => {\n return this.unsubscribe(handler);\n };\n }\n\n unsubscribe(handler?: T): undefined {\n if (handler) {\n this._handlers.delete(handler);\n if (this._handlers.size === 0) {\n this.onUnsubscribeLast();\n }\n }\n return undefined;\n }\n\n unsubscribeAll(): void {\n if (this._handlers.size !== 0) {\n this._handlers.clear();\n this.onUnsubscribeLast();\n }\n }\n\n get hasSubscriptions(): boolean {\n return this._handlers.size !== 0;\n }\n\n // Add iterator over handlers here\n}\n\nexport function tests() {\n class Collection extends BaseObservable<{}> {\n firstSubscribeCalls: number = 0;\n firstUnsubscribeCalls: number = 0;\n\n onSubscribeFirst() { this.firstSubscribeCalls += 1; }\n onUnsubscribeLast() { this.firstUnsubscribeCalls += 1; }\n }\n\n return {\n test_unsubscribe(assert) {\n const c = new Collection();\n const unsubscribe = c.subscribe({});\n unsubscribe();\n assert.equal(c.firstSubscribeCalls, 1);\n assert.equal(c.firstUnsubscribeCalls, 1);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AbortError} from \"../utils/error\";\nimport {BaseObservable} from \"./BaseObservable\";\nimport type {SubscriptionHandle} from \"./BaseObservable\";\n\n// like an EventEmitter, but doesn't have an event type\nexport abstract class BaseObservableValue extends BaseObservable<(value: T) => void> {\n emit(argument: T) {\n for (const h of this._handlers) {\n h(argument);\n }\n }\n\n abstract get(): T;\n\n waitFor(predicate: (value: T) => boolean): IWaitHandle {\n if (predicate(this.get())) {\n return new ResolvedWaitForHandle(Promise.resolve(this.get()));\n } else {\n return new WaitForHandle(this, predicate);\n }\n }\n\n flatMap(mapper: (value: T) => (BaseObservableValue | undefined)): BaseObservableValue {\n return new FlatMapObservableValue(this, mapper);\n }\n}\n\ninterface IWaitHandle {\n promise: Promise;\n dispose(): void;\n}\n\nclass WaitForHandle implements IWaitHandle {\n private _promise: Promise\n private _reject: ((reason?: any) => void) | null;\n private _subscription: (() => void) | null;\n\n constructor(observable: BaseObservableValue, predicate: (value: T) => boolean) {\n this._promise = new Promise((resolve, reject) => {\n this._reject = reject;\n this._subscription = observable.subscribe(v => {\n if (predicate(v)) {\n this._reject = null;\n resolve(v);\n this.dispose();\n }\n });\n });\n }\n\n get promise(): Promise {\n return this._promise;\n }\n\n dispose() {\n if (this._subscription) {\n this._subscription();\n this._subscription = null;\n }\n if (this._reject) {\n this._reject(new AbortError());\n this._reject = null;\n }\n }\n}\n\nclass ResolvedWaitForHandle implements IWaitHandle {\n constructor(public promise: Promise) {}\n dispose() {}\n}\n\nexport class ObservableValue extends BaseObservableValue {\n private _value: T;\n\n constructor(initialValue: T) {\n super();\n this._value = initialValue;\n }\n\n get(): T {\n return this._value;\n }\n\n set(value: T): void {\n if (value !== this._value) {\n this._value = value;\n this.emit(this._value);\n }\n }\n}\n\nexport class RetainedObservableValue extends ObservableValue {\n private _freeCallback: () => void;\n\n constructor(initialValue: T, freeCallback: () => void) {\n super(initialValue);\n this._freeCallback = freeCallback;\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n this._freeCallback();\n }\n}\n\nexport class FlatMapObservableValue extends BaseObservableValue {\n private sourceSubscription?: SubscriptionHandle;\n private targetSubscription?: SubscriptionHandle;\n\n constructor(\n private readonly source: BaseObservableValue

,\n private readonly mapper: (value: P) => (BaseObservableValue | undefined)\n ) {\n super();\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n this.sourceSubscription = this.sourceSubscription!();\n if (this.targetSubscription) {\n this.targetSubscription = this.targetSubscription();\n }\n }\n\n onSubscribeFirst() {\n super.onSubscribeFirst();\n this.sourceSubscription = this.source.subscribe(() => {\n this.updateTargetSubscription();\n this.emit(this.get());\n });\n this.updateTargetSubscription();\n }\n\n private updateTargetSubscription() {\n const sourceValue = this.source.get();\n if (sourceValue) {\n const target = this.mapper(sourceValue);\n if (target) {\n if (!this.targetSubscription) {\n this.targetSubscription = target.subscribe(() => this.emit(this.get()));\n }\n return;\n }\n }\n // if no sourceValue or target\n if (this.targetSubscription) {\n this.targetSubscription = this.targetSubscription();\n }\n }\n\n get(): C | undefined {\n const sourceValue = this.source.get();\n if (!sourceValue) {\n return undefined;\n }\n const mapped = this.mapper(sourceValue);\n return mapped?.get();\n }\n}\n\nexport function tests() {\n return {\n \"set emits an update\": assert => {\n const a = new ObservableValue(0);\n let fired = false;\n const subscription = a.subscribe(v => {\n fired = true;\n assert.strictEqual(v, 5);\n });\n a.set(5);\n assert(fired);\n subscription();\n },\n \"set doesn't emit if value hasn't changed\": assert => {\n const a = new ObservableValue(5);\n let fired = false;\n const subscription = a.subscribe(() => {\n fired = true;\n });\n a.set(5);\n a.set(5);\n assert(!fired);\n subscription();\n },\n \"waitFor promise resolves on matching update\": async assert => {\n const a = new ObservableValue(5);\n const handle = a.waitFor(v => v === 6);\n Promise.resolve().then(() => {\n a.set(6);\n });\n await handle.promise;\n assert.strictEqual(a.get(), 6);\n },\n \"waitFor promise rejects when disposed\": async assert => {\n const a = new ObservableValue(0);\n const handle = a.waitFor(() => false);\n Promise.resolve().then(() => {\n handle.dispose();\n });\n await assert.rejects(handle.promise, AbortError);\n },\n \"flatMap.get\": assert => {\n const a = new ObservableValue}>(undefined);\n const countProxy = a.flatMap(a => a!.count);\n assert.strictEqual(countProxy.get(), undefined);\n const count = new ObservableValue(0);\n a.set({count});\n assert.strictEqual(countProxy.get(), 0);\n },\n \"flatMap update from source\": assert => {\n const a = new ObservableValue}>(undefined);\n const updates: (number | undefined)[] = [];\n a.flatMap(a => a!.count).subscribe(count => {\n updates.push(count);\n });\n const count = new ObservableValue(0);\n a.set({count});\n assert.deepEqual(updates, [0]);\n },\n \"flatMap update from target\": assert => {\n const a = new ObservableValue}>(undefined);\n const updates: (number | undefined)[] = [];\n a.flatMap(a => a!.count).subscribe(count => {\n updates.push(count);\n });\n const count = new ObservableValue(0);\n a.set({count});\n count.set(5);\n assert.deepEqual(updates, [0, 5]);\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableValue, ObservableValue} from \"../observable/ObservableValue\";\n\nexport interface IAbortable {\n abort();\n}\n\nexport type SetAbortableFn = (a: IAbortable) => typeof a;\nexport type SetProgressFn

= (progress: P) => void;\ntype RunFn = (setAbortable: SetAbortableFn, setProgress: SetProgressFn

) => T;\n\nexport class AbortableOperation implements IAbortable {\n public readonly result: T;\n private _abortable?: IAbortable;\n private _progress: ObservableValue

;\n\n constructor(run: RunFn) {\n this._abortable = undefined;\n const setAbortable: SetAbortableFn = abortable => {\n this._abortable = abortable;\n return abortable;\n };\n this._progress = new ObservableValue

(undefined);\n const setProgress: SetProgressFn

= (progress: P) => {\n this._progress.set(progress);\n };\n this.result = run(setAbortable, setProgress);\n }\n\n get progress(): BaseObservableValue

{\n return this._progress;\n }\n\n abort() {\n this._abortable?.abort();\n this._abortable = undefined;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n\n// WARNING: We have to be very careful about what mime-types we allow into blobs.\n//\n// This means that the content is rendered using the origin of the script which\n// called createObjectURL(), and so if the content contains any scripting then it\n// will pose a XSS vulnerability when the browser renders it. This is particularly\n// bad if the user right-clicks the URI and pastes it into a new window or tab,\n// as the blob will then execute with access to Element's full JS environment(!)\n//\n// See https://github.com/matrix-org/matrix-react-sdk/pull/1820#issuecomment-385210647\n// for details.\n//\n// We mitigate this by only allowing mime-types into blobs which we know don't\n// contain any scripting, and instantiate all others as application/octet-stream\n// regardless of what mime-type the event claimed. Even if the payload itself\n// is some malicious HTML, the fact we instantiate it with a media mimetype or\n// application/octet-stream means the browser doesn't try to render it as such.\n//\n// One interesting edge case is image/svg+xml, which empirically *is* rendered\n// correctly if the blob is set to the src attribute of an img tag (for thumbnails)\n// *even if the mimetype is application/octet-stream*. However, empirically JS\n// in the SVG isn't executed in this scenario, so we seem to be okay.\n//\n// Tested on Chrome 65 and Firefox 60\n//\n// The list below is taken mainly from\n// https://developer.mozilla.org/en-US/docs/Web/HTML/Supported_media_formats\n// N.B. Matrix doesn't currently specify which mimetypes are valid in given\n// events, so we pick the ones which HTML5 browsers should be able to display\n//\n// For the record, mime-types which must NEVER enter this list below include:\n// text/html, text/xhtml, image/svg, image/svg+xml, image/pdf, and similar.\n\nconst ALLOWED_BLOB_MIMETYPES = {\n 'image/jpeg': true,\n 'image/gif': true,\n 'image/png': true,\n\n 'video/mp4': true,\n 'video/webm': true,\n 'video/ogg': true,\n 'video/quicktime': true,\n 'video/VP8': true,\n\n 'audio/mp4': true,\n 'audio/webm': true,\n 'audio/aac': true,\n 'audio/mpeg': true,\n 'audio/ogg': true,\n 'audio/wave': true,\n 'audio/wav': true,\n 'audio/x-wav': true,\n 'audio/x-pn-wav': true,\n 'audio/flac': true,\n 'audio/x-flac': true,\n};\n\nconst DEFAULT_MIMETYPE = 'application/octet-stream';\n\nexport class BlobHandle {\n constructor(blob, buffer = null) {\n this._blob = blob;\n this._buffer = buffer;\n this._url = null;\n }\n\n static fromBuffer(buffer, mimetype) {\n mimetype = mimetype ? mimetype.split(\";\")[0].trim() : '';\n if (!ALLOWED_BLOB_MIMETYPES[mimetype]) {\n mimetype = DEFAULT_MIMETYPE;\n }\n return new BlobHandle(new Blob([buffer], {type: mimetype}), buffer);\n }\n\n static fromBlob(blob) {\n // ok to not filter mimetypes as these are local files\n return new BlobHandle(blob);\n }\n\n get nativeBlob() {\n return this._blob;\n }\n\n async readAsBuffer() {\n if (this._buffer) {\n return this._buffer;\n } else {\n const reader = new FileReader();\n const promise = new Promise((resolve, reject) => {\n reader.addEventListener(\"load\", evt => resolve(evt.target.result)); \n reader.addEventListener(\"error\", evt => reject(evt.target.error)); \n });\n reader.readAsArrayBuffer(this._blob);\n return promise;\n }\n }\n\n get url() {\n if (!this._url) {\n this._url = URL.createObjectURL(this._blob);\n }\n return this._url;\n }\n\n get size() {\n return this._blob.size;\n }\n\n get mimeType() {\n return this._blob.type || DEFAULT_MIMETYPE;\n }\n\n dispose() {\n if (this._url) {\n URL.revokeObjectURL(this._url);\n this._url = null;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BlobHandle} from \"../../platform/web/dom/BlobHandle.js\";\n\nexport type RequestBody = BlobHandle | string | Map;\n\nexport type EncodedBody = {\n mimeType: string;\n // the map gets transformed to a FormData object on the web\n body: RequestBody\n}\n\nexport function encodeQueryParams(queryParams?: object): string {\n return Object.entries(queryParams || {})\n .filter(([, value]) => value !== undefined)\n .map(([name, value]) => {\n if (typeof value === \"object\") {\n value = JSON.stringify(value);\n }\n return `${encodeURIComponent(name)}=${encodeURIComponent(value)}`;\n })\n .join(\"&\");\n}\n\nexport function encodeBody(body: BlobHandle | object): EncodedBody {\n if (body instanceof BlobHandle) {\n const blob = body as BlobHandle;\n return {\n mimeType: blob.mimeType,\n body: blob // will be unwrapped in request fn\n };\n } else if (body instanceof Map) {\n return {\n mimeType: \"multipart/form-data\",\n body: body\n }\n } else if (typeof body === \"object\") {\n const json = JSON.stringify(body);\n return {\n mimeType: \"application/json\",\n body: json\n }\n } else {\n throw new Error(\"Unknown body type: \" + body);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class WrappedError extends Error {\n constructor(message, cause) {\n super(`${message}: ${cause.message}`);\n this.cause = cause;\n }\n\n get name() {\n return \"WrappedError\";\n }\n}\n\nexport class HomeServerError extends Error {\n constructor(method, url, body, status) {\n super(`${body ? body.error : status} on ${method} ${url}`);\n this.errcode = body ? body.errcode : null;\n this.retry_after_ms = body ? body.retry_after_ms : 0;\n this.statusCode = status;\n }\n\n get name() {\n return \"HomeServerError\";\n }\n}\n\nexport {AbortError} from \"../utils/error\";\n\nexport class ConnectionError extends Error {\n constructor(message, isTimeout) {\n super(message || \"ConnectionError\");\n this.isTimeout = isTimeout;\n }\n\n get name() {\n return \"ConnectionError\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {HomeServerError, ConnectionError} from \"../error.js\";\nimport type {RequestResult} from \"../../platform/web/dom/request/fetch.js\";\nimport type {ILogItem} from \"../../logging/types\";\n\nexport interface IHomeServerRequest {\n abort(): void;\n response(): Promise;\n responseCode(): Promise;\n}\n\ntype HomeServerRequestOptions = {\n log?: ILogItem;\n allowedStatusCodes?: number[];\n};\n\nexport class HomeServerRequest implements IHomeServerRequest {\n private readonly _log?: ILogItem;\n private _sourceRequest?: RequestResult;\n // as we add types for expected responses from hs, this could be a generic class instead\n private readonly _promise: Promise;\n\n constructor(method: string, url: string, sourceRequest: RequestResult, options?: HomeServerRequestOptions) {\n let log: ILogItem | undefined;\n if (options?.log) {\n const parent = options?.log;\n log = parent.child({ t: \"network\", url, method, }, parent.level.Info);\n }\n this._log = log;\n this._sourceRequest = sourceRequest;\n this._promise = sourceRequest.response().then(response => {\n log?.set(\"status\", response.status);\n // ok?\n if (response.status >= 200 && response.status < 300 || options?.allowedStatusCodes?.includes(response.status)) {\n log?.finish();\n return response.body;\n } else {\n if (response.status >= 500) {\n const err = new ConnectionError(`Internal Server Error`);\n log?.catch(err);\n throw err;\n } else if (response.status >= 400 && !response.body?.errcode) {\n const err = new ConnectionError(`HTTP error status ${response.status} without errcode in body, assume this is a load balancer complaining the server is offline.`);\n log?.catch(err);\n throw err;\n } else {\n const err = new HomeServerError(method, url, response.body, response.status);\n log?.set(\"errcode\", err.errcode);\n log?.catch(err);\n throw err;\n }\n }\n }, err => {\n // if this._sourceRequest is still set,\n // the abort error came not from calling abort here\n if (err.name === \"AbortError\" && this._sourceRequest) {\n // The service worker sometimes (only on Firefox, on long, large request,\n // perhaps it has its own timeout?) aborts the request, see #187.\n // When it happens, the best thing to do seems to be to retry.\n // \n // In the service worker, we will also actively abort all\n // ongoing requests when trying to get a new service worker to activate\n // (this may surface in the app as a TypeError, which already gets mapped\n // to a ConnectionError in the request function, or an AbortError,\n // depending on the browser), as the service worker will only be\n // replaced when there are no more (fetch) events for the\n // current one to handle.\n // \n // In that case, the request function (in fetch.js) will check \n // the haltRequests flag on the service worker handler, and\n // block any new requests, as that would break the update process.\n // \n // So it is OK to return a ConnectionError here.\n // If we're updating the service worker, the /versions polling will\n // be blocked at the fetch level because haltRequests is set.\n // And for #187, retrying is the right thing to do.\n const err = new ConnectionError(`Service worker aborted, either updating or hit #187.`);\n log?.catch(err);\n throw err;\n } else {\n if (err.name === \"ConnectionError\") {\n log?.set(\"timeout\", err.isTimeout);\n }\n log?.catch(err);\n throw err;\n }\n });\n }\n\n abort(): void {\n if (this._sourceRequest) {\n this._log?.set(\"aborted\", true);\n this._sourceRequest.abort();\n // to mark that it was on purpose in above rejection handler\n this._sourceRequest = undefined;\n }\n }\n\n response(): Promise {\n return this._promise;\n }\n\n async responseCode(): Promise {\n const response = await this._sourceRequest.response();\n return response.status;\n }\n}\n\nimport {Request as MockRequest} from \"../../mocks/Request.js\";\nimport {AbortError} from \"../error.js\";\n\nexport function tests() {\n return {\n \"Response is passed through\": async assert => {\n const request = new MockRequest();\n const hsRequest = new HomeServerRequest(\"GET\", \"https://hs.tld/foo\", request);\n request.respond(200, \"foo\");\n assert.equal(await hsRequest.response(), \"foo\");\n },\n \"Unexpected AbortError is mapped to ConnectionError\": async assert => {\n const request = new MockRequest();\n const hsRequest = new HomeServerRequest(\"GET\", \"https://hs.tld/foo\", request);\n request.reject(new AbortError());\n await assert.rejects(hsRequest.response(), ConnectionError);\n },\n \"500 response is mapped to ConnectionError\": async assert => {\n const request = new MockRequest();\n const hsRequest = new HomeServerRequest(\"GET\", \"https://hs.tld/foo\", request);\n request.respond(500);\n await assert.rejects(hsRequest.response(), ConnectionError);\n },\n \"4xx response is mapped to HomeServerError\": async assert => {\n const request = new MockRequest();\n const hsRequest = new HomeServerRequest(\"GET\", \"https://hs.tld/foo\", request);\n request.respond(400, {errcode: \"FOO\"});\n await assert.rejects(hsRequest.response(), HomeServerError);\n },\n \"4xx response without errcode is mapped to ConnectionError\": async assert => {\n const request = new MockRequest();\n const hsRequest = new HomeServerRequest(\"GET\", \"https://hs.tld/foo\", request);\n request.respond(400);\n await assert.rejects(hsRequest.response(), ConnectionError);\n },\n \"Other errors are passed through\": async assert => {\n class MyError extends Error {}\n const request = new MockRequest();\n const hsRequest = new HomeServerRequest(\"GET\", \"https://hs.tld/foo\", request);\n request.reject(new MyError());\n await assert.rejects(hsRequest.response(), MyError);\n },\n };\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {encodeQueryParams, encodeBody} from \"./common\";\nimport {HomeServerRequest} from \"./HomeServerRequest\";\nimport type {IHomeServerRequest} from \"./HomeServerRequest\";\nimport type {Reconnector} from \"./Reconnector\";\nimport type {EncodedBody} from \"./common\";\nimport type {RequestFunction} from \"../../platform/types/types\";\nimport type {ILogItem} from \"../../logging/types\";\n\ntype RequestMethod = \"POST\" | \"GET\" | \"PUT\";\n\nconst CS_R0_PREFIX = \"/_matrix/client/r0\";\nconst CS_V3_PREFIX = \"/_matrix/client/v3\";\nconst DEHYDRATION_PREFIX = \"/_matrix/client/unstable/org.matrix.msc2697.v2\";\n\ntype Options = {\n homeserver: string;\n accessToken: string;\n request: RequestFunction;\n reconnector: Reconnector;\n};\n\ntype BaseRequestOptions = {\n log?: ILogItem;\n allowedStatusCodes?: number[];\n uploadProgress?: (loadedBytes: number) => void;\n timeout?: number;\n prefix?: string;\n};\n\nexport class HomeServerApi {\n private readonly _homeserver: string;\n private readonly _accessToken: string;\n private readonly _requestFn: RequestFunction;\n private readonly _reconnector: Reconnector;\n\n constructor({homeserver, accessToken, request, reconnector}: Options) {\n // store these both in a closure somehow so it's harder to get at in case of XSS?\n // one could change the homeserver as well so the token gets sent there, so both must be protected from read/write\n this._homeserver = homeserver;\n this._accessToken = accessToken;\n this._requestFn = request;\n this._reconnector = reconnector;\n }\n\n private _url(csPath: string, prefix: string = CS_R0_PREFIX): string {\n return this._homeserver + prefix + csPath;\n }\n\n private _baseRequest(method: RequestMethod, url: string, queryParams?: Record, body?: Record, options?: BaseRequestOptions, accessToken?: string): IHomeServerRequest {\n const queryString = encodeQueryParams(queryParams);\n url = `${url}?${queryString}`;\n let encodedBody: EncodedBody[\"body\"];\n const headers: Map = new Map();\n if (accessToken) {\n headers.set(\"Authorization\", `Bearer ${accessToken}`);\n }\n headers.set(\"Accept\", \"application/json\");\n if (body) {\n const encoded = encodeBody(body);\n headers.set(\"Content-Type\", encoded.mimeType);\n encodedBody = encoded.body;\n }\n\n const requestResult = this._requestFn(url, {\n method,\n headers,\n body: encodedBody,\n timeout: options?.timeout,\n uploadProgress: options?.uploadProgress,\n format: \"json\", // response format\n cache: method !== \"GET\",\n });\n\n const hsRequest = new HomeServerRequest(method, url, requestResult, options);\n \n if (this._reconnector) {\n hsRequest.response().catch(err => {\n // Some endpoints such as /sync legitimately time-out\n // (which is also reported as a ConnectionError) and will re-attempt,\n // but spinning up the reconnector in this case is ok,\n // as all code ran on session and sync start should be reentrant\n if (err.name === \"ConnectionError\") {\n this._reconnector.onRequestFailed(this);\n }\n });\n }\n\n return hsRequest;\n }\n\n private _unauthedRequest(method: RequestMethod, url: string, queryParams?: Record, body?: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._baseRequest(method, url, queryParams, body, options);\n }\n\n private _authedRequest(method: RequestMethod, url: string, queryParams?: Record, body?: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._baseRequest(method, url, queryParams, body, options, this._accessToken);\n }\n\n private _post(csPath: string, queryParams: Record, body: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._authedRequest(\"POST\", this._url(csPath, options?.prefix || CS_R0_PREFIX), queryParams, body, options);\n }\n\n private _put(csPath: string, queryParams: Record, body?: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._authedRequest(\"PUT\", this._url(csPath, options?.prefix || CS_R0_PREFIX), queryParams, body, options);\n }\n\n private _get(csPath: string, queryParams?: Record, body?: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._authedRequest(\"GET\", this._url(csPath, options?.prefix || CS_R0_PREFIX), queryParams, body, options);\n }\n\n sync(since: string, filter: string, timeout: number, options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(\"/sync\", {since, timeout, filter}, undefined, options);\n }\n\n context(roomId: string, eventId: string, limit: number, filter: string): IHomeServerRequest {\n return this._get(`/rooms/${encodeURIComponent(roomId)}/context/${encodeURIComponent(eventId)}`, {filter, limit});\n }\n\n // params is from, dir and optionally to, limit, filter.\n messages(roomId: string, params: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(`/rooms/${encodeURIComponent(roomId)}/messages`, params, undefined, options);\n }\n\n // params is at, membership and not_membership\n members(roomId: string, params: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(`/rooms/${encodeURIComponent(roomId)}/members`, params, undefined, options);\n }\n\n send(roomId: string, eventType: string, txnId: string, content: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._put(`/rooms/${encodeURIComponent(roomId)}/send/${encodeURIComponent(eventType)}/${encodeURIComponent(txnId)}`, {}, content, options);\n }\n\n redact(roomId: string, eventId: string, txnId: string, content: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._put(`/rooms/${encodeURIComponent(roomId)}/redact/${encodeURIComponent(eventId)}/${encodeURIComponent(txnId)}`, {}, content, options);\n }\n\n receipt(roomId: string, receiptType: string, eventId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/rooms/${encodeURIComponent(roomId)}/receipt/${encodeURIComponent(receiptType)}/${encodeURIComponent(eventId)}`,\n {}, {}, options);\n }\n\n state(roomId: string, eventType: string, stateKey: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(`/rooms/${encodeURIComponent(roomId)}/state/${encodeURIComponent(eventType)}/${encodeURIComponent(stateKey)}`, {}, undefined, options);\n }\n\n getLoginFlows(): IHomeServerRequest {\n return this._unauthedRequest(\"GET\", this._url(\"/login\"));\n }\n\n register(username: string | null, password: string, initialDeviceDisplayName: string, auth?: Record, inhibitLogin: boolean = true , options: BaseRequestOptions = {}): IHomeServerRequest {\n options.allowedStatusCodes = [401];\n const body: any = {\n auth,\n password,\n initial_device_displayname: initialDeviceDisplayName,\n inhibit_login: inhibitLogin,\n };\n if (username) {\n // username is optional for registration\n body.username = username;\n }\n return this._unauthedRequest( \"POST\", this._url(\"/register\", CS_V3_PREFIX), undefined, body, options);\n }\n\n passwordLogin(username: string, password: string, initialDeviceDisplayName: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._unauthedRequest(\"POST\", this._url(\"/login\"), undefined, {\n \"type\": \"m.login.password\",\n \"identifier\": {\n \"type\": \"m.id.user\",\n \"user\": username\n },\n \"password\": password,\n \"initial_device_display_name\": initialDeviceDisplayName\n }, options);\n }\n\n tokenLogin(loginToken: string, txnId: string, initialDeviceDisplayName: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._unauthedRequest(\"POST\", this._url(\"/login\"), undefined, {\n \"type\": \"m.login.token\",\n \"identifier\": {\n \"type\": \"m.id.user\",\n },\n \"token\": loginToken,\n \"txn_id\": txnId,\n \"initial_device_display_name\": initialDeviceDisplayName\n }, options);\n }\n\n createFilter(userId: string, filter: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/user/${encodeURIComponent(userId)}/filter`, {}, filter, options);\n }\n\n versions(options?: BaseRequestOptions): IHomeServerRequest {\n return this._unauthedRequest(\"GET\", `${this._homeserver}/_matrix/client/versions`, undefined, undefined, options);\n }\n\n uploadKeys(dehydratedDeviceId: string, payload: Record, options?: BaseRequestOptions): IHomeServerRequest {\n let path = \"/keys/upload\";\n if (dehydratedDeviceId) {\n path = path + `/${encodeURIComponent(dehydratedDeviceId)}`;\n }\n return this._post(path, {}, payload, options);\n }\n\n queryKeys(queryRequest: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(\"/keys/query\", {}, queryRequest, options);\n }\n\n claimKeys(payload: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(\"/keys/claim\", {}, payload, options);\n }\n\n sendToDevice(type: string, payload: Record, txnId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._put(`/sendToDevice/${encodeURIComponent(type)}/${encodeURIComponent(txnId)}`, {}, payload, options);\n }\n \n roomKeysVersion(version?: string, options?: BaseRequestOptions): IHomeServerRequest {\n let versionPart = \"\";\n if (version) {\n versionPart = `/${encodeURIComponent(version)}`;\n }\n return this._get(`/room_keys/version${versionPart}`, undefined, undefined, options);\n }\n\n roomKeyForRoomAndSession(version: string, roomId: string, sessionId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(`/room_keys/keys/${encodeURIComponent(roomId)}/${encodeURIComponent(sessionId)}`, {version}, undefined, options);\n }\n\n uploadRoomKeysToBackup(version: string, payload: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._put(`/room_keys/keys`, {version}, payload, options);\n }\n\n uploadAttachment(blob: Blob, filename: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._authedRequest(\"POST\", `${this._homeserver}/_matrix/media/r0/upload`, {filename}, blob, options);\n }\n\n setPusher(pusher: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(\"/pushers/set\", {}, pusher, options);\n }\n\n getPushers(options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(\"/pushers\", undefined, undefined, options);\n }\n\n join(roomId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/rooms/${encodeURIComponent(roomId)}/join`, {}, {}, options);\n }\n\n joinIdOrAlias(roomIdOrAlias: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/join/${encodeURIComponent(roomIdOrAlias)}`, {}, {}, options);\n }\n\n leave(roomId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/rooms/${encodeURIComponent(roomId)}/leave`, {}, {}, options);\n }\n\n forget(roomId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/rooms/${encodeURIComponent(roomId)}/forget`, {}, {}, options);\n }\n\n logout(options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/logout`, {}, {}, options);\n }\n\n getDehydratedDevice(options: BaseRequestOptions = {}): IHomeServerRequest {\n options.prefix = DEHYDRATION_PREFIX;\n return this._get(`/dehydrated_device`, undefined, undefined, options);\n }\n\n createDehydratedDevice(payload: Record, options: BaseRequestOptions = {}): IHomeServerRequest {\n options.prefix = DEHYDRATION_PREFIX;\n return this._put(`/dehydrated_device`, {}, payload, options);\n }\n\n claimDehydratedDevice(deviceId: string, options: BaseRequestOptions = {}): IHomeServerRequest {\n options.prefix = DEHYDRATION_PREFIX;\n return this._post(`/dehydrated_device/claim`, {}, {device_id: deviceId}, options);\n }\n\n profile(userId: string, options?: BaseRequestOptions): IHomeServerRequest {\n return this._get(`/profile/${encodeURIComponent(userId)}`);\n }\n\n createRoom(payload: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._post(`/createRoom`, {}, payload, options);\n }\n \n setAccountData(ownUserId: string, type: string, content: Record, options?: BaseRequestOptions): IHomeServerRequest {\n return this._put(`/user/${encodeURIComponent(ownUserId)}/account_data/${encodeURIComponent(type)}`, {}, content, options);\n }\n}\n\nimport {Request as MockRequest} from \"../../mocks/Request.js\";\n\nexport function tests() {\n return {\n \"superficial happy path for GET\": async assert => {\n // @ts-ignore\n const hsApi = new HomeServerApi({\n request: () => new MockRequest().respond(200, 42),\n homeserver: \"https://hs.tld\",\n });\n // @ts-ignore\n const result = await hsApi._get(\"foo\").response();\n assert.strictEqual(result, 42);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AbortError} from \"../../utils/error\";\nimport type {Timeout} from \"../../platform/web/dom/Clock.js\";\n\ntype TimeoutCreator = (ms: number) => Timeout;\n\nconst enum Default { start = 2000 }\n\nexport class ExponentialRetryDelay {\n private readonly _start: number = Default.start;\n private _current: number = Default.start;\n private readonly _createTimeout: TimeoutCreator;\n private readonly _max: number;\n private _timeout?: Timeout;\n\n constructor(createTimeout: TimeoutCreator) {\n const start = 2000;\n this._start = start;\n this._current = start;\n this._createTimeout = createTimeout;\n this._max = 60 * 5 * 1000; //5 min\n }\n\n async waitForRetry(): Promise {\n this._timeout = this._createTimeout(this._current);\n try {\n await this._timeout.elapsed();\n // only increase delay if we didn't get interrupted\n const next = 2 * this._current;\n this._current = Math.min(this._max, next);\n } catch(err) {\n // swallow AbortError, means abort was called\n if (!(err instanceof AbortError)) {\n throw err;\n }\n } finally {\n this._timeout = undefined;\n }\n }\n\n abort(): void {\n if (this._timeout) {\n this._timeout.abort();\n }\n }\n\n reset(): void {\n this._current = this._start;\n this.abort();\n }\n\n get nextValue(): number {\n return this._current;\n }\n}\n\n\nimport {Clock as MockClock} from \"../../mocks/Clock.js\";\n\nexport function tests() {\n return {\n \"test sequence\": async assert => {\n const clock = new MockClock();\n const retryDelay = new ExponentialRetryDelay(clock.createTimeout);\n let promise;\n\n assert.strictEqual(retryDelay.nextValue, 2000);\n promise = retryDelay.waitForRetry();\n clock.elapse(2000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 4000);\n promise = retryDelay.waitForRetry();\n clock.elapse(4000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 8000);\n promise = retryDelay.waitForRetry();\n clock.elapse(8000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 16000);\n promise = retryDelay.waitForRetry();\n clock.elapse(16000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 32000);\n promise = retryDelay.waitForRetry();\n clock.elapse(32000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 64000);\n promise = retryDelay.waitForRetry();\n clock.elapse(64000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 128000);\n promise = retryDelay.waitForRetry();\n clock.elapse(128000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 256000);\n promise = retryDelay.waitForRetry();\n clock.elapse(256000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 300000);\n promise = retryDelay.waitForRetry();\n clock.elapse(300000);\n await promise;\n\n assert.strictEqual(retryDelay.nextValue, 300000);\n promise = retryDelay.waitForRetry();\n clock.elapse(300000);\n await promise;\n },\n }\n \n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ObservableValue} from \"../../observable/ObservableValue\";\nimport type {ExponentialRetryDelay} from \"./ExponentialRetryDelay\";\nimport type {TimeMeasure} from \"../../platform/web/dom/Clock.js\";\nimport type {OnlineStatus} from \"../../platform/web/dom/OnlineStatus.js\";\nimport type {VersionResponse} from \"./types/response\";\nimport type {HomeServerApi} from \"./HomeServerApi\";\n\nexport enum ConnectionStatus {\n \"Waiting\",\n \"Reconnecting\",\n \"Online\"\n};\n\ntype Ctor = {\n retryDelay: ExponentialRetryDelay;\n createMeasure: () => TimeMeasure;\n onlineStatus: OnlineStatus\n};\n\nexport class Reconnector {\n private readonly _retryDelay: ExponentialRetryDelay;\n private readonly _createTimeMeasure: () => TimeMeasure;\n private readonly _onlineStatus: OnlineStatus;\n private readonly _state: ObservableValue;\n private _isReconnecting: boolean;\n private _versionsResponse?: VersionResponse;\n private _stateSince: TimeMeasure;\n\n constructor({retryDelay, createMeasure, onlineStatus}: Ctor) {\n this._onlineStatus = onlineStatus;\n this._retryDelay = retryDelay;\n this._createTimeMeasure = createMeasure;\n // assume online, and do our thing when something fails\n this._state = new ObservableValue(ConnectionStatus.Online);\n this._isReconnecting = false;\n }\n\n get lastVersionsResponse(): VersionResponse | undefined {\n return this._versionsResponse;\n }\n\n get connectionStatus(): ObservableValue {\n return this._state;\n }\n\n get retryIn(): number {\n if (this._state.get() === ConnectionStatus.Waiting) {\n return this._retryDelay.nextValue - this._stateSince.measure();\n }\n return 0;\n }\n\n async onRequestFailed(hsApi: HomeServerApi): Promise {\n if (!this._isReconnecting) { \n this._isReconnecting = true;\n \n const onlineStatusSubscription = this._onlineStatus && this._onlineStatus.subscribe(online => {\n if (online) {\n this.tryNow();\n }\n });\n\n try {\n await this._reconnectLoop(hsApi);\n } catch (err) {\n // nothing is catching the error above us,\n // so just log here\n console.error(err);\n } finally {\n if (onlineStatusSubscription) {\n // unsubscribe from this._onlineStatus\n onlineStatusSubscription();\n }\n this._isReconnecting = false;\n }\n }\n }\n\n tryNow(): void {\n if (this._retryDelay) {\n // this will interrupt this._retryDelay.waitForRetry() in _reconnectLoop\n this._retryDelay.abort();\n }\n }\n\n private _setState(state: ConnectionStatus): void {\n if (state !== this._state.get()) {\n if (state === ConnectionStatus.Waiting) {\n this._stateSince = this._createTimeMeasure();\n } else {\n this._stateSince = null;\n }\n this._state.set(state);\n }\n }\n \n private async _reconnectLoop(hsApi: HomeServerApi): Promise {\n this._versionsResponse = undefined;\n this._retryDelay.reset();\n\n while (!this._versionsResponse) {\n try {\n this._setState(ConnectionStatus.Reconnecting);\n // use 30s timeout, as a tradeoff between not giving up\n // too quickly on a slow server, and not waiting for\n // a stale connection when we just came online again\n const versionsRequest = hsApi.versions({timeout: 30000});\n this._versionsResponse = await versionsRequest.response();\n this._setState(ConnectionStatus.Online);\n } catch (err) {\n if (err.name === \"ConnectionError\") {\n this._setState(ConnectionStatus.Waiting);\n await this._retryDelay.waitForRetry();\n } else {\n throw err;\n }\n }\n }\n }\n}\n\n\nimport {Clock as MockClock} from \"../../mocks/Clock.js\";\nimport {ExponentialRetryDelay as _ExponentialRetryDelay} from \"./ExponentialRetryDelay\";\nimport {ConnectionError} from \"../error.js\"\n\nexport function tests() {\n function createHsApiMock(remainingFailures) {\n return {\n versions() {\n return {\n response() {\n if (remainingFailures) {\n remainingFailures -= 1;\n return Promise.reject(new ConnectionError());\n } else {\n return Promise.resolve(42);\n }\n }\n };\n }\n }\n }\n\n return {\n \"test reconnecting with 1 failure\": async assert => {\n const clock = new MockClock();\n const {createMeasure} = clock;\n const onlineStatus = new ObservableValue(false);\n const retryDelay = new _ExponentialRetryDelay(clock.createTimeout);\n const reconnector = new Reconnector({retryDelay, onlineStatus, createMeasure});\n const {connectionStatus} = reconnector;\n const statuses: ConnectionStatus[] = [];\n const subscription = reconnector.connectionStatus.subscribe(s => {\n statuses.push(s);\n });\n // @ts-ignore\n reconnector.onRequestFailed(createHsApiMock(1));\n await connectionStatus.waitFor(s => s === ConnectionStatus.Waiting).promise;\n clock.elapse(2000);\n await connectionStatus.waitFor(s => s === ConnectionStatus.Online).promise;\n assert.deepEqual(statuses, [\n ConnectionStatus.Reconnecting,\n ConnectionStatus.Waiting,\n ConnectionStatus.Reconnecting,\n ConnectionStatus.Online\n ]);\n assert.strictEqual(reconnector.lastVersionsResponse, 42);\n subscription();\n },\n \"test reconnecting with onlineStatus\": async assert => {\n const clock = new MockClock();\n const {createMeasure} = clock;\n const onlineStatus = new ObservableValue(false);\n const retryDelay = new _ExponentialRetryDelay(clock.createTimeout);\n const reconnector = new Reconnector({retryDelay, onlineStatus, createMeasure});\n const {connectionStatus} = reconnector;\n // @ts-ignore\n reconnector.onRequestFailed(createHsApiMock(1));\n await connectionStatus.waitFor(s => s === ConnectionStatus.Waiting).promise;\n onlineStatus.set(true); //skip waiting\n await connectionStatus.waitFor(s => s === ConnectionStatus.Online).promise;\n assert.equal(connectionStatus.get(), ConnectionStatus.Online);\n assert.strictEqual(reconnector.lastVersionsResponse, 42);\n },\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * Decrypt an attachment.\n * @param {ArrayBuffer} ciphertextBuffer The encrypted attachment data buffer.\n * @param {Object} info The information needed to decrypt the attachment.\n * @param {Object} info.key AES-CTR JWK key object.\n * @param {string} info.iv Base64 encoded 16 byte AES-CTR IV.\n * @param {string} info.hashes.sha256 Base64 encoded SHA-256 hash of the ciphertext.\n * @return {Promise} A promise that resolves with an ArrayBuffer when the attachment is decrypted.\n */\nexport async function decryptAttachment(platform, ciphertextBuffer, info) {\n if (info === undefined || info.key === undefined || info.iv === undefined\n || info.hashes === undefined || info.hashes.sha256 === undefined) {\n throw new Error(\"Invalid info. Missing info.key, info.iv or info.hashes.sha256 key\");\n }\n\n const {crypto} = platform;\n const {base64} = platform.encoding;\n var ivArray = base64.decode(info.iv);\n // re-encode to not deal with padded vs unpadded\n var expectedSha256base64 = base64.encode(base64.decode(info.hashes.sha256));\n // Check the sha256 hash\n const digestResult = await crypto.digest(\"SHA-256\", ciphertextBuffer);\n if (base64.encode(new Uint8Array(digestResult)) != expectedSha256base64) {\n throw new Error(\"Mismatched SHA-256 digest\");\n }\n var counterLength;\n if (info.v == \"v1\" || info.v == \"v2\") {\n // Version 1 and 2 use a 64 bit counter.\n counterLength = 64;\n } else {\n // Version 0 uses a 128 bit counter.\n counterLength = 128;\n }\n\n const decryptedBuffer = await crypto.aes.decryptCTR({\n jwkKey: info.key,\n iv: ivArray,\n data: ciphertextBuffer,\n counterLength\n });\n return decryptedBuffer;\n}\n\nexport async function encryptAttachment(platform, blob) {\n const {crypto} = platform;\n const {base64} = platform.encoding;\n const iv = await crypto.aes.generateIV();\n const key = await crypto.aes.generateKey(\"jwk\", 256);\n const buffer = await blob.readAsBuffer();\n const ciphertext = await crypto.aes.encryptCTR({jwkKey: key, iv, data: buffer});\n const digest = await crypto.digest(\"SHA-256\", ciphertext);\n return {\n blob: platform.createBlob(ciphertext, 'application/octet-stream'),\n info: {\n v: \"v2\",\n key,\n iv: base64.encodeUnpadded(iv),\n hashes: {\n sha256: base64.encodeUnpadded(digest)\n }\n }\n };\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {encodeQueryParams} from \"./common\";\nimport {decryptAttachment} from \"../e2ee/attachment.js\";\nimport {Platform} from \"../../platform/web/Platform.js\";\nimport {BlobHandle} from \"../../platform/web/dom/BlobHandle.js\";\nimport type {Attachment, EncryptedFile} from \"./types/response\";\n\nexport class MediaRepository {\n private readonly _homeserver: string;\n private readonly _platform: Platform;\n\n constructor({homeserver, platform}: {homeserver:string, platform: Platform}) {\n this._homeserver = homeserver;\n this._platform = platform;\n }\n\n mxcUrlThumbnail(url: string, width: number, height: number, method: \"crop\" | \"scale\"): string | null {\n const parts = this._parseMxcUrl(url);\n if (parts) {\n const [serverName, mediaId] = parts;\n const httpUrl = `${this._homeserver}/_matrix/media/r0/thumbnail/${encodeURIComponent(serverName)}/${encodeURIComponent(mediaId)}`;\n return httpUrl + \"?\" + encodeQueryParams({width: Math.round(width), height: Math.round(height), method});\n }\n return null;\n }\n\n mxcUrl(url: string): string | null {\n const parts = this._parseMxcUrl(url);\n if (parts) {\n const [serverName, mediaId] = parts;\n return `${this._homeserver}/_matrix/media/r0/download/${encodeURIComponent(serverName)}/${encodeURIComponent(mediaId)}`;\n } else {\n return null;\n }\n }\n\n private _parseMxcUrl(url: string): string[] | null {\n const prefix = \"mxc://\";\n if (url.startsWith(prefix)) {\n return url.substr(prefix.length).split(\"/\", 2);\n } else {\n return null;\n }\n }\n\n async downloadEncryptedFile(fileEntry: EncryptedFile, cache: boolean = false): Promise {\n const url = this.mxcUrl(fileEntry.url);\n const {body: encryptedBuffer} = await this._platform.request(url, {method: \"GET\", format: \"buffer\", cache}).response();\n const decryptedBuffer = await decryptAttachment(this._platform, encryptedBuffer, fileEntry);\n return this._platform.createBlob(decryptedBuffer, fileEntry.mimetype);\n }\n\n async downloadPlaintextFile(mxcUrl: string, mimetype: string, cache: boolean = false): Promise {\n const url = this.mxcUrl(mxcUrl);\n const {body: buffer} = await this._platform.request(url, {method: \"GET\", format: \"buffer\", cache}).response();\n return this._platform.createBlob(buffer, mimetype);\n }\n\n async downloadAttachment(content: Attachment, cache: boolean = false): Promise {\n if (content.file) {\n return this.downloadEncryptedFile(content.file, cache);\n } else {\n return this.downloadPlaintextFile(content.url!, content.info?.mimetype, cache);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AbortError} from \"../../utils/error\";\nimport {HomeServerError} from \"../error.js\";\nimport {HomeServerApi} from \"./HomeServerApi\";\nimport {ExponentialRetryDelay} from \"./ExponentialRetryDelay\";\nimport {Clock} from \"../../platform/web/dom/Clock.js\";\nimport type {IHomeServerRequest} from \"./HomeServerRequest.js\";\n\nclass Request implements IHomeServerRequest {\n public readonly methodName: string;\n public readonly args: any[];\n private responseResolve: (result: any) => void;\n public responseReject: (error: Error) => void;\n private responseCodeResolve?: (result: any) => void;\n private responseCodeReject?: (result: any) => void;\n private _requestResult?: IHomeServerRequest;\n private readonly _responsePromise: Promise;\n private _responseCodePromise: Promise;\n\n constructor(methodName: string, args: any[]) {\n this.methodName = methodName;\n this.args = args;\n this._responsePromise = new Promise((resolve, reject) => {\n this.responseResolve = resolve;\n this.responseReject = reject;\n });\n }\n\n abort(): void {\n if (this._requestResult) {\n this._requestResult.abort();\n } else {\n this.responseReject(new AbortError());\n this.responseCodeReject?.(new AbortError());\n }\n }\n\n response(): Promise {\n return this._responsePromise;\n }\n\n responseCode(): Promise {\n if (this.requestResult) {\n return this.requestResult.responseCode();\n }\n if (!this._responseCodePromise) {\n this._responseCodePromise = new Promise((resolve, reject) => {\n this.responseCodeResolve = resolve;\n this.responseCodeReject = reject;\n });\n }\n return this._responseCodePromise;\n }\n\n async setRequestResult(result) {\n this._requestResult = result;\n const response = await this._requestResult?.response();\n this.responseResolve(response);\n const responseCode = await this._requestResult?.responseCode();\n this.responseCodeResolve?.(responseCode);\n }\n\n get requestResult() {\n return this._requestResult;\n }\n}\n\nclass HomeServerApiWrapper {\n private readonly _scheduler: RequestScheduler;\n\n constructor(scheduler: RequestScheduler) {\n this._scheduler = scheduler;\n }\n}\n\n// add request-wrapping methods to prototype\nfor (const methodName of Object.getOwnPropertyNames(HomeServerApi.prototype)) {\n if (methodName !== \"constructor\" && !methodName.startsWith(\"_\")) {\n HomeServerApiWrapper.prototype[methodName] = function(...args) {\n return this._scheduler._hsApiRequest(methodName, args);\n };\n }\n}\n\nexport class RequestScheduler {\n private readonly _hsApi: HomeServerApi;\n private readonly _clock: Clock;\n private readonly _requests: Set = new Set();\n private _stopped = false;\n private _wrapper = new HomeServerApiWrapper(this);\n\n constructor({ hsApi, clock }: { hsApi: HomeServerApi; clock: Clock }) {\n this._hsApi = hsApi;\n this._clock = clock;\n }\n\n get hsApi(): HomeServerApi {\n return this._wrapper as unknown as HomeServerApi;\n }\n\n stop(): void {\n this._stopped = true;\n for (const request of this._requests) {\n request.abort();\n }\n this._requests.clear();\n }\n\n start(): void {\n this._stopped = false;\n }\n\n private _hsApiRequest(name: string, args: any[]): Request {\n const request = new Request(name, args);\n this._doSend(request);\n return request;\n }\n\n private async _doSend(request: Request): Promise {\n this._requests.add(request);\n try {\n let retryDelay: ExponentialRetryDelay | undefined;\n while (!this._stopped) {\n try {\n const requestResult = this._hsApi[\n request.methodName\n ].apply(this._hsApi, request.args);\n // so the request can be aborted\n await request.setRequestResult(requestResult);\n return;\n } catch (err) {\n if (\n err instanceof HomeServerError &&\n err.errcode === \"M_LIMIT_EXCEEDED\"\n ) {\n if (Number.isSafeInteger(err.retry_after_ms)) {\n await this._clock\n .createTimeout(err.retry_after_ms)\n .elapsed();\n } else {\n if (!retryDelay) {\n retryDelay = new ExponentialRetryDelay(\n this._clock.createTimeout\n );\n }\n await retryDelay.waitForRetry();\n }\n } else {\n request.responseReject(err);\n return;\n }\n }\n }\n if (this._stopped) {\n request.abort();\n }\n } finally {\n this._requests.delete(request);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ObservableValue} from \"../observable/ObservableValue\";\nimport {createEnum} from \"../utils/enum\";\n\nconst INCREMENTAL_TIMEOUT = 30000;\n\nexport const SyncStatus = createEnum(\n \"InitialSync\",\n \"CatchupSync\",\n \"Syncing\",\n \"Stopped\"\n);\n\nfunction timelineIsEmpty(roomResponse) {\n try {\n const events = roomResponse?.timeline?.events;\n return Array.isArray(events) && events.length === 0;\n } catch (err) {\n return true;\n }\n}\n\n/**\n * Sync steps in js-pseudocode:\n * ```js\n * // can only read some stores\n * const preparation = await room.prepareSync(roomResponse, membership, newRoomKeys, prepareTxn);\n * // can do async work that is not related to storage (such as decryption)\n * await room.afterPrepareSync(preparation);\n * // writes and calculates changes\n * const changes = await room.writeSync(roomResponse, isInitialSync, preparation, syncTxn);\n * // applies and emits changes once syncTxn is committed\n * room.afterSync(changes);\n * if (room.needsAfterSyncCompleted(changes)) {\n * // can do network requests\n * await room.afterSyncCompleted(changes);\n * }\n * ```\n */\nexport class Sync {\n constructor({hsApi, session, storage, logger}) {\n this._hsApi = hsApi;\n this._logger = logger;\n this._session = session;\n this._storage = storage;\n this._currentRequest = null;\n this._status = new ObservableValue(SyncStatus.Stopped);\n this._error = null;\n }\n\n get status() {\n return this._status;\n }\n\n /** the error that made the sync stop */\n get error() {\n return this._error;\n }\n\n start() {\n // not already syncing?\n if (this._status.get() !== SyncStatus.Stopped) {\n return;\n }\n this._error = null;\n let syncToken = this._session.syncToken;\n if (syncToken) {\n this._status.set(SyncStatus.CatchupSync);\n } else {\n this._status.set(SyncStatus.InitialSync);\n }\n this._syncLoop(syncToken);\n }\n\n async _syncLoop(syncToken) {\n // if syncToken is falsy, it will first do an initial sync ... \n while(this._status.get() !== SyncStatus.Stopped) {\n let roomStates;\n let sessionChanges;\n let wasCatchupOrInitial = this._status.get() === SyncStatus.CatchupSync || this._status.get() === SyncStatus.InitialSync;\n await this._logger.run(\"sync\", async log => {\n log.set(\"token\", syncToken);\n log.set(\"status\", this._status.get());\n try {\n // unless we are happily syncing already, we want the server to return\n // as quickly as possible, even if there are no events queued. This\n // serves two purposes:\n //\n // * When the connection dies, we want to know asap when it comes back,\n // so that we can hide the error from the user. (We don't want to\n // have to wait for an event or a timeout).\n //\n // * We want to know if the server has any to_device messages queued up\n // for us. We do that by calling it with a zero timeout until it\n // doesn't give us any more to_device messages.\n const timeout = this._status.get() === SyncStatus.Syncing ? INCREMENTAL_TIMEOUT : 0; \n const syncResult = await this._syncRequest(syncToken, timeout, log);\n syncToken = syncResult.syncToken;\n roomStates = syncResult.roomStates;\n sessionChanges = syncResult.sessionChanges;\n // initial sync or catchup sync\n if (this._status.get() !== SyncStatus.Syncing && syncResult.hadToDeviceMessages) {\n this._status.set(SyncStatus.CatchupSync);\n } else {\n this._status.set(SyncStatus.Syncing);\n }\n } catch (err) {\n // retry same request on timeout\n if (err.name === \"ConnectionError\" && err.isTimeout) {\n // don't run afterSyncCompleted\n return;\n }\n this._error = err;\n if (err.name !== \"AbortError\") {\n // sync wasn't asked to stop, but is stopping\n // because of the error.\n log.error = err;\n log.logLevel = log.level.Fatal;\n }\n log.set(\"stopping\", true);\n this._status.set(SyncStatus.Stopped);\n }\n if (this._status.get() !== SyncStatus.Stopped) {\n // TODO: if we're not going to run this phase in parallel with the next\n // sync request (because this causes OTKs to be uploaded twice)\n // should we move this inside _syncRequest?\n // Alternatively, we can try to fix the OTK upload issue while still\n // running in parallel.\n await log.wrap(\"afterSyncCompleted\", log => this._runAfterSyncCompleted(sessionChanges, roomStates, log));\n }\n },\n this._logger.level.Info,\n (filter, log) => {\n if (log.durationWithoutType(\"network\") >= 2000 || log.error || wasCatchupOrInitial) {\n return filter.minLevel(log.level.Detail);\n } else {\n return filter.minLevel(log.level.Info);\n }\n });\n }\n }\n\n async _runAfterSyncCompleted(sessionChanges, roomStates, log) {\n const isCatchupSync = this._status.get() === SyncStatus.CatchupSync;\n const sessionPromise = (async () => {\n try {\n await log.wrap(\"session\", log => this._session.afterSyncCompleted(sessionChanges, isCatchupSync, log), log.level.Detail);\n } catch (err) {} // error is logged, but don't fail sessionPromise\n })();\n\n const roomsNeedingAfterSyncCompleted = roomStates.filter(rs => {\n return rs.room.needsAfterSyncCompleted(rs.changes);\n });\n const roomsPromises = roomsNeedingAfterSyncCompleted.map(async rs => {\n try {\n await log.wrap(\"room\", log => rs.room.afterSyncCompleted(rs.changes, log), log.level.Detail);\n } catch (err) {} // error is logged, but don't fail roomsPromises\n });\n // run everything in parallel,\n // we don't want to delay the next sync too much\n // Also, since all promises won't reject (as they have a try/catch)\n // it's fine to use Promise.all\n await Promise.all(roomsPromises.concat(sessionPromise));\n }\n\n async _syncRequest(syncToken, timeout, log) {\n let {syncFilterId} = this._session;\n if (typeof syncFilterId !== \"string\") {\n this._currentRequest = this._hsApi.createFilter(this._session.user.id, {room: {state: {lazy_load_members: true}}}, {log});\n syncFilterId = (await this._currentRequest.response()).filter_id;\n }\n const totalRequestTimeout = timeout + (80 * 1000); // same as riot-web, don't get stuck on wedged long requests\n this._currentRequest = this._hsApi.sync(syncToken, syncFilterId, timeout, {timeout: totalRequestTimeout, log});\n const response = await this._currentRequest.response();\n\n const isInitialSync = !syncToken;\n const sessionState = new SessionSyncProcessState();\n const inviteStates = this._parseInvites(response.rooms);\n const {roomStates, archivedRoomStates} = await this._parseRoomsResponse(\n response.rooms, inviteStates, isInitialSync, log);\n\n try {\n // take a lock on olm sessions used in this sync so sending a message doesn't change them while syncing\n sessionState.lock = await log.wrap(\"obtainSyncLock\", () => this._session.obtainSyncLock(response));\n await log.wrap(\"prepare\", log => this._prepareSync(sessionState, roomStates, response, log));\n await log.wrap(\"afterPrepareSync\", log => Promise.all(roomStates.map(rs => {\n return rs.room.afterPrepareSync(rs.preparation, log);\n })));\n await log.wrap(\"write\", async log => this._writeSync(\n sessionState, inviteStates, roomStates, archivedRoomStates,\n response, syncFilterId, isInitialSync, log));\n } finally {\n sessionState.dispose();\n }\n // sync txn comitted, emit updates and apply changes to in-memory state\n log.wrap(\"after\", log => this._afterSync(\n sessionState, inviteStates, roomStates, archivedRoomStates, log));\n\n const toDeviceEvents = response.to_device?.events;\n return {\n syncToken: response.next_batch,\n roomStates,\n sessionChanges: sessionState.changes,\n hadToDeviceMessages: Array.isArray(toDeviceEvents) && toDeviceEvents.length > 0,\n };\n }\n\n _openPrepareSyncTxn() {\n const storeNames = this._storage.storeNames;\n return this._storage.readTxn([\n storeNames.olmSessions,\n storeNames.inboundGroupSessions,\n // to read fragments when loading sync writer when rejoining archived room\n storeNames.timelineFragments,\n // to read fragments when loading sync writer when rejoining archived room\n // to read events that can now be decrypted\n storeNames.timelineEvents,\n ]);\n }\n\n async _prepareSync(sessionState, roomStates, response, log) {\n const prepareTxn = await this._openPrepareSyncTxn();\n sessionState.preparation = await log.wrap(\"session\", log => this._session.prepareSync(\n response, sessionState.lock, prepareTxn, log));\n\n const newKeysByRoom = sessionState.preparation?.newKeysByRoom;\n\n // add any rooms with new keys but no sync response to the list of rooms to be synced\n if (newKeysByRoom) {\n const {hasOwnProperty} = Object.prototype;\n for (const roomId of newKeysByRoom.keys()) {\n const isRoomInResponse = response.rooms?.join && hasOwnProperty.call(response.rooms.join, roomId);\n if (!isRoomInResponse) {\n let room = this._session.rooms.get(roomId);\n if (room) {\n roomStates.push(new RoomSyncProcessState(room, false, {}, room.membership));\n }\n }\n }\n }\n \n await Promise.all(roomStates.map(async rs => {\n const newKeys = newKeysByRoom?.get(rs.room.id);\n rs.preparation = await log.wrap(\"room\", async log => {\n // if previously joined and we still have the timeline for it,\n // this loads the syncWriter at the correct position to continue writing the timeline\n if (rs.isNewRoom) {\n await rs.room.load(null, prepareTxn, log);\n }\n return rs.room.prepareSync(\n rs.roomResponse, rs.membership, newKeys, prepareTxn, log)\n }, log.level.Detail);\n }));\n\n // This is needed for safari to not throw TransactionInactiveErrors on the syncTxn. See docs/INDEXEDDB.md\n await prepareTxn.complete();\n }\n\n async _writeSync(sessionState, inviteStates, roomStates, archivedRoomStates, response, syncFilterId, isInitialSync, log) {\n const syncTxn = await this._openSyncTxn();\n try {\n sessionState.changes = await log.wrap(\"session\", log => this._session.writeSync(\n response, syncFilterId, sessionState.preparation, syncTxn, log));\n await Promise.all(inviteStates.map(async is => {\n is.changes = await log.wrap(\"invite\", log => is.invite.writeSync(\n is.membership, is.roomResponse, syncTxn, log));\n }));\n await Promise.all(roomStates.map(async rs => {\n rs.changes = await log.wrap(\"room\", log => rs.room.writeSync(\n rs.roomResponse, isInitialSync, rs.preparation, syncTxn, log));\n }));\n // important to do this after roomStates,\n // as we're referring to the roomState to get the summaryChanges\n await Promise.all(archivedRoomStates.map(async ars => {\n const summaryChanges = ars.roomState?.summaryChanges;\n ars.changes = await log.wrap(\"archivedRoom\", log => ars.archivedRoom.writeSync(\n summaryChanges, ars.roomResponse, ars.membership, syncTxn, log));\n }));\n } catch(err) {\n // avoid corrupting state by only\n // storing the sync up till the point\n // the exception occurred\n syncTxn.abort(log);\n throw syncTxn.getCause(err);\n }\n await syncTxn.complete(log);\n }\n\n _afterSync(sessionState, inviteStates, roomStates, archivedRoomStates, log) {\n log.wrap(\"session\", log => this._session.afterSync(sessionState.changes, log), log.level.Detail);\n for(let ars of archivedRoomStates) {\n log.wrap(\"archivedRoom\", log => {\n ars.archivedRoom.afterSync(ars.changes, log);\n ars.archivedRoom.release();\n }, log.level.Detail);\n }\n for(let rs of roomStates) {\n log.wrap(\"room\", log => rs.room.afterSync(rs.changes, log), log.level.Detail);\n }\n for(let is of inviteStates) {\n log.wrap(\"invite\", log => is.invite.afterSync(is.changes, log), log.level.Detail);\n }\n this._session.applyRoomCollectionChangesAfterSync(inviteStates, roomStates, archivedRoomStates, log);\n }\n\n _openSyncTxn() {\n const storeNames = this._storage.storeNames;\n return this._storage.readWriteTxn([\n storeNames.session,\n storeNames.roomSummary,\n storeNames.archivedRoomSummary,\n storeNames.invites,\n storeNames.roomState,\n storeNames.roomMembers,\n storeNames.timelineEvents,\n storeNames.timelineRelations,\n storeNames.timelineFragments,\n storeNames.pendingEvents,\n storeNames.userIdentities,\n storeNames.groupSessionDecryptions,\n storeNames.deviceIdentities,\n // to discard outbound session when somebody leaves a room\n // and to create room key messages when somebody joins\n storeNames.outboundGroupSessions,\n storeNames.operations,\n storeNames.accountData,\n // to decrypt and store new room keys\n storeNames.olmSessions,\n storeNames.inboundGroupSessions,\n ]);\n }\n \n async _parseRoomsResponse(roomsSection, inviteStates, isInitialSync, log) {\n const roomStates = [];\n const archivedRoomStates = [];\n if (roomsSection) {\n const allMemberships = [\"join\", \"leave\"];\n for(const membership of allMemberships) {\n const membershipSection = roomsSection[membership];\n if (membershipSection) {\n for (const [roomId, roomResponse] of Object.entries(membershipSection)) {\n // ignore rooms with empty timelines during initial sync,\n // see https://github.com/vector-im/hydrogen-web/issues/15\n if (isInitialSync && timelineIsEmpty(roomResponse)) {\n continue;\n }\n const invite = this._session.invites.get(roomId);\n // if there is an existing invite, add a process state for it\n // so its writeSync and afterSync will run and remove the invite\n if (invite) {\n inviteStates.push(new InviteSyncProcessState(invite, false, null, membership));\n }\n const roomState = this._createRoomSyncState(roomId, roomResponse, membership, isInitialSync);\n if (roomState) {\n roomStates.push(roomState);\n }\n const ars = await this._createArchivedRoomSyncState(roomId, roomState, roomResponse, membership, isInitialSync, log);\n if (ars) {\n archivedRoomStates.push(ars);\n }\n }\n }\n }\n }\n return {roomStates, archivedRoomStates};\n }\n\n _createRoomSyncState(roomId, roomResponse, membership, isInitialSync) {\n let isNewRoom = false;\n let room = this._session.rooms.get(roomId);\n // create room only either on new join,\n // or for an archived room during initial sync,\n // where we create the summaryChanges with a joined\n // room to then adopt by the archived room.\n // This way the limited timeline, members, ...\n // we receive also gets written.\n // In any case, don't create a room for a rejected invite\n if (!room && (membership === \"join\" || (isInitialSync && membership === \"leave\"))) {\n room = this._session.createJoinedRoom(roomId);\n isNewRoom = true;\n }\n if (room) {\n return new RoomSyncProcessState(\n room, isNewRoom, roomResponse, membership);\n }\n }\n\n async _createArchivedRoomSyncState(roomId, roomState, roomResponse, membership, isInitialSync, log) {\n let archivedRoom;\n if (roomState?.shouldAdd && !isInitialSync) {\n // when adding a joined room during incremental sync,\n // always create the archived room to write the removal\n // of the archived summary\n archivedRoom = this._session.createOrGetArchivedRoomForSync(roomId);\n } else if (membership === \"leave\") {\n if (roomState) {\n // we still have a roomState, so we just left it\n // in this case, create a new archivedRoom\n archivedRoom = this._session.createOrGetArchivedRoomForSync(roomId);\n } else {\n // this is an update of an already left room, restore\n // it from storage first, so we can increment it.\n // this happens for example when our membership changes\n // after leaving (e.g. being (un)banned, possibly after being kicked), etc\n archivedRoom = await this._session.loadArchivedRoom(roomId, log);\n }\n }\n if (archivedRoom) {\n return new ArchivedRoomSyncProcessState(\n archivedRoom, roomState, roomResponse, membership);\n }\n }\n\n _parseInvites(roomsSection) {\n const inviteStates = [];\n if (roomsSection?.invite) {\n for (const [roomId, roomResponse] of Object.entries(roomsSection.invite)) {\n let invite = this._session.invites.get(roomId);\n let isNewInvite = false;\n if (!invite) {\n invite = this._session.createInvite(roomId);\n isNewInvite = true;\n }\n inviteStates.push(new InviteSyncProcessState(invite, isNewInvite, roomResponse, \"invite\"));\n }\n }\n return inviteStates;\n }\n\n stop() {\n if (this._status.get() === SyncStatus.Stopped) {\n return;\n }\n this._status.set(SyncStatus.Stopped);\n if (this._currentRequest) {\n this._currentRequest.abort();\n this._currentRequest = null;\n }\n }\n}\n\nclass SessionSyncProcessState {\n constructor() {\n this.lock = null;\n this.preparation = null;\n this.changes = null;\n }\n\n dispose() {\n this.lock?.release();\n }\n}\n\nclass RoomSyncProcessState {\n constructor(room, isNewRoom, roomResponse, membership) {\n this.room = room;\n this.isNewRoom = isNewRoom;\n this.roomResponse = roomResponse;\n this.membership = membership;\n this.preparation = null;\n this.changes = null;\n }\n\n get id() {\n return this.room.id;\n }\n\n get shouldAdd() {\n return this.isNewRoom && this.membership === \"join\";\n }\n\n get shouldRemove() {\n return !this.isNewRoom && this.membership !== \"join\";\n }\n\n get summaryChanges() {\n return this.changes?.summaryChanges;\n }\n}\n\n\nclass ArchivedRoomSyncProcessState {\n constructor(archivedRoom, roomState, roomResponse, membership, isInitialSync) {\n this.archivedRoom = archivedRoom;\n this.roomState = roomState;\n this.roomResponse = roomResponse;\n this.membership = membership;\n this.isInitialSync = isInitialSync;\n this.changes = null;\n }\n\n get id() {\n return this.archivedRoom.id;\n }\n\n get shouldAdd() {\n return (this.roomState || this.isInitialSync) && this.membership === \"leave\";\n }\n\n get shouldRemove() {\n return this.membership === \"join\";\n }\n}\n\nclass InviteSyncProcessState {\n constructor(invite, isNewInvite, roomResponse, membership) {\n this.invite = invite;\n this.isNewInvite = isNewInvite;\n this.membership = membership;\n this.roomResponse = roomResponse;\n this.changes = null;\n }\n\n get id() {\n return this.invite.id;\n }\n\n get shouldAdd() {\n return this.isNewInvite;\n }\n\n get shouldRemove() {\n return this.membership !== \"invite\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 Daniel Fedorin \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\ntype Handler = (value?: T) => void;\n\nexport class EventEmitter {\n private _handlersByName: { [event in keyof T]?: Set> }\n\n constructor() {\n this._handlersByName = {};\n }\n\n emit(name: K, value?: T[K]): void {\n const handlers = this._handlersByName[name];\n if (handlers) {\n handlers.forEach(h => h(value));\n }\n }\n\n disposableOn(name: K, callback: Handler): () => void {\n this.on(name, callback);\n return () => {\n this.off(name, callback);\n }\n }\n\n on(name: K, callback: Handler): void {\n let handlers = this._handlersByName[name];\n if (!handlers) {\n this.onFirstSubscriptionAdded(name);\n this._handlersByName[name] = handlers = new Set();\n }\n handlers.add(callback);\n }\n\n off(name: K, callback: Handler): void {\n const handlers = this._handlersByName[name];\n if (handlers) {\n handlers.delete(callback);\n if (handlers.size === 0) {\n delete this._handlersByName[name];\n this.onLastSubscriptionRemoved(name);\n }\n }\n }\n\n onFirstSubscriptionAdded(name: K): void {}\n\n onLastSubscriptionRemoved(name: K): void {}\n}\n\nexport function tests() {\n return {\n test_on_off(assert) {\n let counter = 0;\n const e = new EventEmitter<{ change: never }>();\n const callback = () => counter += 1;\n e.on(\"change\", callback);\n e.emit(\"change\");\n e.off(\"change\", callback);\n e.emit(\"change\");\n assert.equal(counter, 1);\n },\n\n test_emit_value(assert) {\n let value = 0;\n const e = new EventEmitter<{ change: number }>();\n const callback = (v) => value = v;\n e.on(\"change\", callback);\n e.emit(\"change\", 5);\n e.off(\"change\", callback);\n assert.equal(value, 5);\n },\n\n test_double_on(assert) {\n let counter = 0;\n const e = new EventEmitter<{ change: never }>();\n const callback = () => counter += 1;\n e.on(\"change\", callback);\n e.on(\"change\", callback);\n e.emit(\"change\");\n e.off(\"change\", callback);\n assert.equal(counter, 1);\n }\n };\n}\n","/* Copyright 2015 Mark Haines\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n'use strict';\n\nvar escaped = /[\\\\\\\"\\x00-\\x1F]/g;\nvar escapes = {};\nfor (var i = 0; i < 0x20; ++i) {\n escapes[String.fromCharCode(i)] = (\n '\\\\U' + ('0000' + i.toString(16)).slice(-4).toUpperCase()\n );\n}\nescapes['\\b'] = '\\\\b';\nescapes['\\t'] = '\\\\t';\nescapes['\\n'] = '\\\\n';\nescapes['\\f'] = '\\\\f';\nescapes['\\r'] = '\\\\r';\nescapes['\\\"'] = '\\\\\\\"';\nescapes['\\\\'] = '\\\\\\\\';\n\nfunction escapeString(value) {\n escaped.lastIndex = 0;\n return value.replace(escaped, function(c) { return escapes[c]; });\n}\n\nfunction stringify(value) {\n switch (typeof value) {\n case 'string':\n return '\"' + escapeString(value) + '\"';\n case 'number':\n return isFinite(value) ? value : 'null';\n case 'boolean':\n return value;\n case 'object':\n if (value === null) {\n return 'null';\n }\n if (Array.isArray(value)) {\n return stringifyArray(value);\n }\n return stringifyObject(value);\n default:\n throw new Error('Cannot stringify: ' + typeof value);\n }\n}\n\nfunction stringifyArray(array) {\n var sep = '[';\n var result = '';\n for (var i = 0; i < array.length; ++i) {\n result += sep;\n sep = ',';\n result += stringify(array[i]);\n }\n if (sep != ',') {\n return '[]';\n } else {\n return result + ']';\n }\n}\n\nfunction stringifyObject(object) {\n var sep = '{';\n var result = '';\n var keys = Object.keys(object);\n keys.sort();\n for (var i = 0; i < keys.length; ++i) {\n var key = keys[i];\n result += sep + '\"' + escapeString(key) + '\":';\n sep = ',';\n result += stringify(object[key]);\n }\n if (sep != ',') {\n return '{}';\n } else {\n return result + '}';\n }\n}\n\n/** */\nmodule.exports = {stringify: stringify};\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport anotherjson from \"another-json\";\nimport {createEnum} from \"../../utils/enum\";\n\nexport const DecryptionSource = createEnum(\"Sync\", \"Timeline\", \"Retry\");\n\n// use common prefix so it's easy to clear properties that are not e2ee related during session clear\nexport const SESSION_E2EE_KEY_PREFIX = \"e2ee:\";\nexport const OLM_ALGORITHM = \"m.olm.v1.curve25519-aes-sha2\";\nexport const MEGOLM_ALGORITHM = \"m.megolm.v1.aes-sha2\";\n\nexport class DecryptionError extends Error {\n constructor(code, event, detailsObj = null) {\n super(`Decryption error ${code}${detailsObj ? \": \"+JSON.stringify(detailsObj) : \"\"}`);\n this.code = code;\n this.event = event;\n this.details = detailsObj;\n }\n}\n\nexport const SIGNATURE_ALGORITHM = \"ed25519\";\n\nexport function verifyEd25519Signature(olmUtil, userId, deviceOrKeyId, ed25519Key, value, log = undefined) {\n const clone = Object.assign({}, value);\n delete clone.unsigned;\n delete clone.signatures;\n const canonicalJson = anotherjson.stringify(clone);\n const signature = value?.signatures?.[userId]?.[`${SIGNATURE_ALGORITHM}:${deviceOrKeyId}`];\n try {\n if (!signature) {\n throw new Error(\"no signature\");\n }\n // throws when signature is invalid\n olmUtil.ed25519_verify(ed25519Key, canonicalJson, signature);\n return true;\n } catch (err) {\n if (log) {\n const logItem = log.log({l: \"Invalid signature, ignoring.\", ed25519Key, canonicalJson, signature});\n logItem.error = err;\n logItem.logLevel = log.level.Warn;\n }\n return false;\n }\n}\n\nexport function createRoomEncryptionEvent() {\n return {\n \"type\": \"m.room.encryption\",\n \"state_key\": \"\",\n \"content\": {\n \"algorithm\": MEGOLM_ALGORITHM,\n \"rotation_period_ms\": 604800000,\n \"rotation_period_msgs\": 100\n }\n }\n}\n\n\n// Use enum when converting to TS\nexport const HistoryVisibility = Object.freeze({\n Joined: \"joined\",\n Invited: \"invited\",\n WorldReadable: \"world_readable\",\n Shared: \"shared\",\n});\n\nexport function shouldShareKey(membership, historyVisibility) {\n switch (historyVisibility) {\n case HistoryVisibility.WorldReadable:\n return true;\n case HistoryVisibility.Shared:\n // was part of room at some time\n return membership !== undefined;\n case HistoryVisibility.Joined:\n return membership === \"join\";\n case HistoryVisibility.Invited:\n return membership === \"invite\" || membership === \"join\";\n default:\n return false;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MEGOLM_ALGORITHM} from \"../e2ee/common.js\";\n\n\nfunction applyTimelineEntries(data, timelineEntries, isInitialSync, canMarkUnread, ownUserId) {\n if (timelineEntries.length) {\n data = timelineEntries.reduce((data, entry) => {\n return processTimelineEvent(data, entry,\n isInitialSync, canMarkUnread, ownUserId);\n }, data);\n }\n return data;\n}\n\nexport function reduceStateEvents(roomResponse, callback, value) {\n const stateEvents = roomResponse?.state?.events;\n // state comes before timeline\n if (Array.isArray(stateEvents)) {\n value = stateEvents.reduce(callback, value);\n }\n const timelineEvents = roomResponse?.timeline?.events;\n // and after that state events in the timeline\n if (Array.isArray(timelineEvents)) {\n value = timelineEvents.reduce((data, event) => {\n if (typeof event.state_key === \"string\") {\n value = callback(value, event);\n }\n return value;\n }, value);\n }\n return value;\n}\n\nfunction applySyncResponse(data, roomResponse, membership, ownUserId) {\n if (roomResponse.summary) {\n data = updateSummary(data, roomResponse.summary);\n }\n if (membership !== data.membership) {\n data = data.cloneIfNeeded();\n data.membership = membership;\n }\n if (roomResponse.account_data) {\n data = roomResponse.account_data.events.reduce(processRoomAccountData, data);\n }\n // process state events in state and in timeline.\n // non-state events are handled by applyTimelineEntries\n // so decryption is handled properly\n data = reduceStateEvents(roomResponse, (data, event) => processStateEvent(data, event, ownUserId), data);\n const unreadNotifications = roomResponse.unread_notifications;\n if (unreadNotifications) {\n data = processNotificationCounts(data, unreadNotifications);\n }\n\n return data;\n}\n\nfunction processNotificationCounts(data, unreadNotifications) {\n const highlightCount = unreadNotifications.highlight_count || 0;\n if (highlightCount !== data.highlightCount) {\n data = data.cloneIfNeeded();\n data.highlightCount = highlightCount;\n }\n const notificationCount = unreadNotifications.notification_count;\n if (notificationCount !== data.notificationCount) {\n data = data.cloneIfNeeded();\n data.notificationCount = notificationCount;\n }\n return data;\n} \n\nfunction processRoomAccountData(data, event) {\n if (event?.type === \"m.tag\") {\n let tags = event?.content?.tags;\n if (!tags || Array.isArray(tags) || typeof tags !== \"object\") {\n tags = null;\n }\n data = data.cloneIfNeeded();\n data.tags = tags;\n }\n return data;\n}\n\nexport function processStateEvent(data, event, ownUserId) {\n if (event.type === \"m.room.create\") {\n data = data.cloneIfNeeded();\n data.lastMessageTimestamp = event.origin_server_ts;\n } else if (event.type === \"m.room.encryption\") {\n const algorithm = event.content?.algorithm;\n if (!data.encryption && algorithm === MEGOLM_ALGORITHM) {\n data = data.cloneIfNeeded();\n data.encryption = event.content;\n }\n } else if (event.type === \"m.room.name\") {\n const newName = event.content?.name;\n if (newName !== data.name) {\n data = data.cloneIfNeeded();\n data.name = newName;\n }\n } else if (event.type === \"m.room.avatar\") {\n const newUrl = event.content?.url;\n if (newUrl !== data.avatarUrl) {\n data = data.cloneIfNeeded();\n data.avatarUrl = newUrl;\n }\n } else if (event.type === \"m.room.canonical_alias\") {\n const content = event.content;\n data = data.cloneIfNeeded();\n data.canonicalAlias = content.alias;\n } else if (event.type === \"m.room.member\") {\n const content = event.content;\n if (content.is_direct === true && content.membership === \"invite\" && !data.isDirectMessage) {\n let other;\n if (event.sender === ownUserId) {\n other = event.state_key;\n } else if (event.state_key === ownUserId) {\n other = event.sender;\n }\n if (other) {\n data = data.cloneIfNeeded();\n data.isDirectMessage = true;\n data.dmUserId = other;\n }\n } else if (content.membership === \"leave\" && data.isDirectMessage && data.dmUserId === event.state_key) {\n data = data.cloneIfNeeded();\n data.isDirectMessage = false;\n data.dmUserId = null;\n }\n }\n return data;\n}\n\nfunction processTimelineEvent(data, eventEntry, isInitialSync, canMarkUnread, ownUserId) {\n if (eventEntry.eventType === \"m.room.message\") {\n if (!data.lastMessageTimestamp || eventEntry.timestamp > data.lastMessageTimestamp) {\n data = data.cloneIfNeeded();\n data.lastMessageTimestamp = eventEntry.timestamp;\n }\n if (!isInitialSync && eventEntry.sender !== ownUserId && canMarkUnread) {\n data = data.cloneIfNeeded();\n data.isUnread = true;\n }\n }\n return data;\n}\n\nfunction updateSummary(data, summary) {\n const heroes = summary[\"m.heroes\"];\n const joinCount = summary[\"m.joined_member_count\"];\n const inviteCount = summary[\"m.invited_member_count\"];\n // TODO: we could easily calculate if all members are available here and set hasFetchedMembers?\n // so we can avoid calling /members...\n // we'd need to do a count query in the roomMembers store though ...\n if (heroes && Array.isArray(heroes)) {\n data = data.cloneIfNeeded();\n data.heroes = heroes;\n }\n if (Number.isInteger(inviteCount)) {\n data = data.cloneIfNeeded();\n data.inviteCount = inviteCount;\n }\n if (Number.isInteger(joinCount)) {\n data = data.cloneIfNeeded();\n data.joinCount = joinCount;\n }\n return data;\n}\n\nexport class SummaryData {\n constructor(copy, roomId) {\n this.roomId = copy ? copy.roomId : roomId;\n this.name = copy ? copy.name : null;\n this.lastMessageTimestamp = copy ? copy.lastMessageTimestamp : null;\n this.isUnread = copy ? copy.isUnread : false;\n this.encryption = copy ? copy.encryption : null;\n this.membership = copy ? copy.membership : null;\n this.inviteCount = copy ? copy.inviteCount : 0;\n this.joinCount = copy ? copy.joinCount : 0;\n this.heroes = copy ? copy.heroes : null;\n this.canonicalAlias = copy ? copy.canonicalAlias : null;\n this.hasFetchedMembers = copy ? copy.hasFetchedMembers : false;\n this.isTrackingMembers = copy ? copy.isTrackingMembers : false;\n this.avatarUrl = copy ? copy.avatarUrl : null;\n this.notificationCount = copy ? copy.notificationCount : 0;\n this.highlightCount = copy ? copy.highlightCount : 0;\n this.tags = copy ? copy.tags : null;\n this.isDirectMessage = copy ? copy.isDirectMessage : false;\n this.dmUserId = copy ? copy.dmUserId : null;\n this.cloned = copy ? true : false;\n }\n\n changedKeys(other) {\n const props = Object.getOwnPropertyNames(this);\n return props.filter(prop => {\n return prop !== \"cloned\" && this[prop] !== other[prop]\n });\n }\n\n cloneIfNeeded() {\n if (this.cloned) {\n return this;\n } else {\n return new SummaryData(this);\n }\n }\n\n serialize() {\n return Object.entries(this).reduce((obj, [key, value]) => {\n if (key !== \"cloned\" && value !== null) {\n obj[key] = value;\n }\n return obj;\n }, {});\n }\n\n applyTimelineEntries(timelineEntries, isInitialSync, canMarkUnread, ownUserId) {\n return applyTimelineEntries(this, timelineEntries, isInitialSync, canMarkUnread, ownUserId);\n }\n\n applySyncResponse(roomResponse, membership, ownUserId) {\n return applySyncResponse(this, roomResponse, membership, ownUserId);\n }\n\n get needsHeroes() {\n return !this.name && !this.canonicalAlias && this.heroes && this.heroes.length > 0;\n }\n\n isNewJoin(oldData) {\n return this.membership === \"join\" && oldData.membership !== \"join\";\n }\n}\n\nexport class RoomSummary {\n\tconstructor(roomId) {\n this._data = null;\n this.applyChanges(new SummaryData(null, roomId));\n\t}\n\n get data() {\n return this._data;\n }\n\n writeClearUnread(txn) {\n const data = new SummaryData(this._data);\n data.isUnread = false;\n data.notificationCount = 0;\n data.highlightCount = 0;\n txn.roomSummary.set(data.serialize());\n return data;\n }\n\n writeHasFetchedMembers(value, txn) {\n const data = new SummaryData(this._data);\n data.hasFetchedMembers = value;\n txn.roomSummary.set(data.serialize());\n return data;\n }\n\n writeIsTrackingMembers(value, txn) {\n const data = new SummaryData(this._data);\n data.isTrackingMembers = value;\n txn.roomSummary.set(data.serialize());\n return data;\n }\n\n\twriteData(data, txn) {\n\t\tif (data !== this._data) {\n txn.roomSummary.set(data.serialize());\n return data;\n\t\t}\n\t}\n\n /** move summary to archived store when leaving the room */\n writeArchivedData(data, txn) {\n if (data !== this._data) {\n txn.archivedRoomSummary.set(data.serialize());\n return data;\n }\n }\n\n async writeAndApplyData(data, storage) {\n if (data === this._data) {\n return false;\n }\n const txn = await storage.readWriteTxn([\n storage.storeNames.roomSummary,\n ]);\n try {\n txn.roomSummary.set(data.serialize());\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n this.applyChanges(data);\n return true;\n }\n\n applyChanges(data) {\n this._data = data;\n // clear cloned flag, so cloneIfNeeded makes a copy and\n // this._data is not modified if any field is changed.\n this._data.cloned = false;\n }\n\n\tasync load(summary) {\n this.applyChanges(new SummaryData(summary));\n\t}\n}\n\nexport function tests() {\n return {\n \"serialize doesn't include null fields or cloned\": assert => {\n const roomId = \"!123:hs.tld\";\n const data = new SummaryData(null, roomId);\n const clone = data.cloneIfNeeded();\n const serialized = clone.serialize();\n assert.strictEqual(serialized.cloned, undefined);\n assert.equal(serialized.roomId, roomId);\n const nullCount = Object.values(serialized).reduce((count, value) => count + value === null ? 1 : 0, 0);\n assert.strictEqual(nullCount, 0);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport enum StoreNames {\n session = \"session\",\n roomState = \"roomState\",\n roomSummary = \"roomSummary\",\n archivedRoomSummary = \"archivedRoomSummary\",\n invites = \"invites\",\n roomMembers = \"roomMembers\",\n timelineEvents = \"timelineEvents\",\n timelineRelations = \"timelineRelations\",\n timelineFragments = \"timelineFragments\",\n pendingEvents = \"pendingEvents\",\n userIdentities = \"userIdentities\",\n deviceIdentities = \"deviceIdentities\",\n olmSessions = \"olmSessions\",\n inboundGroupSessions = \"inboundGroupSessions\",\n outboundGroupSessions = \"outboundGroupSessions\",\n groupSessionDecryptions = \"groupSessionDecryptions\",\n operations = \"operations\",\n accountData = \"accountData\",\n}\n\nexport const STORE_NAMES: Readonly = Object.values(StoreNames);\n\nexport class StorageError extends Error {\n errcode?: string;\n cause: Error | null;\n\n constructor(message: string, cause: Error | null = null) {\n super(message);\n if (cause) {\n this.errcode = cause.name;\n }\n this.cause = cause;\n }\n\n get name(): string {\n return \"StorageError\";\n }\n}\n\nexport const KeyLimits = {\n get minStorageKey(): number {\n // for indexeddb, we use unsigned 32 bit integers as keys\n return 0;\n },\n \n get middleStorageKey(): number {\n // for indexeddb, we use unsigned 32 bit integers as keys\n return 0x7FFFFFFF;\n },\n\n get maxStorageKey(): number {\n // for indexeddb, we use unsigned 32 bit integers as keys\n return 0xFFFFFFFF;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {KeyLimits} from \"../../storage/common\";\nimport {Direction} from \"./Direction\";\n\n// key for events in the timelineEvents store\nexport class EventKey {\n constructor(\n public fragmentId: number,\n public eventIndex: number\n ) {\n }\n\n nextFragmentKey(): EventKey {\n // could take MIN_EVENT_INDEX here if it can't be paged back\n return new EventKey(this.fragmentId + 1, KeyLimits.middleStorageKey);\n }\n\n nextKeyForDirection(direction: Direction): EventKey {\n if (direction.isForward) {\n return this.nextKey();\n } else {\n return this.previousKey();\n }\n }\n\n previousKey(): EventKey {\n return new EventKey(this.fragmentId, this.eventIndex - 1);\n }\n\n nextKey(): EventKey {\n return new EventKey(this.fragmentId, this.eventIndex + 1);\n }\n\n static get maxKey(): EventKey {\n return new EventKey(KeyLimits.maxStorageKey, KeyLimits.maxStorageKey);\n }\n\n static get minKey(): EventKey {\n return new EventKey(KeyLimits.minStorageKey, KeyLimits.minStorageKey);\n }\n\n static get defaultLiveKey(): EventKey {\n return EventKey.defaultFragmentKey(KeyLimits.minStorageKey);\n }\n\n static defaultFragmentKey(fragmentId: number): EventKey {\n return new EventKey(fragmentId, KeyLimits.middleStorageKey);\n }\n\n toString(): string {\n return `[${this.fragmentId}/${this.eventIndex}]`;\n }\n\n equals(other: EventKey): boolean {\n return this.fragmentId === other?.fragmentId && this.eventIndex === other?.eventIndex;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n//entries can be sorted, first by fragment, then by entry index.\nimport {EventKey} from \"../EventKey\";\nexport const PENDING_FRAGMENT_ID = Number.MAX_SAFE_INTEGER;\n\ninterface FragmentIdComparer {\n compare: (a: number, b: number) => number\n}\n\nexport abstract class BaseEntry {\n constructor(\n protected readonly _fragmentIdComparer: FragmentIdComparer\n ) {\n }\n\n abstract get fragmentId(): number;\n abstract get entryIndex(): number;\n abstract updateFrom(other: BaseEntry): void;\n\n compare(otherEntry: BaseEntry): number {\n if (this.fragmentId === otherEntry.fragmentId) {\n return this.entryIndex - otherEntry.entryIndex;\n } else if (this.fragmentId === PENDING_FRAGMENT_ID) {\n return 1;\n } else if (otherEntry.fragmentId === PENDING_FRAGMENT_ID) {\n return -1;\n } else {\n // This might throw if the relation of two fragments is unknown.\n return this._fragmentIdComparer.compare(this.fragmentId, otherEntry.fragmentId);\n }\n }\n\n asEventKey(): EventKey {\n return new EventKey(this.fragmentId, this.entryIndex);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {StateEvent} from \"../storage/types\";\n\nexport function getPrevContentFromStateEvent(event) {\n // where to look for prev_content is a bit of a mess,\n // see https://matrix.to/#/!NasysSDfxKxZBzJJoE:matrix.org/$DvrAbZJiILkOmOIuRsNoHmh2v7UO5CWp_rYhlGk34fQ?via=matrix.org&via=pixie.town&via=amorgan.xyz\n return event.unsigned?.prev_content || event.prev_content;\n}\n\nexport const REDACTION_TYPE = \"m.room.redaction\";\n\nexport function isRedacted(event) {\n return !!event?.unsigned?.redacted_because;\n}\n\nexport enum RoomStatus {\n None = 1 << 0,\n BeingCreated = 1 << 1,\n Invited = 1 << 2,\n Joined = 1 << 3,\n Replaced = 1 << 4,\n Archived = 1 << 5,\n}\n\nexport enum RoomType {\n DirectMessage,\n Private,\n Public\n}\n\ntype RoomResponse = {\n state?: {\n events?: Array\n },\n timeline?: {\n events?: Array\n }\n}\n\n/** iterates over any state events in a sync room response, in the order that they should be applied (from older to younger events) */\nexport function iterateResponseStateEvents(roomResponse: RoomResponse, callback: (StateEvent) => Promise | void): Promise | void {\n let promises: Promise[] | undefined = undefined;\n const callCallback = stateEvent => {\n const result = callback(stateEvent);\n if (result instanceof Promise) {\n promises = promises ?? [];\n promises.push(result);\n }\n };\n // first iterate over state events, they precede the timeline\n const stateEvents = roomResponse.state?.events;\n if (stateEvents) {\n for (let i = 0; i < stateEvents.length; i++) {\n callCallback(stateEvents[i]);\n }\n }\n // now see if there are any state events within the timeline\n let timelineEvents = roomResponse.timeline?.events;\n if (timelineEvents) {\n for (let i = 0; i < timelineEvents.length; i++) {\n const event = timelineEvents[i];\n if (typeof event.state_key === \"string\") {\n callCallback(event);\n }\n }\n }\n if (promises) {\n return Promise.all(promises).then(() => undefined);\n }\n}\n\nexport function tests() {\n return {\n \"test iterateResponseStateEvents with both state and timeline sections\": assert => {\n const roomResponse = {\n state: {\n events: [\n {type: \"m.room.member\", state_key: \"1\"},\n {type: \"m.room.member\", state_key: \"2\", content: {a: 1}},\n ]\n },\n timeline: {\n events: [\n {type: \"m.room.message\"},\n {type: \"m.room.member\", state_key: \"3\"},\n {type: \"m.room.message\"},\n {type: \"m.room.member\", state_key: \"2\", content: {a: 2}},\n ]\n }\n } as unknown as RoomResponse;\n const expectedStateKeys = [\"1\", \"2\", \"3\", \"2\"];\n const expectedAForMember2 = [1, 2];\n iterateResponseStateEvents(roomResponse, event => {\n assert.strictEqual(event.type, \"m.room.member\");\n assert.strictEqual(expectedStateKeys.shift(), event.state_key);\n if (event.state_key === \"2\") {\n assert.strictEqual(expectedAForMember2.shift(), event.content.a);\n }\n });\n assert.strictEqual(expectedStateKeys.length, 0);\n assert.strictEqual(expectedAForMember2.length, 0);\n },\n \"test iterateResponseStateEvents with empty response\": assert => {\n iterateResponseStateEvents({}, () => {\n assert.fail(\"no events expected\");\n });\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {REDACTION_TYPE} from \"../common\";\n\nexport const REACTION_TYPE = \"m.reaction\";\nexport const ANNOTATION_RELATION_TYPE = \"m.annotation\";\n\nexport function createAnnotation(targetId, key) {\n return {\n \"m.relates_to\": {\n \"event_id\": targetId,\n key,\n \"rel_type\": ANNOTATION_RELATION_TYPE\n }\n };\n}\n\nexport function getRelationTarget(relation) {\n return relation.event_id || relation[\"m.in_reply_to\"]?.event_id\n}\n\nexport function setRelationTarget(relation, target) {\n if (relation.event_id !== undefined) {\n relation.event_id = target;\n } else if (relation[\"m.in_reply_to\"]) {\n relation[\"m.in_reply_to\"].event_id = target;\n }\n}\n\nexport function getRelatedEventId(event) {\n\tif (event.type === REDACTION_TYPE) {\n return event.redacts;\n } else {\n const relation = getRelation(event);\n if (relation) {\n return getRelationTarget(relation);\n }\n }\n return null;\n}\n\nexport function getRelationFromContent(content) {\n return content?.[\"m.relates_to\"];\n}\n\nexport function getRelation(event) {\n\treturn getRelationFromContent(event.content);\n}\n\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class PendingAnnotation {\n constructor() {\n // TODO: use simple member for reaction and redaction as we can't/shouldn't really have more than 2 entries\n // this contains both pending annotation entries, and pending redactions of remote annotation entries \n this._entries = [];\n }\n\n get firstTimestamp() {\n return this._entries.reduce((ts, e) => {\n if (e.isRedaction) {\n return ts;\n }\n return Math.min(e.timestamp, ts);\n }, Number.MAX_SAFE_INTEGER);\n }\n\n get annotationEntry() {\n return this._entries.find(e => !e.isRedaction);\n }\n\n get redactionEntry() {\n return this._entries.find(e => e.isRedaction);\n }\n\n get count() {\n return this._entries.reduce((count, e) => {\n return count + (e.isRedaction ? -1 : 1);\n }, 0);\n }\n\n add(entry) {\n this._entries.push(entry);\n }\n\n remove(entry) {\n const idx = this._entries.indexOf(entry);\n if (idx === -1) {\n return false;\n }\n this._entries.splice(idx, 1);\n return true;\n }\n\n get willAnnotate() {\n const lastEntry = this._entries.reduce((lastEntry, e) => {\n if (!lastEntry || e.pendingEvent.queueIndex > lastEntry.pendingEvent.queueIndex) {\n return e;\n }\n return lastEntry;\n }, null);\n if (lastEntry) {\n return !lastEntry.isRedaction;\n }\n return false;\n }\n\n get isEmpty() {\n return this._entries.length === 0;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nfunction htmlEscape(string) {\n return string.replace(/&/g, \"&\").replace(//g, \">\");\n}\n\nfunction fallbackForNonTextualMessage(msgtype) {\n switch (msgtype) {\n case \"m.file\":\n return \"sent a file.\";\n case \"m.image\":\n return \"sent an image.\";\n case \"m.video\":\n return \"sent a video.\";\n case \"m.audio\":\n return \"sent an audio file.\";\n }\n return null;\n}\n\nfunction fallbackPrefix(msgtype) {\n return msgtype === \"m.emote\" ? \"* \" : \"\";\n}\n\nfunction _createReplyContent(targetId, msgtype, body, formattedBody) {\n return {\n msgtype,\n body,\n \"format\": \"org.matrix.custom.html\",\n \"formatted_body\": formattedBody,\n \"m.relates_to\": {\n \"m.in_reply_to\": {\n \"event_id\": targetId\n }\n }\n };\n}\n\nexport function createReplyContent(entry, msgtype, body) {\n // TODO check for absense of sender / body / msgtype / etc?\n const nonTextual = fallbackForNonTextualMessage(entry.content.msgtype);\n const prefix = fallbackPrefix(entry.content.msgtype);\n const sender = entry.sender;\n const name = entry.displayName || sender;\n\n const formattedBody = nonTextual || entry.content.formatted_body ||\n (entry.content.body && htmlEscape(entry.content.body)) || \"\";\n const formattedFallback = `

In reply to ${prefix}` +\n `${name}
` +\n `${formattedBody}
`;\n\n const plainBody = nonTextual || entry.content.body || \"\";\n const bodyLines = plainBody.split(\"\\n\");\n bodyLines[0] = `> ${prefix}<${sender}> ${bodyLines[0]}`\n const plainFallback = bodyLines.join(\"\\n> \");\n\n const newBody = plainFallback + '\\n\\n' + body;\n const newFormattedBody = formattedFallback + htmlEscape(body);\n return _createReplyContent(entry.id, msgtype, newBody, newFormattedBody);\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseEntry} from \"./BaseEntry\";\nimport {REDACTION_TYPE} from \"../../common\";\nimport {createAnnotation, ANNOTATION_RELATION_TYPE, getRelationFromContent} from \"../relations.js\";\nimport {PendingAnnotation} from \"../PendingAnnotation.js\";\nimport {createReplyContent} from \"./reply.js\"\n\n/** Deals mainly with local echo for relations and redactions,\n * so it is shared between PendingEventEntry and EventEntry */\nexport class BaseEventEntry extends BaseEntry {\n constructor(fragmentIdComparer) {\n super(fragmentIdComparer);\n this._pendingRedactions = null;\n this._pendingAnnotations = null;\n this._contextEntry = null;\n this._contextForEntries = null;\n }\n\n get isReply() {\n return !!this.relation?.[\"m.in_reply_to\"];\n }\n\n get isRedacting() {\n return !!this._pendingRedactions;\n }\n\n get isRedacted() {\n return this.isRedacting;\n }\n\n get isRedaction() {\n return this.eventType === REDACTION_TYPE;\n }\n\n get redactionReason() {\n if (this._pendingRedactions) {\n return this._pendingRedactions[0].content?.reason;\n }\n return null;\n }\n\n setContextEntry(entry) {\n this._contextEntry = entry;\n entry._setAsContextOf(this);\n }\n\n _setAsContextOf(entry) {\n if (!this._contextForEntries) {\n this._contextForEntries = [];\n }\n this._contextForEntries.push(entry);\n }\n\n get contextForEntries() {\n return this._contextForEntries;\n }\n\n get contextEntry() {\n return this._contextEntry;\n }\n\n /**\n Aggregates relation or redaction of remote relation. \n Used in two situations:\n - to aggregate local relation/redaction of remote relation\n - to mark this entry as being redacted in Timeline._updateEntriesFetchedFromHomeserver\n @return [string] returns the name of the field that has changed, if any\n */\n addLocalRelation(entry) {\n if (entry.eventType === REDACTION_TYPE && entry.isRelatedToId(this.id)) {\n if (!this._pendingRedactions) {\n this._pendingRedactions = [];\n }\n this._pendingRedactions.push(entry);\n if (this._pendingRedactions.length === 1) {\n return \"isRedacted\";\n }\n } else {\n const relationEntry = entry.redactingEntry || entry;\n if (relationEntry.isRelatedToId(this.id)) {\n if (relationEntry.relation.rel_type === ANNOTATION_RELATION_TYPE) {\n if (this._addPendingAnnotation(entry)) {\n return \"pendingAnnotations\";\n }\n }\n }\n }\n }\n \n /**\n deaggregates local relation or a local redaction of a remote relation.\n @return [string] returns the name of the field that has changed, if any\n */\n removeLocalRelation(entry) {\n if (entry.eventType === REDACTION_TYPE && entry.isRelatedToId(this.id) && this._pendingRedactions) {\n const countBefore = this._pendingRedactions.length;\n this._pendingRedactions = this._pendingRedactions.filter(e => e !== entry);\n if (this._pendingRedactions.length === 0) {\n this._pendingRedactions = null;\n if (countBefore !== 0) {\n return \"isRedacted\";\n }\n }\n } else {\n const relationEntry = entry.redactingEntry || entry;\n if (relationEntry.isRelatedToId(this.id)) {\n if (relationEntry.relation?.rel_type === ANNOTATION_RELATION_TYPE && this._pendingAnnotations) {\n if (this._removePendingAnnotation(entry)) {\n return \"pendingAnnotations\";\n }\n }\n }\n }\n }\n\n _addPendingAnnotation(entry) {\n if (!this._pendingAnnotations) {\n this._pendingAnnotations = new Map();\n }\n const {key} = (entry.redactingEntry || entry).relation;\n if (key) {\n let annotation = this._pendingAnnotations.get(key);\n if (!annotation) {\n annotation = new PendingAnnotation();\n this._pendingAnnotations.set(key, annotation);\n }\n annotation.add(entry);\n return true;\n }\n return false;\n }\n\n _removePendingAnnotation(entry) {\n const {key} = (entry.redactingEntry || entry).relation;\n if (key) {\n let annotation = this._pendingAnnotations.get(key);\n if (annotation.remove(entry) && annotation.isEmpty) {\n this._pendingAnnotations.delete(key);\n }\n if (this._pendingAnnotations.size === 0) {\n this._pendingAnnotations = null;\n }\n return true;\n }\n return false;\n }\n\n async abortPendingRedaction() {\n if (this._pendingRedactions) {\n for (const pee of this._pendingRedactions) {\n await pee.pendingEvent.abort();\n }\n // removing the pending events will call removeLocalRelation,\n // so don't clear _pendingRedactions here\n }\n }\n\n get pendingRedaction() {\n if (this._pendingRedactions) {\n return this._pendingRedactions[0];\n }\n return null;\n }\n\n annotate(key) {\n return createAnnotation(this.id, key);\n }\n\n reply(msgtype, body) {\n return createReplyContent(this, msgtype, body);\n }\n\n /** takes both remote event id and local txn id into account, see overriding in PendingEventEntry */\n isRelatedToId(id) {\n return id && this.relatedEventId === id;\n }\n\n haveAnnotation(key) {\n const haveRemoteReaction = this.annotations?.[key]?.me || false;\n const pendingAnnotation = this.pendingAnnotations?.get(key);\n const willAnnotate = pendingAnnotation?.willAnnotate || false;\n /*\n We have an annotation in these case:\n - remote annotation with me, no pending\n - remote annotation with me, pending redaction and then annotation\n - pending annotation without redaction after it\n */\n return (haveRemoteReaction && (!pendingAnnotation || willAnnotate)) ||\n (!haveRemoteReaction && willAnnotate);\n }\n\n get relation() {\n return getRelationFromContent(this.content);\n }\n\n get pendingAnnotations() {\n return this._pendingAnnotations;\n }\n\n get annotations() {\n return null; //overwritten in EventEntry\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {PENDING_FRAGMENT_ID} from \"./BaseEntry\";\nimport {BaseEventEntry} from \"./BaseEventEntry.js\";\n\nexport class PendingEventEntry extends BaseEventEntry {\n constructor({pendingEvent, member, clock, redactingEntry}) {\n super(null);\n this._pendingEvent = pendingEvent;\n /** @type {RoomMember} */\n this._member = member;\n // try to come up with a timestamp that is around construction time and\n // will be roughly sorted by queueIndex, so it can be used to as a secondary\n // sorting dimension for reactions\n this._timestamp = clock.now() - (100 - pendingEvent.queueIndex);\n this._redactingEntry = redactingEntry;\n }\n\n get fragmentId() {\n return PENDING_FRAGMENT_ID;\n }\n\n get entryIndex() {\n return this._pendingEvent.queueIndex;\n }\n\n get content() {\n return this._pendingEvent.content;\n }\n\n get event() {\n return null;\n }\n\n get eventType() {\n return this._pendingEvent.eventType;\n }\n\n get stateKey() {\n return null;\n }\n\n get sender() {\n return this._member?.userId;\n }\n\n get displayName() {\n return this._member?.name;\n }\n\n get avatarUrl() {\n return this._member?.avatarUrl;\n }\n\n get timestamp() {\n return this._timestamp;\n }\n\n get isPending() {\n return true;\n }\n\n get id() {\n return this._pendingEvent.txnId;\n }\n\n get pendingEvent() {\n return this._pendingEvent;\n }\n\n notifyUpdate() {\n \n }\n\n isRelatedToId(id) {\n if (id && id === this._pendingEvent.relatedTxnId) {\n return true;\n }\n return super.isRelatedToId(id);\n }\n\n get relatedEventId() {\n return this._pendingEvent.relatedEventId;\n }\n\n get redactingEntry() {\n return this._redactingEntry;\n }\n\n get contextEventId() {\n if (this.isReply) {\n return this._pendingEvent.relatedEventId ?? this._pendingEvent.relatedTxnId;\n }\n return null;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {createEnum} from \"../../../utils/enum\";\nimport {AbortError} from \"../../../utils/error\";\nimport {REDACTION_TYPE} from \"../common\";\nimport {getRelationFromContent, getRelationTarget, setRelationTarget} from \"../timeline/relations.js\";\n\nexport const SendStatus = createEnum(\n \"Waiting\",\n \"EncryptingAttachments\",\n \"UploadingAttachments\",\n \"Encrypting\",\n \"Sending\",\n \"Sent\",\n \"Error\",\n);\n\nconst unencryptedContentFields = [ \"m.relates_to\" ];\n\nexport class PendingEvent {\n constructor({data, remove, emitUpdate, attachments}) {\n this._data = data;\n this._attachments = attachments;\n this._emitUpdate = emitUpdate;\n this._removeFromQueueCallback = remove;\n this._aborted = false;\n this._status = SendStatus.Waiting;\n this._sendRequest = null;\n this._attachmentsTotalBytes = 0;\n if (this._attachments) {\n this._attachmentsTotalBytes = Object.values(this._attachments).reduce((t, a) => t + a.size, 0);\n }\n }\n\n get roomId() { return this._data.roomId; }\n get queueIndex() { return this._data.queueIndex; }\n get eventType() { return this._data.eventType; }\n get txnId() { return this._data.txnId; }\n get remoteId() { return this._data.remoteId; }\n get content() { return this._data.content; }\n get relatedTxnId() { return this._data.relatedTxnId; }\n get relatedEventId() {\n const relation = getRelationFromContent(this.content);\n if (relation) {\n // may be null when target is not sent yet, is intended\n return getRelationTarget(relation);\n } else {\n return this._data.relatedEventId;\n }\n }\n\n setRelatedEventId(eventId) {\n const relation = getRelationFromContent(this.content);\n if (relation) {\n setRelationTarget(relation, eventId);\n } else {\n this._data.relatedEventId = eventId;\n }\n }\n\n get data() { return this._data; }\n\n getAttachment(key) {\n return this._attachments && this._attachments[key];\n }\n\n get needsSending() {\n return !this.remoteId && !this.aborted;\n }\n\n get needsEncryption() {\n return this._data.needsEncryption && !this.aborted;\n }\n\n get needsUpload() {\n return this._data.needsUpload && !this.aborted;\n }\n\n get isMissingAttachments() {\n return this.needsUpload && !this._attachments;\n }\n\n setEncrypting() {\n this._status = SendStatus.Encrypting;\n this._emitUpdate(\"status\");\n }\n\n get contentForEncryption() {\n const content = Object.assign({}, this._data.content);\n for (const field of unencryptedContentFields) {\n delete content[field];\n }\n return content;\n }\n\n _preserveContentFields(into) {\n const content = this._data.content;\n for (const field of unencryptedContentFields) {\n if (content[field] !== undefined) {\n into[field] = content[field];\n }\n }\n }\n\n setEncrypted(type, content) {\n this._preserveContentFields(content);\n this._data.encryptedEventType = type;\n this._data.encryptedContent = content;\n this._data.needsEncryption = false;\n }\n\n setError(error) {\n this._status = SendStatus.Error;\n this._error = error;\n this._emitUpdate(\"status\");\n }\n\n setWaiting() {\n this._status = SendStatus.Waiting;\n this._emitUpdate(\"status\");\n }\n\n get status() { return this._status; }\n get error() { return this._error; }\n\n get hasStartedSending() {\n return this._status === SendStatus.Sending || this._status === SendStatus.Sent;\n }\n\n get attachmentsTotalBytes() {\n return this._attachmentsTotalBytes;\n }\n\n get attachmentsSentBytes() {\n return this._attachments && Object.values(this._attachments).reduce((t, a) => t + a.sentBytes, 0);\n }\n\n async uploadAttachments(hsApi, log) {\n if (!this.needsUpload) {\n return;\n }\n if (!this._attachments) {\n throw new Error(\"attachments missing\");\n }\n if (this.needsEncryption) {\n this._status = SendStatus.EncryptingAttachments;\n this._emitUpdate(\"status\");\n for (const attachment of Object.values(this._attachments)) {\n await log.wrap(\"encrypt\", () => {\n log.set(\"size\", attachment.size);\n return attachment.encrypt();\n });\n if (this.aborted) {\n throw new AbortError();\n }\n }\n }\n this._status = SendStatus.UploadingAttachments;\n this._emitUpdate(\"status\");\n const entries = Object.entries(this._attachments);\n // upload smallest attachments first\n entries.sort(([, a1], [, a2]) => a1.size - a2.size);\n for (const [urlPath, attachment] of entries) {\n await log.wrap(\"upload\", log => {\n log.set(\"size\", attachment.size);\n return attachment.upload(hsApi, () => {\n this._emitUpdate(\"attachmentsSentBytes\");\n }, log);\n });\n attachment.applyToContent(urlPath, this.content);\n }\n this._data.needsUpload = false;\n }\n\n async abort() {\n if (!this._aborted) {\n this._aborted = true;\n if (this._attachments) {\n for (const attachment of Object.values(this._attachments)) {\n attachment.abort();\n }\n }\n this._sendRequest?.abort();\n await this._removeFromQueueCallback();\n }\n }\n\n get aborted() {\n return this._aborted;\n }\n\n async send(hsApi, log) {\n this._status = SendStatus.Sending;\n this._emitUpdate(\"status\");\n const eventType = this._data.encryptedEventType || this._data.eventType;\n const content = this._data.encryptedContent || this._data.content;\n if (eventType === REDACTION_TYPE) {\n this._sendRequest = hsApi.redact(\n this.roomId,\n this._data.relatedEventId,\n this.txnId,\n content,\n {log}\n );\n } else {\n this._sendRequest = hsApi.send(\n this.roomId,\n eventType,\n this.txnId,\n content,\n {log}\n );\n }\n const response = await this._sendRequest.response();\n this._sendRequest = null;\n // both /send and /redact have the same response format\n this._data.remoteId = response.event_id;\n log.set(\"id\", this._data.remoteId);\n this._status = SendStatus.Sent;\n this._emitUpdate(\"status\");\n }\n\n dispose() {\n if (this._attachments) {\n for (const attachment of Object.values(this._attachments)) {\n attachment.dispose();\n }\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseEventEntry} from \"./BaseEventEntry.js\";\nimport {getPrevContentFromStateEvent, isRedacted} from \"../../common\";\nimport {getRelationFromContent, getRelatedEventId} from \"../relations.js\";\n\nexport class EventEntry extends BaseEventEntry {\n constructor(eventEntry, fragmentIdComparer) {\n super(fragmentIdComparer);\n this._eventEntry = eventEntry;\n this._decryptionError = null;\n this._decryptionResult = null;\n }\n\n clone() {\n const clone = new EventEntry(this._eventEntry, this._fragmentIdComparer);\n clone.updateFrom(this);\n return clone;\n }\n\n updateFrom(other) {\n if (other._decryptionResult && !this._decryptionResult) {\n this._decryptionResult = other._decryptionResult;\n }\n if (other._decryptionError && !this._decryptionError) {\n this._decryptionError = other._decryptionError;\n }\n this._contextForEntries = other.contextForEntries;\n this._contextEntry = other.contextEntry;\n }\n\n get event() {\n return this._eventEntry.event;\n }\n\n get fragmentId() {\n return this._eventEntry.fragmentId;\n }\n\n get entryIndex() {\n return this._eventEntry.eventIndex;\n }\n\n get content() {\n return this._decryptionResult?.event?.content || this._eventEntry.event.content;\n }\n\n get prevContent() {\n // doesn't look at _decryptionResult because state events are not encrypted\n return getPrevContentFromStateEvent(this._eventEntry.event);\n }\n\n get eventType() {\n return this._decryptionResult?.event?.type || this._eventEntry.event.type;\n }\n\n get stateKey() {\n return this._eventEntry.event.state_key;\n }\n\n get sender() {\n return this._eventEntry.event.sender;\n }\n\n get displayName() {\n return this._eventEntry.displayName;\n }\n\n get avatarUrl() {\n return this._eventEntry.avatarUrl;\n }\n\n get timestamp() {\n return this._eventEntry.event.origin_server_ts;\n }\n\n get id() {\n return this._eventEntry.event.event_id;\n }\n\n setDecryptionResult(result) {\n this._decryptionResult = result;\n }\n\n get isEncrypted() {\n return this._eventEntry.event.type === \"m.room.encrypted\";\n }\n\n get isDecrypted() {\n return !!this._decryptionResult?.event;\n }\n\n get isVerified() {\n return this.isEncrypted && this._decryptionResult?.isVerified;\n }\n\n get isUnverified() {\n return this.isEncrypted && this._decryptionResult?.isUnverified;\n }\n\n setDecryptionError(err) {\n this._decryptionError = err;\n }\n\n get decryptionError() {\n return this._decryptionError;\n }\n\n get relatedEventId() {\n return getRelatedEventId(this.event);\n }\n\n get isRedacted() {\n return super.isRedacted || isRedacted(this._eventEntry.event);\n }\n\n get redactionReason() {\n const redactionEvent = this._eventEntry.event.unsigned?.redacted_because;\n if (redactionEvent) {\n return redactionEvent.content?.reason;\n }\n // fall back to local echo reason\n return super.redactionReason;\n }\n\n get annotations() {\n return this._eventEntry.annotations;\n }\n\n get relation() {\n const originalContent = this._eventEntry.event.content;\n const originalRelation = originalContent && getRelationFromContent(originalContent);\n return originalRelation || getRelationFromContent(this.content);\n }\n\n // similar to relatedEventID but only for replies\n get contextEventId() {\n if (this.isReply) {\n return this.relatedEventId;\n }\n return null;\n }\n\n}\n\nimport {withTextBody, withContent, createEvent} from \"../../../../mocks/event.js\";\nimport {Clock as MockClock} from \"../../../../mocks/Clock.js\";\nimport {PendingEventEntry} from \"./PendingEventEntry.js\";\nimport {PendingEvent} from \"../../sending/PendingEvent.js\";\nimport {createAnnotation} from \"../relations.js\";\n\nexport function tests() {\n let queueIndex = 0;\n const clock = new MockClock();\n\n function addPendingReaction(target, key) {\n queueIndex += 1;\n target.addLocalRelation(new PendingEventEntry({\n pendingEvent: new PendingEvent({data: {\n eventType: \"m.reaction\",\n content: createAnnotation(target.id, key),\n queueIndex,\n txnId: `t${queueIndex}`\n }}),\n clock\n }));\n return target;\n }\n\n function addPendingRedaction(target, key) {\n const pendingReaction = target.pendingAnnotations?.get(key)?.annotationEntry;\n let redactingEntry = pendingReaction;\n // make up a remote entry if we don't have a pending reaction and have an aggregated remote entry\n if (!pendingReaction && target.annotations[key].me) {\n redactingEntry = new EventEntry({\n event: withContent(createAnnotation(target.id, key), createEvent(\"m.reaction\", \"!def\"))\n });\n }\n queueIndex += 1;\n target.addLocalRelation(new PendingEventEntry({\n pendingEvent: new PendingEvent({data: {\n eventType: \"m.room.redaction\",\n relatedTxnId: pendingReaction ? pendingReaction.id : null,\n relatedEventId: pendingReaction ? null : redactingEntry.id,\n queueIndex,\n txnId: `t${queueIndex}`\n }}),\n redactingEntry,\n clock\n }));\n return target;\n }\n\n function remoteAnnotation(key, me, count, obj = {}) {\n obj[key] = {me, count};\n return obj;\n }\n\n return {\n // testing it here because parent class always assumes annotations is null\n \"haveAnnotation\": assert => {\n const msgEvent = withTextBody(\"hi!\", createEvent(\"m.room.message\", \"!abc\"));\n const e1 = new EventEntry({event: msgEvent});\n assert.equal(false, e1.haveAnnotation(\"🚀\"));\n const e2 = new EventEntry({event: msgEvent, annotations: remoteAnnotation(\"🚀\", false, 1)});\n assert.equal(false, e2.haveAnnotation(\"🚀\"));\n const e3 = new EventEntry({event: msgEvent, annotations: remoteAnnotation(\"🚀\", true, 1)});\n assert.equal(true, e3.haveAnnotation(\"🚀\"));\n const e4 = new EventEntry({event: msgEvent, annotations: remoteAnnotation(\"🚀\", true, 2)});\n assert.equal(true, e4.haveAnnotation(\"🚀\"));\n const e5 = addPendingReaction(new EventEntry({event: msgEvent}), \"🚀\");\n assert.equal(true, e5.haveAnnotation(\"🚀\"));\n const e6 = addPendingRedaction(new EventEntry({event: msgEvent, annotations: remoteAnnotation(\"🚀\", true, 1)}), \"🚀\");\n assert.equal(false, e6.haveAnnotation(\"🚀\"));\n const e7 = addPendingReaction(\n addPendingRedaction(\n new EventEntry({event: msgEvent, annotations: remoteAnnotation(\"🚀\", true, 1)}),\n \"🚀\"),\n \"🚀\");\n assert.equal(true, e7.haveAnnotation(\"🚀\"));\n const e8 = addPendingRedaction(\n addPendingReaction(\n new EventEntry({event: msgEvent}),\n \"🚀\"),\n \"🚀\");\n assert.equal(false, e8.haveAnnotation(\"🚀\"));\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function createEventEntry(key, roomId, event) {\n return {\n fragmentId: key.fragmentId,\n eventIndex: key.eventIndex,\n roomId,\n event: event,\n };\n}\n\nexport function directionalAppend(array, value, direction) {\n if (direction.isForward) {\n array.push(value);\n } else {\n array.unshift(value);\n }\n}\n\nexport function directionalConcat(array, otherArray, direction) {\n if (direction.isForward) {\n return array.concat(otherArray);\n } else {\n return otherArray.concat(array);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {getPrevContentFromStateEvent} from \"../common\";\n\nexport const EVENT_TYPE = \"m.room.member\";\n\nexport class RoomMember {\n constructor(data) {\n this._data = data;\n }\n\n static fromUserId(roomId, userId, membership) {\n return new RoomMember({roomId, userId, membership});\n }\n\n static fromMemberEvent(roomId, memberEvent) {\n const userId = memberEvent?.state_key;\n if (typeof userId !== \"string\") {\n return;\n }\n const content = memberEvent.content;\n const prevContent = getPrevContentFromStateEvent(memberEvent);\n const membership = content?.membership;\n // fall back to prev_content for these as synapse doesn't (always?)\n // put them on content for \"leave\" memberships\n const displayName = content?.displayname || prevContent?.displayname;\n const avatarUrl = content?.avatar_url || prevContent?.avatar_url;\n return this._validateAndCreateMember(roomId, userId, membership, displayName, avatarUrl);\n }\n /**\n * Creates a (historical) member from a member event that is the next member event\n * after the point in time where we need a member for. This will use `prev_content`.\n */\n static fromReplacingMemberEvent(roomId, memberEvent) {\n const userId = memberEvent && memberEvent.state_key;\n if (typeof userId !== \"string\") {\n return;\n }\n const content = getPrevContentFromStateEvent(memberEvent);\n return this._validateAndCreateMember(roomId, userId,\n content?.membership,\n content?.displayname,\n content?.avatar_url\n );\n }\n\n static _validateAndCreateMember(roomId, userId, membership, displayName, avatarUrl) {\n if (typeof membership !== \"string\") {\n return;\n }\n return new RoomMember({\n roomId,\n userId,\n membership,\n avatarUrl,\n displayName,\n });\n }\n\n get membership() {\n return this._data.membership;\n }\n\n /**\n * @return {String?} the display name, if any\n */\n get displayName() {\n return this._data.displayName;\n }\n\n /**\n * @return {String} the display name or userId\n */\n get name() {\n return this._data.displayName || this._data.userId;\n }\n\n /**\n * @return {String?} the avatar mxc url, if any\n */\n get avatarUrl() {\n return this._data.avatarUrl;\n }\n\n get roomId() {\n return this._data.roomId;\n }\n\n get userId() {\n return this._data.userId;\n }\n\n serialize() {\n return this._data;\n }\n\n equals(other) {\n const data = this._data;\n const otherData = other._data;\n return data.roomId === otherData.roomId &&\n data.userId === otherData.userId &&\n data.membership === otherData.membership &&\n data.displayName === otherData.displayName &&\n data.avatarUrl === otherData.avatarUrl;\n }\n}\n\nexport class MemberChange {\n constructor(member, previousMembership) {\n this.member = member;\n this.previousMembership = previousMembership;\n }\n\n get roomId() {\n return this.member.roomId;\n }\n\n get userId() {\n return this.member.userId;\n }\n\n get membership() {\n return this.member.membership;\n }\n\n get wasInvited() {\n return this.previousMembership === \"invite\" && this.membership !== \"invite\";\n }\n\n get hasLeft() {\n return this.previousMembership === \"join\" && this.membership !== \"join\";\n }\n\n /** The result can be a false negative when all of these apply:\n * - the complete set of room members hasn't been fetched yet.\n * - the member event for this change was received in the\n * state section and wasn't present in the timeline section.\n * - the room response was limited, e.g. there was a gap.\n * \n * This is because during sync, in this case it is not possible\n * to distinguish between a new member that joined the room\n * during a gap and a lazy-loading member.\n * */\n get hasJoined() {\n return this.previousMembership !== \"join\" && this.membership === \"join\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function isValidFragmentId(id) {\n return typeof id === \"number\";\n}\n\n// copied over from matrix-js-sdk, copyright 2016 OpenMarket Ltd\n/* _REDACT_KEEP_KEY_MAP gives the keys we keep when an event is redacted\n *\n * This is specified here:\n * http://matrix.org/speculator/spec/HEAD/client_server/latest.html#redactions\n *\n * Also:\n * - We keep 'unsigned' since that is created by the local server\n * - We keep user_id for backwards-compat with v1\n */\nconst _REDACT_KEEP_KEY_MAP = [\n 'event_id', 'type', 'room_id', 'user_id', 'sender', 'state_key', 'prev_state',\n 'content', 'unsigned', 'origin_server_ts',\n].reduce(function(ret, val) {\n ret[val] = 1; return ret;\n}, {});\n\n// a map from event type to the .content keys we keep when an event is redacted\nconst _REDACT_KEEP_CONTENT_MAP = {\n 'm.room.member': {'membership': 1},\n 'm.room.create': {'creator': 1},\n 'm.room.join_rules': {'join_rule': 1},\n 'm.room.power_levels': {'ban': 1, 'events': 1, 'events_default': 1,\n 'kick': 1, 'redact': 1, 'state_default': 1,\n 'users': 1, 'users_default': 1,\n },\n 'm.room.aliases': {'aliases': 1},\n};\n// end of matrix-js-sdk code\n\nexport function redactEvent(redactionEvent, redactedEvent) {\n for (const key of Object.keys(redactedEvent)) {\n if (!_REDACT_KEEP_KEY_MAP[key]) {\n delete redactedEvent[key];\n }\n }\n const { content } = redactedEvent;\n const keepMap = _REDACT_KEEP_CONTENT_MAP[redactedEvent.type];\n for (const key of Object.keys(content)) {\n if (!keepMap?.[key]) {\n delete content[key];\n }\n }\n redactedEvent.unsigned = redactedEvent.unsigned || {};\n redactedEvent.unsigned.redacted_because = redactionEvent;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nlookups will be far more frequent than changing fragment order,\nso data structure should be optimized for fast lookup\n\nwe can have a Map: fragmentId to sortIndex\n\nchanging the order, we would need to rebuild the index\nlets do this the stupid way for now, changing any fragment rebuilds all islands\n\nto build this:\nfirst load all fragments\nput them in a map by id\nnow iterate through them\n\nuntil no more fragments\n get the first\n create an island array, and add to list with islands\n going backwards and forwards\n get and remove sibling and prepend/append it to island array\n stop when no more previous/next\n return list with islands\n\n*/\n\nimport {isValidFragmentId} from \"./common.js\";\n\nfunction findBackwardSiblingFragments(current, byId) {\n const sortedSiblings = [];\n while (isValidFragmentId(current.previousId)) {\n const previous = byId.get(current.previousId);\n if (!previous) {\n break;\n }\n if (previous.nextId !== current.id) {\n throw new Error(`Previous fragment ${previous.id} doesn't point back to ${current.id}`);\n }\n byId.delete(current.previousId);\n sortedSiblings.unshift(previous);\n current = previous;\n }\n return sortedSiblings;\n}\n\nfunction findForwardSiblingFragments(current, byId) {\n const sortedSiblings = [];\n while (isValidFragmentId(current.nextId)) {\n const next = byId.get(current.nextId);\n if (!next) {\n break;\n }\n if (next.previousId !== current.id) {\n throw new Error(`Next fragment ${next.id} doesn't point back to ${current.id}`);\n }\n byId.delete(current.nextId);\n sortedSiblings.push(next);\n current = next;\n }\n return sortedSiblings;\n}\n\n\nfunction createIslands(fragments) {\n const byId = new Map();\n for(let f of fragments) {\n byId.set(f.id, f);\n }\n\n const islands = [];\n while(byId.size) {\n const current = byId.values().next().value;\n byId.delete(current.id);\n // new island\n const previousSiblings = findBackwardSiblingFragments(current, byId);\n const nextSiblings = findForwardSiblingFragments(current, byId);\n const island = previousSiblings.concat(current, nextSiblings);\n islands.push(island);\n }\n return islands.map(a => new Island(a));\n}\n\nclass Fragment {\n constructor(id, previousId, nextId) {\n this.id = id;\n this.previousId = previousId;\n this.nextId = nextId;\n }\n}\n\nclass Island {\n constructor(sortedFragments) {\n this._idToSortIndex = new Map();\n sortedFragments.forEach((f, i) => {\n this._idToSortIndex.set(f.id, i);\n });\n }\n\n compare(idA, idB) {\n const sortIndexA = this._idToSortIndex.get(idA);\n if (sortIndexA === undefined) {\n throw new Error(`first id ${idA} isn't part of this island`);\n }\n const sortIndexB = this._idToSortIndex.get(idB);\n if (sortIndexB === undefined) {\n throw new Error(`second id ${idB} isn't part of this island`);\n }\n return sortIndexA - sortIndexB;\n }\n\n get fragmentIds() {\n return this._idToSortIndex.keys();\n }\n}\n\nexport class CompareError extends Error {\n get name() { return \"CompareError\"; }\n}\n\n/*\nindex for fast lookup of how two fragments can be sorted\n*/\nexport class FragmentIdComparer {\n constructor(fragments) {\n this._fragmentsById = fragments.reduce((map, f) => {map.set(f.id, f); return map;}, new Map());\n this.rebuild(fragments);\n }\n\n _getIsland(id) {\n const island = this._idToIsland.get(id);\n if (island === undefined) {\n throw new CompareError(`Unknown fragment id ${id}`);\n }\n return island;\n }\n\n compare(idA, idB) {\n if (idA === idB) {\n return 0;\n }\n const islandA = this._getIsland(idA);\n const islandB = this._getIsland(idB);\n if (islandA !== islandB) {\n throw new CompareError(`${idA} and ${idB} are on different islands, can't tell order`);\n }\n return islandA.compare(idA, idB);\n }\n\n rebuild(fragments) {\n const islands = createIslands(fragments);\n this._idToIsland = new Map();\n for(let island of islands) {\n for(let id of island.fragmentIds) {\n this._idToIsland.set(id, island);\n }\n }\n }\n\n /** use for fragments coming out of persistence, not newly created ones, or also fragments for a new island (like for a permalink) */\n add(fragment) {\n const copy = new Fragment(fragment.id, fragment.previousId, fragment.nextId);\n this._fragmentsById.set(fragment.id, copy);\n this.rebuild(this._fragmentsById.values());\n }\n\n /** use for appending newly created fragments */\n append(id, previousId) {\n const fragment = new Fragment(id, previousId, null);\n const prevFragment = this._fragmentsById.get(previousId);\n if (prevFragment) {\n prevFragment.nextId = id;\n }\n this._fragmentsById.set(id, fragment);\n this.rebuild(this._fragmentsById.values());\n }\n\n /** use for prepending newly created fragments */\n prepend(id, nextId) {\n const fragment = new Fragment(id, null, nextId);\n const nextFragment = this._fragmentsById.get(nextId);\n if (nextFragment) {\n nextFragment.previousId = id;\n }\n this._fragmentsById.set(id, fragment);\n this.rebuild(this._fragmentsById.values());\n }\n}\n\nexport function tests() {\n return {\n test_1_island_3_fragments(assert) {\n const index = new FragmentIdComparer([\n {id: 3, previousId: 2},\n {id: 1, nextId: 2},\n {id: 2, nextId: 3, previousId: 1},\n ]);\n assert(index.compare(1, 2) < 0);\n assert(index.compare(2, 1) > 0);\n\n assert(index.compare(1, 3) < 0);\n assert(index.compare(3, 1) > 0);\n \n assert(index.compare(2, 3) < 0);\n assert(index.compare(3, 2) > 0);\n \n assert.equal(index.compare(1, 1), 0);\n },\n test_falsy_id(assert) {\n const index = new FragmentIdComparer([\n {id: 0, nextId: 1},\n {id: 1, previousId: 0},\n ]);\n assert(index.compare(0, 1) < 0);\n assert(index.compare(1, 0) > 0);\n },\n test_falsy_id_reverse(assert) {\n const index = new FragmentIdComparer([\n {id: 1, previousId: 0},\n {id: 0, nextId: 1},\n ]);\n assert(index.compare(0, 1) < 0);\n assert(index.compare(1, 0) > 0);\n },\n test_allow_unknown_id(assert) {\n // as we tend to load fragments incrementally\n // as events come into view, we need to allow\n // unknown previousId/nextId in the fragments that we do load\n assert.doesNotThrow(() => {\n new FragmentIdComparer([\n {id: 1, previousId: 2},\n {id: 0, nextId: 3},\n ]);\n });\n },\n test_throw_on_link_mismatch(assert) {\n // as we tend to load fragments incrementally\n // as events come into view, we need to allow\n // unknown previousId/nextId in the fragments that we do load\n assert.throws(() => {\n new FragmentIdComparer([\n {id: 1, previousId: 0},\n {id: 0, nextId: 2},\n ]);\n });\n },\n test_2_island_dont_compare(assert) {\n const index = new FragmentIdComparer([\n {id: 1},\n {id: 2},\n ]);\n assert.throws(() => index.compare(1, 2));\n assert.throws(() => index.compare(2, 1));\n },\n test_2_island_compare_internally(assert) {\n const index = new FragmentIdComparer([\n {id: 1, nextId: 2},\n {id: 2, previousId: 1},\n {id: 11, nextId: 12},\n {id: 12, previousId: 11},\n \n ]);\n\n assert(index.compare(1, 2) < 0);\n assert(index.compare(11, 12) < 0);\n \n assert.throws(() => index.compare(1, 11));\n assert.throws(() => index.compare(12, 2));\n },\n test_unknown_id(assert) {\n const index = new FragmentIdComparer([{id: 1}]);\n assert.throws(() => index.compare(1, 2));\n assert.throws(() => index.compare(2, 1));\n },\n test_rebuild_flushes_old_state(assert) {\n const index = new FragmentIdComparer([\n {id: 1, nextId: 2},\n {id: 2, previousId: 1},\n ]);\n index.rebuild([\n {id: 11, nextId: 12},\n {id: 12, previousId: 11},\n ]);\n \n assert.throws(() => index.compare(1, 2));\n assert(index.compare(11, 12) < 0);\n },\n test_append(assert) {\n const index = new FragmentIdComparer([]);\n // add livefragment when opening timeline,\n // note that there is no nextId as the sync\n // hasn't come in yet\n index.add({id: 1});\n // now sync comes in and replaces the live fragment\n index.append(2, 1);\n assert(index.compare(1, 2) < 0);\n },\n test_prepend(assert) {\n const index = new FragmentIdComparer([]);\n index.add({id: 2});\n index.prepend(1, 2);\n assert(index.compare(1, 2) < 0);\n }\n }\n}\n","const scriptRel = (function detectScriptRel() {\n // @ts-ignore\n const relList = document.createElement('link').relList;\n // @ts-ignore\n return relList && relList.supports && relList.supports('modulepreload')\n ? 'modulepreload'\n : 'preload';\n})();const seen = {};const base = './';export const __vitePreload = function preload(baseModule, deps) {\n // @ts-ignore\n if (!__VITE_IS_MODERN__ || !deps || deps.length === 0) {\n return baseModule();\n }\n return Promise.all(deps.map((dep) => {\n // @ts-ignore\n dep = `${base}${dep}`;\n // @ts-ignore\n if (dep in seen)\n return;\n // @ts-ignore\n seen[dep] = true;\n const isCss = dep.endsWith('.css');\n const cssSelector = isCss ? '[rel=\"stylesheet\"]' : '';\n // @ts-ignore check if the file is already preloaded by SSR markup\n if (document.querySelector(`link[href=\"${dep}\"]${cssSelector}`)) {\n return;\n }\n // @ts-ignore\n const link = document.createElement('link');\n // @ts-ignore\n link.rel = isCss ? 'stylesheet' : scriptRel;\n if (!isCss) {\n link.as = 'script';\n link.crossOrigin = '';\n }\n link.href = dep;\n // @ts-ignore\n document.head.appendChild(link);\n if (isCss) {\n return new Promise((res, rej) => {\n link.addEventListener('load', res);\n link.addEventListener('error', () => rej(new Error(`Unable to preload CSS for ${dep}`)));\n });\n }\n })).then(() => baseModule());\n}","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { StorageError } from \"../common\";\n\nfunction _sourceName(source: IDBIndex | IDBObjectStore): string {\n return \"objectStore\" in source ?\n `${source.objectStore.name}.${source.name}` :\n source.name;\n}\n\nfunction _sourceDatabase(source: IDBIndex | IDBObjectStore): string {\n return \"objectStore\" in source ?\n source.objectStore?.transaction?.db?.name :\n source.transaction?.db?.name;\n}\n\nexport class IDBError extends StorageError {\n storeName: string;\n databaseName: string;\n\n constructor(message: string, sourceOrCursor: IDBIndex | IDBCursor | IDBObjectStore | null, cause: DOMException | null = null) {\n const source = (sourceOrCursor && \"source\" in sourceOrCursor) ? sourceOrCursor.source : sourceOrCursor;\n const storeName = source ? _sourceName(source) : \"\";\n const databaseName = source ? _sourceDatabase(source) : \"\";\n let fullMessage = `${message} on ${databaseName}.${storeName}`;\n if (cause) {\n fullMessage += \": \";\n if (typeof cause.name === \"string\") {\n fullMessage += `(name: ${cause.name}) `;\n }\n if (typeof cause.code === \"number\") {\n fullMessage += `(code: ${cause.code}) `;\n }\n }\n if (cause) {\n fullMessage += cause.message;\n }\n super(fullMessage, cause);\n this.storeName = storeName;\n this.databaseName = databaseName;\n }\n}\n\nexport class IDBRequestError extends IDBError {\n private errorEvent: Event;\n\n constructor(errorEvent: Event) {\n const request = errorEvent.target as IDBRequest;\n const source = request.source;\n const cause = request.error;\n super(\"IDBRequest failed\", source, cause);\n this.errorEvent = errorEvent;\n }\n\n preventTransactionAbort() {\n this.errorEvent.preventDefault();\n }\n}\n\nexport class IDBRequestAttemptError extends IDBError {\n constructor(method: string, source: IDBIndex | IDBObjectStore, cause: DOMException, params: any[]) {\n super(`${method}(${params.map(p => JSON.stringify(p)).join(\", \")}) failed`, source, cause);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { IDBRequestError } from \"./error\";\nimport { StorageError } from \"../common\";\nimport { AbortError } from \"../../../utils/error\";\n\nlet needsSyncPromise = false;\n\nexport const DONE = { done: true }\nexport const NOT_DONE = { done: false }\n\n/* should be called on legacy platforms to see\n if transactions close before draining the microtask queue (IE11 on Windows 7).\n If this is the case, promises need to be resolved\n synchronously from the idb request handler to prevent the transaction from closing prematurely.\n*/\nexport async function checkNeedsSyncPromise(): Promise {\n // important to have it turned off while doing the test,\n // otherwise reqAsPromise would not fail\n needsSyncPromise = false;\n const NAME = \"test-idb-needs-sync-promise\";\n const db = await openDatabase(NAME, db => {\n db.createObjectStore(\"test\", {keyPath: \"key\"});\n }, 1);\n const txn = db.transaction(\"test\", \"readonly\");\n try {\n await reqAsPromise(txn.objectStore(\"test\").get(1));\n await reqAsPromise(txn.objectStore(\"test\").get(2));\n } catch (err) {\n // err.name would be either TransactionInactiveError or InvalidStateError,\n // but let's not exclude any other failure modes\n needsSyncPromise = true;\n }\n // we could delete the store here, \n // but let's not create it on every page load on legacy platforms,\n // and just keep it around\n return needsSyncPromise;\n}\n\n// storage keys are defined to be unsigned 32bit numbers in KeyLimits, which is assumed by idb\nexport function encodeUint32(n: number): string {\n const hex = n.toString(16);\n return \"0\".repeat(8 - hex.length) + hex;\n}\n\n// used for logs where timestamp is part of key, which is larger than 32 bit\nexport function encodeUint64(n: number): string {\n const hex = n.toString(16);\n return \"0\".repeat(16 - hex.length) + hex;\n}\n\nexport function decodeUint32(str: string): number {\n return parseInt(str, 16);\n}\n\nexport type CreateObjectStore = (db : IDBDatabase, txn: IDBTransaction | null, oldVersion: number, version: number) => any\n\nexport function openDatabase(name: string, createObjectStore: CreateObjectStore, version: number, idbFactory: IDBFactory = window.indexedDB): Promise {\n const req = idbFactory.open(name, version);\n req.onupgradeneeded = async (ev : IDBVersionChangeEvent) => {\n const req = ev.target as IDBRequest;\n const db = req.result;\n const txn = req.transaction!;\n const oldVersion = ev.oldVersion;\n try {\n await createObjectStore(db, txn, oldVersion, version);\n } catch (err) {\n // try aborting on error, if that hasn't been done already\n try {\n txn.abort();\n } catch (err) {}\n }\n }; \n return reqAsPromise(req);\n}\n\nexport function reqAsPromise(req: IDBRequest): Promise {\n return new Promise((resolve, reject) => {\n req.addEventListener(\"success\", event => {\n resolve((event.target as IDBRequest).result);\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n });\n req.addEventListener(\"error\", event => {\n const error = new IDBRequestError(event);\n reject(error);\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n });\n });\n}\n\nexport function txnAsPromise(txn): Promise {\n let error;\n return new Promise((resolve, reject) => {\n txn.addEventListener(\"complete\", () => {\n resolve();\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n });\n txn.addEventListener(\"abort\", event => {\n reject(new AbortError());\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n });\n });\n}\n\n/**\n * This type is rather complicated, but I hope that this is for a good reason. There\n * are currently two uses for `iterateCursor`: iterating a regular cursor, and iterating\n * a key-only cursor, which does not have values. These two uses are distinct, and iteration\n * never stops or starts having a value halfway through.\n *\n * Each of the argument functions currently either assumes the value will be there, or that it won't. We thus can't\n * just accept a function argument `(T | undefined) => { done: boolean }`, since this messes with\n * the type safety in both cases: the former case will have to check for `undefined`, and\n * the latter would have an argument that can be `T`, even though it never will.\n *\n * So the approach here is to let TypeScript infer and accept (via generics) the type of\n * the cursor, which is either `IDBCursorWithValue` or `IDBCursor`. Since the type is accepted\n * via generics, we can actually vary the types of the actual function arguments depending on it.\n * Thus, when a value is available (an `IDBCursorWithValue` is given), we require a function `(T) => ...`, and when it is not, we require\n * a function `(undefined) => ...`.\n */\ntype CursorIterator = (value: I extends IDBCursorWithValue ? T : undefined, key: IDBValidKey, cursor: I) => { done: boolean, jumpTo?: IDBValidKey }\n\nexport function iterateCursor(cursorRequest: IDBRequest, processValue: CursorIterator): Promise {\n // TODO: does cursor already have a value here??\n return new Promise((resolve, reject) => {\n cursorRequest.onerror = event => {\n reject(new IDBRequestError(event));\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n };\n // collect results\n cursorRequest.onsuccess = (event) => {\n const cursor = (event.target as IDBRequest).result;\n if (!cursor) {\n resolve(false);\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n return; // end of results\n }\n const result = processValue(cursor[\"value\"], cursor.key, cursor);\n // TODO: don't use object for result and assume it's jumpTo when not === true/false or undefined\n const done = result?.done;\n const jumpTo = result?.jumpTo;\n\n if (done) {\n resolve(true);\n // @ts-ignore\n needsSyncPromise && Promise._flush && Promise._flush();\n } else if(jumpTo) {\n cursor.continue(jumpTo);\n } else {\n cursor.continue();\n }\n };\n }).catch(err => {\n throw new StorageError(\"iterateCursor failed\", err);\n });\n}\n\ntype Pred = (value: T) => boolean\n\nexport async function fetchResults(cursor: IDBRequest, isDone: Pred): Promise {\n const results: T[] = [];\n await iterateCursor(cursor, (value) => {\n results.push(value);\n return {done: isDone(results)};\n });\n return results;\n}\n\ntype ToCursor = (store: IDBObjectStore) => IDBRequest\n\nexport async function select(db: IDBDatabase, storeName: string, toCursor: ToCursor, isDone: Pred): Promise {\n if (!isDone) {\n isDone = () => false;\n }\n if (!toCursor) {\n toCursor = store => store.openCursor();\n }\n const tx = db.transaction([storeName], \"readonly\");\n const store = tx.objectStore(storeName);\n const cursor = toCursor(store);\n return await fetchResults(cursor, isDone);\n}\n\nexport async function findStoreValue(db: IDBDatabase, storeName: string, toCursor: ToCursor, matchesValue: Pred): Promise {\n if (!matchesValue) {\n matchesValue = () => true;\n }\n if (!toCursor) {\n toCursor = store => store.openCursor();\n }\n\n const tx = db.transaction([storeName], \"readwrite\");\n const store = tx.objectStore(storeName);\n const cursor = await reqAsPromise(toCursor(store));\n let match;\n const matched = await iterateCursor(cursor, (value) => {\n if (matchesValue(value)) {\n match = value;\n return DONE;\n }\n return NOT_DONE;\n });\n if (!matched) {\n throw new StorageError(\"Value not found\");\n }\n return match;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {iterateCursor, DONE, NOT_DONE, reqAsPromise} from \"./utils\";\nimport {StorageError} from \"../common\";\nimport {ILogItem} from \"../../../logging/types\";\nimport {IDBKey} from \"./Transaction\";\n\n// this is the part of the Transaction class API that is used here and in the Store subclass,\n// to make it easier to replace it with alternative implementations in schema.ts and unit tests\nexport interface ITransaction {\n idbFactory: IDBFactory;\n IDBKeyRange: typeof IDBKeyRange;\n databaseName: string;\n addWriteError(error: StorageError, refItem: ILogItem | undefined, operationName: string, keys: IDBKey[] | undefined);\n}\n\ntype Reducer = (acc: B, val: A) => B\n\nexport type IDBQuery = IDBValidKey | IDBKeyRange | undefined | null\n\ninterface QueryTargetInterface {\n openCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest;\n openKeyCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest;\n supports(method: string): boolean;\n keyPath: string | string[];\n count(keyRange?: IDBKeyRange): IDBRequest;\n get(key: IDBValidKey | IDBKeyRange): IDBRequest;\n getKey(key: IDBValidKey | IDBKeyRange): IDBRequest;\n}\n\nexport class QueryTarget {\n protected _target: QueryTargetInterface;\n protected _transaction: ITransaction;\n\n constructor(target: QueryTargetInterface, transaction: ITransaction) {\n this._target = target;\n this._transaction = transaction;\n }\n\n get idbFactory(): IDBFactory {\n return this._transaction.idbFactory;\n }\n\n get IDBKeyRange(): typeof IDBKeyRange {\n return this._transaction.IDBKeyRange;\n }\n\n get databaseName(): string {\n return this._transaction.databaseName;\n }\n\n _openCursor(range?: IDBQuery, direction?: IDBCursorDirection): IDBRequest {\n if (range && direction) {\n return this._target.openCursor(range, direction);\n } else if (range) {\n return this._target.openCursor(range);\n } else if (direction) {\n return this._target.openCursor(null, direction);\n } else {\n return this._target.openCursor();\n }\n }\n\n supports(methodName: string): boolean {\n return this._target.supports(methodName);\n }\n\n count(keyRange?: IDBKeyRange): Promise {\n return reqAsPromise(this._target.count(keyRange));\n }\n\n get(key: IDBValidKey | IDBKeyRange): Promise {\n return reqAsPromise(this._target.get(key));\n }\n\n getKey(key: IDBValidKey | IDBKeyRange): Promise {\n if (this._target.supports(\"getKey\")) {\n return reqAsPromise(this._target.getKey(key));\n } else {\n return reqAsPromise(this._target.get(key)).then(value => {\n if (value) {\n let keyPath = this._target.keyPath;\n if (typeof keyPath === \"string\") {\n keyPath = [keyPath];\n }\n return keyPath.reduce((obj, key) => obj[key], value);\n }\n });\n }\n }\n\n reduce(range: IDBQuery, reducer: Reducer, initialValue: B): Promise {\n return this._reduce(range, reducer, initialValue, \"next\");\n }\n\n reduceReverse(range: IDBQuery, reducer: Reducer, initialValue: B): Promise {\n return this._reduce(range, reducer, initialValue, \"prev\");\n }\n \n selectLimit(range: IDBQuery, amount: number): Promise {\n return this._selectLimit(range, amount, \"next\");\n }\n\n selectLimitReverse(range: IDBQuery, amount: number): Promise {\n return this._selectLimit(range, amount, \"prev\");\n }\n\n selectWhile(range: IDBQuery, predicate: (v: T) => boolean): Promise {\n return this._selectWhile(range, predicate, \"next\");\n }\n\n selectWhileReverse(range: IDBQuery, predicate: (v: T) => boolean): Promise {\n return this._selectWhile(range, predicate, \"prev\");\n }\n\n async selectAll(range?: IDBQuery, direction?: IDBCursorDirection): Promise {\n const cursor = this._openCursor(range, direction);\n const results: T[] = [];\n await iterateCursor(cursor, (value) => {\n results.push(value);\n return NOT_DONE;\n });\n return results;\n }\n\n selectFirst(range: IDBQuery): Promise {\n return this._find(range, () => true, \"next\");\n }\n\n selectLast(range: IDBQuery): Promise {\n return this._find(range, () => true, \"prev\");\n }\n\n find(range: IDBQuery, predicate: (v: T) => boolean): Promise {\n return this._find(range, predicate, \"next\");\n }\n\n findReverse(range: IDBQuery, predicate: (v : T) => boolean): Promise {\n return this._find(range, predicate, \"prev\");\n }\n\n async findMaxKey(range: IDBQuery): Promise {\n const cursor = this._target.openKeyCursor(range, \"prev\");\n let maxKey;\n await iterateCursor(cursor, (_, key) => {\n maxKey = key;\n return DONE;\n });\n return maxKey;\n }\n\n\n async iterateValues(range: IDBQuery, callback: (val: T, key: IDBValidKey, cur: IDBCursorWithValue) => boolean): Promise {\n const cursor = this._target.openCursor(range, \"next\");\n await iterateCursor(cursor, (value, key, cur) => {\n return {done: callback(value, key, cur)};\n });\n }\n\n async iterateKeys(range: IDBQuery, callback: (key: IDBValidKey, cur: IDBCursor) => boolean): Promise {\n const cursor = this._target.openKeyCursor(range, \"next\");\n await iterateCursor(cursor, (_, key, cur) => {\n return {done: callback(key, cur)};\n });\n }\n\n /**\n * Checks if a given set of keys exist.\n * If the callback returns true, the search is halted and callback won't be called again.\n */\n async findExistingKeys(keys: IDBValidKey[], backwards: boolean, callback: (key: IDBValidKey, pk: IDBValidKey) => boolean): Promise {\n const compareKeys = (a, b) => backwards ? -this.idbFactory.cmp(a, b) : this.idbFactory.cmp(a, b);\n const sortedKeys = keys.slice().sort(compareKeys);\n const firstKey = sortedKeys[0];\n const lastKey = sortedKeys[sortedKeys.length - 1];\n const direction = backwards ? \"prev\" : \"next\";\n const cursor = this._target.openKeyCursor(this.IDBKeyRange.bound(firstKey, lastKey), direction);\n let index = 0;\n await iterateCursor(cursor, (value, key, cursor) => {\n while (index < sortedKeys.length && compareKeys(sortedKeys[index], key) < 0) {\n index += 1;\n }\n let done = false;\n if (sortedKeys[index] === key) {\n const pk = cursor.primaryKey;\n done = callback(key, pk);\n index += 1;\n }\n if (done || index >= sortedKeys.length) {\n return DONE;\n } else {\n return {\n done: false,\n jumpTo: sortedKeys[index],\n }\n }\n });\n }\n\n _reduce(range: IDBQuery, reducer: (reduced: B, value: T) => B, initialValue: B, direction: IDBCursorDirection): Promise {\n let reducedValue = initialValue;\n const cursor = this._openCursor(range, direction);\n return iterateCursor(cursor, (value) => {\n reducedValue = reducer(reducedValue, value);\n return NOT_DONE;\n });\n }\n\n _selectLimit(range: IDBQuery, amount: number, direction: IDBCursorDirection): Promise {\n return this._selectUntil(range, (results) => {\n return results.length === amount;\n }, direction);\n }\n\n async _selectUntil(range: IDBQuery, predicate: (vs: T[], v: T) => boolean, direction: IDBCursorDirection): Promise {\n const cursor = this._openCursor(range, direction);\n const results: T[] = [];\n await iterateCursor(cursor, (value) => {\n results.push(value);\n return {done: predicate(results, value)};\n });\n return results;\n }\n\n // allows you to fetch one too much that won't get added when the predicate fails\n async _selectWhile(range: IDBQuery, predicate: (v: T) => boolean, direction: IDBCursorDirection): Promise {\n const cursor = this._openCursor(range, direction);\n const results: T[] = [];\n await iterateCursor(cursor, (value) => {\n const passesPredicate = predicate(value);\n if (passesPredicate) {\n results.push(value);\n }\n return {done: !passesPredicate};\n });\n return results;\n }\n\n async iterateWhile(range: IDBQuery, predicate: (v: T) => boolean): Promise {\n const cursor = this._openCursor(range, \"next\");\n await iterateCursor(cursor, (value) => {\n const passesPredicate = predicate(value);\n return {done: !passesPredicate};\n });\n }\n\n async _find(range: IDBQuery, predicate: (v: T) => boolean, direction: IDBCursorDirection): Promise {\n const cursor = this._openCursor(range, direction);\n let result;\n const found = await iterateCursor(cursor, (value) => {\n const found = predicate(value);\n if (found) {\n result = value;\n }\n return {done: found};\n });\n if (found) {\n return result;\n }\n }\n}\n\nimport {createMockDatabase, createMockIDBFactory, getMockIDBKeyRange} from \"../../../mocks/Storage\";\nimport {txnAsPromise} from \"./utils\";\nimport {QueryTargetWrapper, Store} from \"./Store\";\n\nexport async function tests() {\n\n class MockTransaction {\n constructor(public readonly idbFactory: IDBFactory, readonly idbKeyRangeType: typeof IDBKeyRange) {}\n\n get IDBKeyRange(): typeof IDBKeyRange {\n return this.idbKeyRangeType;\n }\n get databaseName(): string { return \"mockdb\"; }\n addWriteError(error: StorageError, refItem: ILogItem | undefined, operationName: string, keys: IDBKey[] | undefined) {}\n }\n\n interface TestEntry {\n key: string\n }\n\n async function createTestStore(): Promise> {\n const idbFactory = await createMockIDBFactory();\n const idbKeyRangeType = await getMockIDBKeyRange();\n const mockImpl = new MockTransaction(idbFactory, idbKeyRangeType);\n const db = await createMockDatabase(\"findExistingKeys\", (db: IDBDatabase) => {\n db.createObjectStore(\"test\", {keyPath: \"key\"});\n }, idbFactory);\n const txn = db.transaction([\"test\"], \"readwrite\");\n return new Store(txn.objectStore(\"test\"), mockImpl);\n }\n\n return {\n \"findExistingKeys should not match on empty store\": async assert => {\n const store = await createTestStore();\n await store.findExistingKeys([\"2db1a709-d8f1-4c40-a835-f312badd277a\", \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"], false, () => {\n assert.fail(\"no key should match\");\n return false;\n });\n },\n \"findExistingKeys should not match any existing keys (in between sorting order)\": async assert => {\n const store = await createTestStore();\n store.add({key: \"43cd16eb-a6b4-4b9d-ab36-ab87d1b038c3\"});\n store.add({key: \"b655e7c5-e02d-4823-a7af-4202b12de659\"});\n await store.findExistingKeys([\"2db1a709-d8f1-4c40-a835-f312badd277a\", \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"], false, () => {\n assert.fail(\"no key should match\");\n return false;\n });\n },\n \"findExistingKeys should match only existing keys\": async assert => {\n const store = await createTestStore();\n store.add({key: \"2db1a709-d8f1-4c40-a835-f312badd277a\"});\n store.add({key: \"43cd16eb-a6b4-4b9d-ab36-ab87d1b038c3\"});\n store.add({key: \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"});\n const found: string[] = [];\n await store.findExistingKeys([\n \"2db1a709-d8f1-4c40-a835-f312badd277a\",\n \"eac3ef5c-a48f-4e19-b41d-ebd1d84c53f2\",\n \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"\n ], false, (key: IDBValidKey) => {\n found.push(key as string);\n return false;\n });\n assert.equal(found.length, 2);\n assert.equal(found[0], \"2db1a709-d8f1-4c40-a835-f312badd277a\");\n assert.equal(found[1], \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\");\n },\n \"findExistingKeys should match all if all exist\": async assert => {\n const store = await createTestStore();\n store.add({key: \"2db1a709-d8f1-4c40-a835-f312badd277a\"});\n store.add({key: \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"});\n store.add({key: \"b655e7c5-e02d-4823-a7af-4202b12de659\"});\n const found: string[] = [];\n await store.findExistingKeys([\n \"2db1a709-d8f1-4c40-a835-f312badd277a\",\n \"b655e7c5-e02d-4823-a7af-4202b12de659\",\n \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"\n ], false, (key: IDBValidKey) => {\n found.push(key as string);\n return false;\n });\n assert.equal(found.length, 3);\n assert.equal(found[0], \"2db1a709-d8f1-4c40-a835-f312badd277a\");\n assert.equal(found[1], \"b655e7c5-e02d-4823-a7af-4202b12de659\");\n assert.equal(found[2], \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\");\n },\n \"findExistingKeys should stop matching when callback returns true\": async assert => {\n const store = await createTestStore();\n store.add({key: \"2db1a709-d8f1-4c40-a835-f312badd277a\"});\n store.add({key: \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"});\n store.add({key: \"b655e7c5-e02d-4823-a7af-4202b12de659\"});\n const found: string[] = [];\n await store.findExistingKeys([\n \"2db1a709-d8f1-4c40-a835-f312badd277a\",\n \"b655e7c5-e02d-4823-a7af-4202b12de659\",\n \"fe7aa5c2-d4ed-4278-b3b0-f49d48d11df2\"\n ], false, (key: IDBValidKey) => {\n found.push(key as string);\n return true;\n });\n assert.equal(found.length, 1);\n assert.equal(found[0], \"2db1a709-d8f1-4c40-a835-f312badd277a\");\n },\n \n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {QueryTarget, IDBQuery, ITransaction} from \"./QueryTarget\";\nimport {IDBRequestError, IDBRequestAttemptError} from \"./error\";\nimport {reqAsPromise} from \"./utils\";\nimport {Transaction, IDBKey} from \"./Transaction\";\nimport {ILogItem} from \"../../../logging/types\";\n\nconst LOG_REQUESTS = false;\n\nfunction logRequest(method: string, params: any[], source: any): void {\n const storeName = source?.name;\n const databaseName = source?.transaction?.db?.name;\n console.info(`${databaseName}.${storeName}.${method}(${params.map(p => JSON.stringify(p)).join(\", \")})`);\n}\n\nexport class QueryTargetWrapper {\n private _qt: IDBIndex | IDBObjectStore;\n\n constructor(qt: IDBIndex | IDBObjectStore) {\n this._qt = qt;\n }\n\n get keyPath(): string | string[] {\n return this._qtStore.keyPath;\n }\n\n get _qtStore(): IDBObjectStore {\n if (\"objectStore\" in this._qt) {\n return this._qt.objectStore;\n }\n return this._qt;\n }\n\n supports(methodName: string): boolean {\n return !!this._qt[methodName];\n }\n \n openKeyCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest {\n try {\n // not supported on Edge 15\n if (!this._qt.openKeyCursor) {\n LOG_REQUESTS && logRequest(\"openCursor\", [range, direction], this._qt);\n return this.openCursor(range, direction);\n }\n LOG_REQUESTS && logRequest(\"openKeyCursor\", [range, direction], this._qt);\n return this._qt.openKeyCursor(range, direction)\n } catch(err) {\n throw new IDBRequestAttemptError(\"openKeyCursor\", this._qt, err, [range, direction]);\n }\n }\n \n openCursor(range?: IDBQuery, direction?: IDBCursorDirection | undefined): IDBRequest {\n try {\n LOG_REQUESTS && logRequest(\"openCursor\", [], this._qt);\n return this._qt.openCursor(range, direction)\n } catch(err) {\n throw new IDBRequestAttemptError(\"openCursor\", this._qt, err, [range, direction]);\n }\n }\n\n put(item: T, key?: IDBValidKey | undefined): IDBRequest {\n try {\n LOG_REQUESTS && logRequest(\"put\", [item, key], this._qt);\n return this._qtStore.put(item, key);\n } catch(err) {\n throw new IDBRequestAttemptError(\"put\", this._qt, err, [item, key]);\n }\n }\n\n add(item: T, key?: IDBValidKey | undefined): IDBRequest {\n try {\n LOG_REQUESTS && logRequest(\"add\", [item, key], this._qt);\n return this._qtStore.add(item, key);\n } catch(err) {\n throw new IDBRequestAttemptError(\"add\", this._qt, err, [item, key]);\n }\n }\n\n get(key: IDBValidKey | IDBKeyRange): IDBRequest {\n try {\n LOG_REQUESTS && logRequest(\"get\", [key], this._qt);\n return this._qt.get(key);\n } catch(err) {\n throw new IDBRequestAttemptError(\"get\", this._qt, err, [key]);\n }\n }\n \n getKey(key: IDBValidKey | IDBKeyRange): IDBRequest {\n try {\n LOG_REQUESTS && logRequest(\"getKey\", [key], this._qt);\n return this._qt.getKey(key)\n } catch(err) {\n throw new IDBRequestAttemptError(\"getKey\", this._qt, err, [key]);\n }\n }\n\n delete(key: IDBValidKey | IDBKeyRange): IDBRequest {\n try {\n LOG_REQUESTS && logRequest(\"delete\", [key], this._qt);\n return this._qtStore.delete(key);\n } catch(err) {\n throw new IDBRequestAttemptError(\"delete\", this._qt, err, [key]);\n }\n }\n\n count(keyRange?: IDBKeyRange): IDBRequest {\n try {\n return this._qt.count(keyRange);\n } catch(err) {\n throw new IDBRequestAttemptError(\"count\", this._qt, err, [keyRange]);\n }\n }\n\n index(name: string): IDBIndex {\n try {\n return this._qtStore.index(name);\n } catch(err) {\n // TODO: map to different error? this is not a request\n throw new IDBRequestAttemptError(\"index\", this._qt, err, [name]);\n }\n }\n\n get indexNames(): string[] {\n return Array.from(this._qtStore.indexNames);\n }\n}\n\nexport class Store extends QueryTarget {\n constructor(idbStore: IDBObjectStore, transaction: ITransaction) {\n super(new QueryTargetWrapper(idbStore), transaction);\n }\n\n get _idbStore(): QueryTargetWrapper {\n return (this._target as QueryTargetWrapper);\n }\n\n index(indexName: string): QueryTarget {\n return new QueryTarget(new QueryTargetWrapper(this._idbStore.index(indexName)), this._transaction);\n }\n\n put(value: T, log?: ILogItem): void {\n // If this request fails, the error will bubble up to the transaction and abort it,\n // which is the behaviour we want. Therefore, it is ok to not create a promise for this\n // request and await it.\n // \n // Perhaps at some later point, we will want to handle an error (like ConstraintError) for\n // individual write requests. In that case, we should add a method that returns a promise (e.g. putAndObserve)\n // and call preventDefault on the event to prevent it from aborting the transaction\n // \n // Note that this can still throw synchronously, like it does for TransactionInactiveError,\n // see https://www.w3.org/TR/IndexedDB-2/#transaction-lifetime-concept\n const request = this._idbStore.put(value);\n this._prepareErrorLog(request, log, \"put\", undefined, value);\n }\n\n add(value: T, log?: ILogItem): void {\n // ok to not monitor result of request, see comment in `put`.\n const request = this._idbStore.add(value);\n this._prepareErrorLog(request, log, \"add\", undefined, value);\n }\n\n async tryAdd(value: T, log: ILogItem): Promise {\n try {\n await reqAsPromise(this._idbStore.add(value));\n return true;\n } catch (err) {\n if (err instanceof IDBRequestError) {\n log.log({l: \"could not write\", id: this._getKeys(value), e: err}, log.level.Warn);\n err.preventTransactionAbort();\n return false;\n } else {\n throw err;\n }\n }\n }\n\n delete(keyOrKeyRange: IDBValidKey | IDBKeyRange, log?: ILogItem): void {\n // ok to not monitor result of request, see comment in `put`.\n const request = this._idbStore.delete(keyOrKeyRange);\n this._prepareErrorLog(request, log, \"delete\", keyOrKeyRange, undefined);\n }\n\n private _prepareErrorLog(request: IDBRequest, log: ILogItem | undefined, operationName: string, key: IDBKey | undefined, value: T | undefined) {\n if (log) {\n log.ensureRefId();\n }\n reqAsPromise(request).catch(err => {\n let keys : IDBKey[] | undefined = undefined;\n if (value) {\n keys = this._getKeys(value);\n } else if (key) {\n keys = [key];\n }\n this._transaction.addWriteError(err, log, operationName, keys);\n });\n }\n\n private _getKeys(value: T): IDBValidKey[] {\n const keys: IDBValidKey[] = [];\n const {keyPath} = this._idbStore;\n try {\n keys.push(this._readKeyPath(value, keyPath));\n } catch (err) {\n console.warn(\"could not read keyPath\", keyPath);\n }\n for (const indexName of this._idbStore.indexNames) {\n try {\n const index = this._idbStore.index(indexName);\n keys.push(this._readKeyPath(value, index.keyPath));\n } catch (err) {\n console.warn(\"could not read index\", indexName);\n }\n }\n return keys;\n }\n\n private _readKeyPath(value: T, keyPath: string[] | string): IDBValidKey {\n if (Array.isArray(keyPath)) {\n let field: any = value;\n for (const part of keyPath) {\n if (typeof field === \"object\") {\n field = field[part];\n } else {\n break;\n }\n }\n return field as IDBValidKey;\n } else {\n return value[keyPath] as IDBValidKey;\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function stringify(value: any): string {\n return JSON.stringify(encodeValue(value));\n}\n\nexport function parse(value: string): any {\n return decodeValue(JSON.parse(value));\n}\n\nfunction encodeValue(value: any): any {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n // TypedArray\n if (value.byteLength) {\n return {_type: value.constructor.name, value: Array.from(value)};\n }\n let newObj = {};\n for (const prop in value) {\n if (value.hasOwnProperty(prop)) {\n newObj[prop] = encodeValue(value[prop]);\n }\n }\n return newObj;\n } else {\n return value;\n }\n}\n\nfunction decodeValue(value: any): any {\n if (typeof value === \"object\" && value !== null && !Array.isArray(value)) {\n if (typeof value._type === \"string\") {\n switch (value._type) {\n case \"Int8Array\": return Int8Array.from(value.value);\n case \"Uint8Array\": return Uint8Array.from(value.value);\n case \"Uint8ClampedArray\": return Uint8ClampedArray.from(value.value);\n case \"Int16Array\": return Int16Array.from(value.value);\n case \"Uint16Array\": return Uint16Array.from(value.value);\n case \"Int32Array\": return Int32Array.from(value.value);\n case \"Uint32Array\": return Uint32Array.from(value.value);\n case \"Float32Array\": return Float32Array.from(value.value);\n case \"Float64Array\": return Float64Array.from(value.value);\n case \"BigInt64Array\": return BigInt64Array.from(value.value);\n case \"BigUint64Array\": return BigUint64Array.from(value.value);\n default:\n return value.value;\n }\n }\n let newObj = {};\n for (const prop in value) {\n if (value.hasOwnProperty(prop)) {\n newObj[prop] = decodeValue(value[prop]);\n }\n }\n return newObj;\n } else {\n return value;\n }\n}\n\nexport function tests() {\n return {\n \"Uint8Array and primitives\": assert => {\n const value = {\n foo: \"bar\",\n bar: 5,\n baz: false,\n fuzz: new Uint8Array([3, 1, 2])\n };\n const serialized = stringify(value);\n assert.strictEqual(typeof serialized, \"string\");\n const deserialized = parse(serialized);\n assert.strictEqual(deserialized.foo, \"bar\");\n assert.strictEqual(deserialized.bar, 5);\n assert.strictEqual(deserialized.baz, false);\n assert(deserialized.fuzz instanceof Uint8Array);\n assert.strictEqual(deserialized.fuzz.length, 3);\n assert.strictEqual(deserialized.fuzz[0], 3);\n assert.strictEqual(deserialized.fuzz[1], 1);\n assert.strictEqual(deserialized.fuzz[2], 2);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Store} from \"../Store\";\nimport {IDOMStorage} from \"../types\";\nimport {SESSION_E2EE_KEY_PREFIX} from \"../../../e2ee/common.js\";\nimport {parse, stringify} from \"../../../../utils/typedJSON\";\nimport type {ILogItem} from \"../../../../logging/types\";\n\nexport interface SessionEntry {\n key: string;\n value: any;\n}\n\nexport class SessionStore {\n private _sessionStore: Store\n private _localStorage: IDOMStorage;\n\n constructor(sessionStore: Store, localStorage: IDOMStorage) {\n this._sessionStore = sessionStore;\n this._localStorage = localStorage;\n }\n\n private get _localStorageKeyPrefix(): string {\n return `${this._sessionStore.databaseName}.session.`;\n }\n\n async get(key: string): Promise {\n const entry = await this._sessionStore.get(key);\n if (entry) {\n return entry.value;\n }\n }\n\n _writeKeyToLocalStorage(key: string, value: any) {\n // we backup to localStorage so when idb gets cleared for some reason, we don't lose our e2ee identity\n try {\n const lsKey = this._localStorageKeyPrefix + key;\n const lsValue = stringify(value);\n this._localStorage.setItem(lsKey, lsValue);\n } catch (err) {\n console.error(\"could not write to localStorage\", err);\n }\n }\n\n writeE2EEIdentityToLocalStorage() {\n this._sessionStore.iterateValues(undefined, (entry: SessionEntry, key: string) => {\n if (key.startsWith(SESSION_E2EE_KEY_PREFIX)) {\n this._writeKeyToLocalStorage(key, entry.value);\n }\n return false;\n });\n }\n\n async tryRestoreE2EEIdentityFromLocalStorage(log: ILogItem): Promise {\n let success = false;\n const lsPrefix = this._localStorageKeyPrefix;\n const prefix = lsPrefix + SESSION_E2EE_KEY_PREFIX;\n for(let i = 0; i < this._localStorage.length; i += 1) {\n const lsKey = this._localStorage.key(i)!;\n if (lsKey.startsWith(prefix)) {\n const value = parse(this._localStorage.getItem(lsKey)!);\n const key = lsKey.substr(lsPrefix.length);\n // we check if we don't have this key already, as we don't want to override anything\n const hasKey = (await this._sessionStore.getKey(key)) === key;\n log.set(key, !hasKey);\n if (!hasKey) {\n this._sessionStore.put({key, value});\n success = true;\n }\n }\n }\n return success;\n }\n\n set(key: string, value: any): void {\n if (key.startsWith(SESSION_E2EE_KEY_PREFIX)) {\n this._writeKeyToLocalStorage(key, value);\n }\n this._sessionStore.put({key, value});\n }\n\n add(key: string, value: any): void {\n if (key.startsWith(SESSION_E2EE_KEY_PREFIX)) {\n this._writeKeyToLocalStorage(key, value);\n }\n this._sessionStore.add({key, value});\n }\n\n remove(key: string): void {\n if (key.startsWith(SESSION_E2EE_KEY_PREFIX)) {\n this._localStorage.removeItem(this._localStorageKeyPrefix + key);\n }\n this._sessionStore.delete(key);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\nstore contains:\n\troomId\n\tname\n\tlastMessage\n\tunreadCount\n\tmentionCount\n\tisEncrypted\n\tisDirectMessage\n\tmembership\n\tinviteCount\n\tjoinCount\n*/\nimport {Store} from \"../Store\";\nimport {SummaryData} from \"../../../room/RoomSummary\";\n\n/** Used for both roomSummary and archivedRoomSummary stores */\nexport class RoomSummaryStore {\n private _summaryStore: Store;\n\n constructor(summaryStore: Store) {\n this._summaryStore = summaryStore;\n }\n\n getAll(): Promise {\n return this._summaryStore.selectAll();\n }\n\n set(summary: SummaryData): void {\n this._summaryStore.put(summary);\n }\n\n get(roomId: string): Promise {\n return this._summaryStore.get(roomId);\n }\n\n async has(roomId: string): Promise {\n const fetchedKey = await this._summaryStore.getKey(roomId);\n return roomId === fetchedKey;\n }\n\n remove(roomId: string): void {\n this._summaryStore.delete(roomId);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Store} from \"../Store\";\nimport {MemberData} from \"./RoomMemberStore\";\n\n// TODO: Move to Invite when that's TypeScript.\nexport interface InviteData {\n roomId: string;\n isEncrypted: boolean;\n isDirectMessage: boolean;\n name?: string;\n avatarUrl?: string;\n avatarColorId: number;\n canonicalAlias?: string;\n timestamp: number;\n joinRule: string;\n inviter?: MemberData;\n}\n\nexport class InviteStore {\n private _inviteStore: Store;\n\n constructor(inviteStore: Store) {\n this._inviteStore = inviteStore;\n }\n\n getAll(): Promise {\n return this._inviteStore.selectAll();\n }\n\n set(invite: InviteData): void {\n this._inviteStore.put(invite);\n }\n\n remove(roomId: string): void {\n this._inviteStore.delete(roomId);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {ILogItem, ISerializedItem} from \"./types\";\n\nexport enum LogLevel {\n All = 1,\n Debug,\n Detail,\n Info,\n Warn,\n Error,\n Fatal,\n Off\n}\n\nexport class LogFilter {\n private _min?: LogLevel;\n private _parentFilter?: LogFilter;\n\n constructor(parentFilter?: LogFilter) {\n this._parentFilter = parentFilter;\n }\n\n filter(item: ILogItem, children: ISerializedItem[] | null): boolean {\n if (this._parentFilter) {\n if (!this._parentFilter.filter(item, children)) {\n return false;\n }\n }\n // neither our children or us have a loglevel high enough, filter out.\n if (this._min !== undefined && !Array.isArray(children) && item.logLevel < this._min) {\n return false;\n } else {\n return true;\n }\n }\n\n /* methods to build the filter */\n minLevel(logLevel: LogLevel): LogFilter {\n this._min = logLevel;\n return this;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {LogLevel} from \"./LogFilter\";\nimport type {ILogger, ILogExport, ILogItem, LabelOrValues, LogCallback, LogItemValues} from \"./types\";\n\nfunction noop (): void {}\n\nexport class NullLogger implements ILogger {\n public readonly item: ILogItem = new NullLogItem(this);\n\n log(): void {}\n\n run(_, callback: LogCallback): T {\n return callback(this.item); \n }\n\n wrapOrRun(item: ILogItem | undefined, _, callback: LogCallback): T {\n if (item) {\n return item.wrap(_, callback);\n } else {\n return this.run(_, callback);\n }\n }\n\n runDetached(_, callback): ILogItem {\n new Promise(r => r(callback(this.item))).then(noop, noop);\n return this.item;\n }\n\n async export(): Promise {\n return undefined;\n }\n\n get level(): typeof LogLevel {\n return LogLevel;\n }\n}\n\nexport class NullLogItem implements ILogItem {\n public readonly logger: NullLogger;\n public readonly logLevel: LogLevel;\n public children?: Array;\n public values: LogItemValues;\n public error?: Error;\n\n constructor(logger: NullLogger) {\n this.logger = logger;\n }\n\n wrap(_: LabelOrValues, callback: LogCallback): T {\n return callback(this);\n }\n\n log(): ILogItem {\n return this;\n }\n set(): ILogItem { return this; }\n\n runDetached(_: LabelOrValues, callback: LogCallback): ILogItem {\n new Promise(r => r(callback(this))).then(noop, noop);\n return this;\n }\n\n wrapDetached(_: LabelOrValues, _callback: LogCallback): void {\n return this.refDetached();\n }\n\n refDetached(): void {}\n\n ensureRefId(): void {}\n\n get level(): typeof LogLevel {\n return LogLevel;\n }\n\n get duration(): 0 {\n return 0;\n }\n\n catch(err: Error): Error {\n return err;\n }\n\n child(): ILogItem {\n return this;\n }\n\n finish(): void {}\n\n serialize(): undefined {\n return undefined;\n }\n}\n\nexport const Instance = new NullLogger(); \n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventKey} from \"../../../room/timeline/EventKey\";\nimport { StorageError } from \"../../common\";\nimport { encodeUint32, decodeUint32 } from \"../utils\";\nimport {KeyLimits} from \"../../common\";\nimport {Store} from \"../Store\";\nimport {TimelineEvent, StateEvent} from \"../../types\";\nimport {ILogItem} from \"../../../../logging/types\";\n\ninterface Annotation {\n count: number;\n me: boolean;\n firstTimestamp: number;\n}\n\ninterface TimelineEventEntry {\n roomId: string;\n fragmentId: number;\n eventIndex: number;\n event: TimelineEvent | StateEvent;\n displayName?: string;\n avatarUrl?: string;\n annotations?: { [key : string]: Annotation };\n}\n\ntype TimelineEventStorageEntry = TimelineEventEntry & { key: string, eventIdKey: string };\n\nfunction encodeKey(roomId: string, fragmentId: number, eventIndex: number): string {\n return `${roomId}|${encodeUint32(fragmentId)}|${encodeUint32(eventIndex)}`;\n}\n\nfunction decodeKey(key: string): { roomId: string, eventKey: EventKey } {\n const [roomId, fragmentId, eventIndex] = key.split(\"|\");\n return {roomId, eventKey: new EventKey(decodeUint32(fragmentId), decodeUint32(eventIndex))};\n}\n\nfunction encodeEventIdKey(roomId: string, eventId: string): string {\n return `${roomId}|${eventId}`;\n}\n\nfunction decodeEventIdKey(eventIdKey: string): { roomId: string, eventId: string } {\n const [roomId, eventId] = eventIdKey.split(\"|\");\n return {roomId, eventId};\n}\n\nclass Range {\n private _IDBKeyRange: typeof IDBKeyRange;\n private _only?: EventKey;\n private _lower?: EventKey;\n private _upper?: EventKey;\n private _lowerOpen: boolean;\n private _upperOpen: boolean;\n\n constructor(_IDBKeyRange: any, only?: EventKey, lower?: EventKey, upper?: EventKey, lowerOpen: boolean = false, upperOpen: boolean = false) {\n this._IDBKeyRange = _IDBKeyRange;\n this._only = only;\n this._lower = lower;\n this._upper = upper;\n this._lowerOpen = lowerOpen;\n this._upperOpen = upperOpen;\n }\n\n asIDBKeyRange(roomId: string): IDBKeyRange | undefined {\n try {\n // only\n if (this._only) {\n return this._IDBKeyRange.only(encodeKey(roomId, this._only.fragmentId, this._only.eventIndex));\n }\n // lowerBound\n // also bound as we don't want to move into another roomId\n if (this._lower && !this._upper) {\n return this._IDBKeyRange.bound(\n encodeKey(roomId, this._lower.fragmentId, this._lower.eventIndex),\n encodeKey(roomId, this._lower.fragmentId, KeyLimits.maxStorageKey),\n this._lowerOpen,\n false\n );\n }\n // upperBound\n // also bound as we don't want to move into another roomId\n if (!this._lower && this._upper) {\n return this._IDBKeyRange.bound(\n encodeKey(roomId, this._upper.fragmentId, KeyLimits.minStorageKey),\n encodeKey(roomId, this._upper.fragmentId, this._upper.eventIndex),\n false,\n this._upperOpen\n );\n }\n // bound\n if (this._lower && this._upper) {\n return this._IDBKeyRange.bound(\n encodeKey(roomId, this._lower.fragmentId, this._lower.eventIndex),\n encodeKey(roomId, this._upper.fragmentId, this._upper.eventIndex),\n this._lowerOpen,\n this._upperOpen\n );\n }\n } catch(err) {\n throw new StorageError(`IDBKeyRange failed with data: ` + JSON.stringify(this), err);\n }\n }\n}\n/*\n * @typedef {Object} Gap\n * @property {?string} prev_batch the pagination token for this backwards facing gap\n * @property {?string} next_batch the pagination token for this forwards facing gap\n *\n * @typedef {Object} Event\n * @property {string} event_id the id of the event\n * @property {string} type the\n * @property {?string} state_key the state key of this state event\n *\n * @typedef {Object} Entry\n * @property {string} roomId\n * @property {EventKey} eventKey\n * @property {?Event} event if an event entry, the event\n * @property {?Gap} gap if a gap entry, the gap\n*/\nexport class TimelineEventStore {\n private _timelineStore: Store;\n\n constructor(timelineStore: Store) {\n this._timelineStore = timelineStore;\n }\n\n /** Creates a range that only includes the given key\n * @param eventKey the key\n * @return the created range\n */\n onlyRange(eventKey: EventKey): Range {\n return new Range(this._timelineStore.IDBKeyRange, eventKey);\n }\n\n /** Creates a range that includes all keys before eventKey, and optionally also the key itself.\n * @param eventKey the key\n * @param [open=false] whether the key is included (false) or excluded (true) from the range at the upper end.\n * @return the created range\n */\n upperBoundRange(eventKey: EventKey, open=false): Range {\n return new Range(this._timelineStore.IDBKeyRange, undefined, undefined, eventKey, undefined, open);\n }\n\n /** Creates a range that includes all keys after eventKey, and optionally also the key itself.\n * @param eventKey the key\n * @param [open=false] whether the key is included (false) or excluded (true) from the range at the lower end.\n * @return the created range\n */\n lowerBoundRange(eventKey: EventKey, open=false): Range {\n return new Range(this._timelineStore.IDBKeyRange, undefined, eventKey, undefined, open);\n }\n\n /** Creates a range that includes all keys between `lower` and `upper`, and optionally the given keys as well.\n * @param lower the lower key\n * @param upper the upper key\n * @param [lowerOpen=false] whether the lower key is included (false) or excluded (true) from the range.\n * @param [upperOpen=false] whether the upper key is included (false) or excluded (true) from the range.\n * @return the created range\n */\n boundRange(lower: EventKey, upper: EventKey, lowerOpen=false, upperOpen=false): Range {\n return new Range(this._timelineStore.IDBKeyRange, undefined, lower, upper, lowerOpen, upperOpen);\n }\n\n /** Looks up the last `amount` entries in the timeline for `roomId`.\n * @param roomId\n * @param fragmentId\n * @param amount\n * @return a promise resolving to an array with 0 or more entries, in ascending order.\n */\n async lastEvents(roomId: string, fragmentId: number, amount: number): Promise {\n const eventKey = EventKey.maxKey;\n eventKey.fragmentId = fragmentId;\n return this.eventsBefore(roomId, eventKey, amount);\n }\n\n /** Looks up the first `amount` entries in the timeline for `roomId`.\n * @param roomId\n * @param fragmentId\n * @param amount\n * @return a promise resolving to an array with 0 or more entries, in ascending order.\n */\n async firstEvents(roomId: string, fragmentId: number, amount: number): Promise {\n const eventKey = EventKey.minKey;\n eventKey.fragmentId = fragmentId;\n return this.eventsAfter(roomId, eventKey, amount);\n }\n\n /** Looks up `amount` entries after `eventKey` in the timeline for `roomId` within the same fragment.\n * The entry for `eventKey` is not included.\n * @param roomId\n * @param eventKey\n * @param amount\n * @return a promise resolving to an array with 0 or more entries, in ascending order.\n */\n eventsAfter(roomId: string, eventKey: EventKey, amount: number): Promise {\n const idbRange = this.lowerBoundRange(eventKey, true).asIDBKeyRange(roomId);\n return this._timelineStore.selectLimit(idbRange, amount);\n }\n\n /** Looks up `amount` entries before `eventKey` in the timeline for `roomId` within the same fragment.\n * The entry for `eventKey` is not included.\n * @param roomId\n * @param eventKey\n * @param amount\n * @return a promise resolving to an array with 0 or more entries, in ascending order.\n */\n async eventsBefore(roomId: string, eventKey: EventKey, amount: number): Promise {\n const range = this.upperBoundRange(eventKey, true).asIDBKeyRange(roomId);\n const events = await this._timelineStore.selectLimitReverse(range, amount);\n events.reverse(); // because we fetched them backwards\n return events;\n }\n\n async getEventKeysForIds(roomId: string, eventIds: string[]): Promise> {\n const byEventId = this._timelineStore.index(\"byEventId\");\n const keys = eventIds.map(eventId => encodeEventIdKey(roomId, eventId));\n const results = new Map();\n await byEventId.findExistingKeys(keys, false, (indexKey, pk) => {\n const {eventId} = decodeEventIdKey(indexKey as string);\n const {eventKey} = decodeKey(pk as string);\n results.set(eventId, eventKey);\n return false;\n });\n return results;\n }\n\n /** Finds the first eventId that occurs in the store, if any.\n * For optimal performance, `eventIds` should be in chronological order.\n *\n * The order in which results are returned might be different than `eventIds`.\n * Call the return value to obtain the next {id, event} pair.\n * @param roomId\n * @param eventIds\n * @return\n */\n // performance comment from above refers to the fact that there *might*\n // be a correlation between event_id sorting order and chronology.\n // In that case we could avoid running over all eventIds, as the reported order by findExistingKeys\n // would match the order of eventIds. That's why findLast is also passed as backwards to keysExist.\n // also passing them in chronological order makes sense as that's how we'll receive them almost always.\n async findFirstOccurringEventId(roomId: string, eventIds: string[]): Promise {\n const byEventId = this._timelineStore.index(\"byEventId\");\n const keys = eventIds.map(eventId => encodeEventIdKey(roomId, eventId));\n const results = new Array(keys.length);\n let firstFoundKey: string | undefined;\n\n // find first result that is found and has no undefined results before it\n function firstFoundAndPrecedingResolved(): string | undefined {\n for(let i = 0; i < results.length; ++i) {\n if (results[i] === undefined) {\n return;\n } else if(results[i] === true) {\n return keys[i];\n }\n }\n }\n\n await byEventId.findExistingKeys(keys, false, (key, found) => {\n // T[].search(T, number), but we want T[].search(R, number), so cast\n const index = (keys as IDBValidKey[]).indexOf(key);\n results[index] = found;\n firstFoundKey = firstFoundAndPrecedingResolved();\n return !!firstFoundKey;\n });\n return firstFoundKey && decodeEventIdKey(firstFoundKey).eventId;\n }\n\n /** Inserts a new entry into the store.\n * \n * If the event already exists in the store (either the eventKey or the event id\n * are already known for the given roomId), this operation has no effect.\n * \n * Returns if the event was not yet known and the entry was written.\n */\n tryInsert(entry: TimelineEventEntry, log: ILogItem): Promise {\n (entry as TimelineEventStorageEntry).key = encodeKey(entry.roomId, entry.fragmentId, entry.eventIndex);\n (entry as TimelineEventStorageEntry).eventIdKey = encodeEventIdKey(entry.roomId, entry.event.event_id);\n return this._timelineStore.tryAdd(entry as TimelineEventStorageEntry, log);\n }\n\n /** Updates the entry into the store with the given [roomId, eventKey] combination.\n * If not yet present, will insert. Might be slower than add.\n * @param entry the entry to update.\n * @return nothing. To wait for the operation to finish, await the transaction it's part of.\n */\n update(entry: TimelineEventEntry): void {\n this._timelineStore.put(entry as TimelineEventStorageEntry);\n }\n\n get(roomId: string, eventKey: EventKey): Promise {\n return this._timelineStore.get(encodeKey(roomId, eventKey.fragmentId, eventKey.eventIndex));\n }\n\n getByEventId(roomId: string, eventId: string): Promise {\n return this._timelineStore.index(\"byEventId\").get(encodeEventIdKey(roomId, eventId));\n }\n\n removeAllForRoom(roomId: string): void {\n const minKey = encodeKey(roomId, KeyLimits.minStorageKey, KeyLimits.minStorageKey);\n const maxKey = encodeKey(roomId, KeyLimits.maxStorageKey, KeyLimits.maxStorageKey);\n const range = this._timelineStore.IDBKeyRange.bound(minKey, maxKey);\n this._timelineStore.delete(range);\n }\n}\n\nimport {createMockStorage} from \"../../../../mocks/Storage\";\nimport {createEvent, withTextBody} from \"../../../../mocks/event.js\";\nimport {createEventEntry} from \"../../../room/timeline/persistence/common.js\";\nimport {Instance as nullLogger} from \"../../../../logging/NullLogger\";\n\nexport function tests() {\n\n const sortedIds = [\n \"$2wZy1W-QdcwaAwz68nfz1oc-3SsZKVDy8d86ERP1Pm0\",\n \"$4RWaZ5142grUgTnQyr_5qiPTOwzAOimt5MsXg6m1diM\",\n \"$4izqHE2Wf5US_-e_za942pZ10CDNJjDncUMmhqBUVQw\",\n \"$Oil2Afq2cBLqMAeJTAHjA3Is9T5Wmaa2ogVRlFJ_gzE\",\n \"$Wyl-7u-YqnPJElkPufIRXRFTYP-eFxQ4iD-SmLQo2Rw\",\n \"$b-eWaZtp22vL9mp0h7odbpphOZQ-rnp54qjyTQPARgo\",\n \"$sS9rTv8u2m9o4RaMI2jGOnpMtb9t8_0euiQLhNFW380\",\n \"$uZLkB9rzTKvJAK2QrQNX-prwQ2Niajdi0fvvRnyCtz8\",\n \"$vGecIBZFex9_vlQf1E1LjtQXE3q5GwERIHMiy4mOWv0\",\n \"$vdLgAnwjHj0cicU3MA4ynLHUBGOIFhvvksY3loqzjF\",\n ];\n\n const insertedIds = [\n sortedIds[5],\n sortedIds[3],\n sortedIds[9],\n sortedIds[7],\n sortedIds[1],\n ];\n\n const checkedIds = [\n sortedIds[2],\n sortedIds[4],\n sortedIds[3],\n sortedIds[0],\n sortedIds[8],\n sortedIds[9],\n sortedIds[6],\n ];\n\n const roomId = \"!fjsdf423423jksdfdsf:hs.tld\";\n\n function createEventWithId(id) {\n return withTextBody(\"hello\", createEvent(\"m.room.message\", id, \"@alice:hs.tld\"));\n }\n\n return {\n \"getEventKeysForIds\": async assert => {\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents]);\n let eventKey = EventKey.defaultFragmentKey(109);\n for (const insertedId of insertedIds) {\n const entry = createEventEntry(eventKey.nextKey(), roomId, createEventWithId(insertedId));\n assert(await txn.timelineEvents.tryInsert(entry, nullLogger.item));\n eventKey = eventKey.nextKey();\n }\n const eventKeyMap = await txn.timelineEvents.getEventKeysForIds(roomId, checkedIds);\n assert.equal(eventKeyMap.size, 2);\n const eventKey1 = eventKeyMap.get(\"$Oil2Afq2cBLqMAeJTAHjA3Is9T5Wmaa2ogVRlFJ_gzE\")!;\n assert.equal(eventKey1.fragmentId, 109);\n assert.equal(eventKey1.eventIndex, 0x80000001);\n const eventKey2 = eventKeyMap.get(\"$vdLgAnwjHj0cicU3MA4ynLHUBGOIFhvvksY3loqzjF\")!;\n assert.equal(eventKey2.fragmentId, 109);\n assert.equal(eventKey2.eventIndex, 0x80000002);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport const MIN_UNICODE = \"\\u{0}\";\nexport const MAX_UNICODE = \"\\u{10FFFF}\";\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {MIN_UNICODE, MAX_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\n\nfunction encodeKey(roomId: string, targetEventId: string, relType: string, sourceEventId: string): string {\n return `${roomId}|${targetEventId}|${relType}|${sourceEventId}`;\n}\n\ninterface RelationEntry {\n roomId: string;\n targetEventId: string;\n sourceEventId: string;\n relType: string;\n}\n\nfunction decodeKey(key: string): RelationEntry {\n const [roomId, targetEventId, relType, sourceEventId] = key.split(\"|\");\n return {roomId, targetEventId, relType, sourceEventId};\n}\n\nexport class TimelineRelationStore {\n private _store: Store<{ key: string }>;\n\n constructor(store: Store<{ key: string }>) {\n this._store = store;\n }\n\n add(roomId: string, targetEventId: string, relType: string, sourceEventId: string): void {\n this._store.add({key: encodeKey(roomId, targetEventId, relType, sourceEventId)});\n }\n\n remove(roomId: string, targetEventId: string, relType: string, sourceEventId: string): void {\n this._store.delete(encodeKey(roomId, targetEventId, relType, sourceEventId));\n }\n\n removeAllForTarget(roomId: string, targetId: string): void {\n const range = this._store.IDBKeyRange.bound(\n encodeKey(roomId, targetId, MIN_UNICODE, MIN_UNICODE),\n encodeKey(roomId, targetId, MAX_UNICODE, MAX_UNICODE),\n true,\n true\n );\n this._store.delete(range);\n }\n\n removeAllForRoom(roomId: string) {\n const range = this._store.IDBKeyRange.bound(\n encodeKey(roomId, MIN_UNICODE, MIN_UNICODE, MIN_UNICODE),\n encodeKey(roomId, MAX_UNICODE, MAX_UNICODE, MAX_UNICODE),\n true,\n true\n );\n this._store.delete(range);\n }\n\n async getForTargetAndType(roomId: string, targetId: string, relType: string): Promise {\n // exclude both keys as they are theoretical min and max,\n // but we should't have a match for just the room id, or room id with max\n const range = this._store.IDBKeyRange.bound(\n encodeKey(roomId, targetId, relType, MIN_UNICODE),\n encodeKey(roomId, targetId, relType, MAX_UNICODE),\n true,\n true\n );\n const items = await this._store.selectAll(range);\n return items.map(i => decodeKey(i.key));\n }\n\n async getAllForTarget(roomId: string, targetId: string): Promise {\n // exclude both keys as they are theoretical min and max,\n // but we should't have a match for just the room id, or room id with max\n const range = this._store.IDBKeyRange.bound(\n encodeKey(roomId, targetId, MIN_UNICODE, MIN_UNICODE),\n encodeKey(roomId, targetId, MAX_UNICODE, MAX_UNICODE),\n true,\n true\n );\n const items = await this._store.selectAll(range);\n return items.map(i => decodeKey(i.key));\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MAX_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\nimport {StateEvent} from \"../../types\";\n\nfunction encodeKey(roomId: string, eventType: string, stateKey: string) {\n return `${roomId}|${eventType}|${stateKey}`;\n}\n\nexport interface RoomStateEntry {\n roomId: string;\n event: StateEvent;\n key: string;\n}\n\nexport class RoomStateStore {\n private _roomStateStore: Store;\n\n constructor(idbStore: Store) {\n this._roomStateStore = idbStore;\n }\n\n get(roomId: string, type: string, stateKey: string): Promise {\n const key = encodeKey(roomId, type, stateKey);\n return this._roomStateStore.get(key);\n }\n\n set(roomId: string, event: StateEvent): void {\n const key = encodeKey(roomId, event.type, event.state_key);\n const entry = {roomId, event, key};\n this._roomStateStore.put(entry);\n }\n\n removeAllForRoom(roomId: string): void {\n // exclude both keys as they are theoretical min and max,\n // but we should't have a match for just the room id, or room id with max\n const range = this._roomStateStore.IDBKeyRange.bound(roomId, `${roomId}|${MAX_UNICODE}`, true, true);\n this._roomStateStore.delete(range);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MAX_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\n\nfunction encodeKey(roomId: string, userId: string) {\n return `${roomId}|${userId}`;\n}\n\nfunction decodeKey(key: string): { roomId: string, userId: string } {\n const [roomId, userId] = key.split(\"|\");\n return {roomId, userId};\n}\n\n// TODO: Move to RoomMember when that's TypeScript.\nexport interface MemberData {\n roomId: string;\n userId: string;\n avatarUrl: string;\n displayName: string;\n membership: \"join\" | \"leave\" | \"invite\" | \"ban\";\n}\n\ntype MemberStorageEntry = MemberData & { key: string }\n\n// no historical members\nexport class RoomMemberStore {\n private _roomMembersStore: Store;\n\n constructor(roomMembersStore: Store) {\n this._roomMembersStore = roomMembersStore;\n }\n\n get(roomId: string, userId: string): Promise {\n return this._roomMembersStore.get(encodeKey(roomId, userId));\n }\n\n set(member: MemberData): void {\n // Object.assign would be more typesafe, but small objects \n (member as MemberStorageEntry).key = encodeKey(member.roomId, member.userId);\n this._roomMembersStore.put(member as MemberStorageEntry);\n }\n\n getAll(roomId: string): Promise {\n const range = this._roomMembersStore.IDBKeyRange.lowerBound(encodeKey(roomId, \"\"));\n return this._roomMembersStore.selectWhile(range, member => {\n return member.roomId === roomId;\n });\n }\n\n async getAllUserIds(roomId: string): Promise {\n const userIds: string[] = [];\n const range = this._roomMembersStore.IDBKeyRange.lowerBound(encodeKey(roomId, \"\"));\n await this._roomMembersStore.iterateKeys(range, key => {\n const decodedKey = decodeKey(key as string);\n // prevent running into the next room\n if (decodedKey.roomId === roomId) {\n userIds.push(decodedKey.userId);\n return false; // fetch more\n }\n return true; // done\n });\n return userIds;\n }\n\n removeAllForRoom(roomId: string): void {\n // exclude both keys as they are theoretical min and max,\n // but we should't have a match for just the room id, or room id with max\n const range = this._roomMembersStore.IDBKeyRange.bound(roomId, `${roomId}|${MAX_UNICODE}`, true, true);\n this._roomMembersStore.delete(range);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { StorageError } from \"../../common\";\nimport {KeyLimits} from \"../../common\";\nimport { encodeUint32 } from \"../utils\";\nimport {Store} from \"../Store\";\n\ninterface Fragment {\n roomId: string;\n id: number;\n previousId: number | null;\n nextId: number | null;\n previousToken: string | null;\n nextToken: string | null;\n}\n\ntype FragmentEntry = Fragment & { key: string }\n\nfunction encodeKey(roomId: string, fragmentId: number): string {\n return `${roomId}|${encodeUint32(fragmentId)}`;\n}\n\nexport class TimelineFragmentStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n _allRange(roomId: string): IDBKeyRange {\n try {\n return this._store.IDBKeyRange.bound(\n encodeKey(roomId, KeyLimits.minStorageKey),\n encodeKey(roomId, KeyLimits.maxStorageKey)\n );\n } catch (err) {\n throw new StorageError(`error from IDBKeyRange with roomId ${roomId}`, err);\n }\n }\n\n all(roomId: string): Promise {\n return this._store.selectAll(this._allRange(roomId));\n }\n\n /** Returns the fragment without a nextToken and without nextId,\n if any, with the largest id if there are multiple (which should not happen) */\n liveFragment(roomId: string): Promise {\n // why do we need this?\n // Ok, take the case where you've got a /context fragment and a /sync fragment\n // They are not connected. So, upon loading the persister, which one do we take? We can't sort them ...\n // we assume that the one without a nextToken and without a nextId is a live one\n // there should really be only one like this\n\n // reverse because assuming live fragment has bigger id than non-live ones\n return this._store.findReverse(this._allRange(roomId), fragment => {\n return typeof fragment.nextId !== \"number\" && typeof fragment.nextToken !== \"string\";\n });\n }\n\n // should generate an id an return it?\n // depends if we want to do anything smart with fragment ids,\n // like give them meaning depending on range. not for now probably ...\n add(fragment: Fragment): void {\n (fragment as FragmentEntry).key = encodeKey(fragment.roomId, fragment.id);\n this._store.add(fragment as FragmentEntry);\n }\n\n update(fragment: FragmentEntry): void {\n this._store.put(fragment);\n }\n\n get(roomId: string, fragmentId: number): Promise {\n return this._store.get(encodeKey(roomId, fragmentId));\n }\n\n removeAllForRoom(roomId: string): void {\n this._store.delete(this._allRange(roomId));\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { encodeUint32, decodeUint32 } from \"../utils\";\nimport {KeyLimits} from \"../../common\";\nimport {Store} from \"../Store\";\nimport {Content} from \"../../types\";\n\ninterface PendingEntry {\n roomId: string;\n queueIndex: number;\n eventType: string;\n content: Content;\n relatexTxnId: string | null;\n relatedEventId: string | null;\n txnId?: string;\n needsEncryption: boolean;\n needsUpload: boolean;\n key: string;\n}\n\nfunction encodeKey(roomId: string, queueIndex: number): string {\n return `${roomId}|${encodeUint32(queueIndex)}`;\n}\n\nfunction decodeKey(key: string): { roomId: string, queueIndex: number } {\n const [roomId, encodedQueueIndex] = key.split(\"|\");\n const queueIndex = decodeUint32(encodedQueueIndex);\n return {roomId, queueIndex};\n}\n\nexport class PendingEventStore {\n private _eventStore: Store;\n\n constructor(eventStore: Store) {\n this._eventStore = eventStore;\n }\n\n async getMaxQueueIndex(roomId: string): Promise {\n const range = this._eventStore.IDBKeyRange.bound(\n encodeKey(roomId, KeyLimits.minStorageKey),\n encodeKey(roomId, KeyLimits.maxStorageKey),\n false,\n false,\n );\n const maxKey = await this._eventStore.findMaxKey(range);\n if (maxKey) {\n return decodeKey(maxKey as string).queueIndex;\n }\n }\n\n remove(roomId: string, queueIndex: number) {\n const keyRange = this._eventStore.IDBKeyRange.only(encodeKey(roomId, queueIndex));\n this._eventStore.delete(keyRange);\n }\n\n async exists(roomId: string, queueIndex: number): Promise {\n const keyRange = this._eventStore.IDBKeyRange.only(encodeKey(roomId, queueIndex));\n const key = await this._eventStore.getKey(keyRange);\n return !!key;\n }\n \n add(pendingEvent: PendingEntry): void {\n pendingEvent.key = encodeKey(pendingEvent.roomId, pendingEvent.queueIndex);\n this._eventStore.add(pendingEvent);\n }\n\n update(pendingEvent: PendingEntry): void {\n this._eventStore.put(pendingEvent);\n }\n\n getAll(): Promise {\n return this._eventStore.selectAll();\n }\n\n removeAllForRoom(roomId: string): void {\n const minKey = encodeKey(roomId, KeyLimits.minStorageKey);\n const maxKey = encodeKey(roomId, KeyLimits.maxStorageKey);\n const range = this._eventStore.IDBKeyRange.bound(minKey, maxKey);\n this._eventStore.delete(range);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Store} from \"../Store\";\n\ninterface UserIdentity {\n userId: string;\n roomIds: string[];\n deviceTrackingStatus: number;\n}\n\nexport class UserIdentityStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n get(userId: string): Promise {\n return this._store.get(userId);\n }\n\n set(userIdentity: UserIdentity): void {\n this._store.put(userIdentity);\n }\n\n remove(userId: string): void {\n this._store.delete(userId);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MAX_UNICODE, MIN_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\n\nexport interface DeviceIdentity {\n userId: string;\n deviceId: string;\n ed25519Key: string;\n curve25519Key: string;\n algorithms: string[];\n displayName: string;\n key: string;\n}\n\nfunction encodeKey(userId: string, deviceId: string): string {\n return `${userId}|${deviceId}`;\n}\n\nfunction decodeKey(key: string): { userId: string, deviceId: string } {\n const [userId, deviceId] = key.split(\"|\");\n return {userId, deviceId};\n}\n\nexport class DeviceIdentityStore {\n private _store: Store;\n \n constructor(store: Store) {\n this._store = store;\n }\n\n getAllForUserId(userId: string): Promise {\n const range = this._store.IDBKeyRange.lowerBound(encodeKey(userId, \"\"));\n return this._store.selectWhile(range, device => {\n return device.userId === userId;\n });\n }\n\n async getAllDeviceIds(userId: string): Promise {\n const deviceIds: string[] = [];\n const range = this._store.IDBKeyRange.lowerBound(encodeKey(userId, \"\"));\n await this._store.iterateKeys(range, key => {\n const decodedKey = decodeKey(key as string);\n // prevent running into the next room\n if (decodedKey.userId === userId) {\n deviceIds.push(decodedKey.deviceId);\n return false; // fetch more\n }\n return true; // done\n });\n return deviceIds;\n }\n\n get(userId: string, deviceId: string): Promise {\n return this._store.get(encodeKey(userId, deviceId));\n }\n\n set(deviceIdentity: DeviceIdentity): void {\n deviceIdentity.key = encodeKey(deviceIdentity.userId, deviceIdentity.deviceId);\n this._store.put(deviceIdentity);\n }\n\n getByCurve25519Key(curve25519Key: string): Promise {\n return this._store.index(\"byCurve25519Key\").get(curve25519Key);\n }\n\n remove(userId: string, deviceId: string): void {\n this._store.delete(encodeKey(userId, deviceId));\n }\n\n removeAllForUser(userId: string): void {\n // exclude both keys as they are theoretical min and max,\n // but we should't have a match for just the room id, or room id with max\n const range = this._store.IDBKeyRange.bound(encodeKey(userId, MIN_UNICODE), encodeKey(userId, MAX_UNICODE), true, true);\n this._store.delete(range);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Store} from \"../Store\";\n\nfunction encodeKey(senderKey: string, sessionId: string): string {\n return `${senderKey}|${sessionId}`;\n}\n\nfunction decodeKey(key: string): { senderKey: string, sessionId: string } {\n const [senderKey, sessionId] = key.split(\"|\");\n return {senderKey, sessionId};\n}\n\nexport type OlmSessionEntry = {\n session: string;\n sessionId: string;\n senderKey: string;\n lastUsed: number;\n}\n\ntype OlmSessionStoredEntry = OlmSessionEntry & { key: string };\n\nexport class OlmSessionStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n async getSessionIds(senderKey: string): Promise {\n const sessionIds: string[] = [];\n const range = this._store.IDBKeyRange.lowerBound(encodeKey(senderKey, \"\"));\n await this._store.iterateKeys(range, key => {\n const decodedKey = decodeKey(key as string);\n // prevent running into the next room\n if (decodedKey.senderKey === senderKey) {\n sessionIds.push(decodedKey.sessionId);\n return false; // fetch more\n }\n return true; // done\n });\n return sessionIds;\n }\n\n getAll(senderKey: string): Promise {\n const range = this._store.IDBKeyRange.lowerBound(encodeKey(senderKey, \"\"));\n return this._store.selectWhile(range, session => {\n return session.senderKey === senderKey;\n });\n }\n\n get(senderKey: string, sessionId: string): Promise {\n return this._store.get(encodeKey(senderKey, sessionId));\n }\n\n set(session: OlmSessionEntry): void {\n (session as OlmSessionStoredEntry).key = encodeKey(session.senderKey, session.sessionId);\n this._store.put(session as OlmSessionStoredEntry);\n }\n\n remove(senderKey: string, sessionId: string): void {\n this._store.delete(encodeKey(senderKey, sessionId));\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MIN_UNICODE, MAX_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\n\nexport enum BackupStatus {\n NotBackedUp = 0,\n BackedUp = 1\n}\n\nexport enum KeySource {\n DeviceMessage = 1,\n Backup,\n Outbound\n}\n\nexport interface InboundGroupSessionEntry {\n roomId: string;\n senderKey: string;\n sessionId: string;\n session?: string;\n claimedKeys?: { [algorithm : string] : string };\n eventIds?: string[];\n backup: BackupStatus,\n source: KeySource\n}\n\ntype InboundGroupSessionStorageEntry = InboundGroupSessionEntry & { key: string };\n\n\nfunction encodeKey(roomId: string, senderKey: string, sessionId: string): string {\n return `${roomId}|${senderKey}|${sessionId}`;\n}\n\nexport class InboundGroupSessionStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n async has(roomId: string, senderKey: string, sessionId: string): Promise {\n const key = encodeKey(roomId, senderKey, sessionId);\n const fetchedKey = await this._store.getKey(key);\n return key === fetchedKey;\n }\n\n get(roomId: string, senderKey: string, sessionId: string): Promise {\n return this._store.get(encodeKey(roomId, senderKey, sessionId));\n }\n\n set(session: InboundGroupSessionEntry): void {\n const storageEntry = session as InboundGroupSessionStorageEntry;\n storageEntry.key = encodeKey(session.roomId, session.senderKey, session.sessionId);\n this._store.put(storageEntry);\n }\n\n removeAllForRoom(roomId: string) {\n const range = this._store.IDBKeyRange.bound(\n encodeKey(roomId, MIN_UNICODE, MIN_UNICODE),\n encodeKey(roomId, MAX_UNICODE, MAX_UNICODE)\n );\n this._store.delete(range);\n }\n countNonBackedUpSessions(): Promise {\n return this._store.index(\"byBackup\").count(this._store.IDBKeyRange.only(BackupStatus.NotBackedUp));\n }\n\n getFirstNonBackedUpSessions(amount: number): Promise {\n return this._store.index(\"byBackup\").selectLimit(this._store.IDBKeyRange.only(BackupStatus.NotBackedUp), amount);\n }\n\n async markAsBackedUp(roomId: string, senderKey: string, sessionId: string): Promise {\n const entry = await this._store.get(encodeKey(roomId, senderKey, sessionId));\n if (entry) {\n entry.backup = BackupStatus.BackedUp;\n this._store.put(entry);\n }\n }\n\n async markAllAsNotBackedUp(): Promise {\n const backedUpKey = this._store.IDBKeyRange.only(BackupStatus.BackedUp);\n let count = 0;\n await this._store.index(\"byBackup\").iterateValues(backedUpKey, (val: InboundGroupSessionEntry, key: IDBValidKey, cur: IDBCursorWithValue) => {\n val.backup = BackupStatus.NotBackedUp;\n cur.update(val);\n count += 1;\n return false;\n });\n return count;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Store} from \"../Store\";\n\ninterface OutboundSession {\n roomId: string;\n session: string;\n createdAt: number;\n}\n\nexport class OutboundGroupSessionStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n remove(roomId: string): void {\n this._store.delete(roomId);\n }\n\n get(roomId: string): Promise {\n return this._store.get(roomId);\n }\n\n set(session: OutboundSession): void {\n this._store.put(session);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MIN_UNICODE, MAX_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\n\nfunction encodeKey(roomId: string, sessionId: string, messageIndex: number | string): string {\n return `${roomId}|${sessionId}|${messageIndex}`;\n}\n\ninterface GroupSessionDecryption {\n eventId: string;\n timestamp: number;\n}\n\ntype GroupSessionEntry = GroupSessionDecryption & { key: string }\n\nexport class GroupSessionDecryptionStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n get(roomId: string, sessionId: string, messageIndex: number): Promise {\n return this._store.get(encodeKey(roomId, sessionId, messageIndex));\n }\n\n set(roomId: string, sessionId: string, messageIndex: number, decryption: GroupSessionDecryption): void {\n (decryption as GroupSessionEntry).key = encodeKey(roomId, sessionId, messageIndex);\n this._store.put(decryption as GroupSessionEntry);\n }\n \n removeAllForRoom(roomId: string): void {\n const range = this._store.IDBKeyRange.bound(\n encodeKey(roomId, MIN_UNICODE, MIN_UNICODE),\n encodeKey(roomId, MAX_UNICODE, MAX_UNICODE)\n );\n this._store.delete(range);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {MIN_UNICODE, MAX_UNICODE} from \"./common\";\nimport {Store} from \"../Store\";\n\nexport function encodeScopeTypeKey(scope: string, type: string): string {\n return `${scope}|${type}`;\n}\n\ninterface BaseOperation {\n id: string;\n scope: string;\n userIds: string[];\n}\n\ntype OperationType = { type: \"share_room_key\"; roomKeyMessage: RoomKeyMessage; }\n\ntype Operation = BaseOperation & OperationType\n\ntype OperationEntry = Operation & { scopeTypeKey: string; }\n\ninterface RoomKeyMessage {\n room_id: string;\n session_id: string;\n session_key: string;\n algorithm: string;\n chain_index: number;\n}\n\nexport class OperationStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n getAll(): Promise {\n return this._store.selectAll();\n }\n\n async getAllByTypeAndScope(type: string, scope: string): Promise {\n const key = encodeScopeTypeKey(scope, type);\n const results: Operation[] = [];\n await this._store.index(\"byScopeAndType\").iterateWhile(key, value => {\n if (value.scopeTypeKey !== key) {\n return false;\n }\n results.push(value);\n return true;\n });\n return results;\n }\n\n add(operation: Operation): void {\n (operation as OperationEntry).scopeTypeKey = encodeScopeTypeKey(operation.scope, operation.type);\n this._store.add(operation as OperationEntry);\n }\n\n update(operation: Operation): void {\n this._store.put(operation as OperationEntry);\n }\n\n remove(id: string): void {\n this._store.delete(id);\n }\n\n async removeAllForScope(scope: string): Promise {\n const range = this._store.IDBKeyRange.bound(\n encodeScopeTypeKey(scope, MIN_UNICODE),\n encodeScopeTypeKey(scope, MAX_UNICODE)\n );\n const index = this._store.index(\"byScopeAndType\");\n await index.iterateValues(range, (_, __, cur) => {\n cur.delete();\n return true;\n });\n return;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Store} from \"../Store\";\nimport {Content} from \"../../types\";\n\ninterface AccountDataEntry {\n type: string;\n content: Content;\n}\n\nexport class AccountDataStore {\n private _store: Store;\n\n constructor(store: Store) {\n this._store = store;\n }\n\n async get(type: string): Promise {\n return await this._store.get(type);\n }\n\n set(event: AccountDataEntry): void {\n this._store.put(event);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {StoreNames} from \"../common\";\nimport {txnAsPromise} from \"./utils\";\nimport {StorageError} from \"../common\";\nimport {Store} from \"./Store\";\nimport {Storage} from \"./Storage\";\nimport {SessionStore} from \"./stores/SessionStore\";\nimport {RoomSummaryStore} from \"./stores/RoomSummaryStore\";\nimport {InviteStore} from \"./stores/InviteStore\";\nimport {TimelineEventStore} from \"./stores/TimelineEventStore\";\nimport {TimelineRelationStore} from \"./stores/TimelineRelationStore\";\nimport {RoomStateStore} from \"./stores/RoomStateStore\";\nimport {RoomMemberStore} from \"./stores/RoomMemberStore\";\nimport {TimelineFragmentStore} from \"./stores/TimelineFragmentStore\";\nimport {PendingEventStore} from \"./stores/PendingEventStore\";\nimport {UserIdentityStore} from \"./stores/UserIdentityStore\";\nimport {DeviceIdentityStore} from \"./stores/DeviceIdentityStore\";\nimport {OlmSessionStore} from \"./stores/OlmSessionStore\";\nimport {InboundGroupSessionStore} from \"./stores/InboundGroupSessionStore\";\nimport {OutboundGroupSessionStore} from \"./stores/OutboundGroupSessionStore\";\nimport {GroupSessionDecryptionStore} from \"./stores/GroupSessionDecryptionStore\";\nimport {OperationStore} from \"./stores/OperationStore\";\nimport {AccountDataStore} from \"./stores/AccountDataStore\";\nimport type {ILogger, ILogItem} from \"../../../logging/types\";\n\nexport type IDBKey = IDBValidKey | IDBKeyRange;\n\nclass WriteErrorInfo {\n constructor(\n public readonly error: StorageError,\n public readonly refItem: ILogItem | undefined,\n public readonly operationName: string,\n public readonly keys: IDBKey[] | undefined,\n ) {}\n}\n\nexport class Transaction {\n private _txn: IDBTransaction;\n private _allowedStoreNames: StoreNames[];\n private _stores: { [storeName in StoreNames]?: any };\n private _storage: Storage;\n private _writeErrors: WriteErrorInfo[];\n\n constructor(txn: IDBTransaction, allowedStoreNames: StoreNames[], storage: Storage) {\n this._txn = txn;\n this._allowedStoreNames = allowedStoreNames;\n this._stores = {};\n this._storage = storage;\n this._writeErrors = [];\n }\n\n get idbFactory(): IDBFactory {\n return this._storage.idbFactory;\n }\n\n get IDBKeyRange(): typeof IDBKeyRange {\n return this._storage.IDBKeyRange;\n }\n\n get databaseName(): string {\n return this._storage.databaseName;\n }\n\n get logger(): ILogger {\n return this._storage.logger;\n }\n\n _idbStore(name: StoreNames): Store {\n if (!this._allowedStoreNames.includes(name)) {\n // more specific error? this is a bug, so maybe not ...\n throw new StorageError(`Invalid store for transaction: ${name}, only ${this._allowedStoreNames.join(\", \")} are allowed.`);\n }\n return new Store(this._txn.objectStore(name), this);\n }\n\n _store(name: StoreNames, mapStore: (idbStore: Store) => T): T {\n if (!this._stores[name]) {\n const idbStore = this._idbStore(name);\n this._stores[name] = mapStore(idbStore);\n }\n return this._stores[name];\n }\n\n get session(): SessionStore {\n return this._store(StoreNames.session, idbStore => new SessionStore(idbStore, this._storage.localStorage));\n }\n\n get roomSummary(): RoomSummaryStore {\n return this._store(StoreNames.roomSummary, idbStore => new RoomSummaryStore(idbStore));\n }\n \n get archivedRoomSummary(): RoomSummaryStore {\n return this._store(StoreNames.archivedRoomSummary, idbStore => new RoomSummaryStore(idbStore));\n }\n\n get invites(): InviteStore {\n return this._store(StoreNames.invites, idbStore => new InviteStore(idbStore));\n }\n\n get timelineFragments(): TimelineFragmentStore {\n return this._store(StoreNames.timelineFragments, idbStore => new TimelineFragmentStore(idbStore));\n }\n\n get timelineEvents(): TimelineEventStore {\n return this._store(StoreNames.timelineEvents, idbStore => new TimelineEventStore(idbStore));\n }\n\n get timelineRelations(): TimelineRelationStore {\n return this._store(StoreNames.timelineRelations, idbStore => new TimelineRelationStore(idbStore));\n }\n\n get roomState(): RoomStateStore {\n return this._store(StoreNames.roomState, idbStore => new RoomStateStore(idbStore));\n }\n\n get roomMembers(): RoomMemberStore {\n return this._store(StoreNames.roomMembers, idbStore => new RoomMemberStore(idbStore));\n }\n\n get pendingEvents(): PendingEventStore {\n return this._store(StoreNames.pendingEvents, idbStore => new PendingEventStore(idbStore));\n }\n\n get userIdentities(): UserIdentityStore {\n return this._store(StoreNames.userIdentities, idbStore => new UserIdentityStore(idbStore));\n }\n\n get deviceIdentities(): DeviceIdentityStore {\n return this._store(StoreNames.deviceIdentities, idbStore => new DeviceIdentityStore(idbStore));\n }\n \n get olmSessions(): OlmSessionStore {\n return this._store(StoreNames.olmSessions, idbStore => new OlmSessionStore(idbStore));\n }\n \n get inboundGroupSessions(): InboundGroupSessionStore {\n return this._store(StoreNames.inboundGroupSessions, idbStore => new InboundGroupSessionStore(idbStore));\n }\n \n get outboundGroupSessions(): OutboundGroupSessionStore {\n return this._store(StoreNames.outboundGroupSessions, idbStore => new OutboundGroupSessionStore(idbStore));\n }\n\n get groupSessionDecryptions(): GroupSessionDecryptionStore {\n return this._store(StoreNames.groupSessionDecryptions, idbStore => new GroupSessionDecryptionStore(idbStore));\n }\n\n get operations(): OperationStore {\n return this._store(StoreNames.operations, idbStore => new OperationStore(idbStore));\n }\n\n get accountData(): AccountDataStore {\n return this._store(StoreNames.accountData, idbStore => new AccountDataStore(idbStore));\n }\n\n async complete(log?: ILogItem): Promise {\n try {\n await txnAsPromise(this._txn);\n } catch (err) {\n if (this._writeErrors.length) {\n this._logWriteErrors(log);\n throw this._writeErrors[0].error;\n }\n throw err;\n }\n }\n\n getCause(error: Error) {\n if (error instanceof StorageError) {\n if (error.errcode === \"AbortError\" && this._writeErrors.length) {\n return this._writeErrors[0].error;\n }\n }\n return error;\n }\n\n abort(log?: ILogItem): void {\n // TODO: should we wrap the exception in a StorageError?\n try {\n this._txn.abort();\n } catch (abortErr) {\n log?.set(\"couldNotAbortTxn\", true);\n }\n if (this._writeErrors.length) {\n this._logWriteErrors(log);\n }\n }\n\n addWriteError(error: StorageError, refItem: ILogItem | undefined, operationName: string, keys: IDBKey[] | undefined) {\n // don't log subsequent `AbortError`s\n if (error.errcode !== \"AbortError\" || this._writeErrors.length === 0) {\n this._writeErrors.push(new WriteErrorInfo(error, refItem, operationName, keys));\n }\n }\n\n private _logWriteErrors(parentItem: ILogItem | undefined) {\n const callback = errorGroupItem => {\n // we don't have context when there is no parentItem, so at least log stores\n if (!parentItem) {\n errorGroupItem.set(\"allowedStoreNames\", this._allowedStoreNames);\n }\n for (const info of this._writeErrors) {\n errorGroupItem.wrap({l: info.operationName, id: info.keys}, item => {\n if (info.refItem) {\n item.refDetached(info.refItem);\n }\n item.catch(info.error);\n });\n }\n };\n const label = `${this._writeErrors.length} storage write operation(s) failed`;\n if (parentItem) {\n parentItem.wrap(label, callback);\n } else {\n this.logger.run(label, callback);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {IDOMStorage} from \"./types\";\nimport {Transaction} from \"./Transaction\";\nimport { STORE_NAMES, StoreNames, StorageError } from \"../common\";\nimport { reqAsPromise } from \"./utils\";\nimport { ILogger } from \"../../../logging/types\";\n\nconst WEBKITEARLYCLOSETXNBUG_BOGUS_KEY = \"782rh281re38-boguskey\";\n\nexport class Storage {\n private _db: IDBDatabase;\n private _hasWebkitEarlyCloseTxnBug: boolean;\n\n readonly logger: ILogger;\n readonly idbFactory: IDBFactory\n readonly IDBKeyRange: typeof IDBKeyRange;\n readonly storeNames: typeof StoreNames;\n readonly localStorage: IDOMStorage;\n\n constructor(idbDatabase: IDBDatabase, idbFactory: IDBFactory, _IDBKeyRange: typeof IDBKeyRange, hasWebkitEarlyCloseTxnBug: boolean, localStorage: IDOMStorage, logger: ILogger) {\n this._db = idbDatabase;\n this.idbFactory = idbFactory;\n this.IDBKeyRange = _IDBKeyRange;\n this._hasWebkitEarlyCloseTxnBug = hasWebkitEarlyCloseTxnBug;\n this.storeNames = StoreNames;\n this.localStorage = localStorage;\n this.logger = logger;\n }\n\n _validateStoreNames(storeNames: StoreNames[]): void {\n const idx = storeNames.findIndex(name => !STORE_NAMES.includes(name));\n if (idx !== -1) {\n throw new StorageError(`Tried top, a transaction unknown store ${storeNames[idx]}`);\n }\n }\n\n async readTxn(storeNames: StoreNames[]): Promise {\n this._validateStoreNames(storeNames);\n try {\n const txn = this._db.transaction(storeNames, \"readonly\");\n // https://bugs.webkit.org/show_bug.cgi?id=222746 workaround,\n // await a bogus idb request on the new txn so it doesn't close early if we await a microtask first\n if (this._hasWebkitEarlyCloseTxnBug) {\n await reqAsPromise(txn.objectStore(storeNames[0]).get(WEBKITEARLYCLOSETXNBUG_BOGUS_KEY));\n }\n return new Transaction(txn, storeNames, this);\n } catch(err) {\n throw new StorageError(\"readTxn failed\", err);\n }\n }\n\n async readWriteTxn(storeNames: StoreNames[]): Promise {\n this._validateStoreNames(storeNames);\n try {\n const txn = this._db.transaction(storeNames, \"readwrite\");\n // https://bugs.webkit.org/show_bug.cgi?id=222746 workaround,\n // await a bogus idb request on the new txn so it doesn't close early if we await a microtask first\n if (this._hasWebkitEarlyCloseTxnBug) {\n await reqAsPromise(txn.objectStore(storeNames[0]).get(WEBKITEARLYCLOSETXNBUG_BOGUS_KEY));\n }\n return new Transaction(txn, storeNames, this);\n } catch(err) {\n throw new StorageError(\"readWriteTxn failed\", err);\n }\n }\n\n close(): void {\n this._db.close();\n }\n\n get databaseName(): string {\n return this._db.name;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { iterateCursor, NOT_DONE, txnAsPromise } from \"./utils\";\nimport { STORE_NAMES, StoreNames } from \"../common\";\n\nexport type Export = { [storeName in StoreNames] : any[] }\n\nexport async function exportSession(db: IDBDatabase): Promise {\n const txn = db.transaction(STORE_NAMES, \"readonly\");\n const data = {};\n await Promise.all(STORE_NAMES.map(async name => {\n const results: any[] = data[name] = []; // initialize in deterministic order\n const store = txn.objectStore(name);\n await iterateCursor(store.openCursor(), (value) => {\n results.push(value);\n return NOT_DONE;\n });\n }));\n return data as Export;\n}\n\nexport async function importSession(db: IDBDatabase, data: Export): Promise {\n const txn = db.transaction(STORE_NAMES, \"readwrite\");\n for (const name of STORE_NAMES) {\n const store = txn.objectStore(name);\n for (const value of data[name]) {\n store.add(value);\n }\n }\n await txnAsPromise(txn);\n}\n","import {IDOMStorage} from \"./types\";\nimport {ITransaction} from \"./QueryTarget\";\nimport {iterateCursor, NOT_DONE, reqAsPromise} from \"./utils\";\nimport {RoomMember, EVENT_TYPE as MEMBER_EVENT_TYPE} from \"../../room/members/RoomMember.js\";\nimport {SESSION_E2EE_KEY_PREFIX} from \"../../e2ee/common.js\";\nimport {SummaryData} from \"../../room/RoomSummary\";\nimport {RoomMemberStore, MemberData} from \"./stores/RoomMemberStore\";\nimport {InboundGroupSessionStore, InboundGroupSessionEntry, BackupStatus, KeySource} from \"./stores/InboundGroupSessionStore\";\nimport {RoomStateEntry} from \"./stores/RoomStateStore\";\nimport {SessionStore} from \"./stores/SessionStore\";\nimport {Store} from \"./Store\";\nimport {encodeScopeTypeKey} from \"./stores/OperationStore\";\nimport {MAX_UNICODE} from \"./stores/common\";\nimport {ILogItem} from \"../../../logging/types\";\n\n\nexport type MigrationFunc = (db: IDBDatabase, txn: IDBTransaction, localStorage: IDOMStorage, log: ILogItem) => Promise | void;\n// FUNCTIONS SHOULD ONLY BE APPENDED!!\n// the index in the array is the database version\nexport const schema: MigrationFunc[] = [\n createInitialStores,\n createMemberStore,\n migrateSession,\n createE2EEStores,\n migrateEncryptionFlag,\n createAccountDataStore,\n createInviteStore,\n createArchivedRoomSummaryStore,\n migrateOperationScopeIndex,\n createTimelineRelationsStore,\n fixMissingRoomsInUserIdentities,\n changeSSSSKeyPrefix,\n backupAndRestoreE2EEAccountToLocalStorage,\n clearAllStores,\n addInboundSessionBackupIndex,\n migrateBackupStatus\n];\n// TODO: how to deal with git merge conflicts of this array?\n\n// TypeScript note: for now, do not bother introducing interfaces / alias\n// for old schemas. Just take them as `any`. \n\nfunction createDatabaseNameHelper(db: IDBDatabase): ITransaction {\n // the Store object gets passed in several things through the Transaction class (a wrapper around IDBTransaction),\n // the only thing we should need here is the databaseName though, so we mock it out.\n // ideally we should have an easier way to go from the idb primitive layer to the specific store classes where\n // we implement logic, but for now we need this.\n const databaseNameHelper: ITransaction = {\n databaseName: db.name,\n get idbFactory(): IDBFactory { throw new Error(\"unused\");},\n get IDBKeyRange(): typeof IDBKeyRange { throw new Error(\"unused\");},\n addWriteError() {},\n };\n return databaseNameHelper;\n}\n\n\n// how do we deal with schema updates vs existing data migration in a way that \n//v1\nfunction createInitialStores(db: IDBDatabase): void {\n db.createObjectStore(\"session\", {keyPath: \"key\"});\n // any way to make keys unique here? (just use put?)\n db.createObjectStore(\"roomSummary\", {keyPath: \"roomId\"});\n\n // need index to find live fragment? prooobably ok without for now\n //key = room_id | fragment_id\n db.createObjectStore(\"timelineFragments\", {keyPath: \"key\"});\n //key = room_id | fragment_id | event_index\n const timelineEvents = db.createObjectStore(\"timelineEvents\", {keyPath: \"key\"});\n //eventIdKey = room_id | event_id\n timelineEvents.createIndex(\"byEventId\", \"eventIdKey\", {unique: true});\n //key = room_id | event.type | event.state_key,\n db.createObjectStore(\"roomState\", {keyPath: \"key\"});\n db.createObjectStore(\"pendingEvents\", {keyPath: \"key\"});\n}\n//v2\nasync function createMemberStore(db: IDBDatabase, txn: IDBTransaction): Promise {\n // Cast ok here because only \"set\" is used\n const roomMembers = new RoomMemberStore(db.createObjectStore(\"roomMembers\", {keyPath: \"key\"}) as any);\n // migrate existing member state events over\n const roomState = txn.objectStore(\"roomState\");\n await iterateCursor(roomState.openCursor(), entry => {\n if (entry.event.type === MEMBER_EVENT_TYPE) {\n roomState.delete(entry.key);\n const member = RoomMember.fromMemberEvent(entry.roomId, entry.event);\n if (member) {\n roomMembers.set(member.serialize());\n }\n }\n return NOT_DONE;\n });\n}\n//v3\nasync function migrateSession(db: IDBDatabase, txn: IDBTransaction, localStorage: IDOMStorage): Promise {\n const session = txn.objectStore(\"session\");\n try {\n const PRE_MIGRATION_KEY = 1;\n const entry = await reqAsPromise(session.get(PRE_MIGRATION_KEY));\n if (entry) {\n session.delete(PRE_MIGRATION_KEY);\n const {syncToken, syncFilterId, serverVersions} = entry.value;\n // Cast ok here because only \"set\" is used and we don't look into return\n const store = new SessionStore(session as any, localStorage);\n store.set(\"sync\", {token: syncToken, filterId: syncFilterId});\n store.set(\"serverVersions\", serverVersions);\n }\n } catch (err) {\n txn.abort();\n console.error(\"could not migrate session\", err.stack);\n }\n}\n//v4\nfunction createE2EEStores(db: IDBDatabase): void {\n db.createObjectStore(\"userIdentities\", {keyPath: \"userId\"});\n const deviceIdentities = db.createObjectStore(\"deviceIdentities\", {keyPath: \"key\"});\n deviceIdentities.createIndex(\"byCurve25519Key\", \"curve25519Key\", {unique: true});\n db.createObjectStore(\"olmSessions\", {keyPath: \"key\"});\n db.createObjectStore(\"inboundGroupSessions\", {keyPath: \"key\"});\n db.createObjectStore(\"outboundGroupSessions\", {keyPath: \"roomId\"});\n db.createObjectStore(\"groupSessionDecryptions\", {keyPath: \"key\"});\n const operations = db.createObjectStore(\"operations\", {keyPath: \"id\"});\n operations.createIndex(\"byTypeAndScope\", \"typeScopeKey\", {unique: false});\n}\n\n// v5\nasync function migrateEncryptionFlag(db: IDBDatabase, txn: IDBTransaction): Promise {\n // migrate room summary isEncrypted -> encryption prop\n const roomSummary = txn.objectStore(\"roomSummary\");\n const roomState = txn.objectStore(\"roomState\");\n const summaries: any[] = [];\n await iterateCursor(roomSummary.openCursor(), summary => {\n summaries.push(summary);\n return NOT_DONE;\n });\n for (const summary of summaries) {\n const encryptionEntry = await reqAsPromise(roomState.get(`${summary.roomId}|m.room.encryption|`));\n if (encryptionEntry) {\n summary.encryption = encryptionEntry?.event?.content;\n delete summary.isEncrypted;\n roomSummary.put(summary);\n }\n }\n}\n\n// v6\nfunction createAccountDataStore(db: IDBDatabase): void {\n db.createObjectStore(\"accountData\", {keyPath: \"type\"});\n}\n\n// v7\nfunction createInviteStore(db: IDBDatabase): void {\n db.createObjectStore(\"invites\", {keyPath: \"roomId\"});\n}\n\n// v8\nfunction createArchivedRoomSummaryStore(db: IDBDatabase): void {\n db.createObjectStore(\"archivedRoomSummary\", {keyPath: \"summary.roomId\"});\n}\n\n// v9\nasync function migrateOperationScopeIndex(db: IDBDatabase, txn: IDBTransaction): Promise {\n try {\n const operations = txn.objectStore(\"operations\");\n operations.deleteIndex(\"byTypeAndScope\");\n await iterateCursor(operations.openCursor(), (op, key, cur) => {\n const {typeScopeKey} = op;\n delete op.typeScopeKey;\n const [type, scope] = typeScopeKey.split(\"|\");\n op.scopeTypeKey = encodeScopeTypeKey(scope, type);\n cur.update(op);\n return NOT_DONE;\n });\n operations.createIndex(\"byScopeAndType\", \"scopeTypeKey\", {unique: false});\n } catch (err) {\n txn.abort();\n console.error(\"could not migrate operations\", err.stack);\n }\n}\n\n//v10\nfunction createTimelineRelationsStore(db: IDBDatabase) : void {\n db.createObjectStore(\"timelineRelations\", {keyPath: \"key\"});\n}\n\n//v11 doesn't change the schema,\n// but ensured all userIdentities have all the roomIds they should (see #470)\n\n// 2022-07-20: The fix dated from August 2021, and have removed it now because of a\n// refactoring needed in the device tracker, which made it inconvenient to expose addRoomToIdentity\nfunction fixMissingRoomsInUserIdentities() {}\n\n// v12 move ssssKey to e2ee:ssssKey so it will get backed up in the next step\nasync function changeSSSSKeyPrefix(db: IDBDatabase, txn: IDBTransaction) {\n const session = txn.objectStore(\"session\");\n const ssssKey = await reqAsPromise(session.get(\"ssssKey\"));\n if (ssssKey) {\n session.put({key: `${SESSION_E2EE_KEY_PREFIX}ssssKey`, value: ssssKey.value});\n }\n}\n// v13\nasync function backupAndRestoreE2EEAccountToLocalStorage(db: IDBDatabase, txn: IDBTransaction, localStorage: IDOMStorage, log: ILogItem) {\n const session = txn.objectStore(\"session\");\n const sessionStore = new SessionStore(new Store(session, createDatabaseNameHelper(db)), localStorage);\n // if we already have an e2ee identity, write a backup to local storage.\n // further updates to e2ee keys in the session store will also write to local storage from 0.2.15 on,\n // but here we make sure a backup is immediately created after installing the update and we don't wait until\n // the olm account needs to change\n sessionStore.writeE2EEIdentityToLocalStorage();\n // and if we already have a backup, restore it now for any missing key in idb.\n // this will restore the backup every time the idb database is dropped as it will\n // run through all the migration steps when recreating it.\n const restored = await sessionStore.tryRestoreE2EEIdentityFromLocalStorage(log);\n log.set(\"restored\", restored);\n}\n// v14 clear all stores apart from e2ee keys because of possible timeline corruption in #515, will trigger initial sync\nasync function clearAllStores(db: IDBDatabase, txn: IDBTransaction) {\n for (const storeName of db.objectStoreNames) {\n const store = txn.objectStore(storeName);\n switch (storeName) {\n case \"inboundGroupSessions\":\n case \"outboundGroupSessions\":\n case \"olmSessions\":\n case \"operations\":\n continue;\n case \"session\": {\n await iterateCursor(store.openCursor(), (value, key, cursor) => {\n if (!(key as string).startsWith(SESSION_E2EE_KEY_PREFIX)) {\n cursor.delete();\n }\n return NOT_DONE;\n })\n break;\n }\n default: {\n store.clear();\n break;\n }\n }\n }\n}\n\n// v15 add backup index to inboundGroupSessions\nasync function addInboundSessionBackupIndex(db: IDBDatabase, txn: IDBTransaction, localStorage: IDOMStorage, log: ILogItem): Promise {\n const inboundGroupSessions = txn.objectStore(\"inboundGroupSessions\");\n inboundGroupSessions.createIndex(\"byBackup\", \"backup\", {unique: false});\n}\n\n\n// v16 migrates the backup and source fields of inbound group sessions\nasync function migrateBackupStatus(db: IDBDatabase, txn: IDBTransaction, localStorage: IDOMStorage, log: ILogItem): Promise {\n const inboundGroupSessions = txn.objectStore(\"inboundGroupSessions\");\n let countWithSession = 0;\n let countWithoutSession = 0;\n await iterateCursor(inboundGroupSessions.openCursor(), (value, key, cursor) => {\n if (value.session) {\n value.backup = BackupStatus.NotBackedUp;\n // we'll also have backup keys in here, we can't tell,\n // but the worst thing that can happen is that we try\n // to backup keys that were already in backup, which\n // the server will ignore\n value.source = KeySource.DeviceMessage;\n cursor.update(value);\n countWithSession += 1;\n } else {\n countWithoutSession += 1;\n }\n return NOT_DONE;\n });\n log.set(\"countWithoutSession\", countWithoutSession);\n log.set(\"countWithSession\", countWithSession);\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n\nimport {openDatabase, txnAsPromise, reqAsPromise} from \"./utils\";\n\n// filed as https://bugs.webkit.org/show_bug.cgi?id=222746\nexport async function detectWebkitEarlyCloseTxnBug(idbFactory: IDBFactory): Promise {\n const dbName = \"hydrogen_webkit_test_inactive_txn_bug\";\n try {\n const db = await openDatabase(dbName, db => {\n db.createObjectStore(\"test\", {keyPath: \"key\"});\n }, 1, idbFactory);\n const readTxn = db.transaction([\"test\"], \"readonly\");\n await reqAsPromise(readTxn.objectStore(\"test\").get(\"somekey\"));\n // schedule a macro task in between the two txns\n await new Promise(r => setTimeout(r, 0));\n const writeTxn = db.transaction([\"test\"], \"readwrite\");\n await Promise.resolve();\n writeTxn.objectStore(\"test\").add({key: \"somekey\", value: \"foo\"});\n await txnAsPromise(writeTxn);\n db.close();\n } catch (err) {\n if (err.name === \"TransactionInactiveError\") {\n return true;\n }\n }\n return false;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {IDOMStorage} from \"./types\";\nimport {Storage} from \"./Storage\";\nimport { openDatabase, reqAsPromise } from \"./utils\";\nimport { exportSession, importSession, Export } from \"./export\";\nimport { schema } from \"./schema\";\nimport { detectWebkitEarlyCloseTxnBug } from \"./quirks\";\nimport { ILogItem } from \"../../../logging/types\";\n\nconst sessionName = (sessionId: string) => `hydrogen_session_${sessionId}`;\nconst openDatabaseWithSessionId = function(sessionId: string, idbFactory: IDBFactory, localStorage: IDOMStorage, log: ILogItem) {\n const create = (db, txn, oldVersion, version) => createStores(db, txn, oldVersion, version, localStorage, log);\n return openDatabase(sessionName(sessionId), create, schema.length, idbFactory);\n}\n\ninterface ServiceWorkerHandler {\n preventConcurrentSessionAccess: (sessionId: string) => Promise;\n}\n\nasync function requestPersistedStorage(): Promise {\n // don't assume browser so we can run in node with fake-idb\n const glob = this;\n if (glob?.navigator?.storage?.persist) {\n return await glob.navigator.storage.persist();\n } else if (glob?.document.requestStorageAccess) {\n try {\n await glob.document.requestStorageAccess();\n return true;\n } catch (err) {\n console.warn(\"requestStorageAccess threw an error:\", err);\n return false;\n }\n } else {\n return false;\n }\n}\n\nexport class StorageFactory {\n private _serviceWorkerHandler: ServiceWorkerHandler;\n private _idbFactory: IDBFactory;\n private _IDBKeyRange: typeof IDBKeyRange;\n private _localStorage: IDOMStorage;\n\n constructor(serviceWorkerHandler: ServiceWorkerHandler, idbFactory: IDBFactory = window.indexedDB, _IDBKeyRange = window.IDBKeyRange, localStorage: IDOMStorage = window.localStorage) {\n this._serviceWorkerHandler = serviceWorkerHandler;\n this._idbFactory = idbFactory;\n this._IDBKeyRange = _IDBKeyRange;\n this._localStorage = localStorage;\n }\n\n async create(sessionId: string, log: ILogItem): Promise {\n await this._serviceWorkerHandler?.preventConcurrentSessionAccess(sessionId);\n requestPersistedStorage().then(persisted => {\n // Firefox lies here though, and returns true even if the user denied the request\n if (!persisted) {\n console.warn(\"no persisted storage, database can be evicted by browser\");\n }\n });\n\n const hasWebkitEarlyCloseTxnBug = await detectWebkitEarlyCloseTxnBug(this._idbFactory);\n const db = await openDatabaseWithSessionId(sessionId, this._idbFactory, this._localStorage, log);\n return new Storage(db, this._idbFactory, this._IDBKeyRange, hasWebkitEarlyCloseTxnBug, this._localStorage, log.logger);\n }\n\n delete(sessionId: string): Promise {\n const databaseName = sessionName(sessionId);\n const req = this._idbFactory.deleteDatabase(databaseName);\n return reqAsPromise(req);\n }\n\n async export(sessionId: string, log: ILogItem): Promise {\n const db = await openDatabaseWithSessionId(sessionId, this._idbFactory, this._localStorage, log);\n return await exportSession(db);\n }\n\n async import(sessionId: string, data: Export, log: ILogItem): Promise {\n const db = await openDatabaseWithSessionId(sessionId, this._idbFactory, this._localStorage, log);\n return await importSession(db, data);\n }\n}\n\nasync function createStores(db: IDBDatabase, txn: IDBTransaction, oldVersion: number | null, version: number, localStorage: IDOMStorage, log: ILogItem): Promise {\n const startIdx = oldVersion || 0;\n return log.wrap(\n { l: \"storage migration\", oldVersion, version },\n async (log) => {\n for (let i = startIdx; i < version; ++i) {\n const migrationFunc = schema[i];\n await log.wrap(`v${i + 1}`, (log) => migrationFunc(db, txn, localStorage, log));\n }\n });\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventEntry} from \"../entries/EventEntry.js\";\nimport {REDACTION_TYPE, isRedacted} from \"../../common\";\nimport {ANNOTATION_RELATION_TYPE, getRelation} from \"../relations.js\";\nimport {redactEvent} from \"../common.js\";\n\nexport class RelationWriter {\n constructor({roomId, ownUserId, fragmentIdComparer}) {\n this._roomId = roomId;\n this._ownUserId = ownUserId;\n this._fragmentIdComparer = fragmentIdComparer;\n }\n\n // this needs to happen again after decryption too for edits\n async writeRelation(sourceEntry, txn, log) {\n const {relatedEventId} = sourceEntry;\n if (relatedEventId) {\n const relation = getRelation(sourceEntry.event);\n if (relation && relation.rel_type) {\n // we don't consider replies (which aren't relations in the MSC2674 sense)\n txn.timelineRelations.add(this._roomId, relation.event_id, relation.rel_type, sourceEntry.id);\n }\n const target = await txn.timelineEvents.getByEventId(this._roomId, relatedEventId);\n if (target) {\n const updatedStorageEntries = await this._applyRelation(sourceEntry, target, txn, log);\n if (updatedStorageEntries) {\n return updatedStorageEntries.map(e => {\n txn.timelineEvents.update(e);\n return new EventEntry(e, this._fragmentIdComparer);\n });\n }\n }\n }\n return null;\n }\n\n /**\n * @param {Object} storageEntry the event object, as it will be stored in storage.\n * Will be modified (but not written to storage) in case this event is\n * a relation target for which we've previously received relations.\n * @param {Direction} direction of the gap fill\n * */\n async writeGapRelation(storageEntry, direction, txn, log) {\n const sourceEntry = new EventEntry(storageEntry, this._fragmentIdComparer);\n const result = await this.writeRelation(sourceEntry, txn, log);\n // when back-paginating, it can also happen that we've received relations\n // for this event before, which now upon receiving the target need to be aggregated.\n if (direction.isBackward && !isRedacted(storageEntry.event)) {\n const relations = await txn.timelineRelations.getAllForTarget(this._roomId, sourceEntry.id);\n if (relations.length) {\n for (const r of relations) {\n const relationStorageEntry = await txn.timelineEvents.getByEventId(this._roomId, r.sourceEventId);\n if (relationStorageEntry) {\n const relationEntry = new EventEntry(relationStorageEntry, this._fragmentIdComparer);\n await this._applyRelation(relationEntry, storageEntry, txn, log);\n }\n }\n }\n }\n\n return result;\n }\n\n /**\n * @param {EventEntry} sourceEntry\n * @param {Object} targetStorageEntry event entry as stored in the timelineEvents store\n * @return {[Object]} array of event storage entries that have been updated\n * */\n async _applyRelation(sourceEntry, targetStorageEntry, txn, log) {\n if (sourceEntry.eventType === REDACTION_TYPE) {\n return log.wrap(\"redact\", async log => {\n const redactedEvent = targetStorageEntry.event;\n const relation = getRelation(redactedEvent); // get this before redacting\n const redacted = this._applyRedaction(sourceEntry.event, targetStorageEntry, txn, log);\n if (redacted) {\n const updated = [targetStorageEntry];\n if (relation) {\n const relationTargetStorageEntry = await this._reaggregateRelation(redactedEvent, relation, txn, log);\n if (relationTargetStorageEntry) {\n updated.push(relationTargetStorageEntry);\n }\n }\n return updated;\n }\n return null;\n });\n } else {\n const relation = getRelation(sourceEntry.event);\n if (relation && !isRedacted(targetStorageEntry.event)) {\n const relType = relation.rel_type;\n if (relType === ANNOTATION_RELATION_TYPE) {\n const aggregated = log.wrap(\"react\", log => {\n return this._aggregateAnnotation(sourceEntry.event, targetStorageEntry, log);\n });\n if (aggregated) {\n return [targetStorageEntry];\n }\n }\n }\n }\n return null;\n }\n\n _applyRedaction(redactionEvent, redactedStorageEntry, txn, log) {\n const redactedEvent = redactedStorageEntry.event;\n log.set(\"redactionId\", redactionEvent.event_id);\n log.set(\"id\", redactedEvent.event_id);\n\n const relation = getRelation(redactedEvent);\n if (relation && relation.rel_type) {\n txn.timelineRelations.remove(this._roomId, relation.event_id, relation.rel_type, redactedEvent.event_id);\n }\n // check if we're the target of a relation and remove all relations then as well\n txn.timelineRelations.removeAllForTarget(this._roomId, redactedEvent.event_id);\n\n redactEvent(redactionEvent, redactedEvent);\n delete redactedStorageEntry.annotations;\n\n return true;\n }\n\n _aggregateAnnotation(annotationEvent, targetStorageEntry/*, log*/) {\n // TODO: do we want to verify it is a m.reaction event somehow?\n const relation = getRelation(annotationEvent);\n if (!relation) {\n return false;\n }\n\n let {annotations} = targetStorageEntry;\n if (!annotations) {\n targetStorageEntry.annotations = annotations = {};\n }\n let annotation = annotations[relation.key];\n if (!annotation) {\n annotations[relation.key] = annotation = {\n count: 0,\n me: false,\n firstTimestamp: Number.MAX_SAFE_INTEGER\n };\n }\n const sentByMe = annotationEvent.sender === this._ownUserId;\n\n annotation.me = annotation.me || sentByMe;\n annotation.count += 1;\n annotation.firstTimestamp = Math.min(\n annotation.firstTimestamp,\n annotationEvent.origin_server_ts\n );\n\n return true;\n }\n\n async _reaggregateRelation(redactedRelationEvent, redactedRelation, txn, log) {\n if (redactedRelation.rel_type === ANNOTATION_RELATION_TYPE) {\n return log.wrap(\"reaggregate annotations\", log => this._reaggregateAnnotation(\n redactedRelation.event_id,\n redactedRelation.key,\n txn, log\n ));\n }\n return null;\n }\n\n async _reaggregateAnnotation(targetId, key, txn, log) {\n const target = await txn.timelineEvents.getByEventId(this._roomId, targetId);\n if (!target || !target.annotations) { // unknown or redacted event\n return null;\n }\n log.set(\"id\", targetId);\n const relations = await txn.timelineRelations.getForTargetAndType(this._roomId, targetId, ANNOTATION_RELATION_TYPE);\n log.set(\"relations\", relations.length);\n delete target.annotations[key];\n if (isObjectEmpty(target.annotations)) {\n delete target.annotations;\n }\n await Promise.all(relations.map(async relation => {\n const annotation = await txn.timelineEvents.getByEventId(this._roomId, relation.sourceEventId);\n if (!annotation) {\n log.log({l: \"missing annotation\", id: relation.sourceEventId});\n }\n if (getRelation(annotation.event).key === key) {\n this._aggregateAnnotation(annotation.event, target, log);\n }\n }));\n return target;\n }\n}\n\nfunction isObjectEmpty(obj) {\n for (const key in obj) {\n if (obj.hasOwnProperty(key)) {\n return false;\n }\n }\n return true;\n}\n\n\nimport {createMockStorage} from \"../../../../mocks/Storage\";\nimport {createEvent, withTextBody, withRedacts, withContent} from \"../../../../mocks/event.js\";\nimport {createAnnotation} from \"../relations.js\";\nimport {FragmentIdComparer} from \"../FragmentIdComparer.js\";\nimport {NullLogItem} from \"../../../../logging/NullLogger\";\n\nexport function tests() {\n const fragmentIdComparer = new FragmentIdComparer([]);\n const roomId = \"$abc\";\n const alice = \"@alice:hs.tld\";\n const bob = \"@bob:hs.tld\";\n\n return {\n \"apply redaction\": async assert => {\n const event = withTextBody(\"Dogs > Cats\", createEvent(\"m.room.message\", \"!abc\", bob));\n const reason = \"nonsense, cats are the best!\";\n const redaction = withRedacts(event.event_id, reason, createEvent(\"m.room.redaction\", \"!def\", alice));\n const redactionEntry = new EventEntry({fragmentId: 1, eventIndex: 3, event: redaction, roomId}, fragmentIdComparer);\n const relationWriter = new RelationWriter({roomId, ownUserId: bob, fragmentIdComparer});\n\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 2, event, roomId}, new NullLogItem());\n const updatedEntries = await relationWriter.writeRelation(redactionEntry, txn, new NullLogItem());\n await txn.complete();\n\n assert.equal(updatedEntries.length, 1);\n const redactedMessage = updatedEntries[0];\n assert.equal(redactedMessage.id, \"!abc\");\n assert.equal(redactedMessage.content.body, undefined);\n assert.equal(redactedMessage.redactionReason, reason);\n \n const readTxn = await storage.readTxn([storage.storeNames.timelineEvents]);\n const storedMessage = await readTxn.timelineEvents.getByEventId(roomId, \"!abc\");\n await readTxn.complete();\n assert.equal(storedMessage.event.content.body, undefined);\n assert.equal(storedMessage.event.unsigned.redacted_because.content.reason, reason);\n },\n \"aggregate reaction\": async assert => {\n const event = withTextBody(\"Dogs > Cats\", createEvent(\"m.room.message\", \"!abc\", bob));\n const reaction = withContent(createAnnotation(event.event_id, \"🐶\"), createEvent(\"m.reaction\", \"!def\", alice));\n reaction.origin_server_ts = 5;\n const reactionEntry = new EventEntry({event: reaction, roomId}, fragmentIdComparer);\n const relationWriter = new RelationWriter({roomId, ownUserId: alice, fragmentIdComparer});\n\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 2, event, roomId}, new NullLogItem());\n const updatedEntries = await relationWriter.writeRelation(reactionEntry, txn, new NullLogItem());\n await txn.complete();\n\n assert.equal(updatedEntries.length, 1);\n const reactedMessage = updatedEntries[0];\n assert.equal(reactedMessage.id, \"!abc\");\n const annotation = reactedMessage.annotations[\"🐶\"];\n assert.equal(annotation.me, true);\n assert.equal(annotation.count, 1);\n assert.equal(annotation.firstTimestamp, 5);\n \n const readTxn = await storage.readTxn([storage.storeNames.timelineEvents]);\n const storedMessage = await readTxn.timelineEvents.getByEventId(roomId, \"!abc\");\n await readTxn.complete();\n assert(storedMessage.annotations[\"🐶\"]);\n },\n \"aggregate second reaction\": async assert => {\n const event = withTextBody(\"Dogs > Cats\", createEvent(\"m.room.message\", \"!abc\", bob));\n const reaction1 = withContent(createAnnotation(event.event_id, \"🐶\"), createEvent(\"m.reaction\", \"!def\", alice));\n reaction1.origin_server_ts = 5;\n const reaction1Entry = new EventEntry({event: reaction1, roomId}, fragmentIdComparer);\n const reaction2 = withContent(createAnnotation(event.event_id, \"🐶\"), createEvent(\"m.reaction\", \"!hij\", bob));\n reaction2.origin_server_ts = 10;\n const reaction2Entry = new EventEntry({event: reaction2, roomId}, fragmentIdComparer);\n const relationWriter = new RelationWriter({roomId, ownUserId: alice, fragmentIdComparer});\n\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 2, event, roomId}, new NullLogItem());\n await relationWriter.writeRelation(reaction1Entry, txn, new NullLogItem());\n const updatedEntries = await relationWriter.writeRelation(reaction2Entry, txn, new NullLogItem());\n await txn.complete();\n\n assert.equal(updatedEntries.length, 1);\n\n const reactedMessage = updatedEntries[0];\n assert.equal(reactedMessage.id, \"!abc\");\n const annotation = reactedMessage.annotations[\"🐶\"];\n assert.equal(annotation.me, true);\n assert.equal(annotation.count, 2);\n assert.equal(annotation.firstTimestamp, 5);\n },\n \"redact second reaction\": async assert => {\n const event = withTextBody(\"Dogs > Cats\", createEvent(\"m.room.message\", \"!abc\", bob));\n const myReaction = withContent(createAnnotation(event.event_id, \"🐶\"), createEvent(\"m.reaction\", \"!def\", alice));\n myReaction.origin_server_ts = 5;\n const bobReaction = withContent(createAnnotation(event.event_id, \"🐶\"), createEvent(\"m.reaction\", \"!hij\", bob));\n bobReaction.origin_server_ts = 10;\n const myReactionRedaction = withRedacts(myReaction.event_id, \"\", createEvent(\"m.room.redaction\", \"!pol\", alice));\n\n const myReactionEntry = new EventEntry({event: myReaction, roomId}, fragmentIdComparer);\n const bobReactionEntry = new EventEntry({event: bobReaction, roomId}, fragmentIdComparer);\n const myReactionRedactionEntry = new EventEntry({event: myReactionRedaction, roomId}, fragmentIdComparer);\n const relationWriter = new RelationWriter({roomId, ownUserId: alice, fragmentIdComparer});\n\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 2, event, roomId}, new NullLogItem());\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 3, event: myReaction, roomId}, new NullLogItem());\n await relationWriter.writeRelation(myReactionEntry, txn, new NullLogItem());\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 4, event: bobReaction, roomId}, new NullLogItem());\n await relationWriter.writeRelation(bobReactionEntry, txn, new NullLogItem());\n const updatedEntries = await relationWriter.writeRelation(myReactionRedactionEntry, txn, new NullLogItem());\n await txn.complete();\n\n assert.equal(updatedEntries.length, 2);\n\n const redactedReaction = updatedEntries[0];\n assert.equal(redactedReaction.id, \"!def\");\n const reaggregatedMessage = updatedEntries[1];\n assert.equal(reaggregatedMessage.id, \"!abc\");\n const annotation = reaggregatedMessage.annotations[\"🐶\"];\n assert.equal(annotation.me, false);\n assert.equal(annotation.count, 1);\n assert.equal(annotation.firstTimestamp, 10);\n\n const readTxn = await storage.readTxn([storage.storeNames.timelineEvents]);\n const storedMessage = await readTxn.timelineEvents.getByEventId(roomId, \"!abc\");\n await readTxn.complete();\n assert.equal(storedMessage.annotations[\"🐶\"].count, 1);\n },\n \n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class Direction {\n constructor(public readonly isForward: boolean) {\n }\n\n get isBackward(): boolean {\n return !this.isForward;\n }\n\n asApiString(): string {\n return this.isForward ? \"f\" : \"b\";\n }\n\n reverse(): Direction {\n return this.isForward ? Direction.Backward : Direction.Forward\n }\n\n static get Forward(): Direction {\n return _forward;\n }\n\n static get Backward(): Direction {\n return _backward;\n }\n}\n\nconst _forward = new Direction(true);\nconst _backward = new Direction(false);\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseEntry} from \"./BaseEntry\";\nimport {Direction} from \"../Direction\";\nimport {isValidFragmentId} from \"../common.js\";\nimport {KeyLimits} from \"../../../storage/common\";\n\nexport class FragmentBoundaryEntry extends BaseEntry {\n constructor(fragment, isFragmentStart, fragmentIdComparer) {\n super(fragmentIdComparer);\n this._fragment = fragment;\n // TODO: should isFragmentStart be Direction instead of bool?\n this._isFragmentStart = isFragmentStart;\n }\n\n static start(fragment, fragmentIdComparer) {\n return new FragmentBoundaryEntry(fragment, true, fragmentIdComparer);\n }\n\n static end(fragment, fragmentIdComparer) {\n return new FragmentBoundaryEntry(fragment, false, fragmentIdComparer);\n }\n \n get started() {\n return this._isFragmentStart;\n }\n\n get hasEnded() {\n return !this.started;\n }\n\n get fragment() {\n return this._fragment;\n }\n\n get fragmentId() {\n return this._fragment.id;\n }\n\n get entryIndex() {\n if (this.started) {\n return KeyLimits.minStorageKey;\n } else {\n return KeyLimits.maxStorageKey;\n }\n }\n\n get isGap() {\n return !!this.token && !this.edgeReached;\n }\n\n get token() {\n if (this.started) {\n return this.fragment.previousToken;\n } else {\n return this.fragment.nextToken;\n }\n }\n\n set token(token) {\n if (this.started) {\n this.fragment.previousToken = token;\n } else {\n this.fragment.nextToken = token;\n }\n }\n\n get edgeReached() {\n if (this.started) {\n return this.fragment.startReached;\n } else {\n return this.fragment.endReached;\n }\n }\n\n set edgeReached(reached) {\n \n if (this.started) {\n this.fragment.startReached = reached;\n } else {\n this.fragment.endReached = reached;\n }\n }\n\n \n\n get linkedFragmentId() {\n if (this.started) {\n return this.fragment.previousId;\n } else {\n return this.fragment.nextId;\n }\n }\n\n set linkedFragmentId(id) {\n if (this.started) {\n this.fragment.previousId = id;\n } else {\n this.fragment.nextId = id;\n }\n }\n\n get hasLinkedFragment() {\n return isValidFragmentId(this.linkedFragmentId);\n }\n\n get direction() {\n if (this.started) {\n return Direction.Backward;\n } else {\n return Direction.Forward;\n }\n }\n\n withUpdatedFragment(fragment) {\n return new FragmentBoundaryEntry(fragment, this._isFragmentStart, this._fragmentIdComparer);\n }\n\n createNeighbourEntry(neighbour) {\n return new FragmentBoundaryEntry(neighbour, !this._isFragmentStart, this._fragmentIdComparer);\n }\n\n addLocalRelation() {}\n removeLocalRelation() {}\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventKey} from \"../EventKey\";\nimport {EventEntry} from \"../entries/EventEntry.js\";\nimport {FragmentBoundaryEntry} from \"../entries/FragmentBoundaryEntry.js\";\nimport {createEventEntry} from \"./common.js\";\nimport {EVENT_TYPE as MEMBER_EVENT_TYPE} from \"../../members/RoomMember.js\";\n\n// Synapse bug? where the m.room.create event appears twice in sync response\n// when first syncing the room\nfunction deduplicateEvents(events) {\n const eventIds = new Set();\n return events.filter(e => {\n if (eventIds.has(e.event_id)) {\n return false;\n } else {\n eventIds.add(e.event_id);\n return true;\n }\n });\n}\n\nexport class SyncWriter {\n constructor({roomId, fragmentIdComparer, memberWriter, relationWriter}) {\n this._roomId = roomId;\n this._memberWriter = memberWriter;\n this._relationWriter = relationWriter;\n this._fragmentIdComparer = fragmentIdComparer;\n this._lastLiveKey = null;\n }\n\n async load(txn, log) {\n const liveFragment = await txn.timelineFragments.liveFragment(this._roomId);\n if (liveFragment) {\n const [lastEvent] = await txn.timelineEvents.lastEvents(this._roomId, liveFragment.id, 1);\n // fall back to the default event index in case the fragment was somehow written but no events\n // we should only create fragments when really writing timeline events now\n // (see https://github.com/vector-im/hydrogen-web/issues/112) but can't hurt to be extra robust.\n const eventIndex = lastEvent ? lastEvent.eventIndex : EventKey.defaultLiveKey.eventIndex;\n this._lastLiveKey = new EventKey(liveFragment.id, eventIndex);\n }\n // if there is no live fragment, we don't create it here because load gets a readonly txn.\n // this is on purpose, load shouldn't modify the store\n if (this._lastLiveKey) {\n log.set(\"live key\", this._lastLiveKey.toString());\n }\n }\n\n async _createLiveFragment(txn, previousToken) {\n const liveFragment = await txn.timelineFragments.liveFragment(this._roomId);\n if (!liveFragment) {\n if (!previousToken) {\n previousToken = null;\n }\n const fragment = {\n roomId: this._roomId,\n id: EventKey.defaultLiveKey.fragmentId,\n previousId: null,\n nextId: null,\n previousToken: previousToken,\n nextToken: null\n };\n txn.timelineFragments.add(fragment);\n this._fragmentIdComparer.add(fragment);\n return fragment;\n } else {\n return liveFragment;\n }\n }\n\n async _replaceLiveFragment(oldFragmentId, newFragmentId, previousToken, txn) {\n const oldFragment = await txn.timelineFragments.get(this._roomId, oldFragmentId);\n if (!oldFragment) {\n throw new Error(`old live fragment doesn't exist: ${oldFragmentId}`);\n }\n oldFragment.nextId = newFragmentId;\n txn.timelineFragments.update(oldFragment);\n const newFragment = {\n roomId: this._roomId,\n id: newFragmentId,\n previousId: oldFragmentId,\n nextId: null,\n previousToken: previousToken,\n nextToken: null\n };\n txn.timelineFragments.add(newFragment);\n this._fragmentIdComparer.append(newFragmentId, oldFragmentId);\n return {oldFragment, newFragment};\n }\n\n /**\n * creates a new live fragment if the timeline is limited, or if no live fragment is created yet\n * @param {EventKey} currentKey current key so far, might be none if room hasn't synced yet\n * @param {Array} entries array to add fragment boundary entries when creating a new fragment\n * @param {Object} timeline timeline part of the room sync response\n * @param {Transaction} txn used to read and write from the fragment store\n * @return {EventKey} the new event key to start writing events at\n */\n async _ensureLiveFragment(currentKey, entries, timeline, txn, log) {\n if (!currentKey) {\n // means we haven't synced this room yet (just joined or did initial sync)\n \n // as this is probably a limited sync, prev_batch should be there\n // (but don't fail if it isn't, we won't be able to back-paginate though)\n let liveFragment = await this._createLiveFragment(txn, timeline.prev_batch);\n currentKey = new EventKey(liveFragment.id, EventKey.defaultLiveKey.eventIndex);\n entries.push(FragmentBoundaryEntry.start(liveFragment, this._fragmentIdComparer));\n log.log({l: \"live fragment\", first: true, id: currentKey.fragmentId});\n } else if (timeline.limited) {\n // replace live fragment for limited sync, *only* if we had a live fragment already\n const oldFragmentId = currentKey.fragmentId;\n currentKey = currentKey.nextFragmentKey();\n const {oldFragment, newFragment} = await this._replaceLiveFragment(oldFragmentId, currentKey.fragmentId, timeline.prev_batch, txn);\n entries.push(FragmentBoundaryEntry.end(oldFragment, this._fragmentIdComparer));\n entries.push(FragmentBoundaryEntry.start(newFragment, this._fragmentIdComparer));\n log.log({l: \"live fragment\", limited: true, id: currentKey.fragmentId});\n }\n return currentKey;\n }\n\n async _writeStateEvents(stateEvents, txn, log) {\n let nonMemberStateEvents = 0;\n for (const event of stateEvents) {\n // member events are written prior by MemberWriter\n if (event.type !== MEMBER_EVENT_TYPE) {\n txn.roomState.set(this._roomId, event);\n nonMemberStateEvents += 1;\n }\n }\n log.set(\"stateEvents\", nonMemberStateEvents);\n }\n\n async _writeTimeline(timelineEvents, timeline, memberSync, currentKey, txn, log) {\n const entries = [];\n const updatedEntries = [];\n if (timelineEvents?.length) {\n // only create a fragment when we will really write an event\n currentKey = await this._ensureLiveFragment(currentKey, entries, timeline, txn, log);\n log.set(\"timelineEvents\", timelineEvents.length);\n let timelineStateEventCount = 0;\n for(const event of timelineEvents) {\n // store event in timeline\n currentKey = currentKey.nextKey();\n const storageEntry = createEventEntry(currentKey, this._roomId, event);\n let member = await memberSync.lookupMemberAtEvent(event.sender, event, txn);\n if (member) {\n storageEntry.displayName = member.displayName;\n storageEntry.avatarUrl = member.avatarUrl;\n }\n const couldInsert = await txn.timelineEvents.tryInsert(storageEntry, log);\n if (!couldInsert) {\n continue;\n }\n const entry = new EventEntry(storageEntry, this._fragmentIdComparer);\n entries.push(entry);\n const updatedRelationTargetEntries = await this._relationWriter.writeRelation(entry, txn, log);\n if (updatedRelationTargetEntries) {\n updatedEntries.push(...updatedRelationTargetEntries);\n }\n // update state events after writing event, so for a member event,\n // we only update the member info after having written the member event\n // to the timeline, as we want that event to have the old profile info.\n // member events are written prior by MemberWriter.\n if (typeof event.state_key === \"string\" && event.type !== MEMBER_EVENT_TYPE) {\n timelineStateEventCount += 1;\n txn.roomState.set(this._roomId, event);\n }\n }\n log.set(\"timelineStateEventCount\", timelineStateEventCount);\n }\n return {currentKey, entries, updatedEntries};\n }\n\n async _handleRejoinOverlap(timeline, txn, log) {\n if (this._lastLiveKey) {\n const {fragmentId} = this._lastLiveKey;\n const [lastEvent] = await txn.timelineEvents.lastEvents(this._roomId, fragmentId, 1);\n if (lastEvent) {\n const lastEventId = lastEvent.event.event_id;\n const {events} = timeline;\n const index = events.findIndex(event => event.event_id === lastEventId);\n if (index !== -1) {\n log.set(\"overlap_event_id\", lastEventId);\n return Object.assign({}, timeline, {\n limited: false,\n events: events.slice(index + 1),\n });\n }\n }\n }\n if (!timeline.limited) {\n log.set(\"force_limited_without_overlap\", true);\n return Object.assign({}, timeline, {limited: true});\n }\n return timeline;\n }\n\n /**\n * @type {SyncWriterResult}\n * @property {Array} entries new timeline entries written\n * @property {EventKey} newLiveKey the advanced key to write events at\n * \n * @param {Object} roomResponse [description]\n * @param {boolean} isRejoin whether the room was rejoined in the sync being processed\n * @param {Transaction} txn \n * @return {SyncWriterResult}\n */\n async writeSync(roomResponse, isRejoin, hasFetchedMembers, txn, log) {\n let {timeline} = roomResponse;\n // we have rejoined the room after having synced it before,\n // check for overlap with the last synced event\n log.set(\"isRejoin\", isRejoin);\n if (isRejoin) {\n timeline = await this._handleRejoinOverlap(timeline, txn, log);\n }\n let timelineEvents;\n if (Array.isArray(timeline?.events)) {\n timelineEvents = deduplicateEvents(timeline.events);\n }\n const {state} = roomResponse;\n let stateEvents;\n if (Array.isArray(state?.events)) {\n stateEvents = state.events;\n }\n const memberSync = this._memberWriter.prepareMemberSync(stateEvents, timelineEvents, hasFetchedMembers);\n if (stateEvents) {\n await this._writeStateEvents(stateEvents, txn, log);\n }\n const {currentKey, entries, updatedEntries} =\n await this._writeTimeline(timelineEvents, timeline, memberSync, this._lastLiveKey, txn, log);\n const memberChanges = await memberSync.write(txn);\n return {entries, updatedEntries, newLiveKey: currentKey, memberChanges};\n }\n\n afterSync(newLiveKey) {\n this._lastLiveKey = newLiveKey;\n }\n\n get lastMessageKey() {\n return this._lastLiveKey;\n }\n}\n\nimport {createMockStorage} from \"../../../../mocks/Storage\";\nimport {createEvent, withTextBody} from \"../../../../mocks/event.js\";\nimport {Instance as nullLogger} from \"../../../../logging/NullLogger\";\nexport function tests() {\n const roomId = \"!abc:hs.tld\";\n return {\n \"calling timelineEvents.tryInsert with the same event id a second time fails\": async assert => {\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents]);\n const event = withTextBody(\"hello!\", createEvent(\"m.room.message\", \"$abc\", \"@alice:hs.tld\"));\n const entry1 = createEventEntry(EventKey.defaultLiveKey, roomId, event);\n assert.equal(await txn.timelineEvents.tryInsert(entry1, nullLogger.item), true);\n const entry2 = createEventEntry(EventKey.defaultLiveKey.nextKey(), roomId, event);\n assert.equal(await txn.timelineEvents.tryInsert(entry2, nullLogger.item), false);\n // fake-indexeddb still aborts the transaction when preventDefault is called by tryInsert, so don't await as it will abort\n // await txn.complete();\n },\n \"calling timelineEvents.tryInsert with the same event key a second time fails\": async assert => {\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents]);\n const event1 = withTextBody(\"hello!\", createEvent(\"m.room.message\", \"$abc\", \"@alice:hs.tld\"));\n const entry1 = createEventEntry(EventKey.defaultLiveKey, roomId, event1);\n assert.equal(await txn.timelineEvents.tryInsert(entry1, nullLogger.item), true);\n const event2 = withTextBody(\"hello!\", createEvent(\"m.room.message\", \"$def\", \"@alice:hs.tld\"));\n const entry2 = createEventEntry(EventKey.defaultLiveKey, roomId, event2);\n assert.equal(await txn.timelineEvents.tryInsert(entry2, nullLogger.item), false);\n // fake-indexeddb still aborts the transaction when preventDefault is called by tryInsert, so don't await as it will abort\n // await txn.complete();\n },\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n\ntype FindCallback = (value: T) => boolean;\n/**\n * Very simple least-recently-used cache implementation\n * that should be fast enough for very small cache sizes\n */\nexport class BaseLRUCache {\n\n public readonly limit: number;\n protected _entries: T[];\n\n constructor(limit: number) {\n this.limit = limit;\n this._entries = [];\n }\n\n get size() { return this._entries.length; }\n\n protected _get(findEntryFn: FindCallback) {\n return this._getByIndexAndMoveUp(this._entries.findIndex(findEntryFn));\n }\n\n protected _getByIndexAndMoveUp(idx: number) {\n if (idx !== -1) {\n const entry = this._entries[idx];\n // move to top\n if (idx > 0) {\n this._entries.splice(idx, 1);\n this._entries.unshift(entry);\n }\n return entry;\n }\n }\n\n protected _set(value: T, findEntryFn?: FindCallback) {\n let indexToRemove = findEntryFn ? this._entries.findIndex(findEntryFn) : -1;\n this._entries.unshift(value);\n if (indexToRemove === -1) {\n if (this._entries.length > this.limit) {\n indexToRemove = this._entries.length - 1;\n }\n } else {\n // we added the entry at the start since we looked for the index\n indexToRemove += 1;\n }\n if (indexToRemove !== -1) {\n this.onEvictEntry(this._entries[indexToRemove]);\n this._entries.splice(indexToRemove, 1);\n }\n }\n\n protected onEvictEntry(entry: T) {}\n}\n\nexport class LRUCache extends BaseLRUCache {\n private _keyFn: (T) => K;\n\n constructor(limit, keyFn: (T) => K) {\n super(limit);\n this._keyFn = keyFn;\n }\n\n get(key: K): T | undefined {\n return this._get(e => this._keyFn(e) === key);\n }\n\n set(value: T) {\n const key = this._keyFn(value);\n this._set(value, e => this._keyFn(e) === key);\n }\n}\n\nexport function tests() {\n interface NameTuple {\n id: number;\n name: string;\n }\n\n return {\n \"can retrieve added entries\": assert => {\n const cache = new LRUCache(2, e => e.id);\n cache.set({id: 1, name: \"Alice\"});\n cache.set({id: 2, name: \"Bob\"});\n assert.equal(cache.get(1)!.name, \"Alice\");\n assert.equal(cache.get(2)!.name, \"Bob\");\n },\n \"first entry is evicted first\": assert => {\n const cache = new LRUCache(2, e => e.id);\n cache.set({id: 1, name: \"Alice\"});\n cache.set({id: 2, name: \"Bob\"});\n cache.set({id: 3, name: \"Charly\"});\n assert.equal(cache.get(1), undefined);\n assert.equal(cache.get(2)!.name, \"Bob\");\n assert.equal(cache.get(3)!.name, \"Charly\");\n assert.equal(cache.size, 2);\n },\n \"second entry is evicted if first is requested\": assert => {\n const cache = new LRUCache(2, e => e.id);\n cache.set({id: 1, name: \"Alice\"});\n cache.set({id: 2, name: \"Bob\"});\n cache.get(1);\n cache.set({id: 3, name: \"Charly\"});\n assert.equal(cache.get(1)!.name, \"Alice\");\n assert.equal(cache.get(2), undefined);\n assert.equal(cache.get(3)!.name, \"Charly\");\n assert.equal(cache.size, 2);\n },\n \"setting an entry twice removes the first\": assert => {\n const cache = new LRUCache(2, e => e.id);\n cache.set({id: 1, name: \"Alice\"});\n cache.set({id: 2, name: \"Bob\"});\n cache.set({id: 1, name: \"Al Ice\"});\n cache.set({id: 3, name: \"Charly\"});\n assert.equal(cache.get(1)!.name, \"Al Ice\");\n assert.equal(cache.get(2), undefined);\n assert.equal(cache.get(3)!.name, \"Charly\");\n assert.equal(cache.size, 2);\n },\n \"evict callback is called\": assert => {\n let evictions = 0;\n class CustomCache extends LRUCache {\n onEvictEntry(entry) {\n assert.equal(entry.name, \"Alice\");\n evictions += 1;\n }\n }\n const cache = new CustomCache(2, e => e.id);\n cache.set({id: 1, name: \"Alice\"});\n cache.set({id: 2, name: \"Bob\"});\n cache.set({id: 3, name: \"Charly\"});\n assert.equal(evictions, 1);\n },\n \"evict callback is called when replacing entry with same identity\": assert => {\n let evictions = 0;\n class CustomCache extends LRUCache {\n onEvictEntry(entry) {\n assert.equal(entry.name, \"Alice\");\n evictions += 1;\n }\n }\n const cache = new CustomCache(2, e => e.id);\n cache.set({id: 1, name: \"Alice\"});\n cache.set({id: 1, name: \"Bob\"});\n assert.equal(evictions, 1);\n },\n \n };\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MemberChange, RoomMember, EVENT_TYPE as MEMBER_EVENT_TYPE} from \"../../members/RoomMember.js\";\nimport {LRUCache} from \"../../../../utils/LRUCache\";\n\nexport class MemberWriter {\n constructor(roomId) {\n this._roomId = roomId;\n this._cache = new LRUCache(5, member => member.userId);\n }\n\n prepareMemberSync(stateEvents, timelineEvents, hasFetchedMembers) {\n return new MemberSync(this, stateEvents, timelineEvents, hasFetchedMembers);\n }\n\n async _writeMember(member, txn) {\n let existingMember = this._cache.get(member.userId);\n if (!existingMember) {\n const memberData = await txn.roomMembers.get(this._roomId, member.userId);\n if (memberData) {\n existingMember = new RoomMember(memberData);\n }\n }\n // either never heard of the member, or something changed\n if (!existingMember || !existingMember.equals(member)) {\n txn.roomMembers.set(member.serialize());\n this._cache.set(member);\n return new MemberChange(member, existingMember?.membership);\n }\n }\n\n async lookupMember(userId, txn) {\n let member = this._cache.get(userId);\n if (!member) {\n const memberData = await txn.roomMembers.get(this._roomId, userId);\n if (memberData) {\n member = new RoomMember(memberData);\n this._cache.set(member);\n }\n }\n return member;\n }\n}\n\nclass MemberSync {\n constructor(memberWriter, stateEvents, timelineEvents, hasFetchedMembers) {\n this._memberWriter = memberWriter;\n this._timelineEvents = timelineEvents;\n this._hasFetchedMembers = hasFetchedMembers;\n this._newStateMembers = null;\n if (stateEvents) {\n this._newStateMembers = this._stateEventsToMembers(stateEvents);\n }\n }\n\n get _roomId() {\n return this._memberWriter._roomId;\n }\n\n _stateEventsToMembers(stateEvents) {\n let members;\n for (const event of stateEvents) {\n if (event.type === MEMBER_EVENT_TYPE) {\n const member = RoomMember.fromMemberEvent(this._roomId, event);\n if (member) {\n if (!members) {\n members = new Map();\n }\n members.set(member.userId, member);\n }\n }\n }\n return members;\n }\n\n _timelineEventsToMembers(timelineEvents) {\n let members;\n // iterate backwards to only add the last member in the timeline\n for (let i = timelineEvents.length - 1; i >= 0; i--) {\n const e = timelineEvents[i];\n const userId = e.state_key;\n if (e.type === MEMBER_EVENT_TYPE && !members?.has(userId)) {\n const member = RoomMember.fromMemberEvent(this._roomId, e);\n if (member) {\n if (!members) {\n members = new Map();\n }\n members.set(member.userId, member);\n }\n }\n }\n return members;\n }\n\n async lookupMemberAtEvent(userId, event, txn) {\n let member;\n if (this._timelineEvents) {\n member = this._findPrecedingMemberEventInTimeline(userId, event);\n if (member) {\n return member;\n }\n }\n member = this._newStateMembers?.get(userId);\n if (member) {\n return member;\n }\n return await this._memberWriter.lookupMember(userId, txn);\n }\n\n async write(txn) {\n const memberChanges = new Map();\n let newTimelineMembers;\n if (this._timelineEvents) {\n newTimelineMembers = this._timelineEventsToMembers(this._timelineEvents);\n }\n if (this._newStateMembers) {\n for (const member of this._newStateMembers.values()) {\n if (!newTimelineMembers?.has(member.userId)) {\n const memberChange = await this._memberWriter._writeMember(member, txn);\n if (memberChange) {\n // if the member event appeared only in the state section,\n // AND we haven't heard about it AND we haven't fetched all members yet (to avoid #470),\n // this may be a lazy loading member (if it's not in a gap, we are certain\n // it is a ll member, in a gap, we can't tell), so we pass in our own membership as\n // as the previous one so we won't consider it a join to not have false positives (to avoid #192).\n // see also MemberChange.hasJoined\n const maybeLazyLoadingMember = !this._hasFetchedMembers && !memberChange.previousMembership;\n if (maybeLazyLoadingMember) {\n memberChange.previousMembership = member.membership;\n }\n memberChanges.set(memberChange.userId, memberChange);\n }\n }\n }\n }\n if (newTimelineMembers) {\n for (const member of newTimelineMembers.values()) {\n const memberChange = await this._memberWriter._writeMember(member, txn);\n if (memberChange) {\n memberChanges.set(memberChange.userId, memberChange);\n }\n }\n }\n return memberChanges;\n }\n\n // try to find the first member event before the given event,\n // so we respect historical display names within the chunk of timeline\n _findPrecedingMemberEventInTimeline(userId, event) {\n let eventIndex = -1;\n for (let i = this._timelineEvents.length - 1; i >= 0; i--) {\n const e = this._timelineEvents[i];\n if (e.event_id === event.event_id) {\n eventIndex = i;\n break;\n }\n }\n for (let i = eventIndex - 1; i >= 0; i--) {\n const e = this._timelineEvents[i];\n if (e.type === MEMBER_EVENT_TYPE && e.state_key === userId) {\n const member = RoomMember.fromMemberEvent(this._roomId, e);\n if (member) {\n return member;\n }\n }\n }\n }\n}\n\nexport function tests() {\n\n let idCounter = 0;\n\n function createMemberEvent(membership, userId, displayName, avatarUrl) {\n idCounter += 1;\n return {\n content: {\n membership,\n \"displayname\": displayName,\n \"avatar_url\": avatarUrl\n },\n event_id: `$${idCounter}`,\n sender: userId,\n \"state_key\": userId,\n type: \"m.room.member\"\n };\n }\n\n function createStorage(initialMembers = []) {\n const members = new Map();\n for (const m of initialMembers) {\n members.set(m.userId, m);\n }\n return {\n members,\n roomMembers: {\n async get(_, userId) {\n return members.get(userId);\n },\n set(member) {\n members.set(member.userId, member);\n }\n }\n }\n }\n\n function member(...args) {\n return RoomMember.fromMemberEvent(roomId, createMemberEvent.apply(null, args));\n }\n\n const roomId = \"abc\";\n const alice = \"@alice:hs.tld\";\n const avatar = \"mxc://hs.tld/def\";\n\n return {\n \"new join\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"join\", alice)], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasJoined);\n assert.equal(txn.members.get(alice).membership, \"join\");\n },\n \"accept invite\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"invite\", alice)]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"join\", alice)], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert.equal(change.previousMembership, \"invite\");\n assert(change.hasJoined);\n assert.equal(txn.members.get(alice).membership, \"join\");\n },\n \"change display name\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"join\", alice, \"Alies\")], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(!change.hasJoined);\n assert.equal(change.member.displayName, \"Alies\");\n assert.equal(txn.members.get(alice).displayName, \"Alies\");\n },\n \"set avatar\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"join\", alice, \"Alice\", avatar)], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(!change.hasJoined);\n assert.equal(change.member.avatarUrl, avatar);\n assert.equal(txn.members.get(alice).avatarUrl, avatar);\n },\n \"ignore redundant member event in timeline\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\", avatar)]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"join\", alice, \"Alice\", avatar)], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 0);\n },\n \"ignore redundant member event in state\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\", avatar)]);\n const memberSync = writer.prepareMemberSync([createMemberEvent(\"join\", alice, \"Alice\", avatar)], [], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 0);\n },\n \"leave\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"leave\", alice, \"Alice\")], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasLeft);\n assert(!change.hasJoined);\n },\n \"ban\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"ban\", alice, \"Alice\")], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasLeft);\n assert(!change.hasJoined);\n },\n \"reject invite\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"invite\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([], [createMemberEvent(\"leave\", alice, \"Alice\")], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(!change.hasLeft);\n assert(!change.hasJoined);\n },\n \"lazy loaded member we already know about doens't return change\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([createMemberEvent(\"join\", alice, \"Alice\")], [], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 0);\n },\n \"lazy loaded member we already know about changes display name\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage([member(\"join\", alice, \"Alice\")]);\n const memberSync = writer.prepareMemberSync([createMemberEvent(\"join\", alice, \"Alies\")], [], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(!change.hasJoined);\n assert.equal(change.member.displayName, \"Alies\");\n },\n \"unknown lazy loaded member returns change, but not considered a join\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const memberSync = writer.prepareMemberSync([createMemberEvent(\"join\", alice, \"Alice\")], [], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(!change.hasJoined);\n assert(!change.hasLeft);\n assert.equal(change.member.membership, \"join\");\n assert.equal(txn.members.get(alice).displayName, \"Alice\");\n },\n \"new join through both timeline and state\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const aliceJoin = createMemberEvent(\"join\", alice, \"Alice\");\n const memberSync = writer.prepareMemberSync([aliceJoin], [aliceJoin], false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasJoined);\n assert(!change.hasLeft);\n },\n \"change display name in timeline with lazy loaded member in state\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const memberSync = writer.prepareMemberSync(\n [createMemberEvent(\"join\", alice, \"Alice\")],\n [createMemberEvent(\"join\", alice, \"Alies\")],\n false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasJoined);\n assert(!change.hasLeft);\n assert.equal(change.member.displayName, \"Alies\");\n },\n \"lookupMemberAtEvent returns closest member in the past\": async assert => {\n const event1 = createMemberEvent(\"join\", alice, \"Alice\");\n const event2 = createMemberEvent(\"join\", alice, \"Alies\");\n const event3 = createMemberEvent(\"join\", alice, \"Alys\");\n const events = [event1, event2, event3];\n // we write first because the MemberWriter assumes it is called before\n // the SyncWriter does any lookups\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const memberSync = await writer.prepareMemberSync([], events, false);\n let member = await memberSync.lookupMemberAtEvent(event1.sender, event1, txn);\n assert.equal(member, undefined);\n member = await memberSync.lookupMemberAtEvent(event2.sender, event2, txn);\n assert.equal(member.displayName, \"Alice\");\n member = await memberSync.lookupMemberAtEvent(event3.sender, event3, txn);\n assert.equal(member.displayName, \"Alies\");\n\n assert.equal(txn.members.size, 0);\n const changes = await memberSync.write(txn);\n assert.equal(txn.members.size, 1);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasJoined);\n },\n \"lookupMemberAtEvent falls back on state event\": async assert => {\n const event1 = createMemberEvent(\"join\", alice, \"Alice\");\n const event2 = createMemberEvent(\"join\", alice, \"Alies\");\n // we write first because the MemberWriter assumes it is called before\n // the SyncWriter does any lookups\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const memberSync = await writer.prepareMemberSync([event1], [event2], false);\n const member = await memberSync.lookupMemberAtEvent(event2.sender, event2, txn);\n assert.equal(member.displayName, \"Alice\");\n\n assert.equal(txn.members.size, 0);\n const changes = await memberSync.write(txn);\n assert.equal(txn.members.size, 1);\n assert.equal(changes.size, 1);\n const change = changes.get(alice);\n assert(change.hasJoined);\n },\n \"write works without event arrays\": async assert => {\n const writer = new MemberWriter(roomId);\n const txn = createStorage();\n const memberSync = await writer.prepareMemberSync(undefined, undefined, false);\n const changes = await memberSync.write(txn);\n assert.equal(changes.size, 0);\n },\n };\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventKey} from \"../EventKey\";\nimport {EventEntry} from \"../entries/EventEntry.js\";\nimport {createEventEntry, directionalAppend} from \"./common.js\";\nimport {RoomMember, EVENT_TYPE as MEMBER_EVENT_TYPE} from \"../../members/RoomMember.js\";\n\nexport class GapWriter {\n constructor({roomId, storage, fragmentIdComparer, relationWriter}) {\n this._roomId = roomId;\n this._storage = storage;\n this._fragmentIdComparer = fragmentIdComparer;\n this._relationWriter = relationWriter;\n }\n\n async _findOverlappingEvents(fragmentEntry, events, txn, log) {\n const eventIds = events.map(e => e.event_id);\n const existingEventKeyMap = await txn.timelineEvents.getEventKeysForIds(this._roomId, eventIds);\n log.set(\"existingEvents\", existingEventKeyMap.size);\n const nonOverlappingEvents = events.filter(e => !existingEventKeyMap.has(e.event_id));\n log.set(\"nonOverlappingEvents\", nonOverlappingEvents.length);\n let neighbourFragmentEntry;\n if (fragmentEntry.hasLinkedFragment) {\n log.set(\"linkedFragmentId\", fragmentEntry.linkedFragmentId);\n for (const eventKey of existingEventKeyMap.values()) {\n if (eventKey.fragmentId === fragmentEntry.linkedFragmentId) {\n log.set(\"foundLinkedFragment\", true);\n const neighbourFragment = await txn.timelineFragments.get(this._roomId, fragmentEntry.linkedFragmentId);\n neighbourFragmentEntry = fragmentEntry.createNeighbourEntry(neighbourFragment);\n break;\n }\n }\n }\n return {nonOverlappingEvents, neighbourFragmentEntry};\n }\n\n async _findFragmentEdgeEventKey(fragmentEntry, txn) {\n const {fragmentId, direction} = fragmentEntry;\n const event = await this._findFragmentEdgeEvent(fragmentId, direction, txn);\n if (event) {\n return new EventKey(event.fragmentId, event.eventIndex);\n } else {\n // no events yet in the fragment ... odd, but let's not fail and take the default key\n return EventKey.defaultFragmentKey(fragmentEntry.fragmentId);\n }\n }\n\n async _findFragmentEdgeEvent(fragmentId, direction, txn) {\n if (direction.isBackward) {\n const [firstEvent] = await txn.timelineEvents.firstEvents(this._roomId, fragmentId, 1);\n return firstEvent;\n } else {\n const [lastEvent] = await txn.timelineEvents.lastEvents(this._roomId, fragmentId, 1);\n return lastEvent;\n }\n }\n\n async _storeEvents(events, startKey, direction, state, txn, log) {\n const entries = [];\n const updatedEntries = [];\n // events is in reverse chronological order for backwards pagination,\n // e.g. order is moving away from the `from` point.\n let key = startKey;\n for (let i = 0; i < events.length; ++i) {\n const event = events[i];\n key = key.nextKeyForDirection(direction);\n const eventStorageEntry = createEventEntry(key, this._roomId, event);\n const member = this._findMember(event.sender, state, events, i, direction);\n if (member) {\n eventStorageEntry.displayName = member.displayName;\n eventStorageEntry.avatarUrl = member.avatarUrl;\n }\n // this will modify eventStorageEntry if it is a relation target\n const updatedRelationTargetEntries = await this._relationWriter.writeGapRelation(eventStorageEntry, direction, txn, log);\n if (updatedRelationTargetEntries) {\n updatedEntries.push(...updatedRelationTargetEntries);\n }\n if (await txn.timelineEvents.tryInsert(eventStorageEntry, log)) {\n const eventEntry = new EventEntry(eventStorageEntry, this._fragmentIdComparer);\n directionalAppend(entries, eventEntry, direction);\n }\n }\n return {entries, updatedEntries};\n }\n\n _findMember(userId, state, events, index, direction) {\n function isOurUser(event) {\n return event.type === MEMBER_EVENT_TYPE && event.state_key === userId;\n }\n // older messages are at a higher index in the array when going backwards\n const inc = direction.isBackward ? 1 : -1;\n for (let i = index + inc; i >= 0 && i < events.length; i += inc) {\n const event = events[i];\n if (isOurUser(event)) {\n return RoomMember.fromMemberEvent(this._roomId, event);\n }\n }\n // look into newer events, but using prev_content if found.\n // We do this before looking into `state` because it is not well specified\n // in the spec whether the events in there represent state before or after `chunk`.\n // So we look both directions first in chunk to make sure it doesn't matter.\n for (let i = index; i >= 0 && i < events.length; i -= inc) {\n const event = events[i];\n if (isOurUser(event)) {\n return RoomMember.fromReplacingMemberEvent(this._roomId, event);\n }\n }\n // assuming the member hasn't changed within the chunk, just take it from state if it's there.\n // Don't assume state is set though, as it can be empty at the top of the timeline in some circumstances \n const stateMemberEvent = state?.find(isOurUser);\n if (stateMemberEvent) {\n return RoomMember.fromMemberEvent(this._roomId, stateMemberEvent);\n }\n }\n\n async _updateFragments(fragmentEntry, neighbourFragmentEntry, end, entries, txn, log) {\n const {direction} = fragmentEntry;\n const changedFragments = [];\n directionalAppend(entries, fragmentEntry, direction);\n // set `end` as token, and if we found an event in the step before, link up the fragments in the fragment entry\n if (neighbourFragmentEntry) {\n // if neighbourFragmentEntry was found, it means the events were overlapping,\n // so no pagination should happen anymore.\n log.set(\"closedGapWith\", neighbourFragmentEntry.fragmentId);\n neighbourFragmentEntry.token = null;\n fragmentEntry.token = null;\n\n txn.timelineFragments.update(neighbourFragmentEntry.fragment);\n directionalAppend(entries, neighbourFragmentEntry, direction);\n\n // fragments that need to be changed in the fragmentIdComparer here\n // after txn succeeds\n changedFragments.push(fragmentEntry.fragment);\n changedFragments.push(neighbourFragmentEntry.fragment);\n } else {\n fragmentEntry.token = end;\n }\n txn.timelineFragments.update(fragmentEntry.fragment);\n\n return changedFragments;\n }\n\n async writeFragmentFill(fragmentEntry, response, txn, log) {\n const {fragmentId, direction} = fragmentEntry;\n // chunk is in reverse-chronological order when backwards\n const {chunk, start, state} = response;\n let {end} = response;\n\n if (!Array.isArray(chunk)) {\n throw new Error(\"Invalid chunk in response\");\n }\n if (typeof end !== \"string\" && typeof end !== \"undefined\") {\n throw new Error(\"Invalid end token in response\");\n }\n\n // make sure we have the latest fragment from the store\n const fragment = await txn.timelineFragments.get(this._roomId, fragmentId);\n if (!fragment) {\n throw new Error(`Unknown fragment: ${fragmentId}`);\n }\n fragmentEntry = fragmentEntry.withUpdatedFragment(fragment);\n // check that the request was done with the token we are aware of (extra care to avoid timeline corruption)\n if (fragmentEntry.token !== start) {\n throw new Error(\"start is not equal to prev_batch or next_batch\");\n }\n\n // begin (or end) of timeline reached\n if (chunk.length === 0) {\n fragmentEntry.edgeReached = true;\n await txn.timelineFragments.update(fragmentEntry.fragment);\n return {entries: [fragmentEntry], updatedEntries: [], fragments: []};\n }\n\n // find last event in fragment so we get the eventIndex to begin creating keys at\n let lastKey = await this._findFragmentEdgeEventKey(fragmentEntry, txn);\n log.set(\"lastKey\", lastKey.toString());\n // find out if any event in chunk is already present using findFirstOrLastOccurringEventId\n const {\n nonOverlappingEvents,\n neighbourFragmentEntry\n } = await this._findOverlappingEvents(fragmentEntry, chunk, txn, log);\n // create entries for all events in chunk, add them to entries\n const {entries, updatedEntries} = await this._storeEvents(nonOverlappingEvents, lastKey, direction, state, txn, log);\n const fragments = await this._updateFragments(fragmentEntry, neighbourFragmentEntry, end, entries, txn, log);\n \n return {entries, updatedEntries, fragments};\n }\n}\n\nimport {FragmentIdComparer} from \"../FragmentIdComparer.js\";\nimport {RelationWriter} from \"./RelationWriter.js\";\nimport {createMockStorage} from \"../../../../mocks/Storage\";\nimport {FragmentBoundaryEntry} from \"../entries/FragmentBoundaryEntry.js\";\nimport {NullLogItem} from \"../../../../logging/NullLogger\";\nimport {TimelineMock, eventIds, eventId} from \"../../../../mocks/TimelineMock.ts\";\nimport {SyncWriter} from \"./SyncWriter.js\";\nimport {MemberWriter} from \"./MemberWriter.js\";\nimport {KeyLimits} from \"../../../storage/common\";\n\nexport function tests() {\n const roomId = \"!room:hs.tdl\";\n const alice = \"alice@hs.tdl\";\n const logger = new NullLogItem();\n\n async function createGapFillTxn(storage) {\n return storage.readWriteTxn([\n storage.storeNames.roomMembers,\n storage.storeNames.pendingEvents,\n storage.storeNames.timelineEvents,\n storage.storeNames.timelineRelations,\n storage.storeNames.timelineFragments,\n ]);\n }\n\n async function setup() {\n const storage = await createMockStorage();\n const txn = await createGapFillTxn(storage);\n const fragmentIdComparer = new FragmentIdComparer([]);\n const relationWriter = new RelationWriter({\n roomId, fragmentIdComparer, ownUserId: alice,\n });\n const gapWriter = new GapWriter({\n roomId, storage, fragmentIdComparer, relationWriter\n });\n const memberWriter = new MemberWriter(roomId);\n const syncWriter = new SyncWriter({\n roomId,\n fragmentIdComparer,\n memberWriter,\n relationWriter\n });\n return { storage, txn, fragmentIdComparer, gapWriter, syncWriter, timelineMock: new TimelineMock() };\n }\n\n async function syncAndWrite(mocks, { previous, limit } = {}) {\n const {txn, timelineMock, syncWriter, fragmentIdComparer} = mocks;\n const syncResponse = timelineMock.sync(previous?.next_batch, limit);\n const {newLiveKey} = await syncWriter.writeSync(syncResponse, false, false, txn, logger);\n syncWriter.afterSync(newLiveKey);\n return {\n syncResponse,\n fragmentEntry: newLiveKey ? FragmentBoundaryEntry.start(\n await txn.timelineFragments.get(roomId, newLiveKey.fragmentId),\n fragmentIdComparer,\n ) : null,\n };\n }\n\n async function backfillAndWrite(mocks, fragmentEntry, limit) {\n const {txn, timelineMock, gapWriter} = mocks;\n const messageResponse = timelineMock.messages(fragmentEntry.token, undefined, fragmentEntry.direction.asApiString(), limit);\n await gapWriter.writeFragmentFill(fragmentEntry, messageResponse, txn, logger);\n }\n\n async function allFragmentEvents(mocks, fragmentId) {\n const {txn} = mocks;\n const entries = await txn.timelineEvents.eventsAfter(roomId, new EventKey(fragmentId, KeyLimits.minStorageKey));\n return entries.map(e => e.event);\n }\n\n async function fetchFragment(mocks, fragmentId) {\n const {txn} = mocks;\n return txn.timelineFragments.get(roomId, fragmentId);\n }\n\n function assertFilledLink(assert, fragment1, fragment2) {\n assert.equal(fragment1.nextId, fragment2.id);\n assert.equal(fragment2.previousId, fragment1.id);\n assert.equal(fragment1.nextToken, null);\n assert.equal(fragment2.previousToken, null);\n }\n\n function assertGapLink(assert, fragment1, fragment2) {\n assert.equal(fragment1.nextId, fragment2.id);\n assert.equal(fragment2.previousId, fragment1.id);\n assert.notEqual(fragment2.previousToken, null);\n }\n\n return {\n \"Backfilling after one sync\": async assert => {\n const mocks = await setup();\n const { timelineMock } = mocks;\n timelineMock.append(30);\n const {fragmentEntry} = await syncAndWrite(mocks);\n await backfillAndWrite(mocks, fragmentEntry, 10);\n const events = await allFragmentEvents(mocks, fragmentEntry.fragmentId);\n assert.deepEqual(events.map(e => e.event_id), eventIds(10, 30));\n await mocks.txn.complete();\n },\n \"Backfilling a fragment that is expected to close a gap, and does\": async assert => {\n const mocks = await setup();\n const { timelineMock } = mocks;\n timelineMock.append(10);\n const {syncResponse, fragmentEntry: firstFragmentEntry} = await syncAndWrite(mocks, { limit: 10 });\n timelineMock.append(15);\n const {fragmentEntry: secondFragmentEntry} = await syncAndWrite(mocks, { previous: syncResponse, limit: 10 });\n await backfillAndWrite(mocks, secondFragmentEntry, 10);\n\n const firstFragment = await fetchFragment(mocks, firstFragmentEntry.fragmentId);\n const secondFragment = await fetchFragment(mocks, secondFragmentEntry.fragmentId);\n assertFilledLink(assert, firstFragment, secondFragment)\n const firstEvents = await allFragmentEvents(mocks, firstFragmentEntry.fragmentId);\n assert.deepEqual(firstEvents.map(e => e.event_id), eventIds(0, 10));\n const secondEvents = await allFragmentEvents(mocks, secondFragmentEntry.fragmentId);\n assert.deepEqual(secondEvents.map(e => e.event_id), eventIds(10, 25));\n await mocks.txn.complete();\n },\n \"Backfilling a fragment that is expected to close a gap, but doesn't yet\": async assert => {\n const mocks = await setup();\n const { timelineMock } = mocks;\n timelineMock.append(10);\n const {syncResponse, fragmentEntry: firstFragmentEntry} = await syncAndWrite(mocks, { limit: 10 });\n timelineMock.append(20);\n const {fragmentEntry: secondFragmentEntry} = await syncAndWrite(mocks, { previous: syncResponse, limit: 10 });\n await backfillAndWrite(mocks, secondFragmentEntry, 10);\n\n const firstFragment = await fetchFragment(mocks, firstFragmentEntry.fragmentId);\n const secondFragment = await fetchFragment(mocks, secondFragmentEntry.fragmentId);\n assertGapLink(assert, firstFragment, secondFragment)\n const firstEvents = await allFragmentEvents(mocks, firstFragmentEntry.fragmentId);\n assert.deepEqual(firstEvents.map(e => e.event_id), eventIds(0, 10));\n const secondEvents = await allFragmentEvents(mocks, secondFragmentEntry.fragmentId);\n assert.deepEqual(secondEvents.map(e => e.event_id), eventIds(10, 30));\n await mocks.txn.complete();\n },\n \"Receiving a sync with the same events as the current fragment does not create infinite link\": async assert => {\n const mocks = await setup();\n const { txn, timelineMock } = mocks;\n timelineMock.append(10);\n const {syncResponse, fragmentEntry: fragmentEntry} = await syncAndWrite(mocks, { limit: 10 });\n // Mess with the saved token to receive old events in backfill\n fragmentEntry.token = syncResponse.next_batch;\n txn.timelineFragments.update(fragmentEntry.fragment);\n await backfillAndWrite(mocks, fragmentEntry, 10);\n\n const fragment = await fetchFragment(mocks, fragmentEntry.fragmentId);\n assert.notEqual(fragment.nextId, fragment.id);\n assert.notEqual(fragment.previousId, fragment.id);\n await mocks.txn.complete();\n },\n \"An event received by sync does not interrupt backfilling\": async assert => {\n const mocks = await setup();\n const { timelineMock } = mocks;\n timelineMock.append(10);\n const {syncResponse, fragmentEntry: firstFragmentEntry} = await syncAndWrite(mocks, { limit: 10 });\n timelineMock.append(11);\n const {fragmentEntry: secondFragmentEntry} = await syncAndWrite(mocks, { previous: syncResponse, limit: 10 });\n timelineMock.insertAfter(eventId(9), 5);\n await backfillAndWrite(mocks, secondFragmentEntry, 10);\n\n const firstEvents = await allFragmentEvents(mocks, firstFragmentEntry.fragmentId);\n assert.deepEqual(firstEvents.map(e => e.event_id), eventIds(0, 10));\n const secondEvents = await allFragmentEvents(mocks, secondFragmentEntry.fragmentId);\n assert.deepEqual(secondEvents.map(e => e.event_id), [...eventIds(21,26), ...eventIds(10, 21)]);\n const firstFragment = await fetchFragment(mocks, firstFragmentEntry.fragmentId);\n const secondFragment = await fetchFragment(mocks, secondFragmentEntry.fragmentId);\n assertFilledLink(assert, firstFragment, secondFragment)\n await mocks.txn.complete();\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservable} from \"../BaseObservable\";\n\nexport interface IListObserver {\n onReset(list: BaseObservableList): void;\n onAdd(index: number, value:T, list: BaseObservableList): void;\n onUpdate(index: number, value: T, params: any, list: BaseObservableList): void;\n onRemove(index: number, value: T, list: BaseObservableList): void\n onMove(from: number, to: number, value: T, list: BaseObservableList): void\n}\n\nexport function defaultObserverWith(overrides: { [key in keyof IListObserver]?: IListObserver[key] }): IListObserver {\n const defaults = {\n onReset(){},\n onAdd(){},\n onUpdate(){},\n onRemove(){},\n onMove(){},\n }\n return Object.assign(defaults, overrides);\n}\n\nexport abstract class BaseObservableList extends BaseObservable> implements Iterable {\n emitReset() {\n for(let h of this._handlers) {\n h.onReset(this);\n }\n }\n // we need batch events, mostly on index based collection though?\n // maybe we should get started without?\n emitAdd(index: number, value: T): void {\n for(let h of this._handlers) {\n h.onAdd(index, value, this);\n }\n }\n\n emitUpdate(index: number, value: T, params?: any): void {\n for(let h of this._handlers) {\n h.onUpdate(index, value, params, this);\n }\n }\n\n emitRemove(index: number, value: T): void {\n for(let h of this._handlers) {\n h.onRemove(index, value, this);\n }\n }\n\n // toIdx assumes the item has already\n // been removed from its fromIdx\n emitMove(fromIdx: number, toIdx: number, value: T): void {\n for(let h of this._handlers) {\n h.onMove(fromIdx, toIdx, value, this);\n }\n }\n\n abstract [Symbol.iterator](): Iterator;\n abstract get length(): number;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/**\n * @license\n * Based off baseSortedIndex function in Lodash \n * Copyright JS Foundation and other contributors \n * Released under MIT license \n * Based on Underscore.js 1.8.3 \n * Copyright Jeremy Ashkenas, DocumentCloud and Investigative Reporters & Editors\n */\nexport function sortedIndex(array: T[], value: T, comparator: (x:T, y:T) => number): number {\n let low = 0;\n let high = array.length;\n\n while (low < high) {\n let mid = (low + high) >>> 1;\n let cmpResult = comparator(value, array[mid]);\n\n if (cmpResult > 0) {\n low = mid + 1;\n } else if (cmpResult < 0) {\n high = mid;\n } else {\n low = high = mid;\n }\n }\n return high;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservable} from \"../BaseObservable\";\n\nexport interface IMapObserver {\n onReset(): void;\n onAdd(key: K, value:V): void;\n onUpdate(key: K, value: V, params: any): void;\n onRemove(key: K, value: V): void\n}\n\nexport abstract class BaseObservableMap extends BaseObservable> {\n emitReset() {\n for(let h of this._handlers) {\n h.onReset();\n }\n }\n // we need batch events, mostly on index based collection though?\n // maybe we should get started without?\n emitAdd(key: K, value: V) {\n for(let h of this._handlers) {\n h.onAdd(key, value);\n }\n }\n\n emitUpdate(key, value, params) {\n for(let h of this._handlers) {\n h.onUpdate(key, value, params);\n }\n }\n\n emitRemove(key, value) {\n for(let h of this._handlers) {\n h.onRemove(key, value);\n }\n }\n\n abstract [Symbol.iterator](): Iterator<[K, V]>;\n abstract get size(): number;\n abstract get(key: K): V | undefined;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableMap} from \"./BaseObservableMap\";\n\nexport class ObservableMap extends BaseObservableMap {\n private readonly _values: Map;\n\n constructor(initialValues?: (readonly [K, V])[]) {\n super();\n this._values = new Map(initialValues);\n }\n\n update(key: K, params?: any): boolean {\n const value = this._values.get(key);\n if (value !== undefined) {\n // could be the same value, so it's already updated\n // but we don't assume this here\n this._values.set(key, value);\n this.emitUpdate(key, value, params);\n return true;\n }\n return false; // or return existing value?\n }\n\n add(key: K, value: V): boolean {\n if (!this._values.has(key)) {\n this._values.set(key, value);\n this.emitAdd(key, value);\n return true;\n }\n return false; // or return existing value?\n }\n\n remove(key: K): boolean {\n const value = this._values.get(key);\n if (value !== undefined) {\n this._values.delete(key);\n this.emitRemove(key, value);\n return true;\n } else {\n return false;\n }\n }\n\n set(key: K, value: V): boolean {\n if (this._values.has(key)) {\n // We set the value here because update only supports inline updates\n this._values.set(key, value);\n return this.update(key, undefined);\n } \n else {\n return this.add(key, value);\n }\n }\n\n reset(): void {\n this._values.clear();\n this.emitReset();\n }\n\n get(key: K): V | undefined {\n return this._values.get(key);\n }\n\n get size(): number {\n return this._values.size;\n }\n\n [Symbol.iterator](): Iterator<[K, V]> {\n return this._values.entries();\n }\n\n values(): Iterator {\n return this._values.values();\n }\n\n keys(): Iterator {\n return this._values.keys();\n }\n}\n\nexport function tests() {\n return {\n test_initial_values(assert) {\n const map = new ObservableMap([\n [\"a\", 5],\n [\"b\", 10]\n ]);\n assert.equal(map.size, 2);\n assert.equal(map.get(\"a\"), 5);\n assert.equal(map.get(\"b\"), 10);\n },\n\n test_add(assert) {\n let fired = 0;\n const map = new ObservableMap();\n map.subscribe({\n onAdd(key, value) {\n fired += 1;\n assert.equal(key, 1);\n assert.deepEqual(value, {value: 5}); \n },\n onUpdate() {},\n onRemove() {},\n onReset() {}\n });\n map.add(1, {value: 5});\n assert.equal(map.size, 1);\n assert.equal(fired, 1);\n },\n\n test_update(assert) {\n let fired = 0;\n const map = new ObservableMap();\n const value = {number: 5};\n map.add(1, value);\n map.subscribe({\n onUpdate(key, value, params) {\n fired += 1;\n assert.equal(key, 1);\n assert.deepEqual(value, {number: 6}); \n assert.equal(params, \"test\");\n },\n onAdd() {},\n onRemove() {},\n onReset() {}\n });\n value.number = 6;\n map.update(1, \"test\");\n assert.equal(fired, 1);\n },\n\n test_update_unknown(assert) {\n let fired = 0;\n const map = new ObservableMap();\n map.subscribe({\n onUpdate() { fired += 1; },\n onAdd() {},\n onRemove() {},\n onReset() {}\n });\n const result = map.update(1);\n assert.equal(fired, 0);\n assert.equal(result, false);\n },\n\n test_set(assert) {\n let add_fired = 0, update_fired = 0;\n const map = new ObservableMap();\n map.subscribe({\n onAdd(key, value) {\n add_fired += 1;\n assert.equal(key, 1);\n assert.deepEqual(value, {value: 5}); \n },\n onUpdate(key, value/*, params*/) {\n update_fired += 1;\n assert.equal(key, 1);\n assert.deepEqual(value, {value: 7}); \n },\n onRemove() {},\n onReset() {}\n });\n // Add\n map.set(1, {value: 5});\n assert.equal(map.size, 1);\n assert.equal(add_fired, 1);\n // Update\n map.set(1, {value: 7});\n assert.equal(map.size, 1);\n assert.equal(update_fired, 1);\n },\n\n test_remove(assert) {\n let fired = 0;\n const map = new ObservableMap();\n const value = {value: 5};\n map.add(1, value);\n map.subscribe({\n onRemove(key, value) {\n fired += 1;\n assert.equal(key, 1);\n assert.deepEqual(value, {value: 5}); \n },\n onAdd() {},\n onUpdate() {},\n onReset() {}\n });\n map.remove(1);\n assert.equal(map.size, 0);\n assert.equal(fired, 1);\n },\n\n test_iterate(assert) {\n const results: any[] = [];\n const map = new ObservableMap();\n map.add(1, {number: 5});\n map.add(2, {number: 6});\n map.add(3, {number: 7});\n for (let e of map) {\n results.push(e);\n }\n assert.equal(results.length, 3);\n assert.equal(results.find(([key]) => key === 1)[1].number, 5);\n assert.equal(results.find(([key]) => key === 2)[1].number, 6);\n assert.equal(results.find(([key]) => key === 3)[1].number, 7);\n },\n test_size(assert) {\n const map = new ObservableMap();\n map.add(1, {number: 5});\n map.add(2, {number: 6});\n assert.equal(map.size, 2);\n },\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableList} from \"./BaseObservableList\";\nimport {sortedIndex} from \"../../utils/sortedIndex\";\n\n/*\n\nwhen a value changes, it sorting order can change. It would still be at the old index prior to firing an onUpdate event.\nSo how do you know where it was before it changed, if not by going over all values?\n\nhow to make this fast?\n\nseems hard to solve with an array, because you need to map the key to it's previous location somehow, to efficiently find it,\nand move it.\n\nI wonder if we could do better with a binary search tree (BST).\nThe tree has a value with {key, value}. There is a plain Map mapping keys to this tuple,\nfor easy lookup. Now how do we find the index of this tuple in the BST?\n\neither we store in every node the amount of nodes on the left and right, or we decend into the part\nof the tree preceding the node we want to know about. Updating the counts upwards would probably be fine as this is log2 of\nthe size of the container.\n\nto be able to go from a key to an index, the value would have the have a link with the tree node though\n\nso key -> Map -> value -> node -> *parentNode -> rootNode\nwith a node containing {value, leftCount, rightCount, leftNode, rightNode, parentNode}\n*/\n\n// does not assume whether or not the values are reference\n// types modified outside of the collection (and affecting sort order) or not\n\n// no duplicates allowed for now\nexport class SortedMapList extends BaseObservableList {\n constructor(sourceMap, comparator) {\n super();\n this._sourceMap = sourceMap;\n this._comparator = (a, b) => comparator(a.value, b.value);\n this._sortedPairs = null;\n this._mapSubscription = null;\n }\n \n onAdd(key, value) {\n const pair = {key, value};\n const idx = sortedIndex(this._sortedPairs, pair, this._comparator);\n this._sortedPairs.splice(idx, 0, pair);\n this.emitAdd(idx, value);\n }\n\n onRemove(key, value) {\n const pair = {key, value};\n const idx = sortedIndex(this._sortedPairs, pair, this._comparator);\n // assert key === this._sortedPairs[idx].key;\n this._sortedPairs.splice(idx, 1);\n this.emitRemove(idx, value);\n }\n\n onUpdate(key, value, params) {\n // if an update is emitted while calling source.subscribe() from onSubscribeFirst, ignore it\n if (!this._sortedPairs) {\n return;\n }\n // TODO: suboptimal for performance, see above for idea with BST to speed this up if we need to\n const oldIdx = this._sortedPairs.findIndex(p => p.key === key);\n // neccesary to remove pair from array before\n // doing sortedIndex as it relies on being sorted\n this._sortedPairs.splice(oldIdx, 1);\n const pair = {key, value};\n const newIdx = sortedIndex(this._sortedPairs, pair, this._comparator);\n this._sortedPairs.splice(newIdx, 0, pair);\n if (oldIdx !== newIdx) {\n this.emitMove(oldIdx, newIdx, value);\n }\n this.emitUpdate(newIdx, value, params);\n }\n\n onReset() {\n this._sortedPairs = [];\n this.emitReset();\n }\n\n onSubscribeFirst() {\n this._mapSubscription = this._sourceMap.subscribe(this);\n this._sortedPairs = new Array(this._sourceMap.size);\n let i = 0;\n for (let [key, value] of this._sourceMap) {\n this._sortedPairs[i] = {key, value};\n ++i;\n }\n this._sortedPairs.sort(this._comparator);\n super.onSubscribeFirst();\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n this._sortedPairs = null;\n this._mapSubscription = this._mapSubscription();\n }\n\n get(index) {\n return this._sortedPairs[index].value;\n }\n\n get length() {\n return this._sourceMap.size;\n }\n\n [Symbol.iterator]() {\n const it = this._sortedPairs.values();\n return {\n next() {\n const v = it.next();\n if (v.value) {\n v.value = v.value.value;\n }\n return v;\n }\n }\n }\n}\n\nimport {ObservableMap} from \"../map/ObservableMap\";\n\nexport function tests() {\n return {\n test_sortIndex(assert) {\n const a = [1, 5, 6, 8];\n const cmp = (a, b) => a - b;\n let idx = sortedIndex(a, 0, cmp);\n assert.equal(idx, 0);\n idx = sortedIndex(a, 3, cmp);\n assert.equal(idx, 1);\n idx = sortedIndex(a, 5, cmp);\n assert.equal(idx, 1);\n idx = sortedIndex(a, 8, cmp);\n assert.equal(idx, 3);\n },\n\n test_sortIndex_reverse(assert) {\n let idx = sortedIndex([8, 6, 5, 1], 6, (a, b) => b - a);\n assert.equal(idx, 1);\n },\n\n test_sortIndex_comparator_Array_compatible(assert) {\n const a = [5, 1, 8, 2];\n const cmp = (a, b) => a - b;\n a.sort(cmp);\n assert.deepEqual(a, [1, 2, 5, 8]);\n let idx = sortedIndex(a, 2, cmp);\n assert.equal(idx, 1);\n },\n\n test_initial_values(assert) {\n const map = new ObservableMap([\n [\"a\", 50],\n [\"b\", 6],\n [\"c\", -5],\n ]);\n const list = new SortedMapList(map, (a, b) => a - b);\n list.subscribe({}); //needed to populate iterator\n assert.deepEqual(Array.from(list), [-5, 6, 50]);\n assert.equal(list.length, 3);\n },\n\n test_add(assert) {\n const map = new ObservableMap([[\"a\", 50], [\"b\", 6], [\"c\", -5]]);\n const list = new SortedMapList(map, (a, b) => a - b);\n let fired = 0;\n list.subscribe({\n onAdd(idx, value) {\n fired++;\n assert.equal(idx, 2);\n assert.equal(value, 20);\n }\n });\n map.add(\"d\", 20);\n assert.equal(fired, 1);\n assert.equal(list.length, 4);\n },\n\n test_remove(assert) {\n const map = new ObservableMap([[\"a\", 50], [\"b\", 6], [\"c\", -5]]);\n const list = new SortedMapList(map, (a, b) => a - b);\n let fired = 0;\n list.subscribe({\n onRemove(idx, value) {\n fired++;\n assert.equal(idx, 2);\n assert.equal(value, 50);\n }\n });\n map.remove(\"a\");\n assert.equal(fired, 1);\n assert.equal(list.length, 2);\n },\n\n test_move_reference(assert) {\n const a = {number: 3};\n const map = new ObservableMap([\n [\"a\", a],\n [\"b\", {number: 11}],\n [\"c\", {number: 1}],\n ]);\n const list = new SortedMapList(map, (a, b) => a.number - b.number);\n let updateFired = 0, moveFired = 0;\n list.subscribe({\n onUpdate(idx, value, param) {\n updateFired++;\n assert.equal(idx, 2);\n assert.equal(value, a);\n assert.equal(param, \"number\");\n },\n\n onMove(oldIdx, newIdx, value) {\n moveFired++;\n assert.equal(oldIdx, 1);\n assert.equal(newIdx, 2);\n assert.equal(value, a);\n }\n });\n a.number = 111;\n map.update(\"a\", \"number\");\n assert.equal(moveFired, 1);\n assert.equal(updateFired, 1);\n },\n\n test_update_without_move(assert) {\n const a = {number: 3};\n const map = new ObservableMap([\n [\"a\", a],\n [\"b\", {number: 11}],\n [\"c\", {number: 1}],\n ]);\n const list = new SortedMapList(map, (a, b) => a.number - b.number);\n let updateFired = 0, moveFired = 0;\n list.subscribe({\n onUpdate(idx, value, param) {\n updateFired++;\n assert.equal(idx, 1);\n assert.equal(value, a);\n assert.equal(param, \"number\");\n },\n\n onMove() {\n moveFired++;\n }\n });\n assert.deepEqual(Array.from(list).map(v => v.number), [1, 3, 11]);\n // asume some part of a that doesn't affect\n // sorting order has changed here\n map.update(\"a\", \"number\");\n assert.equal(moveFired, 0);\n assert.equal(updateFired, 1);\n assert.deepEqual(Array.from(list).map(v => v.number), [1, 3, 11]);\n },\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableMap} from \"./BaseObservableMap\";\n\nexport class FilteredMap extends BaseObservableMap {\n constructor(source, filter) {\n super();\n this._source = source;\n this._filter = filter;\n /** @type {Map} */\n this._included = null;\n this._subscription = null;\n }\n\n setFilter(filter) {\n this._filter = filter;\n if (this._subscription) {\n this._reapplyFilter();\n }\n }\n\n /**\n * reapply the filter\n */\n _reapplyFilter(silent = false) {\n if (this._filter) {\n const oldIncluded = this._included;\n this._included = this._included || new Map();\n for (const [key, value] of this._source) {\n const isIncluded = this._filter(value, key);\n this._included.set(key, isIncluded);\n if (!silent) {\n const wasIncluded = oldIncluded ? oldIncluded.get(key) : true;\n this._emitForUpdate(wasIncluded, isIncluded, key, value);\n }\n }\n } else { // no filter\n // did we have a filter before?\n if (this._included && !silent) {\n // add any non-included items again\n for (const [key, value] of this._source) {\n if (!this._included.get(key)) {\n this.emitAdd(key, value);\n }\n }\n }\n this._included = null;\n }\n }\n\n onAdd(key, value) {\n if (this._filter) {\n const included = this._filter(value, key);\n this._included.set(key, included);\n if (!included) {\n return;\n }\n }\n this.emitAdd(key, value);\n }\n\n onRemove(key, value) {\n const wasIncluded = !this._filter || this._included.get(key);\n this._included.delete(key);\n if (wasIncluded) {\n this.emitRemove(key, value);\n }\n }\n\n onUpdate(key, value, params) {\n // if an update is emitted while calling source.subscribe() from onSubscribeFirst, ignore it\n if (!this._included) {\n return;\n }\n if (this._filter) {\n const wasIncluded = this._included.get(key);\n const isIncluded = this._filter(value, key);\n this._included.set(key, isIncluded);\n this._emitForUpdate(wasIncluded, isIncluded, key, value, params);\n } else {\n this.emitUpdate(key, value, params);\n }\n }\n\n _emitForUpdate(wasIncluded, isIncluded, key, value, params = null) {\n if (wasIncluded && !isIncluded) {\n this.emitRemove(key, value);\n } else if (!wasIncluded && isIncluded) {\n this.emitAdd(key, value);\n } else if (wasIncluded && isIncluded) {\n this.emitUpdate(key, value, params);\n }\n }\n\n onSubscribeFirst() {\n this._subscription = this._source.subscribe(this);\n this._reapplyFilter(true);\n super.onSubscribeFirst();\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n this._included = null;\n this._subscription = this._subscription();\n }\n\n onReset() {\n this._reapplyFilter();\n this.emitReset();\n }\n\n [Symbol.iterator]() {\n return new FilterIterator(this._source, this._included);\n }\n\n get size() {\n let count = 0;\n this._included.forEach(included => {\n if (included) {\n count += 1;\n }\n });\n return count;\n }\n\n get(key) {\n const value = this._source.get(key);\n if (value && this._filter(value, key)) {\n return value;\n }\n }\n}\n\nclass FilterIterator {\n constructor(map, _included) {\n this._included = _included;\n this._sourceIterator = map[Symbol.iterator]();\n }\n\n next() {\n // eslint-disable-next-line no-constant-condition\n while (true) {\n const sourceResult = this._sourceIterator.next();\n if (sourceResult.done) {\n return sourceResult;\n }\n const key = sourceResult.value[0];\n if (this._included.get(key)) {\n return sourceResult;\n }\n }\n }\n}\n\nimport {ObservableMap} from \"./ObservableMap\";\nexport function tests() {\n return {\n \"filter preloaded list\": assert => {\n const source = new ObservableMap();\n source.add(\"one\", 1);\n source.add(\"two\", 2);\n source.add(\"three\", 3);\n const oddNumbers = new FilteredMap(source, x => x % 2 !== 0);\n // can only iterate after subscribing\n oddNumbers.subscribe({});\n assert.equal(oddNumbers.size, 2);\n const it = oddNumbers[Symbol.iterator]();\n assert.deepEqual(it.next().value, [\"one\", 1]);\n assert.deepEqual(it.next().value, [\"three\", 3]);\n assert.equal(it.next().done, true);\n },\n // \"filter added values\": assert => {\n\n // },\n // \"filter removed values\": assert => {\n\n // },\n // \"filter changed values\": assert => {\n\n // },\n\n \"emits must trigger once\": assert => {\n const source = new ObservableMap();\n let count_add = 0, count_update = 0, count_remove = 0;\n source.add(\"num1\", 1);\n source.add(\"num2\", 2);\n source.add(\"num3\", 3);\n const oddMap = new FilteredMap(source, x => x % 2 !== 0);\n oddMap.subscribe({\n onAdd() {\n count_add += 1;\n },\n onRemove() {\n count_remove += 1;\n },\n onUpdate() {\n count_update += 1;\n }\n });\n source.set(\"num3\", 4);\n source.set(\"num3\", 5);\n source.set(\"num3\", 7);\n assert.strictEqual(count_add, 1);\n assert.strictEqual(count_update, 1);\n assert.strictEqual(count_remove, 1);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableMap} from \"./BaseObservableMap\";\n/*\nso a mapped value can emit updates on it's own with this._emitSpontaneousUpdate that is passed in the mapping function\nhow should the mapped value be notified of an update though? and can it then decide to not propagate the update?\n*/\nexport class MappedMap extends BaseObservableMap {\n constructor(source, mapper, updater) {\n super();\n this._source = source;\n this._mapper = mapper;\n this._updater = updater;\n this._mappedValues = new Map();\n }\n\n _emitSpontaneousUpdate(key, params) {\n const value = this._mappedValues.get(key);\n if (value) {\n this.emitUpdate(key, value, params);\n }\n }\n\n onAdd(key, value) {\n const emitSpontaneousUpdate = this._emitSpontaneousUpdate.bind(this, key);\n const mappedValue = this._mapper(value, emitSpontaneousUpdate);\n this._mappedValues.set(key, mappedValue);\n this.emitAdd(key, mappedValue);\n }\n\n onRemove(key/*, _value*/) {\n const mappedValue = this._mappedValues.get(key);\n if (this._mappedValues.delete(key)) {\n this.emitRemove(key, mappedValue);\n }\n }\n\n onUpdate(key, value, params) {\n // if an update is emitted while calling source.subscribe() from onSubscribeFirst, ignore it\n if (!this._mappedValues) {\n return;\n }\n const mappedValue = this._mappedValues.get(key);\n if (mappedValue !== undefined) {\n this._updater?.(mappedValue, params, value);\n // TODO: map params somehow if needed?\n this.emitUpdate(key, mappedValue, params);\n }\n }\n\n onSubscribeFirst() {\n this._subscription = this._source.subscribe(this);\n for (let [key, value] of this._source) {\n const emitSpontaneousUpdate = this._emitSpontaneousUpdate.bind(this, key);\n const mappedValue = this._mapper(value, emitSpontaneousUpdate);\n this._mappedValues.set(key, mappedValue);\n }\n super.onSubscribeFirst();\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n this._subscription = this._subscription();\n this._mappedValues.clear();\n }\n\n onReset() {\n this._mappedValues.clear();\n this.emitReset();\n }\n\n [Symbol.iterator]() {\n return this._mappedValues.entries();\n }\n\n get size() {\n return this._mappedValues.size;\n }\n\n get(key) {\n return this._mappedValues.get(key);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableMap} from \"./BaseObservableMap\";\n\nexport class JoinedMap extends BaseObservableMap {\n constructor(sources) {\n super();\n this._sources = sources;\n this._subscriptions = null;\n }\n\n onAdd(source, key, value) {\n if (!this._isKeyAtSourceOccluded(source, key)) {\n const occludingValue = this._getValueFromOccludedSources(source, key);\n if (occludingValue !== undefined) {\n // adding a value that will occlude another one should\n // first emit a remove\n this.emitRemove(key, occludingValue);\n }\n this.emitAdd(key, value);\n }\n }\n\n onRemove(source, key, value) {\n if (!this._isKeyAtSourceOccluded(source, key)) {\n this.emitRemove(key, value);\n const occludedValue = this._getValueFromOccludedSources(source, key);\n if (occludedValue !== undefined) {\n // removing a value that so far occluded another one should\n // emit an add for the occluded value after the removal\n this.emitAdd(key, occludedValue);\n }\n }\n }\n\n onUpdate(source, key, value, params) {\n // if an update is emitted while calling source.subscribe() from onSubscribeFirst, ignore it\n if (!this._subscriptions) {\n return;\n }\n if (!this._isKeyAtSourceOccluded(source, key)) {\n this.emitUpdate(key, value, params);\n }\n }\n\n onReset() {\n this.emitReset();\n }\n\n onSubscribeFirst() {\n this._subscriptions = this._sources.map(source => new SourceSubscriptionHandler(source, this).subscribe());\n super.onSubscribeFirst();\n }\n\n _isKeyAtSourceOccluded(source, key) {\n // sources that come first in the sources array can\n // hide the keys in later sources, to prevent events\n // being emitted for the same key and different values,\n // so check the key is not present in earlier sources\n const index = this._sources.indexOf(source);\n for (let i = 0; i < index; i += 1) {\n if (this._sources[i].get(key) !== undefined) {\n return true;\n }\n }\n return false;\n }\n\n // get the value that the given source and key occlude, if any\n _getValueFromOccludedSources(source, key) {\n // sources that come first in the sources array can\n // hide the keys in later sources, to prevent events\n // being emitted for the same key and different values,\n // so check the key is not present in earlier sources\n const index = this._sources.indexOf(source);\n for (let i = index + 1; i < this._sources.length; i += 1) {\n const source = this._sources[i];\n const occludedValue = source.get(key);\n if (occludedValue !== undefined) {\n return occludedValue;\n }\n }\n return undefined;\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n for (const s of this._subscriptions) {\n s.dispose();\n }\n }\n\n [Symbol.iterator]() {\n return new JoinedIterator(this._sources);\n }\n\n get size() {\n return this._sources.reduce((sum, s) => sum + s.size, 0);\n }\n\n get(key) {\n for (const s of this._sources) {\n const value = s.get(key);\n if (value) {\n return value;\n }\n }\n return null;\n }\n}\n\nclass JoinedIterator {\n constructor(sources) {\n this._sources = sources;\n this._sourceIndex = -1;\n this._currentIterator = null;\n this._encounteredKeys = new Set();\n }\n\n next() {\n let result;\n while (!result) {\n if (!this._currentIterator) {\n this._sourceIndex += 1;\n if (this._sources.length <= this._sourceIndex) {\n return {done: true};\n }\n this._currentIterator = this._sources[this._sourceIndex][Symbol.iterator]();\n }\n const sourceResult = this._currentIterator.next();\n if (sourceResult.done) {\n this._currentIterator = null;\n continue;\n } else {\n const key = sourceResult.value[0];\n if (!this._encounteredKeys.has(key)) {\n this._encounteredKeys.add(key);\n result = sourceResult;\n }\n }\n }\n return result;\n }\n}\n\nclass SourceSubscriptionHandler {\n constructor(source, joinedMap) {\n this._source = source;\n this._joinedMap = joinedMap;\n this._subscription = null;\n }\n\n subscribe() {\n this._subscription = this._source.subscribe(this);\n return this;\n }\n\n dispose() {\n this._subscription = this._subscription();\n }\n\n onAdd(key, value) {\n this._joinedMap.onAdd(this._source, key, value);\n }\n\n onRemove(key, value) {\n this._joinedMap.onRemove(this._source, key, value);\n }\n\n onUpdate(key, value, params) {\n this._joinedMap.onUpdate(this._source, key, value, params);\n }\n\n onReset() {\n this._joinedMap.onReset(this._source);\n }\n}\n\n\nimport { ObservableMap } from \"./ObservableMap\";\n\nexport function tests() {\n\n function observeMap(map) {\n const events = [];\n map.subscribe({\n onAdd(key, value) { events.push({type: \"add\", key, value}); },\n onRemove(key, value) { events.push({type: \"remove\", key, value}); },\n onUpdate(key, value, params) { events.push({type: \"update\", key, value, params}); }\n });\n return events;\n }\n\n return {\n \"joined iterator\": assert => {\n const firstKV = [\"a\", 1];\n const secondKV = [\"b\", 2];\n const thirdKV = [\"c\", 3];\n const it = new JoinedIterator([[firstKV, secondKV], [thirdKV]]);\n assert.equal(it.next().value, firstKV);\n assert.equal(it.next().value, secondKV);\n assert.equal(it.next().value, thirdKV);\n assert.equal(it.next().done, true);\n },\n \"prevent key collision during iteration\": assert => {\n const first = new ObservableMap();\n const second = new ObservableMap();\n const join = new JoinedMap([first, second]);\n second.add(\"a\", 2);\n second.add(\"b\", 3);\n first.add(\"a\", 1);\n const it = join[Symbol.iterator]();\n assert.deepEqual(it.next().value, [\"a\", 1]);\n assert.deepEqual(it.next().value, [\"b\", 3]);\n assert.equal(it.next().done, true);\n },\n \"adding occluded key doesn't emit add\": assert => {\n const first = new ObservableMap();\n const second = new ObservableMap();\n const join = new JoinedMap([first, second]);\n const events = observeMap(join);\n first.add(\"a\", 1);\n second.add(\"a\", 2);\n assert.equal(events.length, 1);\n assert.equal(events[0].type, \"add\");\n assert.equal(events[0].key, \"a\");\n assert.equal(events[0].value, 1);\n },\n \"updating occluded key doesn't emit update\": assert => {\n const first = new ObservableMap();\n const second = new ObservableMap();\n const join = new JoinedMap([first, second]);\n first.add(\"a\", 1);\n second.add(\"a\", 2);\n const events = observeMap(join);\n second.update(\"a\", 3);\n assert.equal(events.length, 0);\n },\n \"removal of occluding key emits add after remove\": assert => {\n const first = new ObservableMap();\n const second = new ObservableMap();\n const join = new JoinedMap([first, second]);\n first.add(\"a\", 1);\n second.add(\"a\", 2);\n const events = observeMap(join);\n first.remove(\"a\");\n assert.equal(events.length, 2);\n assert.equal(events[0].type, \"remove\");\n assert.equal(events[0].key, \"a\");\n assert.equal(events[0].value, 1);\n assert.equal(events[1].type, \"add\");\n assert.equal(events[1].key, \"a\");\n assert.equal(events[1].value, 2);\n },\n \"adding occluding key emits remove first\": assert => {\n const first = new ObservableMap();\n const second = new ObservableMap();\n const join = new JoinedMap([first, second]);\n second.add(\"a\", 2);\n const events = observeMap(join);\n first.add(\"a\", 1);\n assert.equal(events.length, 2);\n assert.equal(events[0].type, \"remove\");\n assert.equal(events[0].key, \"a\");\n assert.equal(events[0].value, 2);\n assert.equal(events[1].type, \"add\");\n assert.equal(events[1].key, \"a\");\n assert.equal(events[1].value, 1);\n }\n };\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableList} from \"./BaseObservableList\";\n\nexport class ObservableArray extends BaseObservableList {\n private _items: T[];\n\n constructor(initialValues: T[] = []) {\n super();\n this._items = initialValues;\n }\n\n append(item: T): void {\n this._items.push(item);\n this.emitAdd(this._items.length - 1, item);\n }\n\n remove(idx: number): void {\n const [item] = this._items.splice(idx, 1);\n this.emitRemove(idx, item);\n }\n\n insertMany(idx: number, items: T[]): void {\n for(let item of items) {\n this.insert(idx, item);\n idx += 1;\n }\n }\n\n insert(idx: number, item: T): void {\n this._items.splice(idx, 0, item);\n this.emitAdd(idx, item);\n }\n\n move(fromIdx: number, toIdx: number): void {\n if (fromIdx < this._items.length && toIdx < this._items.length) {\n const [item] = this._items.splice(fromIdx, 1);\n this._items.splice(toIdx, 0, item);\n this.emitMove(fromIdx, toIdx, item);\n }\n }\n\n update(idx: number, item: T, params: any = null): void {\n if (idx < this._items.length) {\n this._items[idx] = item;\n this.emitUpdate(idx, item, params);\n }\n }\n\n get array(): Readonly {\n return this._items;\n }\n\n at(idx: number): T | undefined {\n if (this._items && idx >= 0 && idx < this._items.length) {\n return this._items[idx];\n }\n }\n\n get length(): number {\n return this._items.length;\n }\n\n [Symbol.iterator]() {\n return this._items.values();\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {BaseObservableList} from \"./BaseObservableList\";\n\n/* inline update of item in collection backed by array, without replacing the preexising item */\nexport function findAndUpdateInArray(predicate: (value: T) => boolean, array: T[], observable: BaseObservableList, updater: (value: T) => any | false) {\n const index = array.findIndex(predicate);\n if (index !== -1) {\n const value = array[index];\n // allow bailing out of sending an emit if updater determined its not needed\n const params = updater(value);\n if (params !== false) {\n observable.emitUpdate(index, value, params);\n }\n // found\n return true;\n }\n return false;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableList} from \"./BaseObservableList\";\nimport {sortedIndex} from \"../../utils/sortedIndex\";\nimport {findAndUpdateInArray} from \"./common\";\n\nexport class SortedArray extends BaseObservableList {\n private _comparator: (left: T, right: T) => number;\n private _items: T[] = [];\n\n constructor(comparator: (left: T, right: T) => number) {\n super();\n this._comparator = comparator;\n }\n\n setManyUnsorted(items: T[]): void {\n this.setManySorted(items);\n }\n\n setManySorted(items: T[]): void {\n // TODO: we can make this way faster by only looking up the first and last key,\n // and merging whatever is inbetween with items\n // if items is not sorted, 💩🌀 will follow!\n // should we check?\n // Also, once bulk events are supported in collections,\n // we can do a bulk add event here probably if there are no updates\n // BAD CODE!\n for(let item of items) {\n this.set(item);\n }\n }\n\n findAndUpdate(predicate: (value: T) => boolean, updater: (value: T) => any | false): boolean {\n return findAndUpdateInArray(predicate, this._items, this, updater);\n }\n\n getAndUpdate(item: T, updater: (existing: T, item: T) => any, updateParams: any = null): void {\n const idx = this.indexOf(item);\n if (idx !== -1) {\n const existingItem = this._items[idx];\n const newItem = updater(existingItem, item);\n this._items[idx] = newItem;\n this.emitUpdate(idx, newItem, updateParams);\n }\n }\n\n update(item: T, updateParams: any = null): void {\n const idx = this.indexOf(item);\n if (idx !== -1) {\n this._items[idx] = item;\n this.emitUpdate(idx, item, updateParams);\n }\n }\n\n indexOf(item: T): number {\n const idx = sortedIndex(this._items, item, this._comparator);\n if (idx < this._items.length && this._comparator(this._items[idx], item) === 0) {\n return idx;\n } else {\n return -1;\n }\n }\n\n _getNext(item: T): T | undefined {\n let idx = sortedIndex(this._items, item, this._comparator);\n while(idx < this._items.length && this._comparator(this._items[idx], item) <= 0) {\n idx += 1;\n }\n return this.get(idx);\n }\n\n set(item: T, updateParams: any = null): void {\n const idx = sortedIndex(this._items, item, this._comparator);\n if (idx >= this._items.length || this._comparator(this._items[idx], item) !== 0) {\n this._items.splice(idx, 0, item);\n this.emitAdd(idx, item)\n } else {\n this._items[idx] = item;\n this.emitUpdate(idx, item, updateParams);\n }\n }\n\n get(idx: number): T | undefined {\n return this._items[idx];\n }\n\n remove(idx: number): void {\n const item = this._items[idx];\n this._items.splice(idx, 1);\n this.emitRemove(idx, item);\n }\n\n get array(): T[] {\n return this._items;\n }\n\n get length(): number {\n return this._items.length;\n }\n\n [Symbol.iterator]() {\n return new Iterator(this);\n }\n}\n\n// iterator that works even if the current value is removed while iterating\nclass Iterator {\n private _sortedArray: SortedArray | null\n private _current: T | null | undefined\n\n constructor(sortedArray: SortedArray) {\n this._sortedArray = sortedArray;\n this._current = null;\n }\n\n next() {\n if (this._sortedArray) {\n if (this._current) {\n this._current = this._sortedArray._getNext(this._current);\n } else {\n this._current = this._sortedArray.get(0);\n }\n if (this._current) {\n return {value: this._current};\n } else {\n // cause done below\n this._sortedArray = null;\n }\n }\n if (!this._sortedArray) {\n return {done: true};\n }\n }\n}\n\nexport function tests() {\n return {\n \"setManyUnsorted\": assert => {\n const sa = new SortedArray((a, b) => a.localeCompare(b));\n sa.setManyUnsorted([\"b\", \"a\", \"c\"]);\n assert.equal(sa.length, 3);\n assert.equal(sa.get(0), \"a\");\n assert.equal(sa.get(1), \"b\");\n assert.equal(sa.get(2), \"c\");\n }, \n \"_getNext\": assert => {\n const sa = new SortedArray((a, b) => a.localeCompare(b));\n sa.setManyUnsorted([\"b\", \"a\", \"f\"]);\n assert.equal(sa._getNext(\"a\"), \"b\");\n assert.equal(sa._getNext(\"b\"), \"f\");\n // also finds the next if the value is not in the collection\n assert.equal(sa._getNext(\"c\"), \"f\");\n assert.equal(sa._getNext(\"f\"), undefined);\n },\n \"iterator with removals\": assert => {\n const queue = new SortedArray<{idx: number}>((a, b) => a.idx - b.idx);\n queue.setManyUnsorted([{idx: 5}, {idx: 3}, {idx: 1}, {idx: 4}, {idx: 2}]);\n const it = queue[Symbol.iterator]();\n assert.equal(it.next().value.idx, 1);\n assert.equal(it.next().value.idx, 2);\n queue.remove(1);\n assert.equal(it.next().value.idx, 3);\n queue.remove(1);\n assert.equal(it.next().value.idx, 4);\n queue.remove(1);\n assert.equal(it.next().value.idx, 5);\n queue.remove(1);\n assert.equal(it.next().done, true);\n // check done persists\n assert.equal(it.next().done, true);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableList} from \"./BaseObservableList\";\nimport {findAndUpdateInArray} from \"./common\";\n\nexport type Mapper = (value: F) => T\nexport type Updater = (mappedValue: T, params: any, value: F) => void;\n\nexport class BaseMappedList extends BaseObservableList {\n protected _sourceList: BaseObservableList;\n protected _sourceUnsubscribe: (() => void) | null = null;\n _mapper: Mapper;\n _updater?: Updater;\n _removeCallback?: (value: T) => void;\n _mappedValues: T[] | null = null;\n\n constructor(sourceList: BaseObservableList, mapper: Mapper, updater?: Updater, removeCallback?: (value: T) => void) {\n super();\n this._sourceList = sourceList;\n this._mapper = mapper;\n this._updater = updater;\n this._removeCallback = removeCallback;\n }\n\n findAndUpdate(predicate: (value: T) => boolean, updater: (value: T) => any | false) {\n return findAndUpdateInArray(predicate, this._mappedValues!, this, updater);\n }\n\n get length() {\n return this._mappedValues!.length;\n }\n\n [Symbol.iterator]() {\n return this._mappedValues!.values();\n }\n}\n\nexport function runAdd(list: BaseMappedList, index: number, mappedValue: T): void {\n list._mappedValues!.splice(index, 0, mappedValue);\n list.emitAdd(index, mappedValue);\n}\n\nexport function runUpdate(list: BaseMappedList, index: number, value: F, params: any): void {\n const mappedValue = list._mappedValues![index];\n if (list._updater) {\n list._updater(mappedValue, params, value);\n }\n list.emitUpdate(index, mappedValue, params);\n}\n\nexport function runRemove(list: BaseMappedList, index: number): void {\n const mappedValue = list._mappedValues![index];\n list._mappedValues!.splice(index, 1);\n if (list._removeCallback) {\n list._removeCallback(mappedValue);\n }\n list.emitRemove(index, mappedValue);\n}\n\nexport function runMove(list: BaseMappedList, fromIdx: number, toIdx: number): void {\n const mappedValue = list._mappedValues![fromIdx];\n list._mappedValues!.splice(fromIdx, 1);\n list._mappedValues!.splice(toIdx, 0, mappedValue);\n list.emitMove(fromIdx, toIdx, mappedValue);\n}\n\nexport function runReset(list: BaseMappedList): void {\n list._mappedValues = [];\n list.emitReset();\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {IListObserver} from \"./BaseObservableList\";\nimport {BaseMappedList, Mapper, Updater, runAdd, runUpdate, runRemove, runMove, runReset} from \"./BaseMappedList\";\n\nexport class AsyncMappedList extends BaseMappedList> implements IListObserver {\n private _eventQueue: AsyncEvent[] | null = null;\n private _flushing: boolean = false;\n\n onSubscribeFirst(): void {\n this._sourceUnsubscribe = this._sourceList.subscribe(this);\n this._eventQueue = [];\n this._mappedValues = [];\n let idx = 0;\n for (const item of this._sourceList) {\n this._eventQueue.push(new AddEvent(idx, item));\n idx += 1;\n }\n this._flush();\n }\n\n async _flush(): Promise {\n if (this._flushing) {\n return;\n }\n this._flushing = true;\n try {\n while (this._eventQueue!.length) {\n const event = this._eventQueue!.shift();\n await event!.run(this);\n }\n } finally {\n this._flushing = false;\n }\n }\n\n onReset(): void {\n if (this._eventQueue) {\n this._eventQueue.push(new ResetEvent());\n this._flush();\n }\n }\n\n onAdd(index: number, value: F): void {\n if (this._eventQueue) {\n this._eventQueue.push(new AddEvent(index, value));\n this._flush();\n }\n }\n\n onUpdate(index: number, value: F, params: any): void {\n if (this._eventQueue) {\n this._eventQueue.push(new UpdateEvent(index, value, params));\n this._flush();\n }\n }\n\n onRemove(index: number): void {\n if (this._eventQueue) {\n this._eventQueue.push(new RemoveEvent(index));\n this._flush();\n }\n }\n\n onMove(fromIdx: number, toIdx: number): void {\n if (this._eventQueue) {\n this._eventQueue.push(new MoveEvent(fromIdx, toIdx));\n this._flush();\n }\n }\n\n onUnsubscribeLast(): void {\n this._sourceUnsubscribe!();\n this._eventQueue = null;\n this._mappedValues = null;\n }\n}\n\ntype AsyncEvent = AddEvent | UpdateEvent | RemoveEvent | MoveEvent | ResetEvent\n\nclass AddEvent {\n constructor(public index: number, public value: F) {}\n\n async run(list: AsyncMappedList): Promise {\n const mappedValue = await list._mapper(this.value);\n runAdd(list, this.index, mappedValue);\n }\n}\n\nclass UpdateEvent {\n constructor(public index: number, public value: F, public params: any) {}\n\n async run(list: AsyncMappedList): Promise {\n runUpdate(list, this.index, this.value, this.params);\n }\n}\n\nclass RemoveEvent {\n constructor(public index: number) {}\n\n async run(list: AsyncMappedList): Promise {\n runRemove(list, this.index);\n }\n}\n\nclass MoveEvent {\n constructor(public fromIdx: number, public toIdx: number) {}\n\n async run(list: AsyncMappedList): Promise {\n runMove(list, this.fromIdx, this.toIdx);\n }\n}\n\nclass ResetEvent {\n async run(list: AsyncMappedList): Promise {\n runReset(list);\n }\n}\n\nimport {ObservableArray} from \"./ObservableArray\";\nimport {ListObserver} from \"../../mocks/ListObserver.js\";\n\nexport function tests() {\n return {\n \"events are emitted in order\": async assert => {\n const double = n => n * n;\n const source = new ObservableArray();\n const mapper = new AsyncMappedList(source, async n => {\n await new Promise(r => setTimeout(r, n));\n return {n: double(n)};\n }, (o, params, n) => {\n o.n = double(n);\n });\n const observer = new ListObserver();\n mapper.subscribe(observer);\n source.append(2); // will sleep this amount, so second append would take less time\n source.append(1);\n source.update(0, 7, \"lucky seven\")\n source.remove(0);\n {\n const {type, index, value} = await observer.next();\n assert.equal(mapper.length, 1);\n assert.equal(type, \"add\");\n assert.equal(index, 0);\n assert.equal(value.n, 4);\n }\n {\n const {type, index, value} = await observer.next();\n assert.equal(mapper.length, 2);\n assert.equal(type, \"add\");\n assert.equal(index, 1);\n assert.equal(value.n, 1);\n }\n {\n const {type, index, value, params} = await observer.next();\n assert.equal(mapper.length, 2);\n assert.equal(type, \"update\");\n assert.equal(index, 0);\n assert.equal(value.n, 49);\n assert.equal(params, \"lucky seven\");\n }\n {\n const {type, index, value} = await observer.next();\n assert.equal(mapper.length, 1);\n assert.equal(type, \"remove\");\n assert.equal(index, 0);\n assert.equal(value.n, 49);\n }\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableList, IListObserver} from \"./BaseObservableList\";\n\nexport class ConcatList extends BaseObservableList implements IListObserver {\n protected _sourceLists: BaseObservableList[];\n protected _sourceUnsubscribes: (() => void)[] | null = null;\n\n constructor(...sourceLists: BaseObservableList[]) {\n super();\n this._sourceLists = sourceLists;\n }\n\n _offsetForSource(sourceList: BaseObservableList): number {\n const listIdx = this._sourceLists.indexOf(sourceList);\n let offset = 0;\n for (let i = 0; i < listIdx; ++i) {\n offset += this._sourceLists[i].length;\n }\n return offset;\n }\n\n onSubscribeFirst(): void {\n this._sourceUnsubscribes = this._sourceLists.map(sourceList => sourceList.subscribe(this));\n }\n\n onUnsubscribeLast(): void {\n for (const sourceUnsubscribe of this._sourceUnsubscribes!) {\n sourceUnsubscribe();\n }\n }\n\n onReset(): void {\n // TODO: not ideal if other source lists are large\n // but working impl for now\n // reset, and \n this.emitReset();\n let idx = 0;\n for(const item of this) {\n this.emitAdd(idx, item);\n idx += 1;\n }\n }\n\n onAdd(index: number, value: T, sourceList: BaseObservableList): void {\n this.emitAdd(this._offsetForSource(sourceList) + index, value);\n }\n\n onUpdate(index: number, value: T, params: any, sourceList: BaseObservableList): void {\n // if an update is emitted while calling source.subscribe() from onSubscribeFirst, ignore it\n // as we are not supposed to call `length` on any uninitialized list\n if (!this._sourceUnsubscribes) {\n return;\n }\n this.emitUpdate(this._offsetForSource(sourceList) + index, value, params);\n }\n\n onRemove(index: number, value: T, sourceList: BaseObservableList): void {\n this.emitRemove(this._offsetForSource(sourceList) + index, value);\n }\n\n onMove(fromIdx: number, toIdx: number, value: T, sourceList: BaseObservableList): void {\n const offset = this._offsetForSource(sourceList);\n this.emitMove(offset + fromIdx, offset + toIdx, value);\n }\n\n get length(): number {\n let len = 0;\n for (let i = 0; i < this._sourceLists.length; ++i) {\n len += this._sourceLists[i].length;\n }\n return len;\n }\n\n [Symbol.iterator]() {\n let sourceListIdx = 0;\n let it = this._sourceLists[0][Symbol.iterator]();\n return {\n next: () => {\n let result = it.next();\n while (result.done) {\n sourceListIdx += 1;\n if (sourceListIdx >= this._sourceLists.length) {\n return result; //done\n }\n it = this._sourceLists[sourceListIdx][Symbol.iterator]();\n result = it.next();\n }\n return result;\n }\n }\n }\n}\n\nimport {ObservableArray} from \"./ObservableArray\";\nimport {defaultObserverWith} from \"./BaseObservableList\";\nexport async function tests() {\n return {\n test_length(assert) {\n const all = new ConcatList(\n new ObservableArray([1, 2, 3]),\n new ObservableArray([11, 12, 13])\n );\n assert.equal(all.length, 6);\n },\n test_iterator(assert) {\n const all = new ConcatList(\n new ObservableArray([1, 2, 3]),\n new ObservableArray([11, 12, 13])\n );\n const it = all[Symbol.iterator]();\n assert.equal(it.next().value, 1);\n assert.equal(it.next().value, 2);\n assert.equal(it.next().value, 3);\n assert.equal(it.next().value, 11);\n assert.equal(it.next().value, 12);\n assert.equal(it.next().value, 13);\n assert(it.next().done);\n },\n test_add(assert) {\n const list1 = new ObservableArray([1, 2, 3]);\n const list2 = new ObservableArray([11, 12, 13]);\n const all = new ConcatList(list1, list2);\n let fired = false;\n all.subscribe(defaultObserverWith({\n onAdd(index, value) {\n fired = true;\n assert.equal(index, 4);\n assert.equal(value, 11.5);\n }\n }));\n list2.insert(1, 11.5);\n assert(fired);\n },\n test_update(assert) {\n const list1 = new ObservableArray([1, 2, 3]);\n const list2 = new ObservableArray([11, 12, 13]);\n const all = new ConcatList(list1, list2);\n let fired = false;\n all.subscribe(defaultObserverWith({\n onUpdate(index, value) {\n fired = true;\n assert.equal(index, 4);\n assert.equal(value, 10);\n }\n }));\n list2.emitUpdate(1, 10);\n assert(fired);\n },\n };\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SortedMapList} from \"./list/SortedMapList.js\";\nimport {FilteredMap} from \"./map/FilteredMap.js\";\nimport {MappedMap} from \"./map/MappedMap.js\";\nimport {JoinedMap} from \"./map/JoinedMap.js\";\nimport {BaseObservableMap} from \"./map/BaseObservableMap\";\n// re-export \"root\" (of chain) collections\nexport { ObservableArray } from \"./list/ObservableArray\";\nexport { SortedArray } from \"./list/SortedArray\";\nexport { MappedList } from \"./list/MappedList\";\nexport { AsyncMappedList } from \"./list/AsyncMappedList\";\nexport { ConcatList } from \"./list/ConcatList\";\nexport { ObservableMap } from \"./map/ObservableMap\";\n\n// avoid circular dependency between these classes\n// and BaseObservableMap (as they extend it)\nObject.assign(BaseObservableMap.prototype, {\n sortValues(comparator) {\n return new SortedMapList(this, comparator);\n },\n\n mapValues(mapper, updater) {\n return new MappedMap(this, mapper, updater);\n },\n\n filterValues(filter) {\n return new FilteredMap(this, filter);\n },\n\n join(...otherMaps) {\n return new JoinedMap([this].concat(otherMaps));\n }\n});\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport interface IDisposable {\n dispose(): void;\n}\n\nexport type Disposable = IDisposable | (() => void);\n\nfunction disposeValue(value: Disposable): void {\n if (typeof value === \"function\") {\n value();\n } else {\n value.dispose();\n }\n}\n\nfunction isDisposable(value: Disposable): boolean {\n return value && (typeof value === \"function\" || typeof value.dispose === \"function\");\n}\n\nexport class Disposables {\n private _disposables?: Disposable[] = [];\n\n track(disposable: D): D {\n if (!isDisposable(disposable)) {\n throw new Error(\"Not a disposable\");\n }\n if (this.isDisposed) {\n console.warn(\"Disposables already disposed, disposing new value\");\n disposeValue(disposable);\n return disposable;\n }\n this._disposables!.push(disposable);\n return disposable;\n }\n\n untrack(disposable: Disposable): undefined {\n if (this.isDisposed) {\n console.warn(\"Disposables already disposed, cannot untrack\");\n return undefined;\n }\n const idx = this._disposables!.indexOf(disposable);\n if (idx >= 0) {\n this._disposables!.splice(idx, 1);\n }\n return undefined;\n }\n\n dispose(): void {\n if (this._disposables) {\n for (const d of this._disposables) {\n disposeValue(d);\n }\n this._disposables = undefined;\n }\n }\n\n get isDisposed(): boolean {\n return this._disposables === undefined;\n }\n\n disposeTracked(value: Disposable | undefined): undefined {\n if (value === undefined || value === null || this.isDisposed) {\n return undefined;\n }\n const idx = this._disposables!.indexOf(value);\n if (idx !== -1) {\n const [foundValue] = this._disposables!.splice(idx, 1);\n disposeValue(foundValue);\n } else {\n console.warn(\"disposable not found, did it leak?\", value);\n }\n return undefined;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {directionalConcat, directionalAppend} from \"./common.js\";\nimport {Direction} from \"../Direction\";\nimport {EventEntry} from \"../entries/EventEntry.js\";\nimport {FragmentBoundaryEntry} from \"../entries/FragmentBoundaryEntry.js\";\n\nclass ReaderRequest {\n constructor(fn, log) {\n this.decryptRequest = null;\n this._promise = fn(this, log);\n }\n\n complete() {\n return this._promise;\n }\n\n dispose() {\n if (this.decryptRequest) {\n this.decryptRequest.dispose();\n this.decryptRequest = null;\n }\n }\n}\n\n/**\n * Raw because it doesn't do decryption and in the future it should not read relations either.\n * It is just about reading entries and following fragment links\n */\nasync function readRawTimelineEntriesWithTxn(roomId, eventKey, direction, amount, fragmentIdComparer, txn) {\n let entries = [];\n const timelineStore = txn.timelineEvents;\n const fragmentStore = txn.timelineFragments;\n\n while (entries.length < amount && eventKey) {\n let eventsWithinFragment;\n if (direction.isForward) {\n // TODO: should we pass amount - entries.length here?\n eventsWithinFragment = await timelineStore.eventsAfter(roomId, eventKey, amount);\n } else {\n eventsWithinFragment = await timelineStore.eventsBefore(roomId, eventKey, amount);\n }\n let eventEntries = eventsWithinFragment.map(e => new EventEntry(e, fragmentIdComparer));\n entries = directionalConcat(entries, eventEntries, direction);\n // prepend or append eventsWithinFragment to entries, and wrap them in EventEntry\n\n if (entries.length < amount) {\n const fragment = await fragmentStore.get(roomId, eventKey.fragmentId);\n // TODO: why does the first fragment not need to be added? (the next *is* added below)\n // it looks like this would be fine when loading in the sync island\n // (as the live fragment should be added already) but not for permalinks when we support them\n // \n // fragmentIdComparer.addFragment(fragment);\n let fragmentEntry = new FragmentBoundaryEntry(fragment, direction.isBackward, fragmentIdComparer);\n // append or prepend fragmentEntry, reuse func from GapWriter?\n directionalAppend(entries, fragmentEntry, direction);\n // only continue loading if the fragment boundary can't be backfilled\n if (!fragmentEntry.token && fragmentEntry.hasLinkedFragment) {\n const nextFragment = await fragmentStore.get(roomId, fragmentEntry.linkedFragmentId);\n fragmentIdComparer.add(nextFragment);\n const nextFragmentEntry = new FragmentBoundaryEntry(nextFragment, direction.isForward, fragmentIdComparer);\n directionalAppend(entries, nextFragmentEntry, direction);\n eventKey = nextFragmentEntry.asEventKey();\n } else {\n eventKey = null;\n }\n }\n }\n return entries;\n}\n\nexport class TimelineReader {\n constructor({roomId, storage, fragmentIdComparer}) {\n this._roomId = roomId;\n this._storage = storage;\n this._fragmentIdComparer = fragmentIdComparer;\n this._decryptEntries = null;\n }\n\n enableEncryption(decryptEntries) {\n this._decryptEntries = decryptEntries;\n }\n\n get readTxnStores() {\n const stores = [\n this._storage.storeNames.timelineEvents,\n this._storage.storeNames.timelineFragments,\n ];\n if (this._decryptEntries) {\n stores.push(this._storage.storeNames.inboundGroupSessions);\n }\n return stores;\n }\n\n readFrom(eventKey, direction, amount, log) {\n return new ReaderRequest(async (r, log) => {\n const txn = await this._storage.readTxn(this.readTxnStores);\n return await this._readFrom(eventKey, direction, amount, r, txn, log);\n }, log);\n }\n\n readFromEnd(amount, existingTxn = null, log) {\n return new ReaderRequest(async (r, log) => {\n const txn = existingTxn || await this._storage.readTxn(this.readTxnStores);\n const liveFragment = await txn.timelineFragments.liveFragment(this._roomId);\n let entries;\n // room hasn't been synced yet\n if (!liveFragment) {\n entries = [];\n } else {\n this._fragmentIdComparer.add(liveFragment);\n const liveFragmentEntry = FragmentBoundaryEntry.end(liveFragment, this._fragmentIdComparer);\n const eventKey = liveFragmentEntry.asEventKey();\n entries = await this._readFrom(eventKey, Direction.Backward, amount, r, txn, log);\n entries.unshift(liveFragmentEntry);\n }\n return entries;\n }, log);\n }\n\n async readById(id, log) {\n let stores = [this._storage.storeNames.timelineEvents];\n if (this._decryptEntries) {\n stores.push(this._storage.storeNames.inboundGroupSessions);\n }\n const txn = await this._storage.readTxn(stores); // todo: can we just use this.readTxnStores here? probably\n const storageEntry = await txn.timelineEvents.getByEventId(this._roomId, id);\n if (storageEntry) {\n const entry = new EventEntry(storageEntry, this._fragmentIdComparer);\n if (this._decryptEntries) {\n const request = this._decryptEntries([entry], txn, log);\n await request.complete();\n }\n return entry;\n }\n }\n\n async _readFrom(eventKey, direction, amount, r, txn, log) {\n const entries = await readRawTimelineEntriesWithTxn(this._roomId, eventKey, direction, amount, this._fragmentIdComparer, txn);\n if (this._decryptEntries) {\n r.decryptRequest = this._decryptEntries(entries, txn, log);\n try {\n await r.decryptRequest.complete();\n } finally {\n r.decryptRequest = null;\n }\n }\n return entries;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventEntry} from \"./EventEntry.js\";\n\n// EventEntry but without the two properties that are populated via SyncWriter\n// Useful if you want to create an EventEntry that is ephemeral\n\nexport class NonPersistedEventEntry extends EventEntry {\n get fragmentId() {\n throw new Error(\"Cannot access fragmentId for non-persisted EventEntry\");\n }\n\n get entryIndex() {\n throw new Error(\"Cannot access entryIndex for non-persisted EventEntry\");\n }\n\n get isNonPersisted() {\n return true;\n }\n\n // overridden here because we reuse addLocalRelation() for updating this entry\n // we don't want the RedactedTile created using this entry to ever show \"is being redacted\"\n get isRedacting() {\n return false;\n }\n\n get isRedacted() {\n return super.isRedacting;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class User {\n constructor(userId) {\n this._userId = userId;\n }\n\n get id() {\n return this._userId;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SortedArray, AsyncMappedList, ConcatList, ObservableArray} from \"../../../observable/index.js\";\nimport {Disposables} from \"../../../utils/Disposables\";\nimport {Direction} from \"./Direction\";\nimport {TimelineReader} from \"./persistence/TimelineReader.js\";\nimport {PendingEventEntry} from \"./entries/PendingEventEntry.js\";\nimport {RoomMember} from \"../members/RoomMember.js\";\nimport {getRelation, ANNOTATION_RELATION_TYPE} from \"./relations.js\";\nimport {REDACTION_TYPE} from \"../common\";\nimport {NonPersistedEventEntry} from \"./entries/NonPersistedEventEntry.js\";\nimport {EVENT_TYPE as MEMBER_EVENT_TYPE} from \"../members/RoomMember.js\";\n\nexport class Timeline {\n constructor({roomId, storage, closeCallback, fragmentIdComparer, pendingEvents, clock, powerLevelsObservable, hsApi}) {\n this._roomId = roomId;\n this._storage = storage;\n this._closeCallback = closeCallback;\n this._fragmentIdComparer = fragmentIdComparer;\n this._disposables = new Disposables();\n this._pendingEvents = pendingEvents;\n this._clock = clock;\n // constructing this early avoid some problem while sync and openTimeline race\n this._remoteEntries = new SortedArray((a, b) => a.compare(b));\n this._ownMember = null;\n this._timelineReader = new TimelineReader({\n roomId: this._roomId,\n storage: this._storage,\n fragmentIdComparer: this._fragmentIdComparer\n });\n this._readerRequest = null;\n this._allEntries = null;\n /** Stores event entries that we had to fetch from hs/storage for reply previews (because they were not in timeline) */ \n this._contextEntriesNotInTimeline = new Map();\n /** Only used to decrypt non-persisted context entries fetched from the homeserver */\n this._decryptEntries = null;\n this._hsApi = hsApi;\n this.initializePowerLevels(powerLevelsObservable);\n }\n\n initializePowerLevels(observable) {\n if (observable) {\n this._powerLevels = observable.get();\n this._disposables.track(observable.subscribe(powerLevels => this._powerLevels = powerLevels));\n }\n }\n\n /** @package */\n async load(user, membership, log) {\n const txn = await this._storage.readTxn(this._timelineReader.readTxnStores.concat(\n this._storage.storeNames.roomMembers,\n this._storage.storeNames.roomState\n ));\n const memberData = await txn.roomMembers.get(this._roomId, user.id);\n if (memberData) {\n this._ownMember = new RoomMember(memberData);\n } else {\n // this should never happen, as our own join into the room would have\n // made us receive our own member event, but just to be on the safe side and not crash,\n // fall back to bare user id\n this._ownMember = RoomMember.fromUserId(this._roomId, user.id, membership);\n }\n // it should be fine to not update the local entries,\n // as they should only populate once the view subscribes to it\n // if they are populated already, the sender profile would be empty\n\n // choose good amount here between showing messages initially and\n // not spending too much time decrypting messages before showing the timeline.\n // more messages should be loaded automatically until the viewport is full by the view if needed.\n const readerRequest = this._disposables.track(this._timelineReader.readFromEnd(20, txn, log));\n try {\n const entries = await readerRequest.complete();\n this._loadContextEntriesWhereNeeded(entries);\n this._setupEntries(entries);\n } finally {\n this._disposables.disposeTracked(readerRequest);\n }\n // txn should be assumed to have finished here, as decryption will close it.\n }\n\n _setupEntries(timelineEntries) {\n this._remoteEntries.setManySorted(timelineEntries);\n if (this._pendingEvents) {\n this._localEntries = new AsyncMappedList(this._pendingEvents,\n pe => this._mapPendingEventToEntry(pe),\n (pee, params) => {\n // is sending but redacted, who do we detect that here to remove the relation?\n pee.notifyUpdate(params);\n },\n pee => this._applyAndEmitLocalRelationChange(pee, target => target.removeLocalRelation(pee))\n );\n } else {\n this._localEntries = new ObservableArray();\n }\n this._allEntries = new ConcatList(this._remoteEntries, this._localEntries);\n }\n\n async _mapPendingEventToEntry(pe) {\n // we load the redaction target for pending events,\n // so if we are redacting a relation, we can pass the redaction\n // to the relation target and the removal of the relation can\n // be taken into account for local echo.\n let redactingEntry;\n if (pe.eventType === REDACTION_TYPE) {\n redactingEntry = await this._getOrLoadEntry(pe.relatedTxnId, pe.relatedEventId);\n }\n const pee = new PendingEventEntry({\n pendingEvent: pe, member: this._ownMember,\n clock: this._clock, redactingEntry\n });\n this._loadContextEntriesWhereNeeded([pee]);\n this._applyAndEmitLocalRelationChange(pee, target => target.addLocalRelation(pee));\n return pee;\n }\n\n _applyAndEmitLocalRelationChange(pee, updater) {\n // this is the contract of findAndUpdate, used in _findAndUpdateRelatedEntry\n const updateOrFalse = e => {\n const params = updater(e);\n return params ? params : false;\n };\n this._findAndUpdateEntryById(pee.pendingEvent.relatedTxnId, pee.relatedEventId, updateOrFalse);\n // also look for a relation target to update with this redaction\n if (pee.redactingEntry) {\n // redactingEntry might be a PendingEventEntry or an EventEntry, so don't assume pendingEvent\n const relatedTxnId = pee.redactingEntry.pendingEvent?.relatedTxnId;\n this._findAndUpdateEntryById(relatedTxnId, pee.redactingEntry.relatedEventId, updateOrFalse);\n pee.redactingEntry.contextForEntries?.forEach(e => this._emitUpdateForEntry(e, \"contextEntry\"));\n }\n }\n\n _findAndUpdateEntryById(txnId, eventId, updateOrFalse) {\n let found = false;\n // first, look in local entries based on txn id\n if (txnId) {\n found = this._localEntries.findAndUpdate(\n e => e.id === txnId,\n updateOrFalse,\n );\n }\n // if not found here, look in remote entries based on event id\n if (!found && eventId) {\n this._remoteEntries.findAndUpdate(\n e => e.id === eventId,\n updateOrFalse\n );\n }\n }\n\n async getOwnAnnotationEntry(targetId, key) {\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.timelineEvents,\n this._storage.storeNames.timelineRelations,\n ]);\n const relations = await txn.timelineRelations.getForTargetAndType(this._roomId, targetId, ANNOTATION_RELATION_TYPE);\n for (const relation of relations) {\n const annotation = await txn.timelineEvents.getByEventId(this._roomId, relation.sourceEventId);\n if (annotation && annotation.event.sender === this._ownMember.userId && getRelation(annotation.event).key === key) {\n const eventEntry = new EventEntry(annotation, this._fragmentIdComparer);\n this._addLocalRelationsToNewRemoteEntries([eventEntry]);\n return eventEntry;\n }\n }\n return null;\n }\n\n /** @package */\n updateOwnMember(member) {\n this._ownMember = member;\n }\n\n _addLocalRelationsToNewRemoteEntries(entries) {\n // because it is not safe to iterate a derived observable collection\n // before it has any subscriptions, we bail out if this isn't\n // the case yet. This can happen when sync adds or replaces entries\n // before load has finished and the view has subscribed to the timeline.\n // \n // Once the subscription is setup, MappedList will set up the local\n // relations as needed with _applyAndEmitLocalRelationChange,\n // so we're not missing anything by bailing out.\n //\n // _localEntries can also not yet exist\n if (!this._localEntries?.hasSubscriptions) {\n return;\n }\n // find any local relations to this new remote event\n for (const pee of this._localEntries) {\n // this will work because we set relatedEventId when removing remote echos\n if (pee.relatedEventId) {\n const relationTarget = entries.find(e => e.id === pee.relatedEventId);\n // no need to emit here as this entry is about to be added\n relationTarget?.addLocalRelation(pee);\n }\n if (pee.redactingEntry) {\n const eventId = pee.redactingEntry.relatedEventId;\n const relationTarget = entries.find(e => e.id === eventId);\n relationTarget?.addLocalRelation(pee);\n }\n }\n }\n\n // used in replaceEntries\n static _entryUpdater(existingEntry, entry) {\n // ensure other entries for which this existingEntry is a context point to the new entry instead of existingEntry\n existingEntry.contextForEntries?.forEach(event => event.setContextEntry(entry));\n entry.updateFrom(existingEntry);\n return entry;\n }\n\n /** @package */\n replaceEntries(entries) {\n this._addLocalRelationsToNewRemoteEntries(entries);\n for (const entry of entries) {\n try {\n this._remoteEntries.getAndUpdate(entry, Timeline._entryUpdater);\n const oldEntry = this._contextEntriesNotInTimeline.get(entry.id)\n if (oldEntry) {\n Timeline._entryUpdater(oldEntry, entry);\n this._contextEntriesNotInTimeline.set(entry.id, entry);\n }\n // Since this entry changed, all dependent entries should be updated\n entry.contextForEntries?.forEach(e => this._emitUpdateForEntry(e, \"contextEntry\"));\n } catch (err) {\n if (err.name === \"CompareError\") {\n // see FragmentIdComparer, if the replacing entry is on a fragment\n // that is currently not loaded into the FragmentIdComparer, it will\n // throw a CompareError, and it means that the event is not loaded \n // in the timeline (like when receiving a relation for an event\n // that is not loaded in memory) so we can just drop this error as\n // replacing an event that is not already loaded is a no-op.\n continue;\n } else {\n // don't swallow other errors\n throw err;\n }\n }\n }\n }\n\n /** @package */\n addEntries(newEntries) {\n this._addLocalRelationsToNewRemoteEntries(newEntries);\n this._updateEntriesFetchedFromHomeserver(newEntries);\n this._moveEntryToRemoteEntries(newEntries);\n this._loadContextEntriesWhereNeeded(newEntries);\n this._remoteEntries.setManySorted(newEntries);\n }\n\n /**\n * Update entries based on newly received events.\n * This is specific to events that are not in the timeline but had to be fetched from the homeserver\n * because they are context-events for other events in the timeline (i.e fetched from hs so that we\n * can render things like reply previews)\n */\n _updateEntriesFetchedFromHomeserver(entries) {\n /**\n * Updates for entries in timeline is handled by remoteEntries observable collection\n * Updates for entries not in timeline but fetched from storage is handled in this.replaceEntries()\n * This code is specific to entries fetched from HomeServer i.e NonPersistedEventEntry\n */\n for (const entry of entries) {\n const relatedEntry = this._contextEntriesNotInTimeline.get(entry.relatedEventId);\n if (relatedEntry?.isNonPersisted && relatedEntry?.addLocalRelation(entry)) {\n // update other entries for which this entry is a context entry\n relatedEntry.contextForEntries?.forEach(e => this._emitUpdateForEntry(e, \"contextEntry\"));\n }\n }\n }\n\n /**\n * If an event we had to fetch from hs/storage is now in the timeline (for eg, due to gap fill),\n * remove the event from _contextEntriesNotInTimeline since it is now in remoteEntries\n */\n _moveEntryToRemoteEntries(entries) {\n for (const entry of entries) {\n const fetchedEntry = this._contextEntriesNotInTimeline.get(entry.id);\n if (fetchedEntry) {\n fetchedEntry.contextForEntries.forEach(e => {\n e.setContextEntry(entry);\n this._emitUpdateForEntry(e, \"contextEntry\");\n });\n this._contextEntriesNotInTimeline.delete(entry.id);\n }\n }\n }\n\n _emitUpdateForEntry(entry, param) {\n const txnId = entry.isPending ? entry.id : null;\n const eventId = entry.isPending ? null : entry.id;\n this._findAndUpdateEntryById(txnId, eventId, () => param);\n }\n\n /**\n * For each entry in entries, this method associates a context-entry (if needed) to it.\n * The context-entry is fetched using the following strategies (in the same order as given):\n * - timeline\n * - storage\n * - homeserver\n * @param {EventEntry[]} entries \n */\n async _loadContextEntriesWhereNeeded(entries) {\n for (const entry of entries) {\n if (!entry.contextEventId) {\n continue;\n }\n const id = entry.contextEventId;\n // before looking into remoteEntries, check the entries\n // that about to be added first\n let contextEvent = entries.find(e => e.id === id);\n if (!contextEvent) {\n contextEvent = this._findLoadedEventById(id);\n }\n if (contextEvent) {\n entry.setContextEntry(contextEvent);\n // we don't emit an update here, as the add or update\n // that the callee will emit hasn't been emitted yet.\n } else {\n // we don't await here, which is not ideal,\n // but one of our callers, addEntries, is not async\n // so there is not much point.\n // Also, we want to run the entry fetching in parallel.\n this._loadContextEntryNotInTimeline(entry);\n }\n }\n }\n\n async _loadContextEntryNotInTimeline(entry) {\n const id = entry.contextEventId;\n let contextEvent = await this._getEventFromStorage(id);\n if (!contextEvent) {\n contextEvent = await this._getEventFromHomeserver(id);\n }\n if (contextEvent) {\n // this entry was created from storage/hs, so it's not tracked by remoteEntries\n // we track them here so that we can update reply previews later\n this._contextEntriesNotInTimeline.set(id, contextEvent);\n entry.setContextEntry(contextEvent);\n // here, we awaited something, so from now on we do have to emit\n // an update if we set the context entry.\n this._emitUpdateForEntry(entry, \"contextEntry\");\n }\n }\n\n /**\n * Fetches an entry with the given event-id from localEntries, remoteEntries or contextEntriesNotInTimeline.\n * @param {string} eventId event-id of the entry\n * @returns entry if found, undefined otherwise\n */\n _findLoadedEventById(eventId) {\n return this.getByEventId(eventId) ?? this._contextEntriesNotInTimeline.get(eventId);\n }\n\n async _getEventFromStorage(eventId) {\n const entry = await this._timelineReader.readById(eventId);\n return entry;\n }\n\n async _getEventFromHomeserver(eventId) {\n const response = await this._hsApi.context(this._roomId, eventId, 0).response();\n const sender = response.event.sender;\n const member = response.state.find(e => e.type === MEMBER_EVENT_TYPE && e.user_id === sender);\n const entry = {\n event: response.event,\n displayName: member.content.displayname,\n avatarUrl: member.content.avatar_url\n };\n const eventEntry = new NonPersistedEventEntry(entry, this._fragmentIdComparer);\n if (this._decryptEntries) {\n const request = this._decryptEntries([eventEntry]);\n await request.complete();\n }\n return eventEntry;\n }\n\n // tries to prepend `amount` entries to the `entries` list.\n /**\n * [loadAtTop description]\n * @param {[type]} amount [description]\n * @return {boolean} true if the top of the timeline has been reached\n * \n */\n async loadAtTop(amount) {\n if (this._disposables.isDisposed) {\n return true;\n }\n const firstEventEntry = this._remoteEntries.array.find(e => !!e.eventType);\n if (!firstEventEntry) {\n return true;\n }\n const readerRequest = this._disposables.track(this._timelineReader.readFrom(\n firstEventEntry.asEventKey(),\n Direction.Backward,\n amount\n ));\n try {\n const entries = await readerRequest.complete();\n this.addEntries(entries);\n return entries.length < amount;\n } finally {\n this._disposables.disposeTracked(readerRequest);\n }\n }\n\n async _getOrLoadEntry(txnId, eventId) {\n if (txnId) {\n // also look for redacting relation in pending events, in case the target is already being sent\n for (const p of this._localEntries) {\n if (p.id === txnId) {\n return p;\n }\n }\n }\n if (eventId) {\n return this.getByEventId(eventId) ?? await this._getEventFromStorage(eventId);\n }\n return null;\n }\n\n getByEventId(eventId) {\n for (let i = 0; i < this._remoteEntries.length; i += 1) {\n const entry = this._remoteEntries.get(i);\n if (entry.id === eventId) {\n return entry;\n }\n }\n return null;\n }\n\n /** @public */\n get entries() {\n return this._allEntries;\n }\n\n /**\n * @internal\n * @return {Array} remote event entries, should not be modified\n */\n get remoteEntries() {\n return this._remoteEntries.array;\n }\n\n /** @public */\n dispose() {\n if (this._closeCallback) {\n this._disposables.dispose();\n this._closeCallback();\n this._closeCallback = null;\n }\n }\n\n /** @internal */\n enableEncryption(decryptEntries) {\n this._decryptEntries = decryptEntries;\n this._timelineReader.enableEncryption(decryptEntries);\n }\n\n get powerLevels() {\n return this._powerLevels;\n }\n\n get me() {\n return this._ownMember;\n }\n}\n\nimport {FragmentIdComparer} from \"./FragmentIdComparer.js\";\nimport {poll} from \"../../../mocks/poll.js\";\nimport {Clock as MockClock} from \"../../../mocks/Clock.js\";\nimport {createMockStorage} from \"../../../mocks/Storage\";\nimport {ListObserver} from \"../../../mocks/ListObserver.js\";\nimport {createEvent, withTextBody, withContent, withSender, withRedacts, withReply} from \"../../../mocks/event.js\";\nimport {NullLogItem} from \"../../../logging/NullLogger\";\nimport {EventEntry} from \"./entries/EventEntry.js\";\nimport {User} from \"../../User.js\";\nimport {PendingEvent} from \"../sending/PendingEvent.js\";\nimport {createAnnotation} from \"./relations.js\";\nimport {redactEvent} from \"./common.js\";\n\nexport function tests() {\n const fragmentIdComparer = new FragmentIdComparer([]);\n const roomId = \"$abc\";\n const alice = \"@alice:hs.tld\";\n const bob = \"@bob:hs.tld\";\n const hsApi = {\n context() {\n const result = {\n event: withTextBody(\"foo\", createEvent(\"m.room.message\", \"event_id_1\", alice)),\n state: [{\n type: MEMBER_EVENT_TYPE,\n user_id: alice,\n content: {\n displayName: \"\",\n avatarUrl: \"\"\n }\n }]\n };\n return { response: () => result };\n }\n };\n\n function getIndexFromIterable(it, n) {\n let i = 0;\n for (const item of it) {\n if (i === n) {\n return item;\n }\n i += 1;\n }\n throw new Error(\"not enough items in iterable\");\n }\n\n return {\n \"adding or replacing entries before subscribing to entries does not lose local relations\": async assert => {\n const pendingEvents = new ObservableArray();\n const timeline = new Timeline({roomId, storage: await createMockStorage(),\n closeCallback: () => {}, fragmentIdComparer, pendingEvents, clock: new MockClock()});\n // 1. load timeline\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n // 2. test replaceEntries and addEntries don't fail\n const event1 = withTextBody(\"hi!\", withSender(bob, createEvent(\"m.room.message\", \"!abc\")));\n const entry1 = new EventEntry({event: event1, fragmentId: 1, eventIndex: 1}, fragmentIdComparer);\n timeline.replaceEntries([entry1]);\n const event2 = withTextBody(\"hi bob!\", withSender(alice, createEvent(\"m.room.message\", \"!def\")));\n const entry2 = new EventEntry({event: event2, fragmentId: 1, eventIndex: 2}, fragmentIdComparer);\n timeline.addEntries([entry2]);\n // 3. add local relation (redaction)\n pendingEvents.append(new PendingEvent({data: {\n roomId,\n queueIndex: 1,\n eventType: \"m.room.redaction\",\n txnId: \"t123\",\n content: {},\n relatedEventId: event2.event_id\n }}));\n // 4. subscribe (it's now safe to iterate timeline.entries) \n timeline.entries.subscribe(new ListObserver());\n // 5. check the local relation got correctly aggregated\n const locallyRedacted = await poll(() => Array.from(timeline.entries)[0].isRedacting);\n assert.equal(locallyRedacted, true);\n },\n \"add and remove local reaction, and cancel again\": async assert => {\n // 1. setup timeline with message\n const pendingEvents = new ObservableArray();\n const timeline = new Timeline({roomId, storage: await createMockStorage(),\n closeCallback: () => {}, fragmentIdComparer, pendingEvents, clock: new MockClock()});\n await timeline.load(new User(bob), \"join\", new NullLogItem());\n timeline.entries.subscribe(new ListObserver());\n const event = withTextBody(\"hi bob!\", withSender(alice, createEvent(\"m.room.message\", \"!abc\")));\n timeline.addEntries([new EventEntry({event, fragmentId: 1, eventIndex: 2}, fragmentIdComparer)]);\n let entry = getIndexFromIterable(timeline.entries, 0);\n // 2. add local reaction\n pendingEvents.append(new PendingEvent({data: {\n roomId,\n queueIndex: 1,\n eventType: \"m.reaction\",\n txnId: \"t123\",\n content: entry.annotate(\"👋\"),\n relatedEventId: entry.id\n }}));\n await poll(() => timeline.entries.length === 2);\n assert.equal(entry.pendingAnnotations.get(\"👋\").count, 1);\n const reactionEntry = getIndexFromIterable(timeline.entries, 1);\n // 3. add redaction to timeline\n pendingEvents.append(new PendingEvent({data: {\n roomId,\n queueIndex: 2,\n eventType: \"m.room.redaction\",\n txnId: \"t456\",\n content: {},\n relatedTxnId: reactionEntry.id\n }}));\n // TODO: await nextUpdate here with ListObserver, to ensure entry emits an update when pendingAnnotations changes\n await poll(() => timeline.entries.length === 3);\n assert.equal(entry.pendingAnnotations.get(\"👋\").count, 0);\n // 4. cancel redaction\n pendingEvents.remove(1);\n await poll(() => timeline.entries.length === 2);\n assert.equal(entry.pendingAnnotations.get(\"👋\").count, 1);\n // 5. cancel reaction\n pendingEvents.remove(0);\n await poll(() => timeline.entries.length === 1);\n assert(!entry.pendingAnnotations);\n },\n \"getOwnAnnotationEntry\": async assert => {\n const messageId = \"!abc\";\n const reactionId = \"!def\";\n // 1. put event and reaction into storage\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({\n event: withContent(createAnnotation(messageId, \"👋\"), createEvent(\"m.reaction\", reactionId, bob)),\n fragmentId: 1, eventIndex: 1, roomId\n }, new NullLogItem());\n txn.timelineRelations.add(roomId, messageId, ANNOTATION_RELATION_TYPE, reactionId);\n await txn.complete();\n // 2. setup the timeline\n const timeline = new Timeline({roomId, storage, closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock()});\n await timeline.load(new User(bob), \"join\", new NullLogItem());\n // 3. get the own annotation out\n const reactionEntry = await timeline.getOwnAnnotationEntry(messageId, \"👋\");\n assert.equal(reactionEntry.id, reactionId);\n assert.equal(reactionEntry.relation.key, \"👋\");\n },\n \"remote reaction\": async assert => {\n const messageEntry = new EventEntry({\n event: withTextBody(\"hi bob!\", createEvent(\"m.room.message\", \"!abc\", alice)),\n fragmentId: 1, eventIndex: 2, roomId,\n annotations: { // aggregated like RelationWriter would\n \"👋\": {count: 1, me: true, firstTimestamp: 0}\n },\n }, fragmentIdComparer);\n // 2. setup timeline\n const pendingEvents = new ObservableArray();\n const timeline = new Timeline({roomId, storage: await createMockStorage(),\n closeCallback: () => {}, fragmentIdComparer, pendingEvents, clock: new MockClock()});\n await timeline.load(new User(bob), \"join\", new NullLogItem());\n timeline.entries.subscribe(new ListObserver());\n // 3. add message to timeline\n timeline.addEntries([messageEntry]);\n const entry = getIndexFromIterable(timeline.entries, 0);\n assert.equal(entry, messageEntry);\n assert.equal(entry.annotations[\"👋\"].count, 1);\n },\n \"remove remote reaction\": async assert => {\n // 1. setup timeline\n const pendingEvents = new ObservableArray();\n const timeline = new Timeline({roomId, storage: await createMockStorage(),\n closeCallback: () => { }, fragmentIdComparer, pendingEvents, clock: new MockClock()});\n await timeline.load(new User(bob), \"join\", new NullLogItem());\n timeline.entries.subscribe(new ListObserver());\n // 2. add message and reaction to timeline\n const messageEntry = new EventEntry({\n event: withTextBody(\"hi bob!\", createEvent(\"m.room.message\", \"!abc\", alice)),\n fragmentId: 1, eventIndex: 2, roomId,\n }, fragmentIdComparer);\n const reactionEntry = new EventEntry({\n event: withContent(createAnnotation(messageEntry.id, \"👋\"), createEvent(\"m.reaction\", \"!def\", bob)),\n fragmentId: 1, eventIndex: 3, roomId\n }, fragmentIdComparer);\n timeline.addEntries([messageEntry, reactionEntry]);\n // 3. redact reaction\n pendingEvents.append(new PendingEvent({data: {\n roomId,\n queueIndex: 1,\n eventType: \"m.room.redaction\",\n txnId: \"t123\",\n content: {},\n relatedEventId: reactionEntry.id\n }}));\n await poll(() => timeline.entries.length >= 3);\n assert.equal(messageEntry.pendingAnnotations.get(\"👋\").count, -1);\n },\n \"local reaction gets applied after remote echo is added to timeline\": async assert => {\n const messageEntry = new EventEntry({event: withTextBody(\"hi bob!\", withSender(alice, createEvent(\"m.room.message\", \"!abc\"))),\n fragmentId: 1, eventIndex: 2}, fragmentIdComparer);\n // 1. setup timeline\n const pendingEvents = new ObservableArray();\n const timeline = new Timeline({roomId, storage: await createMockStorage(),\n closeCallback: () => {}, fragmentIdComparer, pendingEvents, clock: new MockClock()});\n await timeline.load(new User(bob), \"join\", new NullLogItem());\n timeline.entries.subscribe(new ListObserver());\n // 2. add local reaction\n pendingEvents.append(new PendingEvent({data: {\n roomId,\n queueIndex: 1,\n eventType: \"m.reaction\",\n txnId: \"t123\",\n content: messageEntry.annotate(\"👋\"),\n relatedEventId: messageEntry.id\n }}));\n await poll(() => timeline.entries.length === 1);\n // 3. add remote reaction target\n timeline.addEntries([messageEntry]);\n await poll(() => timeline.entries.length === 2);\n const entry = getIndexFromIterable(timeline.entries, 0);\n assert.equal(entry, messageEntry);\n assert.equal(entry.pendingAnnotations.get(\"👋\").count, 1);\n },\n \"local reaction removal gets applied after remote echo is added to timeline with reaction not loaded\": async assert => {\n const messageId = \"!abc\";\n const reactionId = \"!def\";\n // 1. put reaction in storage\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({\n event: withContent(createAnnotation(messageId, \"👋\"), createEvent(\"m.reaction\", reactionId, bob)),\n fragmentId: 1, eventIndex: 3, roomId\n }, new NullLogItem());\n await txn.complete();\n // 2. setup timeline\n const pendingEvents = new ObservableArray();\n const timeline = new Timeline({roomId, storage, closeCallback: () => {},\n fragmentIdComparer, pendingEvents, clock: new MockClock()});\n await timeline.load(new User(bob), \"join\", new NullLogItem());\n timeline.entries.subscribe(new ListObserver());\n // 3. add local redaction for reaction\n pendingEvents.append(new PendingEvent({data: {\n roomId,\n queueIndex: 1,\n eventType: \"m.room.redaction\",\n txnId: \"t123\",\n content: {},\n relatedEventId: reactionId\n }}));\n await poll(() => timeline.entries.length === 1);\n // 4. add reaction target\n timeline.addEntries([new EventEntry({\n event: withTextBody(\"hi bob!\", createEvent(\"m.room.message\", messageId, alice)),\n fragmentId: 1, eventIndex: 2}, fragmentIdComparer)\n ]);\n await poll(() => timeline.entries.length === 2);\n // 5. check that redaction was linked to reaction target\n const entry = getIndexFromIterable(timeline.entries, 0);\n assert.equal(entry.pendingAnnotations.get(\"👋\").count, -1);\n },\n \"decrypted entry preserves content when receiving other update without decryption\": async assert => {\n // 1. create encrypted and decrypted entry\n const encryptedEntry = new EventEntry({\n event: withContent({ciphertext: \"abc\"}, createEvent(\"m.room.encrypted\", \"!abc\", alice)),\n fragmentId: 1, eventIndex: 1, roomId\n }, fragmentIdComparer);\n const decryptedEntry = encryptedEntry.clone();\n decryptedEntry.setDecryptionResult({\n event: withTextBody(\"hi bob!\", createEvent(\"m.room.message\", encryptedEntry.id, encryptedEntry.sender))\n });\n // 2. setup the timeline\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock()});\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.addEntries([decryptedEntry]);\n const observer = new ListObserver();\n timeline.entries.subscribe(observer);\n // 3. replace the entry with one that is not decrypted\n // (as would happen when receiving a reaction,\n // as it does not rerun the decryption)\n // and check that the decrypted content is preserved\n timeline.replaceEntries([encryptedEntry]);\n const {value, type} = await observer.next();\n assert.equal(type, \"update\");\n assert.equal(value.eventType, \"m.room.message\");\n assert.equal(value.content.body, \"hi bob!\");\n },\n\n \"context entry is fetched from remoteEntries\": async assert => {\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock()});\n const entryA = new EventEntry({ event: withTextBody(\"foo\", createEvent(\"m.room.message\", \"event_id_1\", alice)) });\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.entries.subscribe({\n onAdd() {},\n });\n timeline.addEntries([entryA, entryB]);\n assert.deepEqual(entryB.contextEntry, entryA);\n },\n\n \"context entry is fetched from storage\": async assert => {\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([storage.storeNames.timelineEvents, storage.storeNames.timelineRelations]);\n txn.timelineEvents.tryInsert({ event: withTextBody(\"foo\", createEvent(\"m.room.message\", \"event_id_1\", alice)), fragmentId: 1, eventIndex: 1, roomId });\n await txn.complete();\n const timeline = new Timeline({roomId, storage, closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock()});\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.entries.subscribe({ onAdd: () => null, onUpdate: () => null });\n timeline.addEntries([entryB]);\n await poll(() => entryB.contextEntry);\n assert.strictEqual(entryB.contextEntry.id, \"event_id_1\");\n },\n\n \"context entry is fetched from hs\": async assert => {\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock(), hsApi});\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.entries.subscribe({ onAdd: () => null, onUpdate: () => null });\n timeline.addEntries([entryB]);\n await poll(() => entryB.contextEntry);\n assert.strictEqual(entryB.contextEntry.id, \"event_id_1\");\n },\n\n \"context entry has a list of entries to which it forms the context\": async assert => {\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock()});\n const entryA = new EventEntry({ event: withTextBody(\"foo\", createEvent(\"m.room.message\", \"event_id_1\", alice)), eventIndex: 1 });\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2 });\n const entryC = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_3\", bob)), eventIndex: 3 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.entries.subscribe({ onAdd: () => null, onUpdate: () => null });\n timeline.addEntries([entryA, entryB, entryC]);\n await poll(() => entryA.contextForEntries.length === 2);\n assert.deepEqual(entryA.contextForEntries, [entryB, entryC]);\n },\n\n \"context entry in contextEntryNotInTimeline gets updated based on incoming redaction\": async assert => {\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock(), hsApi});\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.entries.subscribe({ onAdd: () => null, onUpdate: () => null });\n timeline.addEntries([entryB]);\n await poll(() => entryB.contextEntry);\n const redactingEntry = new EventEntry({ event: withRedacts(\"event_id_1\", \"foo\", createEvent(\"m.room.redaction\", \"event_id_3\", alice)), eventIndex: 3 });\n timeline.addEntries([redactingEntry]);\n assert.strictEqual(entryB.contextEntry.isRedacted, true);\n },\n\n \"redaction of context entry triggers updates in other entries\": async assert => {\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock(), hsApi});\n const entryA = new EventEntry({ event: withTextBody(\"foo\", createEvent(\"m.room.message\", \"event_id_1\", alice)), eventIndex: 1, fragmentId: 1 });\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2, fragmentId: 1 });\n const entryC = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_3\", bob)), eventIndex: 3, fragmentId: 1 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n const bin = [];\n timeline.entries.subscribe({\n onUpdate: (index, e) => {\n bin.push(e.id);\n },\n onAdd: () => null,\n });\n timeline.addEntries([entryA, entryB, entryC]);\n const eventAClone = JSON.parse(JSON.stringify(entryA.event));\n redactEvent(withRedacts(\"event_id_1\", \"foo\", createEvent(\"m.room.redaction\", \"event_id_4\", alice)), eventAClone);\n const redactedEntry = new EventEntry({ event: eventAClone, eventIndex: 1, fragmentId: 1 });\n timeline.replaceEntries([redactedEntry]);\n assert.strictEqual(bin.includes(\"event_id_2\"), true);\n assert.strictEqual(bin.includes(\"event_id_3\"), true);\n },\n\n \"context entries fetched from storage/hs are moved to remoteEntries\": async assert => {\n const timeline = new Timeline({roomId, storage: await createMockStorage(), closeCallback: () => {},\n fragmentIdComparer, pendingEvents: new ObservableArray(), clock: new MockClock(), hsApi});\n const entryA = new EventEntry({ event: withTextBody(\"foo\", createEvent(\"m.room.message\", \"event_id_1\", alice)), eventIndex: 1 });\n const entryB = new EventEntry({ event: withReply(\"event_id_1\", createEvent(\"m.room.message\", \"event_id_2\", bob)), eventIndex: 2 });\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n timeline.entries.subscribe({ onAdd: () => null, onUpdate: () => null });\n timeline.addEntries([entryB]);\n await poll(() => entryB.contextEntry);\n assert.strictEqual(timeline._contextEntriesNotInTimeline.has(entryA.id), true);\n timeline.addEntries([entryA]);\n assert.strictEqual(timeline._contextEntriesNotInTimeline.has(entryA.id), false);\n const movedEntry = timeline.remoteEntries[0];\n assert.deepEqual(movedEntry, entryA);\n assert.deepEqual(movedEntry.contextForEntries[0], entryB);\n assert.deepEqual(entryB.contextEntry, movedEntry);\n }\n };\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {RoomMember} from \"./RoomMember.js\";\n\nasync function loadMembers({roomId, storage, txn}) {\n if (!txn) {\n txn = await storage.readTxn([\n storage.storeNames.roomMembers,\n ]);\n }\n const memberDatas = await txn.roomMembers.getAll(roomId);\n return memberDatas.map(d => new RoomMember(d));\n}\n\nasync function fetchMembers({summary, syncToken, roomId, hsApi, storage, setChangedMembersMap}, log) {\n // if any members are changed by sync while we're fetching members,\n // they will end up here, so we check not to override them\n const changedMembersDuringSync = new Map();\n setChangedMembersMap(changedMembersDuringSync);\n \n const memberResponse = await hsApi.members(roomId, {at: syncToken}, {log}).response();\n\n const txn = await storage.readWriteTxn([\n storage.storeNames.roomSummary,\n storage.storeNames.roomMembers,\n ]);\n\n let summaryChanges;\n let members;\n \n try {\n summaryChanges = summary.writeHasFetchedMembers(true, txn);\n const {roomMembers} = txn;\n const memberEvents = memberResponse.chunk;\n if (!Array.isArray(memberEvents)) {\n throw new Error(\"malformed\");\n }\n log.set(\"members\", memberEvents.length);\n members = await Promise.all(memberEvents.map(async memberEvent => {\n const userId = memberEvent?.state_key;\n if (!userId) {\n throw new Error(\"malformed\");\n }\n // this member was changed during a sync that happened while calling /members\n // and thus is more recent, so don't overwrite\n const changedMember = changedMembersDuringSync.get(userId);\n if (changedMember) {\n return changedMember;\n } else {\n const member = RoomMember.fromMemberEvent(roomId, memberEvent);\n if (member) {\n roomMembers.set(member.serialize());\n }\n return member;\n }\n }));\n } catch (err) {\n // abort txn on any error\n txn.abort();\n throw err;\n } finally {\n // important this gets cleared\n // or otherwise Room remains in \"fetching-members\" mode\n setChangedMembersMap(null);\n }\n await txn.complete();\n summary.applyChanges(summaryChanges);\n return members;\n}\n\nexport async function fetchOrLoadMembers(options, logger) {\n const {summary} = options;\n if (!summary.data.hasFetchedMembers) {\n // we only want to log if we fetch members, so start or continue the optional log operation here\n return logger.wrapOrRun(options.log, \"fetchMembers\", log => fetchMembers(options, log));\n } else {\n return loadMembers(options);\n }\n}\n\nexport async function fetchOrLoadMember(options, logger) {\n const member = await loadMember(options);\n const {summary} = options;\n if (!summary.data.hasFetchedMembers && !member) {\n // We haven't fetched the memberlist yet; so ping the hs to see if this member does exist\n return logger.wrapOrRun(options.log, \"fetchMember\", log => fetchMember(options, log));\n }\n return member;\n}\n\nasync function loadMember({roomId, userId, storage}) {\n const txn = await storage.readTxn([storage.storeNames.roomMembers,]);\n const member = await txn.roomMembers.get(roomId, userId);\n return member? new RoomMember(member) : null;\n}\n\nasync function fetchMember({roomId, userId, hsApi, storage}, log) {\n let memberData;\n try {\n memberData = await hsApi.state(roomId, \"m.room.member\", userId, { log }).response();\n }\n catch (error) {\n if (error.name === \"HomeServerError\" && error.errcode === \"M_NOT_FOUND\") {\n return null;\n }\n throw error;\n }\n const member = new RoomMember({\n roomId,\n userId,\n membership: memberData.membership,\n avatarUrl: memberData.avatar_url,\n displayName: memberData.displayname,\n });\n const txn = await storage.readWriteTxn([storage.storeNames.roomMembers]);\n try {\n txn.roomMembers.set(member.serialize());\n }\n catch(e) {\n txn.abort();\n throw e;\n }\n await txn.complete();\n return member;\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class RetainedValue {\n private readonly _freeCallback: () => void;\n private _retentionCount: number = 1;\n\n constructor(freeCallback: () => void) {\n this._freeCallback = freeCallback;\n }\n\n retain(): void {\n this._retentionCount += 1;\n }\n\n release(): void {\n this._retentionCount -= 1;\n if (this._retentionCount === 0) {\n this._freeCallback();\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ObservableMap} from \"../../../observable/map/ObservableMap\";\nimport {RetainedValue} from \"../../../utils/RetainedValue\";\n\nexport class MemberList extends RetainedValue {\n constructor({members, closeCallback}) {\n super(closeCallback);\n this._members = new ObservableMap();\n for (const member of members) {\n this._members.add(member.userId, member);\n }\n }\n\n afterSync(memberChanges) {\n for (const [userId, memberChange] of memberChanges.entries()) {\n this._members.set(userId, memberChange.member);\n }\n }\n\n get members() {\n return this._members;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {RoomMember} from \"./RoomMember.js\";\n\nexport function calculateRoomName(sortedMembers, summaryData, log) {\n const countWithoutMe = summaryData.joinCount + summaryData.inviteCount - 1;\n if (sortedMembers.length >= countWithoutMe) {\n if (sortedMembers.length > 1) {\n const lastMember = sortedMembers[sortedMembers.length - 1];\n const firstMembers = sortedMembers.slice(0, sortedMembers.length - 1);\n return firstMembers.map(m => m.name).join(\", \") + \" and \" + lastMember.name;\n } else {\n const otherMember = sortedMembers[0];\n if (otherMember) {\n return otherMember.name;\n } else {\n log.log({l: \"could get get other member name\", length: sortedMembers.length, otherMember: !!otherMember, otherMemberMembership: otherMember?.membership});\n return \"Unknown DM Name\";\n }\n }\n } else if (sortedMembers.length < countWithoutMe) {\n return sortedMembers.map(m => m.name).join(\", \") + ` and ${countWithoutMe} others`;\n } else {\n // Empty Room\n return null;\n }\n}\n\nexport class Heroes {\n constructor(roomId) {\n this._roomId = roomId;\n this._members = new Map();\n }\n\n /**\n * @param {string[]} newHeroes array of user ids\n * @param {Map} memberChanges map of changed memberships\n * @param {Transaction} txn\n * @return {Promise}\n */\n async calculateChanges(newHeroes, memberChanges, txn) {\n const updatedHeroMembers = new Map();\n const removedUserIds = [];\n // remove non-present members\n for (const existingUserId of this._members.keys()) {\n if (newHeroes.indexOf(existingUserId) === -1) {\n removedUserIds.push(existingUserId);\n }\n }\n // update heroes with synced member changes\n for (const [userId, memberChange] of memberChanges.entries()) {\n if (this._members.has(userId) || newHeroes.indexOf(userId) !== -1) {\n updatedHeroMembers.set(userId, memberChange.member);\n }\n }\n // load member for new heroes from storage\n for (const userId of newHeroes) {\n if (!this._members.has(userId) && !updatedHeroMembers.has(userId)) {\n const memberData = await txn.roomMembers.get(this._roomId, userId);\n if (memberData) {\n const member = new RoomMember(memberData);\n updatedHeroMembers.set(member.userId, member);\n }\n }\n }\n return {updatedHeroMembers: updatedHeroMembers.values(), removedUserIds};\n }\n\n applyChanges({updatedHeroMembers, removedUserIds}, summaryData, log) {\n for (const userId of removedUserIds) {\n this._members.delete(userId);\n }\n for (const member of updatedHeroMembers) {\n this._members.set(member.userId, member);\n }\n const sortedMembers = Array.from(this._members.values()).sort((a, b) => a.name.localeCompare(b.name));\n this._roomName = calculateRoomName(sortedMembers, summaryData, log);\n }\n\n get roomName() {\n return this._roomName;\n }\n\n get roomAvatarUrl() {\n if (this._members.size === 1) {\n for (const member of this._members.values()) {\n return member.avatarUrl;\n }\n }\n return null;\n }\n\n /**\n * In DM rooms, we want the room's color to be\n * the same as the other user's color. Thus, if the room\n * only has one hero, we use their ID, instead\n * of the room's, to get the avatar color.\n *\n * @returns {?string} the ID of the single hero.\n */\n get roomAvatarColorId() {\n if (this._members.size === 1) {\n for (const member of this._members.keys()) {\n return member\n }\n }\n return null;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableValue} from \"../../observable/ObservableValue\";\n\nexport class ObservedEventMap {\n constructor(notifyEmpty) {\n this._map = new Map();\n this._notifyEmpty = notifyEmpty;\n }\n\n observe(eventId, eventEntry = null) {\n let observable = this._map.get(eventId);\n if (!observable) {\n observable = new ObservedEvent(this, eventEntry, eventId);\n this._map.set(eventId, observable);\n }\n return observable;\n }\n\n updateEvents(eventEntries) {\n for (let i = 0; i < eventEntries.length; i += 1) {\n const entry = eventEntries[i];\n const observable = this._map.get(entry.id);\n observable?.update(entry);\n }\n }\n\n _remove(id) {\n this._map.delete(id);\n if (this._map.size === 0) {\n this._notifyEmpty();\n }\n }\n}\n\nclass ObservedEvent extends BaseObservableValue {\n constructor(eventMap, entry, id) {\n super();\n this._eventMap = eventMap;\n this._entry = entry;\n this._id = id;\n // remove subscription in microtask after creating it\n // otherwise ObservedEvents would easily never get\n // removed if you never subscribe\n Promise.resolve().then(() => {\n if (!this.hasSubscriptions) {\n this._eventMap._remove(this._id);\n this._eventMap = null;\n }\n });\n }\n\n subscribe(handler) {\n if (!this._eventMap) {\n throw new Error(\"ObservedEvent expired, subscribe right after calling room.observeEvent()\");\n }\n return super.subscribe(handler);\n }\n\n onUnsubscribeLast() {\n this._eventMap._remove(this._id);\n this._eventMap = null;\n super.onUnsubscribeLast();\n }\n\n update(entry) {\n // entries are mostly updated in-place,\n // apart from when they are created,\n // but doesn't hurt to reassign\n this._entry = entry;\n this.emit(this._entry);\n }\n\n get() {\n return this._entry;\n }\n}\n","// these are helper functions if you can't assume you always have a log item (e.g. some code paths call with one set, others don't)\n// if you know you always have a log item, better to use the methods on the log item than these utility functions.\n\nimport {Instance as NullLoggerInstance} from \"./NullLogger\";\nimport type {FilterCreator, ILogItem, LabelOrValues, LogCallback} from \"./types\";\nimport {LogLevel} from \"./LogFilter\";\n\nexport function wrapOrRunNullLogger(logItem: ILogItem | undefined, labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): T | Promise {\n if (logItem) {\n return logItem.wrap(labelOrValues, callback, logLevel, filterCreator);\n } else {\n return NullLoggerInstance.run(null, callback);\n }\n}\n\nexport function ensureLogItem(logItem: ILogItem): ILogItem {\n return logItem || NullLoggerInstance.item;\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport const EVENT_TYPE = \"m.room.power_levels\";\n\nexport class PowerLevels {\n constructor({powerLevelEvent, createEvent, ownUserId, membership}) {\n this._plEvent = powerLevelEvent;\n this._createEvent = createEvent;\n this._ownUserId = ownUserId;\n this._membership = membership;\n }\n\n canRedactFromSender(userId) {\n if (userId === this._ownUserId && this._membership === \"join\") {\n return true;\n } else {\n return this.canRedact;\n }\n }\n\n canSendType(eventType) {\n return this._myLevel >= this._getEventTypeLevel(eventType);\n }\n\n get canRedact() {\n return this._myLevel >= this._getActionLevel(\"redact\");\n }\n\n get _myLevel() {\n if (this._membership !== \"join\") {\n return Number.MIN_SAFE_INTEGER;\n }\n return this.getUserLevel(this._ownUserId);\n }\n\n getUserLevel(userId) {\n if (this._plEvent) {\n let userLevel = this._plEvent.content?.users?.[userId];\n if (typeof userLevel !== \"number\") {\n userLevel = this._plEvent.content?.users_default;\n }\n if (typeof userLevel === \"number\") {\n return userLevel;\n }\n } else if (this._createEvent) {\n if (userId === this._createEvent.content?.creator) {\n return 100;\n }\n }\n return 0;\n }\n\n /** @param {string} action either \"invite\", \"kick\", \"ban\" or \"redact\". */\n _getActionLevel(action) {\n const level = this._plEvent?.content[action];\n if (typeof level === \"number\") {\n return level;\n } else {\n return 50;\n }\n }\n\n _getEventTypeLevel(eventType) {\n const level = this._plEvent?.content.events?.[eventType];\n if (typeof level === \"number\") {\n return level;\n } else {\n const level = this._plEvent?.content.events_default;\n if (typeof level === \"number\") {\n return level;\n } else {\n return 0;\n }\n }\n }\n}\n\nexport function tests() {\n const alice = \"@alice:hs.tld\";\n const bob = \"@bob:hs.tld\";\n const charly = \"@charly:hs.tld\";\n const createEvent = {content: {creator: alice}};\n const redactPowerLevelEvent = {content: {\n redact: 50,\n users: {\n [alice]: 50\n },\n users_default: 0\n }};\n const eventsPowerLevelEvent = {content: {\n events_default: 5,\n events: {\n \"m.room.message\": 45,\n \"m.room.topic\": 50,\n },\n users: {\n [alice]: 50,\n [bob]: 10\n },\n users_default: 0\n }};\n\n return {\n \"redact somebody else event with power level event\": assert => {\n const pl1 = new PowerLevels({powerLevelEvent: redactPowerLevelEvent, ownUserId: alice, membership: \"join\"});\n assert.equal(pl1.canRedact, true);\n const pl2 = new PowerLevels({powerLevelEvent: redactPowerLevelEvent, ownUserId: bob, membership: \"join\"});\n assert.equal(pl2.canRedact, false);\n },\n \"redact somebody else event with create event\": assert => {\n const pl1 = new PowerLevels({createEvent, ownUserId: alice, membership: \"join\"});\n assert.equal(pl1.canRedact, true);\n const pl2 = new PowerLevels({createEvent, ownUserId: bob, membership: \"join\"});\n assert.equal(pl2.canRedact, false);\n },\n \"redact own event\": assert => {\n const pl = new PowerLevels({ownUserId: alice, membership: \"join\"});\n assert.equal(pl.canRedactFromSender(alice), true);\n assert.equal(pl.canRedactFromSender(bob), false);\n },\n \"can send event without power levels\": assert => {\n const pl = new PowerLevels({createEvent, ownUserId: charly, membership: \"join\"});\n assert.equal(pl.canSendType(\"m.room.message\"), true);\n },\n \"can't send any event below events_default\": assert => {\n const pl = new PowerLevels({powerLevelEvent: eventsPowerLevelEvent, ownUserId: charly, membership: \"join\"});\n assert.equal(pl.canSendType(\"m.foo\"), false);\n },\n \"can't send event below events[type]\": assert => {\n const pl = new PowerLevels({powerLevelEvent: eventsPowerLevelEvent, ownUserId: bob, membership: \"join\"});\n assert.equal(pl.canSendType(\"m.foo\"), true);\n assert.equal(pl.canSendType(\"m.room.message\"), false);\n },\n \"can send event above or at events[type]\": assert => {\n const pl = new PowerLevels({powerLevelEvent: eventsPowerLevelEvent, ownUserId: alice, membership: \"join\"});\n assert.equal(pl.canSendType(\"m.room.message\"), true);\n assert.equal(pl.canSendType(\"m.room.topic\"), true);\n },\n \"can't redact or send in non-joined room'\": assert => {\n const pl = new PowerLevels({createEvent, ownUserId: alice, membership: \"leave\"});\n assert.equal(pl.canRedact, false);\n assert.equal(pl.canRedactFromSender(alice), false);\n assert.equal(pl.canSendType(\"m.room.message\"), false);\n },\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventEmitter} from \"../../utils/EventEmitter\";\nimport {RoomSummary} from \"./RoomSummary.js\";\nimport {GapWriter} from \"./timeline/persistence/GapWriter.js\";\nimport {RelationWriter} from \"./timeline/persistence/RelationWriter.js\";\nimport {Timeline} from \"./timeline/Timeline.js\";\nimport {FragmentIdComparer} from \"./timeline/FragmentIdComparer.js\";\nimport {WrappedError} from \"../error.js\"\nimport {fetchOrLoadMembers, fetchOrLoadMember} from \"./members/load.js\";\nimport {MemberList} from \"./members/MemberList.js\";\nimport {Heroes} from \"./members/Heroes.js\";\nimport {EventEntry} from \"./timeline/entries/EventEntry.js\";\nimport {ObservedEventMap} from \"./ObservedEventMap.js\";\nimport {DecryptionSource} from \"../e2ee/common.js\";\nimport {ensureLogItem} from \"../../logging/utils\";\nimport {PowerLevels} from \"./PowerLevels.js\";\nimport {RetainedObservableValue} from \"../../observable/ObservableValue\";\nimport {TimelineReader} from \"./timeline/persistence/TimelineReader\";\n\nconst EVENT_ENCRYPTED_TYPE = \"m.room.encrypted\";\n\nexport class BaseRoom extends EventEmitter {\n constructor({roomId, storage, hsApi, mediaRepository, emitCollectionChange, user, createRoomEncryption, getSyncToken, platform}) {\n super();\n this._roomId = roomId;\n this._storage = storage;\n this._hsApi = hsApi;\n this._mediaRepository = mediaRepository;\n this._summary = new RoomSummary(roomId);\n this._fragmentIdComparer = new FragmentIdComparer([]);\n this._emitCollectionChange = emitCollectionChange;\n this._timeline = null;\n this._user = user;\n this._changedMembersDuringSync = null;\n this._memberList = null;\n this._createRoomEncryption = createRoomEncryption;\n this._roomEncryption = null;\n this._getSyncToken = getSyncToken;\n this._platform = platform;\n this._observedEvents = null;\n this._powerLevels = null;\n this._powerLevelLoading = null;\n this._observedMembers = null;\n }\n\n async _eventIdsToEntries(eventIds, txn) {\n const retryEntries = [];\n await Promise.all(eventIds.map(async eventId => {\n const storageEntry = await txn.timelineEvents.getByEventId(this._roomId, eventId);\n if (storageEntry) {\n retryEntries.push(new EventEntry(storageEntry, this._fragmentIdComparer));\n }\n }));\n return retryEntries;\n }\n\n _getAdditionalTimelineRetryEntries(otherRetryEntries, roomKeys) {\n let retryTimelineEntries = this._roomEncryption.filterUndecryptedEventEntriesForKeys(this._timeline.remoteEntries, roomKeys);\n // filter out any entries already in retryEntries so we don't decrypt them twice\n const existingIds = otherRetryEntries.reduce((ids, e) => {ids.add(e.id); return ids;}, new Set());\n retryTimelineEntries = retryTimelineEntries.filter(e => !existingIds.has(e.id));\n return retryTimelineEntries;\n }\n\n /**\n * Used for retrying decryption from other sources than sync, like key backup.\n * @internal\n * @param {RoomKey} roomKey\n * @param {Array} eventIds any event ids that should be retried. There might be more in the timeline though for this key.\n * @return {Promise}\n */\n async notifyRoomKey(roomKey, eventIds, log) {\n if (!this._roomEncryption) {\n return;\n }\n const txn = await this._storage.readTxn([\n this._storage.storeNames.timelineEvents,\n this._storage.storeNames.inboundGroupSessions,\n ]);\n let retryEntries = await this._eventIdsToEntries(eventIds, txn);\n if (this._timeline) {\n const retryTimelineEntries = this._getAdditionalTimelineRetryEntries(retryEntries, [roomKey]);\n retryEntries = retryEntries.concat(retryTimelineEntries);\n }\n if (retryEntries.length) {\n const decryptRequest = this._decryptEntries(DecryptionSource.Retry, retryEntries, txn, log);\n // this will close txn while awaiting decryption\n await decryptRequest.complete();\n\n this._timeline?.replaceEntries(retryEntries);\n // we would ideally write the room summary in the same txn as the groupSessionDecryptions in the\n // _decryptEntries entries and could even know which events have been decrypted for the first\n // time from DecryptionChanges.write and only pass those to the summary. As timeline changes\n // are not essential to the room summary, it's fine to write this in a separate txn for now.\n const changes = this._summary.data.applyTimelineEntries(retryEntries, false, false);\n if (await this._summary.writeAndApplyData(changes, this._storage)) {\n this._emitUpdate();\n }\n }\n }\n\n _setEncryption(roomEncryption) {\n if (roomEncryption && !this._roomEncryption) {\n this._roomEncryption = roomEncryption;\n if (this._timeline) {\n this._timeline.enableEncryption(this._decryptEntries.bind(this, DecryptionSource.Timeline));\n }\n return true;\n }\n return false;\n }\n\n /**\n * Used for decrypting when loading/filling the timeline, and retrying decryption,\n * not during sync, where it is split up during the multiple phases.\n */\n _decryptEntries(source, entries, inboundSessionTxn, log = null) {\n const request = new DecryptionRequest(async (r, log) => {\n if (!inboundSessionTxn) {\n inboundSessionTxn = await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);\n }\n if (r.cancelled) return;\n const events = entries.filter(entry => {\n return entry.eventType === EVENT_ENCRYPTED_TYPE;\n }).map(entry => entry.event);\n r.preparation = await this._roomEncryption.prepareDecryptAll(events, null, source, inboundSessionTxn);\n if (r.cancelled) return;\n const changes = await r.preparation.decrypt();\n r.preparation = null;\n if (r.cancelled) return;\n const stores = [this._storage.storeNames.groupSessionDecryptions];\n const isTimelineOpen = this._isTimelineOpen;\n if (isTimelineOpen) {\n // read to fetch devices if timeline is open\n stores.push(this._storage.storeNames.deviceIdentities);\n }\n const writeTxn = await this._storage.readWriteTxn(stores);\n let decryption;\n try {\n decryption = await changes.write(writeTxn, log);\n if (isTimelineOpen) {\n await decryption.verifySenders(writeTxn);\n }\n } catch (err) {\n writeTxn.abort();\n throw err;\n }\n await writeTxn.complete();\n // TODO: log decryption errors here\n decryption.applyToEntries(entries);\n if (this._observedEvents) {\n this._observedEvents.updateEvents(entries);\n }\n }, ensureLogItem(log));\n return request;\n }\n\n // TODO: move this to Room\n async _getSyncRetryDecryptEntries(newKeys, roomEncryption, txn) {\n const entriesPerKey = await Promise.all(newKeys.map(async key => {\n const retryEventIds = await roomEncryption.getEventIdsForMissingKey(key, txn);\n if (retryEventIds) {\n return this._eventIdsToEntries(retryEventIds, txn);\n }\n }));\n let retryEntries = entriesPerKey.reduce((allEntries, entries) => entries ? allEntries.concat(entries) : allEntries, []);\n // If we have the timeline open, see if there are more entries for the new keys\n // as we only store missing session information for synced events, not backfilled.\n // We want to decrypt all events we can though if the user is looking\n // at them when the timeline is open\n if (this._timeline) {\n const retryTimelineEntries = this._getAdditionalTimelineRetryEntries(retryEntries, newKeys);\n // make copies so we don't modify the original entry in writeSync, before the afterSync stage\n const retryTimelineEntriesCopies = retryTimelineEntries.map(e => e.clone());\n // add to other retry entries\n retryEntries = retryEntries.concat(retryTimelineEntriesCopies);\n }\n return retryEntries;\n }\n\n /** @package */\n async load(summary, txn, log) {\n log.set(\"id\", this.id);\n try {\n // if called from sync, there is no summary yet\n if (summary) {\n this._summary.load(summary);\n }\n if (this._summary.data.encryption) {\n const roomEncryption = this._createRoomEncryption(this, this._summary.data.encryption);\n this._setEncryption(roomEncryption);\n }\n // need to load members for name?\n if (this._summary.data.needsHeroes) {\n this._heroes = new Heroes(this._roomId);\n const changes = await this._heroes.calculateChanges(this._summary.data.heroes, [], txn);\n this._heroes.applyChanges(changes, this._summary.data, log);\n }\n } catch (err) {\n throw new WrappedError(`Could not load room ${this._roomId}`, err);\n }\n }\n\n async observeMember(userId) {\n if (!this._observedMembers) {\n this._observedMembers = new Map();\n }\n const mapMember = this._observedMembers.get(userId);\n if (mapMember) {\n // Hit, we're already observing this member\n return mapMember;\n }\n // Miss, load from storage/hs and set in map\n const member = await fetchOrLoadMember({\n summary: this._summary,\n roomId: this._roomId,\n userId,\n storage: this._storage,\n hsApi: this._hsApi\n }, this._platform.logger);\n if (!member) {\n return null;\n }\n const observableMember = new RetainedObservableValue(member, () => this._observedMembers.delete(userId));\n this._observedMembers.set(userId, observableMember);\n return observableMember;\n }\n\n\n /** @public */\n async loadMemberList(txn = undefined, log = null) {\n if (this._memberList) {\n // TODO: also await fetchOrLoadMembers promise here\n this._memberList.retain();\n return this._memberList;\n } else {\n const members = await fetchOrLoadMembers({\n summary: this._summary,\n roomId: this._roomId,\n hsApi: this._hsApi,\n storage: this._storage,\n // pass in a transaction if we know we won't need to fetch (which would abort the transaction)\n // and we want to make this operation part of the larger transaction\n txn,\n syncToken: this._getSyncToken(),\n // to handle race between /members and /sync\n setChangedMembersMap: map => this._changedMembersDuringSync = map,\n log,\n }, this._platform.logger);\n this._memberList = new MemberList({\n members,\n closeCallback: () => { this._memberList = null; }\n });\n return this._memberList;\n }\n } \n\n /** @public */\n fillGap(fragmentEntry, amount, log = null) {\n // TODO move some/all of this out of BaseRoom\n return this._platform.logger.wrapOrRun(log, \"fillGap\", async log => {\n log.set(\"id\", this.id);\n log.set(\"fragment\", fragmentEntry.fragmentId);\n log.set(\"dir\", fragmentEntry.direction.asApiString());\n if (fragmentEntry.edgeReached) {\n log.set(\"edgeReached\", true);\n return;\n }\n const response = await this._hsApi.messages(this._roomId, {\n from: fragmentEntry.token,\n dir: fragmentEntry.direction.asApiString(),\n limit: amount,\n filter: {\n lazy_load_members: true,\n include_redundant_members: true,\n }\n }, {log}).response();\n\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.pendingEvents,\n this._storage.storeNames.timelineEvents,\n this._storage.storeNames.timelineRelations,\n this._storage.storeNames.timelineFragments,\n ]);\n let extraGapFillChanges;\n let gapResult;\n try {\n // detect remote echos of pending messages in the gap\n extraGapFillChanges = await this._writeGapFill(response.chunk, txn, log);\n // write new events into gap\n const relationWriter = new RelationWriter({\n roomId: this._roomId,\n fragmentIdComparer: this._fragmentIdComparer,\n ownUserId: this._user.id,\n });\n const gapWriter = new GapWriter({\n roomId: this._roomId,\n storage: this._storage,\n fragmentIdComparer: this._fragmentIdComparer,\n relationWriter\n });\n gapResult = await gapWriter.writeFragmentFill(fragmentEntry, response, txn, log);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n if (this._roomEncryption) {\n const decryptRequest = this._decryptEntries(DecryptionSource.Timeline, gapResult.entries, null, log);\n await decryptRequest.complete();\n }\n // once txn is committed, update in-memory state & emit events\n for (const fragment of gapResult.fragments) {\n this._fragmentIdComparer.add(fragment);\n }\n if (extraGapFillChanges) {\n this._applyGapFill(extraGapFillChanges);\n }\n if (this._timeline) {\n // these should not be added if not already there\n this._timeline.replaceEntries(gapResult.updatedEntries);\n this._timeline.addEntries(gapResult.entries);\n }\n });\n }\n\n /**\n allow sub classes to integrate in the gap fill lifecycle.\n JoinedRoom uses this update remote echos.\n */\n // eslint-disable-next-line no-unused-vars\n async _writeGapFill(chunk, txn, log) {}\n _applyGapFill() {}\n\n /** @public */\n get name() {\n if (this._heroes) {\n return this._heroes.roomName;\n }\n const summaryData = this._summary.data;\n if (summaryData.name) {\n return summaryData.name;\n }\n if (summaryData.canonicalAlias) {\n return summaryData.canonicalAlias;\n }\n return null;\n }\n\n /** @public */\n get id() {\n return this._roomId;\n }\n\n get avatarUrl() {\n if (this._summary.data.avatarUrl) {\n return this._summary.data.avatarUrl;\n } else if (this._heroes) {\n return this._heroes.roomAvatarUrl;\n }\n return null;\n }\n\n /**\n * Retrieve the identifier that should be used to color\n * this room's avatar. By default this is the room's\n * ID, but DM rooms should be the same color as their\n * user's avatar.\n */\n get avatarColorId() {\n return this._roomId;\n }\n\n get lastMessageTimestamp() {\n return this._summary.data.lastMessageTimestamp;\n }\n\n get isLowPriority() {\n const tags = this._summary.data.tags;\n return !!(tags && tags['m.lowpriority']);\n }\n\n get isEncrypted() {\n return !!this._summary.data.encryption;\n }\n\n get isJoined() {\n return this.membership === \"join\";\n }\n\n get isLeft() {\n return this.membership === \"leave\";\n }\n\n get canonicalAlias() {\n return this._summary.data.canonicalAlias;\n }\n\n get joinedMemberCount() {\n return this._summary.data.joinCount;\n }\n\n get mediaRepository() {\n return this._mediaRepository;\n }\n\n get membership() {\n return this._summary.data.membership;\n }\n\n isDirectMessageForUserId(userId) {\n if (this._summary.data.dmUserId === userId) {\n return true;\n } else {\n // fall back to considering any room a DM containing heroes (e.g. no name) and 2 members,\n // on of which the userId we're looking for.\n // We need this because we're not yet processing m.direct account data correctly.\n const {heroes, joinCount, inviteCount} = this._summary.data;\n if (heroes && heroes.includes(userId) && (joinCount + inviteCount) === 2) {\n return true;\n }\n }\n return false;\n }\n\n async _loadPowerLevels() {\n const txn = await this._storage.readTxn([this._storage.storeNames.roomState]);\n const powerLevelsState = await txn.roomState.get(this._roomId, \"m.room.power_levels\", \"\");\n if (powerLevelsState) {\n return new PowerLevels({\n powerLevelEvent: powerLevelsState.event,\n ownUserId: this._user.id,\n membership: this.membership\n });\n }\n const createState = await txn.roomState.get(this._roomId, \"m.room.create\", \"\");\n if (createState) {\n return new PowerLevels({\n createEvent: createState.event,\n ownUserId: this._user.id,\n membership: this.membership\n });\n } else {\n const membership = this.membership;\n return new PowerLevels({ownUserId: this._user.id, membership});\n }\n }\n\n /**\n * Get the PowerLevels of the room.\n * Always subscribe to the value returned by this method.\n * @returns {RetainedObservableValue} PowerLevels of the room\n */\n async observePowerLevels() {\n if (this._powerLevelLoading) { await this._powerLevelLoading; }\n let observable = this._powerLevels;\n if (!observable) {\n this._powerLevelLoading = this._loadPowerLevels();\n const powerLevels = await this._powerLevelLoading;\n observable = new RetainedObservableValue(powerLevels, () => { this._powerLevels = null; });\n this._powerLevels = observable;\n this._powerLevelLoading = null;\n }\n return observable;\n }\n\n enableKeyBackup(keyBackup) {\n this._roomEncryption?.enableKeyBackup(keyBackup);\n // TODO: do we really want to do this every time you open the app?\n if (this._timeline && keyBackup) {\n this._platform.logger.run(\"enableKeyBackup\", log => {\n return this._roomEncryption.restoreMissingSessionsFromBackup(this._timeline.remoteEntries, log);\n });\n }\n }\n\n get _isTimelineOpen() {\n return !!this._timeline;\n }\n\n _emitUpdate() {\n // once for event emitter listeners\n this.emit(\"change\");\n // and once for collection listeners\n this._emitCollectionChange(this);\n }\n\n /** @public */\n openTimeline(log = null) {\n return this._platform.logger.wrapOrRun(log, \"open timeline\", async log => {\n log.set(\"id\", this.id);\n if (this._timeline) {\n throw new Error(\"not dealing with load race here for now\");\n }\n this._timeline = new Timeline({\n roomId: this.id,\n storage: this._storage,\n fragmentIdComparer: this._fragmentIdComparer,\n pendingEvents: this._getPendingEvents(),\n closeCallback: () => {\n this._timeline = null;\n if (this._roomEncryption) {\n this._roomEncryption.notifyTimelineClosed();\n }\n },\n clock: this._platform.clock,\n logger: this._platform.logger,\n powerLevelsObservable: await this.observePowerLevels(),\n hsApi: this._hsApi\n });\n try {\n if (this._roomEncryption) {\n this._timeline.enableEncryption(this._decryptEntries.bind(this, DecryptionSource.Timeline));\n }\n await this._timeline.load(this._user, this.membership, log);\n } catch (err) {\n // this also clears this._timeline in the closeCallback\n this._timeline.dispose();\n throw err;\n }\n return this._timeline;\n });\n }\n\n /* allow subclasses to provide an observable list with pending events when opening the timeline */\n _getPendingEvents() { return null; }\n\n observeEvent(eventId) {\n if (!this._observedEvents) {\n this._observedEvents = new ObservedEventMap(() => {\n this._observedEvents = null;\n });\n }\n let entry = null;\n if (this._timeline) {\n entry = this._timeline.getByEventId(eventId);\n }\n const observable = this._observedEvents.observe(eventId, entry);\n if (!entry) {\n // update in the background\n this._readEventById(eventId).then(entry => {\n observable.update(entry);\n }).catch(err => {\n console.warn(`could not load event ${eventId} from storage`, err);\n });\n }\n return observable;\n }\n\n async _readEventById(eventId) {\n const reader = new TimelineReader({ roomId: this._roomId, storage: this._storage, fragmentIdComparer: this._fragmentIdComparer });\n const entry = await reader.readById(eventId);\n return entry;\n }\n\n dispose() {\n this._roomEncryption?.dispose();\n this._timeline?.dispose();\n }\n}\n\nclass DecryptionRequest {\n constructor(decryptFn, log) {\n this._cancelled = false;\n this.preparation = null;\n this._promise = log.wrap(\"decryptEntries\", log => decryptFn(this, log));\n }\n\n complete() {\n return this._promise;\n }\n\n get cancelled() {\n return this._cancelled;\n }\n\n dispose() {\n this._cancelled = true;\n if (this.preparation) {\n this.preparation.dispose();\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function makeTxnId() {\n const n = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER);\n const str = n.toString(16);\n return \"t\" + \"0\".repeat(14 - str.length) + str;\n}\n\nexport function isTxnId(txnId) {\n\treturn txnId.startsWith(\"t\") && txnId.length === 15;\n}\n\nexport function tests() {\n\treturn {\n\t\t\"isTxnId succeeds on result of makeTxnId\": assert => {\n\t\t\tassert(isTxnId(makeTxnId()));\n\t\t},\n\t\t\"isTxnId fails on event id\": assert => {\n\t\t\tassert(!isTxnId(\"$yS_n5n3cIO2aTtek0_2ZSlv-7g4YYR2zKrk2mFCW_rm\"));\n\t\t},\n\t}\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SortedArray} from \"../../../observable/list/SortedArray\";\nimport {ConnectionError} from \"../../error.js\";\nimport {PendingEvent, SendStatus} from \"./PendingEvent.js\";\nimport {makeTxnId, isTxnId} from \"../../common.js\";\nimport {REDACTION_TYPE} from \"../common\";\nimport {getRelationFromContent, getRelationTarget, setRelationTarget, REACTION_TYPE, ANNOTATION_RELATION_TYPE} from \"../timeline/relations.js\";\n\nexport class SendQueue {\n constructor({roomId, storage, hsApi, pendingEvents}) {\n pendingEvents = pendingEvents || [];\n this._roomId = roomId;\n this._storage = storage;\n this._hsApi = hsApi;\n this._pendingEvents = new SortedArray((a, b) => a.queueIndex - b.queueIndex);\n this._pendingEvents.setManyUnsorted(pendingEvents.map(data => this._createPendingEvent(data)));\n this._isSending = false;\n this._offline = false;\n this._roomEncryption = null;\n this._currentQueueIndex = 0;\n }\n\n _createPendingEvent(data, attachments = null) {\n const pendingEvent = new PendingEvent({\n data,\n remove: () => this._removeEvent(pendingEvent),\n emitUpdate: params => this._pendingEvents.update(pendingEvent, params),\n attachments\n });\n return pendingEvent;\n }\n\n enableEncryption(roomEncryption) {\n this._roomEncryption = roomEncryption;\n }\n\n _sendLoop(log) {\n this._isSending = true;\n this._sendLoopLogItem = log.runDetached(\"send queue flush\", async log => {\n try {\n for (const pendingEvent of this._pendingEvents) {\n await log.wrap(\"send event\", async log => {\n log.set(\"queueIndex\", pendingEvent.queueIndex);\n try {\n this._currentQueueIndex = pendingEvent.queueIndex;\n await this._sendEvent(pendingEvent, log);\n } catch(err) {\n if (err instanceof ConnectionError) {\n this._offline = true;\n log.set(\"offline\", true);\n pendingEvent.setWaiting();\n } else {\n log.catch(err);\n const isPermanentError = err.name === \"HomeServerError\" && (\n err.statusCode === 400 || // bad request, must be a bug on our end\n err.statusCode === 403 || // forbidden\n err.statusCode === 404 // not found\n );\n if (isPermanentError) {\n log.set(\"remove\", true);\n await pendingEvent.abort();\n } else {\n pendingEvent.setError(err);\n }\n }\n } finally {\n this._currentQueueIndex = 0;\n }\n });\n }\n } finally {\n this._isSending = false;\n this._sendLoopLogItem = null;\n }\n });\n }\n\n async _sendEvent(pendingEvent, log) {\n if (pendingEvent.needsUpload) {\n await log.wrap(\"upload attachments\", log => pendingEvent.uploadAttachments(this._hsApi, log));\n await this._tryUpdateEvent(pendingEvent);\n }\n if (pendingEvent.needsEncryption) {\n pendingEvent.setEncrypting();\n const encryptionContent = pendingEvent.contentForEncryption;\n const {type, content} = await log.wrap(\"encrypt\", log => this._roomEncryption.encrypt(\n pendingEvent.eventType, encryptionContent, this._hsApi, log));\n pendingEvent.setEncrypted(type, content);\n await this._tryUpdateEvent(pendingEvent);\n }\n if (pendingEvent.needsSending) {\n await pendingEvent.send(this._hsApi, log);\n // we now have a remoteId, but this pending event may be removed at any point in the future\n // (or past, so can't assume it still exists) once the remote echo comes in.\n // So if we have any related events that need to resolve the relatedTxnId to a related event id,\n // they need to do so now.\n // We ensure this by writing the new remote id for the pending event and all related events\n // with unresolved relatedTxnId in the queue in one transaction.\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);\n try {\n await this._tryUpdateEventWithTxn(pendingEvent, txn);\n await this._resolveRemoteIdInPendingRelations(\n pendingEvent.txnId, pendingEvent.remoteId, txn);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n }\n }\n\n async _resolveRemoteIdInPendingRelations(txnId, remoteId, txn) {\n const relatedEventWithoutRemoteId = this._pendingEvents.array.filter(pe => {\n return pe.relatedTxnId === txnId && pe.relatedEventId !== remoteId;\n });\n for (const relatedPE of relatedEventWithoutRemoteId) {\n relatedPE.setRelatedEventId(remoteId);\n await this._tryUpdateEventWithTxn(relatedPE, txn);\n }\n return relatedEventWithoutRemoteId;\n }\n\n async removeRemoteEchos(events, txn, parentLog) {\n const removed = [];\n for (const event of events) {\n const txnId = event.unsigned && event.unsigned.transaction_id;\n let idx;\n if (txnId) {\n idx = this._pendingEvents.array.findIndex(pe => pe.txnId === txnId);\n } else {\n idx = this._pendingEvents.array.findIndex(pe => pe.remoteId === event.event_id);\n }\n if (idx !== -1) {\n const pendingEvent = this._pendingEvents.get(idx);\n const remoteId = event.event_id;\n parentLog.log({l: \"removeRemoteEcho\", queueIndex: pendingEvent.queueIndex, remoteId, txnId});\n txn.pendingEvents.remove(pendingEvent.roomId, pendingEvent.queueIndex);\n removed.push(pendingEvent);\n await this._resolveRemoteIdInPendingRelations(txnId, remoteId, txn);\n }\n }\n return removed;\n }\n\n async _removeEvent(pendingEvent) {\n let hasEvent = this._pendingEvents.array.indexOf(pendingEvent) !== -1;\n if (hasEvent) {\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);\n try {\n txn.pendingEvents.remove(pendingEvent.roomId, pendingEvent.queueIndex);\n } catch (err) {\n txn.abort();\n }\n await txn.complete();\n // lookup index after async txn is complete,\n // to make sure we're not racing with anything\n const idx = this._pendingEvents.array.indexOf(pendingEvent);\n if (idx !== -1) {\n this._pendingEvents.remove(idx);\n }\n }\n pendingEvent.dispose();\n }\n\n emitRemovals(pendingEvents) {\n for (const pendingEvent of pendingEvents) {\n const idx = this._pendingEvents.array.indexOf(pendingEvent);\n if (idx !== -1) {\n this._pendingEvents.remove(idx);\n }\n pendingEvent.dispose();\n }\n }\n\n resumeSending(parentLog) {\n this._offline = false;\n if (this._pendingEvents.length) {\n parentLog.wrap(\"resumeSending\", log => {\n log.set(\"id\", this._roomId);\n log.set(\"pendingEvents\", this._pendingEvents.length);\n if (!this._isSending) {\n this._sendLoop(log);\n }\n if (this._sendLoopLogItem) {\n log.refDetached(this._sendLoopLogItem);\n }\n });\n }\n }\n\n async enqueueEvent(eventType, content, attachments, log) {\n const relation = getRelationFromContent(content);\n let relatedTxnId = null;\n if (relation) {\n const relationTarget = getRelationTarget(relation);\n if (isTxnId(relationTarget)) {\n relatedTxnId = relationTarget;\n setRelationTarget(relation, null);\n }\n if (relation.rel_type === ANNOTATION_RELATION_TYPE) {\n // Here we know the shape of the relation, and can use event_id safely\n const isAlreadyAnnotating = this._pendingEvents.array.some(pe => {\n const r = getRelationFromContent(pe.content);\n return pe.eventType === eventType && r && r.key === relation.key &&\n (pe.relatedTxnId === relatedTxnId || r.event_id === relation.event_id);\n });\n if (isAlreadyAnnotating) {\n log.set(\"already_annotating\", true);\n return;\n }\n }\n }\n await this._enqueueEvent(eventType, content, attachments, relatedTxnId, null, log);\n }\n\n async _enqueueEvent(eventType, content, attachments, relatedTxnId, relatedEventId, log) {\n const pendingEvent = await this._createAndStoreEvent(eventType, content, relatedTxnId, relatedEventId, attachments);\n this._pendingEvents.set(pendingEvent);\n log.set(\"queueIndex\", pendingEvent.queueIndex);\n log.set(\"pendingEvents\", this._pendingEvents.length);\n if (!this._isSending && !this._offline) {\n this._sendLoop(log);\n }\n if (this._sendLoopLogItem) {\n log.refDetached(this._sendLoopLogItem);\n }\n }\n\n async enqueueRedaction(eventIdOrTxnId, reason, log) {\n const isAlreadyRedacting = this._pendingEvents.array.some(pe => {\n return pe.eventType === REDACTION_TYPE &&\n (pe.relatedTxnId === eventIdOrTxnId || pe.relatedEventId === eventIdOrTxnId);\n });\n if (isAlreadyRedacting) {\n log.set(\"already_redacting\", true);\n return;\n }\n let relatedTxnId;\n let relatedEventId;\n if (isTxnId(eventIdOrTxnId)) {\n relatedTxnId = eventIdOrTxnId;\n const txnId = eventIdOrTxnId;\n const pe = this._pendingEvents.array.find(pe => pe.txnId === txnId);\n if (pe && !pe.remoteId && pe.status !== SendStatus.Sending) {\n // haven't started sending this event yet,\n // just remove it from the queue\n log.set(\"remove\", relatedTxnId);\n await pe.abort();\n return;\n } else if (pe) {\n relatedEventId = pe.remoteId;\n } else {\n // we don't have the pending event anymore,\n // the remote echo must have arrived in the meantime.\n // we could look for it in the timeline, but for now\n // we don't do anything as this race is quite unlikely\n // and a bit complicated to fix.\n return;\n }\n } else {\n relatedEventId = eventIdOrTxnId;\n const pe = this._pendingEvents.array.find(pe => pe.remoteId === relatedEventId);\n if (pe) {\n // also set the txn id just in case that an event id was passed\n // for relating to a pending event that is still waiting for the remote echo\n relatedTxnId = pe.txnId;\n }\n }\n log.set(\"relatedTxnId\", relatedTxnId);\n log.set(\"relatedEventId\", relatedEventId);\n await this._enqueueEvent(REDACTION_TYPE, {reason}, null, relatedTxnId, relatedEventId, log);\n }\n\n get pendingEvents() {\n return this._pendingEvents;\n }\n\n async _tryUpdateEvent(pendingEvent) {\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);\n try {\n this._tryUpdateEventWithTxn(pendingEvent, txn);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n }\n\n async _tryUpdateEventWithTxn(pendingEvent, txn) {\n // pendingEvent might have been removed already here\n // by a racing remote echo, so check first so we don't recreate it\n if (await txn.pendingEvents.exists(pendingEvent.roomId, pendingEvent.queueIndex)) {\n txn.pendingEvents.update(pendingEvent.data);\n }\n }\n\n async _createAndStoreEvent(eventType, content, relatedTxnId, relatedEventId, attachments) {\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.pendingEvents]);\n let pendingEvent;\n try {\n const pendingEventsStore = txn.pendingEvents;\n const maxStorageQueueIndex = await pendingEventsStore.getMaxQueueIndex(this._roomId) || 0;\n // don't use the queueIndex of the pendingEvent currently waiting for /send to return\n // if the remote echo already removed the pendingEvent in storage, as the send loop\n // wouldn't be able to detect the remote echo already arrived and end up overwriting the new event\n const maxQueueIndex = Math.max(maxStorageQueueIndex, this._currentQueueIndex);\n const queueIndex = maxQueueIndex + 1;\n const needsEncryption = eventType !== REDACTION_TYPE &&\n eventType !== REACTION_TYPE &&\n !!this._roomEncryption;\n pendingEvent = this._createPendingEvent({\n roomId: this._roomId,\n queueIndex,\n eventType,\n content,\n relatedTxnId,\n relatedEventId,\n txnId: makeTxnId(),\n needsEncryption,\n needsUpload: !!attachments\n }, attachments);\n pendingEventsStore.add(pendingEvent.data);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n return pendingEvent;\n }\n\n dispose() {\n for (const pe of this._pendingEvents) {\n pe.dispose();\n }\n }\n}\n\nimport {HomeServer as MockHomeServer} from \"../../../mocks/HomeServer.js\";\nimport {createMockStorage} from \"../../../mocks/Storage\";\nimport {ListObserver} from \"../../../mocks/ListObserver.js\";\nimport {NullLogger, NullLogItem} from \"../../../logging/NullLogger\";\nimport {createEvent, withTextBody, withTxnId} from \"../../../mocks/event.js\";\nimport {poll} from \"../../../mocks/poll.js\";\nimport {createAnnotation} from \"../timeline/relations.js\";\n\nexport function tests() {\n const logger = new NullLogger();\n return {\n \"enqueue second message when remote echo of first arrives before /send returns\": async assert => {\n const storage = await createMockStorage();\n const hs = new MockHomeServer();\n // 1. enqueue and start send event 1\n const queue = new SendQueue({roomId: \"!abc\", storage, hsApi: hs.api});\n const event1 = withTextBody(\"message 1\", createEvent(\"m.room.message\", \"$123\"));\n await logger.run(\"event1\", log => queue.enqueueEvent(event1.type, event1.content, null, log));\n assert.equal(queue.pendingEvents.length, 1);\n const sendRequest1 = hs.requests.send[0];\n // 2. receive remote echo, before /send has returned\n const remoteEcho = withTxnId(sendRequest1.arguments[2], event1);\n const txn = await storage.readWriteTxn([storage.storeNames.pendingEvents]);\n const removal = await logger.run(\"remote echo\", log => queue.removeRemoteEchos([remoteEcho], txn, log));\n await txn.complete();\n assert.equal(removal.length, 1);\n queue.emitRemovals(removal);\n assert.equal(queue.pendingEvents.length, 0);\n // 3. now enqueue event 2\n const event2 = withTextBody(\"message 2\", createEvent(\"m.room.message\", \"$456\"));\n await logger.run(\"event2\", log => queue.enqueueEvent(event2.type, event2.content, null, log));\n // even though the first pending event has been removed by the remote echo,\n // the second should get the next index, as the send loop is still blocking on the first one\n assert.equal(Array.from(queue.pendingEvents)[0].queueIndex, 2);\n // 4. send for event 1 comes back\n sendRequest1.respond({event_id: event1.event_id});\n // 5. now expect second send request for event 2\n const sendRequest2 = await poll(() => hs.requests.send[1]);\n sendRequest2.respond({event_id: event2.event_id});\n await poll(() => !queue._isSending);\n },\n \"redaction of pending event that hasn't started sending yet aborts it\": async assert => {\n const queue = new SendQueue({\n roomId: \"!abc\",\n storage: await createMockStorage(),\n hsApi: new MockHomeServer().api\n });\n // first, enqueue a message that will be attempted to send, but we don't respond\n await queue.enqueueEvent(\"m.room.message\", {body: \"hello!\"}, null, new NullLogItem());\n\n const observer = new ListObserver();\n queue.pendingEvents.subscribe(observer);\n await queue.enqueueEvent(\"m.room.message\", {body: \"...world\"}, null, new NullLogItem());\n let txnId;\n {\n const {type, index, value} = await observer.next();\n assert.equal(type, \"add\");\n assert.equal(index, 1);\n assert.equal(typeof value.txnId, \"string\");\n txnId = value.txnId;\n }\n await queue.enqueueRedaction(txnId, null, new NullLogItem());\n {\n const {type, value, index} = await observer.next();\n assert.equal(type, \"remove\");\n assert.equal(index, 1);\n assert.equal(txnId, value.txnId);\n }\n },\n \"duplicate redaction gets dropped\": async assert => {\n const queue = new SendQueue({\n roomId: \"!abc\",\n storage: await createMockStorage(),\n hsApi: new MockHomeServer().api\n });\n assert.equal(queue.pendingEvents.length, 0);\n await queue.enqueueRedaction(\"!event\", null, new NullLogItem());\n assert.equal(queue.pendingEvents.length, 1);\n await queue.enqueueRedaction(\"!event\", null, new NullLogItem());\n assert.equal(queue.pendingEvents.length, 1);\n },\n \"duplicate reaction gets dropped\": async assert => {\n const queue = new SendQueue({\n roomId: \"!abc\",\n storage: await createMockStorage(),\n hsApi: new MockHomeServer().api\n });\n assert.equal(queue.pendingEvents.length, 0);\n await queue.enqueueEvent(\"m.reaction\", createAnnotation(\"!target\", \"🚀\"), null, new NullLogItem());\n assert.equal(queue.pendingEvents.length, 1);\n await queue.enqueueEvent(\"m.reaction\", createAnnotation(\"!target\", \"👋\"), null, new NullLogItem());\n assert.equal(queue.pendingEvents.length, 2);\n await queue.enqueueEvent(\"m.reaction\", createAnnotation(\"!target\", \"🚀\"), null, new NullLogItem());\n assert.equal(queue.pendingEvents.length, 2);\n },\n \n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {encryptAttachment} from \"../e2ee/attachment.js\";\n\nexport class AttachmentUpload {\n constructor({filename, blob, platform}) {\n this._filename = filename;\n // need to keep around for local preview while uploading\n this._unencryptedBlob = blob;\n this._transferredBlob = this._unencryptedBlob;\n this._platform = platform;\n this._mxcUrl = null;\n this._encryptionInfo = null;\n this._uploadRequest = null;\n this._aborted = false;\n this._error = null;\n this._sentBytes = 0;\n }\n\n /** important to call after encrypt() if encryption is needed */\n get size() {\n return this._transferredBlob.size;\n }\n\n get sentBytes() {\n return this._sentBytes;\n }\n\n abort() {\n this._uploadRequest?.abort();\n }\n\n get localPreview() {\n return this._unencryptedBlob;\n }\n\n /** @internal */\n async encrypt() {\n if (this._encryptionInfo) {\n throw new Error(\"already encrypted\");\n }\n const {info, blob} = await encryptAttachment(this._platform, this._transferredBlob);\n this._transferredBlob = blob;\n this._encryptionInfo = info;\n }\n\n /** @internal */\n async upload(hsApi, progressCallback, log) {\n this._uploadRequest = hsApi.uploadAttachment(this._transferredBlob, this._filename, {\n uploadProgress: sentBytes => {\n this._sentBytes = sentBytes;\n progressCallback();\n },\n log\n });\n const {content_uri} = await this._uploadRequest.response();\n this._mxcUrl = content_uri;\n }\n\n /** @internal */\n applyToContent(urlPath, content) {\n if (!this._mxcUrl) {\n throw new Error(\"upload has not finished\");\n }\n let prefix = urlPath.substr(0, urlPath.lastIndexOf(\"url\"));\n setPath(`${prefix}info.size`, content, this._transferredBlob.size);\n setPath(`${prefix}info.mimetype`, content, this._unencryptedBlob.mimeType);\n if (this._encryptionInfo) {\n setPath(`${prefix}file`, content, Object.assign(this._encryptionInfo, {\n mimetype: this._unencryptedBlob.mimeType,\n url: this._mxcUrl\n }));\n } else {\n setPath(`${prefix}url`, content, this._mxcUrl);\n }\n }\n\n dispose() {\n this._unencryptedBlob.dispose();\n this._transferredBlob.dispose();\n }\n}\n\nfunction setPath(path, content, value) {\n const parts = path.split(\".\");\n let obj = content;\n for (let i = 0; i < (parts.length - 1); i += 1) {\n const key = parts[i];\n if (!obj[key]) {\n obj[key] = {};\n }\n obj = obj[key];\n }\n const propKey = parts[parts.length - 1];\n obj[propKey] = value;\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseRoom} from \"./BaseRoom.js\";\nimport {SyncWriter} from \"./timeline/persistence/SyncWriter.js\";\nimport {MemberWriter} from \"./timeline/persistence/MemberWriter.js\";\nimport {RelationWriter} from \"./timeline/persistence/RelationWriter.js\";\nimport {SendQueue} from \"./sending/SendQueue.js\";\nimport {WrappedError} from \"../error.js\"\nimport {Heroes} from \"./members/Heroes.js\";\nimport {AttachmentUpload} from \"./AttachmentUpload.js\";\nimport {DecryptionSource} from \"../e2ee/common.js\";\nimport {PowerLevels, EVENT_TYPE as POWERLEVELS_EVENT_TYPE } from \"./PowerLevels.js\";\n\nconst EVENT_ENCRYPTED_TYPE = \"m.room.encrypted\";\n\nexport class Room extends BaseRoom {\n constructor(options) {\n super(options);\n // TODO: pass pendingEvents to start like pendingOperations?\n const {pendingEvents} = options;\n const relationWriter = new RelationWriter({\n roomId: this.id,\n fragmentIdComparer: this._fragmentIdComparer,\n ownUserId: this._user.id\n });\n this._syncWriter = new SyncWriter({\n roomId: this.id,\n fragmentIdComparer: this._fragmentIdComparer,\n relationWriter,\n memberWriter: new MemberWriter(this.id)\n });\n this._sendQueue = new SendQueue({roomId: this.id, storage: this._storage, hsApi: this._hsApi, pendingEvents});\n }\n\n _setEncryption(roomEncryption) {\n if (super._setEncryption(roomEncryption)) {\n this._sendQueue.enableEncryption(this._roomEncryption);\n return true;\n }\n return false;\n }\n\n async prepareSync(roomResponse, membership, newKeys, txn, log) {\n log.set(\"id\", this.id);\n if (newKeys) {\n log.set(\"newKeys\", newKeys.length);\n }\n let summaryChanges = this._summary.data.applySyncResponse(roomResponse, membership, this._user.id);\n let roomEncryption = this._roomEncryption;\n // encryption is enabled in this sync\n if (!roomEncryption && summaryChanges.encryption) {\n log.set(\"enableEncryption\", true);\n roomEncryption = this._createRoomEncryption(this, summaryChanges.encryption);\n }\n\n let retryEntries;\n let decryptPreparation;\n if (roomEncryption) {\n let eventsToDecrypt = roomResponse?.timeline?.events || [];\n // when new keys arrive, also see if any older events can now be retried to decrypt\n if (newKeys) {\n // TODO: if a key is considered by roomEncryption.prepareDecryptAll to use for decryption,\n // key.eventIds will be set. We could somehow try to reuse that work, but retrying also needs\n // to happen if a key is not needed to decrypt this sync or there are indeed no encrypted messages\n // in this sync at all.\n retryEntries = await this._getSyncRetryDecryptEntries(newKeys, roomEncryption, txn);\n if (retryEntries.length) {\n log.set(\"retry\", retryEntries.length);\n eventsToDecrypt = eventsToDecrypt.concat(retryEntries.map(entry => entry.event));\n }\n }\n eventsToDecrypt = eventsToDecrypt.filter(event => {\n return event?.type === EVENT_ENCRYPTED_TYPE;\n });\n if (eventsToDecrypt.length) {\n decryptPreparation = await roomEncryption.prepareDecryptAll(\n eventsToDecrypt, newKeys, DecryptionSource.Sync, txn);\n }\n }\n\n return {\n roomEncryption,\n summaryChanges,\n decryptPreparation,\n decryptChanges: null,\n retryEntries\n };\n }\n\n async afterPrepareSync(preparation, parentLog) {\n if (preparation.decryptPreparation) {\n await parentLog.wrap(\"decrypt\", async log => {\n log.set(\"id\", this.id);\n preparation.decryptChanges = await preparation.decryptPreparation.decrypt();\n preparation.decryptPreparation = null;\n }, parentLog.level.Detail);\n }\n }\n\n /** @package */\n async writeSync(roomResponse, isInitialSync, {summaryChanges, decryptChanges, roomEncryption, retryEntries}, txn, log) {\n log.set(\"id\", this.id);\n const isRejoin = summaryChanges.isNewJoin(this._summary.data);\n if (isRejoin) {\n // remove all room state before calling syncWriter,\n // so no old state sticks around\n txn.roomState.removeAllForRoom(this.id);\n txn.roomMembers.removeAllForRoom(this.id);\n }\n const {entries: newEntries, updatedEntries, newLiveKey, memberChanges} =\n await log.wrap(\"syncWriter\", log => this._syncWriter.writeSync(\n roomResponse, isRejoin, summaryChanges.hasFetchedMembers, txn, log), log.level.Detail);\n if (decryptChanges) {\n const decryption = await log.wrap(\"decryptChanges\", log => decryptChanges.write(txn, log));\n log.set(\"decryptionResults\", decryption.results.size);\n log.set(\"decryptionErrors\", decryption.errors.size);\n if (this._isTimelineOpen) {\n await decryption.verifySenders(txn);\n }\n decryption.applyToEntries(newEntries);\n if (retryEntries?.length) {\n decryption.applyToEntries(retryEntries);\n updatedEntries.push(...retryEntries);\n }\n }\n log.set(\"newEntries\", newEntries.length);\n log.set(\"updatedEntries\", updatedEntries.length);\n let encryptionChanges;\n // pass member changes to device tracker\n if (roomEncryption) {\n encryptionChanges = await roomEncryption.writeSync(roomResponse, memberChanges, txn, log);\n log.set(\"shouldFlushKeyShares\", encryptionChanges.shouldFlush);\n }\n const allEntries = newEntries.concat(updatedEntries);\n // also apply (decrypted) timeline entries to the summary changes\n summaryChanges = summaryChanges.applyTimelineEntries(\n allEntries, isInitialSync, !this._isTimelineOpen, this._user.id);\n \n // if we've have left the room, remove the summary\n if (summaryChanges.membership !== \"join\") {\n txn.roomSummary.remove(this.id);\n } else {\n // write summary changes, and unset if nothing was actually changed\n summaryChanges = this._summary.writeData(summaryChanges, txn);\n }\n if (summaryChanges) {\n log.set(\"summaryChanges\", summaryChanges.changedKeys(this._summary.data));\n }\n // fetch new members while we have txn open,\n // but don't make any in-memory changes yet\n let heroChanges;\n // if any hero changes their display name, the summary in the room response\n // is also updated, which will trigger a RoomSummary update\n // and make summaryChanges non-falsy here\n if (summaryChanges?.needsHeroes) {\n // room name disappeared, open heroes\n if (!this._heroes) {\n this._heroes = new Heroes(this._roomId);\n }\n heroChanges = await this._heroes.calculateChanges(summaryChanges.heroes, memberChanges, txn);\n }\n let removedPendingEvents;\n if (Array.isArray(roomResponse.timeline?.events)) {\n removedPendingEvents = await this._sendQueue.removeRemoteEchos(roomResponse.timeline.events, txn, log);\n }\n const powerLevelsEvent = this._getPowerLevelsEvent(roomResponse);\n return {\n summaryChanges,\n roomEncryption,\n newEntries,\n updatedEntries,\n newLiveKey,\n removedPendingEvents,\n memberChanges,\n heroChanges,\n powerLevelsEvent,\n encryptionChanges,\n };\n }\n\n /**\n * @package\n * Called with the changes returned from `writeSync` to apply them and emit changes.\n * No storage or network operations should be done here.\n */\n afterSync(changes, log) {\n const {\n summaryChanges, newEntries, updatedEntries, newLiveKey,\n removedPendingEvents, memberChanges, powerLevelsEvent,\n heroChanges, roomEncryption, encryptionChanges\n } = changes;\n log.set(\"id\", this.id);\n this._syncWriter.afterSync(newLiveKey);\n this._setEncryption(roomEncryption);\n if (this._roomEncryption) {\n this._roomEncryption.afterSync(encryptionChanges);\n }\n if (memberChanges.size) {\n if (this._changedMembersDuringSync) {\n for (const [userId, memberChange] of memberChanges.entries()) {\n this._changedMembersDuringSync.set(userId, memberChange.member);\n }\n }\n if (this._memberList) {\n this._memberList.afterSync(memberChanges);\n }\n if (this._observedMembers) {\n this._updateObservedMembers(memberChanges);\n }\n if (this._timeline) {\n for (const [userId, memberChange] of memberChanges.entries()) {\n if (userId === this._user.id) {\n this._timeline.updateOwnMember(memberChange.member);\n break;\n }\n }\n }\n }\n let emitChange = false;\n if (summaryChanges) {\n this._summary.applyChanges(summaryChanges);\n if (!this._summary.data.needsHeroes) {\n this._heroes = null;\n }\n emitChange = true;\n }\n if (this._heroes && heroChanges) {\n const oldName = this.name;\n this._heroes.applyChanges(heroChanges, this._summary.data, log);\n if (oldName !== this.name) {\n emitChange = true;\n }\n }\n if (powerLevelsEvent) {\n this._updatePowerLevels(powerLevelsEvent);\n }\n if (emitChange) {\n this._emitUpdate();\n }\n if (this._timeline) {\n // these should not be added if not already there\n this._timeline.replaceEntries(updatedEntries);\n this._timeline.addEntries(newEntries);\n }\n if (this._observedEvents) {\n this._observedEvents.updateEvents(updatedEntries);\n this._observedEvents.updateEvents(newEntries);\n }\n if (removedPendingEvents) {\n this._sendQueue.emitRemovals(removedPendingEvents);\n }\n }\n\n _updateObservedMembers(memberChanges) {\n for (const [userId, memberChange] of memberChanges) {\n const observableMember = this._observedMembers.get(userId);\n if (observableMember) {\n observableMember.set(memberChange.member);\n }\n }\n }\n\n _getPowerLevelsEvent(roomResponse) {\n const isPowerlevelEvent = event => event.state_key === \"\" && event.type === POWERLEVELS_EVENT_TYPE;\n const powerLevelEvent = roomResponse.timeline?.events.find(isPowerlevelEvent) ?? roomResponse.state?.events.find(isPowerlevelEvent);\n return powerLevelEvent;\n }\n\n _updatePowerLevels(powerLevelEvent) {\n if (this._powerLevels) {\n const newPowerLevels = new PowerLevels({\n powerLevelEvent,\n ownUserId: this._user.id,\n membership: this.membership,\n });\n this._powerLevels.set(newPowerLevels);\n }\n }\n\n needsAfterSyncCompleted({encryptionChanges}) {\n return encryptionChanges?.shouldFlush;\n }\n\n /**\n * Only called if the result of writeSync had `needsAfterSyncCompleted` set.\n * Can be used to do longer running operations that resulted from the last sync,\n * like network operations.\n */\n async afterSyncCompleted(changes, log) {\n log.set(\"id\", this.id);\n if (this._roomEncryption) {\n await this._roomEncryption.flushPendingRoomKeyShares(this._hsApi, null, log);\n }\n }\n\n /** @package */\n start(pendingOperations, parentLog) {\n if (this._roomEncryption) {\n const roomKeyShares = pendingOperations?.get(\"share_room_key\");\n if (roomKeyShares) {\n // if we got interrupted last time sending keys to newly joined members\n parentLog.wrapDetached(\"flush room keys\", log => {\n log.set(\"id\", this.id);\n return this._roomEncryption.flushPendingRoomKeyShares(this._hsApi, roomKeyShares, log);\n });\n }\n }\n \n this._sendQueue.resumeSending(parentLog);\n }\n\n /** @package */\n async load(summary, txn, log) {\n try {\n await super.load(summary, txn, log);\n await this._syncWriter.load(txn, log);\n } catch (err) {\n throw new WrappedError(`Could not load room ${this._roomId}`, err);\n }\n }\n\n async _writeGapFill(gapChunk, txn, log) {\n const removedPendingEvents = await this._sendQueue.removeRemoteEchos(gapChunk, txn, log);\n return removedPendingEvents;\n }\n\n _applyGapFill(removedPendingEvents) {\n this._sendQueue.emitRemovals(removedPendingEvents);\n }\n\n /** @public */\n sendEvent(eventType, content, attachments, log = null) {\n return this._platform.logger.wrapOrRun(log, \"send\", log => {\n log.set(\"id\", this.id);\n return this._sendQueue.enqueueEvent(eventType, content, attachments, log);\n });\n }\n\n /** @public */\n sendRedaction(eventIdOrTxnId, reason, log = null) {\n return this._platform.logger.wrapOrRun(log, \"redact\", log => {\n log.set(\"id\", this.id);\n return this._sendQueue.enqueueRedaction(eventIdOrTxnId, reason, log);\n });\n }\n\n /** @public */\n async ensureMessageKeyIsShared(log = null) {\n if (!this._roomEncryption) {\n return;\n }\n return this._platform.logger.wrapOrRun(log, \"ensureMessageKeyIsShared\", log => {\n log.set(\"id\", this.id);\n return this._roomEncryption.ensureMessageKeyIsShared(this._hsApi, log);\n });\n }\n\n get avatarColorId() {\n return this._heroes?.roomAvatarColorId || this._roomId;\n }\n\n get isUnread() {\n return this._summary.data.isUnread;\n }\n\n get notificationCount() {\n return this._summary.data.notificationCount;\n }\n \n get highlightCount() {\n return this._summary.data.highlightCount;\n }\n\n get isTrackingMembers() {\n return this._summary.data.isTrackingMembers;\n }\n\n async _getLastEventId() {\n const lastKey = this._syncWriter.lastMessageKey;\n if (lastKey) {\n const txn = await this._storage.readTxn([\n this._storage.storeNames.timelineEvents,\n ]);\n const eventEntry = await txn.timelineEvents.get(this._roomId, lastKey);\n return eventEntry?.event?.event_id;\n }\n }\n\n async clearUnread(log = null) {\n if (this.isUnread || this.notificationCount) {\n return await this._platform.logger.wrapOrRun(log, \"clearUnread\", async log => {\n log.set(\"id\", this.id);\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.roomSummary,\n ]);\n let data;\n try {\n data = this._summary.writeClearUnread(txn);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n this._summary.applyChanges(data);\n this._emitUpdate();\n \n try {\n const lastEventId = await this._getLastEventId();\n if (lastEventId) {\n await this._hsApi.receipt(this._roomId, \"m.read\", lastEventId);\n }\n } catch (err) {\n // ignore ConnectionError\n if (err.name !== \"ConnectionError\") {\n throw err;\n }\n }\n });\n }\n }\n\n leave(log = null) {\n return this._platform.logger.wrapOrRun(log, \"leave room\", async log => {\n log.set(\"id\", this.id);\n await this._hsApi.leave(this.id, {log}).response();\n });\n }\n\n /* called by BaseRoom to pass pendingEvents when opening the timeline */\n _getPendingEvents() {\n return this._sendQueue.pendingEvents;\n }\n\n /** @package */\n writeIsTrackingMembers(value, txn) {\n return this._summary.writeIsTrackingMembers(value, txn);\n }\n\n /** @package */\n applyIsTrackingMembersChanges(changes) {\n this._summary.applyChanges(changes);\n }\n\n createAttachment(blob, filename) {\n return new AttachmentUpload({blob, filename, platform: this._platform});\n }\n\n dispose() {\n super.dispose();\n this._sendQueue.dispose();\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {reduceStateEvents} from \"./RoomSummary.js\";\nimport {BaseRoom} from \"./BaseRoom.js\";\nimport {RoomMember, EVENT_TYPE as MEMBER_EVENT_TYPE} from \"./members/RoomMember.js\";\n\nexport class ArchivedRoom extends BaseRoom {\n constructor(options) {\n super(options);\n // archived rooms are reference counted,\n // as they are not kept in memory when not needed\n this._releaseCallback = options.releaseCallback;\n this._forgetCallback = options.forgetCallback;\n this._retentionCount = 1;\n /**\n Some details from our own member event when being kicked or banned.\n We can't get this from the member store, because we don't store the reason field there.\n */\n this._kickDetails = null;\n this._kickedBy = null;\n }\n\n retain() {\n this._retentionCount += 1;\n }\n\n release() {\n this._retentionCount -= 1;\n if (this._retentionCount === 0) {\n this._releaseCallback();\n }\n }\n\n async _getKickAuthor(sender, txn) {\n const senderMember = await txn.roomMembers.get(this.id, sender);\n if (senderMember) {\n return new RoomMember(senderMember);\n } else {\n return RoomMember.fromUserId(this.id, sender, \"join\");\n }\n }\n \n async load(archivedRoomSummary, txn, log) {\n const {summary, kickDetails} = archivedRoomSummary;\n this._kickDetails = kickDetails;\n if (this._kickDetails) {\n this._kickedBy = await this._getKickAuthor(this._kickDetails.sender, txn);\n }\n return super.load(summary, txn, log);\n }\n\n /** @package */\n async writeSync(joinedSummaryData, roomResponse, membership, txn, log) {\n log.set(\"id\", this.id);\n if (membership === \"leave\") {\n const newKickDetails = findKickDetails(roomResponse, this._user.id);\n if (newKickDetails || joinedSummaryData) {\n const kickDetails = newKickDetails || this._kickDetails;\n let kickedBy;\n if (newKickDetails) {\n kickedBy = await this._getKickAuthor(newKickDetails.sender, txn);\n }\n const summaryData = joinedSummaryData || this._summary.data;\n txn.archivedRoomSummary.set({\n summary: summaryData.serialize(),\n kickDetails,\n });\n return {kickDetails, kickedBy, summaryData};\n }\n } else if (membership === \"join\") {\n txn.archivedRoomSummary.remove(this.id);\n }\n // always return object\n return {};\n }\n\n /**\n * @package\n * Called with the changes returned from `writeSync` to apply them and emit changes.\n * No storage or network operations should be done here.\n */\n afterSync({summaryData, kickDetails, kickedBy}, log) {\n log.set(\"id\", this.id);\n if (summaryData) {\n this._summary.applyChanges(summaryData);\n }\n if (kickDetails) {\n this._kickDetails = kickDetails;\n }\n if (kickedBy) {\n this._kickedBy = kickedBy;\n }\n this._emitUpdate();\n }\n\n get isKicked() {\n return this._kickDetails?.membership === \"leave\";\n }\n\n get isBanned() {\n return this._kickDetails?.membership === \"ban\";\n }\n\n get kickedBy() {\n return this._kickedBy;\n }\n\n get kickReason() {\n return this._kickDetails?.reason;\n }\n\n isArchived() {\n return true;\n }\n\n forget(log = null) {\n return this._platform.logger.wrapOrRun(log, \"forget room\", async log => {\n log.set(\"id\", this.id);\n await this._hsApi.forget(this.id, {log}).response();\n const storeNames = this._storage.storeNames;\n const txn = await this._storage.readWriteTxn([\n storeNames.roomState,\n storeNames.archivedRoomSummary,\n storeNames.roomMembers,\n storeNames.timelineEvents,\n storeNames.timelineFragments,\n storeNames.timelineRelations,\n storeNames.pendingEvents,\n storeNames.inboundGroupSessions,\n storeNames.groupSessionDecryptions,\n storeNames.operations,\n ]);\n\n txn.roomState.removeAllForRoom(this.id);\n txn.archivedRoomSummary.remove(this.id);\n txn.roomMembers.removeAllForRoom(this.id);\n txn.timelineEvents.removeAllForRoom(this.id);\n txn.timelineFragments.removeAllForRoom(this.id);\n txn.timelineRelations.removeAllForRoom(this.id);\n txn.pendingEvents.removeAllForRoom(this.id);\n txn.inboundGroupSessions.removeAllForRoom(this.id);\n txn.groupSessionDecryptions.removeAllForRoom(this.id);\n await txn.operations.removeAllForScope(this.id);\n\n await txn.complete();\n\n this._retentionCount = 0;\n this._releaseCallback();\n \n this._forgetCallback(this.id);\n });\n }\n\n join(log = null) {\n return this._platform.logger.wrapOrRun(log, \"rejoin archived room\", async log => {\n await this._hsApi.join(this.id, {log}).response();\n });\n }\n}\n\nfunction findKickDetails(roomResponse, ownUserId) {\n const kickEvent = reduceStateEvents(roomResponse, (kickEvent, event) => {\n if (event.type === MEMBER_EVENT_TYPE) {\n // did we get kicked?\n if (event.state_key === ownUserId && event.sender !== event.state_key) {\n kickEvent = event;\n }\n }\n return kickEvent;\n }, null);\n if (kickEvent) {\n return {\n // this is different from the room membership in the sync section, which can only be leave\n membership: kickEvent.content?.membership, // could be leave or ban\n reason: kickEvent.content?.reason,\n sender: kickEvent.sender,\n };\n }\n}\n\nexport function tests() {\n function createMemberEvent(sender, target, membership, reason) {\n return {\n sender,\n state_key: target,\n type: \"m.room.member\",\n content: { reason, membership }\n };\n }\n const bob = \"@bob:hs.tld\";\n const alice = \"@alice:hs.tld\";\n\n return {\n \"ban/kick sets kickDetails from state event\": assert => {\n const reason = \"Bye!\";\n const leaveEvent = createMemberEvent(alice, bob, \"ban\", reason);\n const kickDetails = findKickDetails({state: {events: [leaveEvent]}}, bob);\n assert.equal(kickDetails.membership, \"ban\");\n assert.equal(kickDetails.reason, reason);\n assert.equal(kickDetails.sender, alice);\n },\n \"ban/kick sets kickDetails from timeline state event, taking precedence over state\": assert => {\n const reason = \"Bye!\";\n const inviteEvent = createMemberEvent(alice, bob, \"invite\");\n const leaveEvent = createMemberEvent(alice, bob, \"ban\", reason);\n const kickDetails = findKickDetails({\n state: { events: [inviteEvent] },\n timeline: {events: [leaveEvent] }\n }, bob);\n assert.equal(kickDetails.membership, \"ban\");\n assert.equal(kickDetails.reason, reason);\n assert.equal(kickDetails.sender, alice);\n },\n \"leaving without being kicked doesn't produce kickDetails\": assert => {\n const leaveEvent = createMemberEvent(bob, bob, \"leave\");\n const kickDetails = findKickDetails({state: {events: [leaveEvent]}}, bob);\n assert.equal(kickDetails, null);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {HomeServerApi} from \"./net/HomeServerApi\";\nimport type {ILogItem} from \"../logging/types\";\n\nexport async function loadProfiles(userIds: string[], hsApi: HomeServerApi, log: ILogItem): Promise {\n const profiles = await Promise.all(userIds.map(async userId => {\n const response = await hsApi.profile(userId, {log}).response();\n return new Profile(userId, response.displayname as string, response.avatar_url as string);\n }));\n profiles.sort((a, b) => a.name.localeCompare(b.name));\n return profiles;\n}\n\nexport interface IProfile {\n get userId(): string;\n get displayName(): string | undefined;\n get avatarUrl(): string | undefined;\n get name(): string;\n}\n\nexport class Profile implements IProfile {\n constructor(\n public readonly userId: string,\n public readonly displayName: string,\n public readonly avatarUrl: string | undefined\n ) {}\n\n get name() { return this.displayName || this.userId; }\n}\n\nexport class UserIdProfile implements IProfile {\n constructor(public readonly userId: string) {}\n get displayName() { return undefined; }\n get name() { return this.userId; }\n get avatarUrl() { return undefined; }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {calculateRoomName} from \"./members/Heroes\";\nimport {createRoomEncryptionEvent} from \"../e2ee/common\";\nimport {MediaRepository} from \"../net/MediaRepository\";\nimport {EventEmitter} from \"../../utils/EventEmitter\";\nimport {AttachmentUpload} from \"./AttachmentUpload\";\nimport {loadProfiles, Profile, UserIdProfile} from \"../profile\";\nimport {RoomType} from \"./common\";\n\nimport type {HomeServerApi} from \"../net/HomeServerApi\";\nimport type {ILogItem} from \"../../logging/types\";\nimport type {Platform} from \"../../platform/web/Platform\";\nimport type {IBlobHandle} from \"../../platform/types/types\";\nimport type {User} from \"../User\";\nimport type {Storage} from \"../storage/idb/Storage\";\n\ntype CreateRoomPayload = {\n is_direct?: boolean;\n preset?: string;\n name?: string;\n topic?: string;\n invite?: string[];\n room_alias_name?: string;\n creation_content?: {\"m.federate\": boolean};\n initial_state: { type: string; state_key: string; content: Record }[];\n power_level_content_override?: Record;\n}\n\ntype ImageInfo = {\n w: number;\n h: number;\n mimetype: string;\n size: number;\n}\n\ntype Avatar = {\n info: ImageInfo;\n blob: IBlobHandle;\n name: string;\n}\n\ntype Options = {\n type: RoomType;\n isEncrypted?: boolean;\n isFederationDisabled?: boolean;\n name?: string;\n topic?: string;\n invites?: string[];\n avatar?: Avatar;\n alias?: string;\n powerLevelContentOverride?: Record;\n}\n\nfunction defaultE2EEStatusForType(type: RoomType): boolean {\n switch (type) {\n case RoomType.DirectMessage:\n case RoomType.Private:\n return true;\n case RoomType.Public:\n return false;\n }\n}\n\nfunction presetForType(type: RoomType): string {\n switch (type) {\n case RoomType.DirectMessage:\n return \"trusted_private_chat\";\n case RoomType.Private:\n return \"private_chat\";\n case RoomType.Public:\n return \"public_chat\";\n }\n}\n\nexport class RoomBeingCreated extends EventEmitter<{change: never}> {\n private _roomId?: string;\n private profiles: Profile[] = [];\n\n public readonly isEncrypted: boolean;\n private _calculatedName: string;\n private _error?: Error;\n private _isCancelled = false;\n\n constructor(\n public readonly id: string,\n private readonly options: Options,\n private readonly updateCallback: (self: RoomBeingCreated, params: string | undefined) => void,\n public readonly mediaRepository: MediaRepository,\n public readonly platform: Platform,\n log: ILogItem\n ) {\n super();\n this.isEncrypted = options.isEncrypted === undefined ? defaultE2EEStatusForType(options.type) : options.isEncrypted;\n if (options.name) {\n this._calculatedName = options.name;\n } else {\n const summaryData = {\n joinCount: 1, // ourselves\n inviteCount: (options.invites?.length || 0)\n };\n const userIdProfiles = (options.invites || []).map(userId => new UserIdProfile(userId));\n this._calculatedName = calculateRoomName(userIdProfiles, summaryData, log);\n }\n }\n\n /** @internal */\n async create(hsApi: HomeServerApi, log: ILogItem): Promise {\n try {\n let avatarEventContent;\n if (this.options.avatar) {\n const {avatar} = this.options;\n const attachment = new AttachmentUpload({filename: avatar.name, blob: avatar.blob, platform: this.platform});\n await attachment.upload(hsApi, () => {}, log);\n avatarEventContent = {\n info: avatar.info\n };\n attachment.applyToContent(\"url\", avatarEventContent);\n }\n const createOptions: CreateRoomPayload = {\n is_direct: this.options.type === RoomType.DirectMessage,\n preset: presetForType(this.options.type),\n initial_state: []\n };\n if (this.options.name) {\n createOptions.name = this.options.name;\n }\n if (this.options.topic) {\n createOptions.topic = this.options.topic;\n }\n if (this.options.invites) {\n createOptions.invite = this.options.invites;\n }\n if (this.options.alias) {\n createOptions.room_alias_name = this.options.alias;\n }\n if (this.options.isFederationDisabled === true) {\n createOptions.creation_content = {\n \"m.federate\": false\n };\n }\n if (this.options.powerLevelContentOverride) {\n createOptions.power_level_content_override = this.options.powerLevelContentOverride;\n }\n if (this.isEncrypted) {\n createOptions.initial_state.push(createRoomEncryptionEvent());\n }\n if (avatarEventContent) {\n createOptions.initial_state.push({\n type: \"m.room.avatar\",\n state_key: \"\",\n content: avatarEventContent\n });\n }\n const response = await hsApi.createRoom(createOptions, {log}).response();\n this._roomId = response[\"room_id\"];\n } catch (err) {\n this._error = err;\n }\n this.emitChange();\n }\n\n /** requests the profiles of the invitees if needed to give an accurate\n * estimated room name in case an explicit room name is not set.\n * The room is being created in the background whether this is called\n * or not, and this just gives a more accurate name while that request\n * is running. */\n /** @internal */\n async loadProfiles(hsApi: HomeServerApi, log: ILogItem): Promise {\n try {\n // only load profiles if we need it for the room name and avatar\n if (!this.options.name && this.options.invites) {\n this.profiles = await loadProfiles(this.options.invites, hsApi, log);\n const summaryData = {\n joinCount: 1, // ourselves\n inviteCount: this.options.invites.length\n };\n this._calculatedName = calculateRoomName(this.profiles, summaryData, log);\n this.emitChange();\n }\n } catch (err) {} // swallow error, loading profiles is not essential\n }\n\n private emitChange(params?: string) {\n this.updateCallback(this, params);\n this.emit(\"change\");\n }\n\n get avatarColorId(): string { return this.options.invites?.[0] ?? this._roomId ?? this.id; }\n get avatarUrl(): string | undefined { return this.profiles?.[0]?.avatarUrl; }\n get avatarBlobUrl(): string | undefined { return this.options.avatar?.blob?.url; }\n get roomId(): string | undefined { return this._roomId; }\n get name() { return this._calculatedName; }\n get isBeingCreated(): boolean { return true; }\n get error(): Error | undefined { return this._error; }\n\n cancel() {\n if (!this._isCancelled) {\n this.dispose();\n this._isCancelled = true;\n this.emitChange(\"isCancelled\");\n }\n }\n // called from Session when updateCallback is invoked to remove it from the collection\n get isCancelled() { return this._isCancelled; }\n\n /** @internal */\n dispose() {\n if (this.options.avatar) {\n this.options.avatar.blob.dispose();\n }\n }\n\n async adjustDirectMessageMapIfNeeded(user: User, storage: Storage, hsApi: HomeServerApi, log: ILogItem): Promise {\n if (!this.options.invites || this.options.type !== RoomType.DirectMessage) {\n return;\n }\n const userId = this.options.invites[0];\n const DM_MAP_TYPE = \"m.direct\";\n await log.wrap(\"set \" + DM_MAP_TYPE, async log => {\n try {\n const txn = await storage.readWriteTxn([storage.storeNames.accountData]);\n let mapEntry;\n try {\n mapEntry = await txn.accountData.get(DM_MAP_TYPE);\n if (!mapEntry) {\n mapEntry = {type: DM_MAP_TYPE, content: {}};\n }\n const map = mapEntry.content;\n let userRooms = map[userId];\n if (!userRooms) {\n map[userId] = userRooms = [];\n }\n // this is a new room id so no need to check if it's already there\n userRooms.push(this._roomId);\n txn.accountData.set(mapEntry);\n await txn.complete();\n } catch (err) {\n txn.abort();\n throw err;\n }\n await hsApi.setAccountData(user.id, DM_MAP_TYPE, mapEntry.content, {log}).response();\n } catch (err) {\n // we can't really do anything else but logging here\n log.catch(err);\n }\n });\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {EventEmitter} from \"../../utils/EventEmitter\";\nimport {SummaryData, processStateEvent} from \"./RoomSummary.js\";\nimport {Heroes} from \"./members/Heroes.js\";\nimport {MemberChange, RoomMember, EVENT_TYPE as MEMBER_EVENT_TYPE} from \"./members/RoomMember.js\";\n\nexport class Invite extends EventEmitter {\n constructor({roomId, user, hsApi, mediaRepository, emitCollectionRemove, emitCollectionUpdate, platform}) {\n super();\n this._roomId = roomId;\n this._user = user;\n this._hsApi = hsApi;\n this._emitCollectionRemove = emitCollectionRemove;\n this._emitCollectionUpdate = emitCollectionUpdate;\n this._mediaRepository = mediaRepository;\n this._platform = platform;\n this._inviteData = null;\n this._accepting = false;\n this._rejecting = false;\n this._accepted = false;\n this._rejected = false;\n }\n\n get isInvite() {\n return true;\n }\n\n get id() {\n return this._roomId;\n }\n\n get name() {\n return this._inviteData.name || this._inviteData.canonicalAlias;\n }\n\n get isDirectMessage() {\n return this._inviteData.isDirectMessage;\n }\n\n get avatarUrl() {\n return this._inviteData.avatarUrl;\n }\n\n /** @see BaseRoom.avatarColorId */\n get avatarColorId() {\n return this._inviteData.avatarColorId || this.id;\n }\n\n get timestamp() {\n return this._inviteData.timestamp;\n }\n\n get isEncrypted() {\n return this._inviteData.isEncrypted;\n }\n\n get inviter() {\n return this._inviter;\n }\n\n isDirectMessageForUserId(userId) {\n return this.isDirectMessage && this._inviter.userId === userId;\n }\n\n get isPublic() {\n return this._inviteData.joinRule === \"public\";\n }\n\n get canonicalAlias() {\n return this._inviteData.canonicalAlias;\n }\n\n async accept(log = null) {\n await this._platform.logger.wrapOrRun(log, \"acceptInvite\", async log => {\n this._accepting = true;\n this._emitChange(\"accepting\");\n await this._hsApi.join(this._roomId, {log}).response();\n });\n }\n\n async reject(log = null) {\n await this._platform.logger.wrapOrRun(log, \"rejectInvite\", async log => {\n this._rejecting = true;\n this._emitChange(\"rejecting\");\n await this._hsApi.leave(this._roomId, {log}).response();\n });\n }\n\n get accepting() {\n return this._accepting;\n }\n\n get accepted() {\n return this._accepted;\n }\n\n get rejecting() {\n return this._rejecting;\n }\n\n get rejected() {\n return this._rejected;\n }\n\n get mediaRepository() {\n return this._mediaRepository;\n }\n\n _emitChange(params) {\n this.emit(\"change\");\n this._emitCollectionUpdate(this, params);\n }\n\n load(inviteData, log) {\n log.set(\"id\", this.id);\n this._inviteData = inviteData;\n this._inviter = inviteData.inviter ? new RoomMember(inviteData.inviter) : null;\n }\n\n async writeSync(membership, roomResponse, txn, log) {\n if (membership === \"invite\") {\n log.set(\"id\", this.id);\n log.set(\"add\", true);\n const inviteState = roomResponse[\"invite_state\"]?.events;\n if (!Array.isArray(inviteState)) {\n return null;\n }\n const summaryData = this._createSummaryData(inviteState);\n let heroes;\n if (!summaryData.name && !summaryData.canonicalAlias) {\n heroes = await this._createHeroes(inviteState, log);\n }\n const myInvite = this._getMyInvite(inviteState);\n if (!myInvite) {\n return null;\n }\n const inviter = this._getInviter(myInvite, inviteState);\n const inviteData = this._createData(inviteState, myInvite, inviter, summaryData, heroes);\n txn.invites.set(inviteData);\n return {inviteData, inviter};\n } else {\n log.set(\"id\", this.id);\n log.set(\"membership\", membership);\n txn.invites.remove(this.id);\n return {removed: true, membership};\n }\n }\n\n afterSync(changes, log) {\n log.set(\"id\", this.id);\n if (changes) {\n if (changes.removed) {\n this._accepting = false;\n this._rejecting = false;\n if (changes.membership === \"join\") {\n this._accepted = true;\n } else {\n this._rejected = true;\n }\n this.emit(\"change\");\n } else {\n // no emit change, adding to the collection is done by sync\n this._inviteData = changes.inviteData;\n this._inviter = changes.inviter;\n }\n }\n }\n\n _createData(inviteState, myInvite, inviter, summaryData, heroes) {\n const name = heroes ? heroes.roomName : summaryData.name;\n const avatarUrl = heroes ? heroes.roomAvatarUrl : summaryData.avatarUrl;\n const avatarColorId = heroes?.roomAvatarColorId || this.id;\n return {\n roomId: this.id,\n isEncrypted: !!summaryData.encryption,\n isDirectMessage: summaryData.isDirectMessage,\n// type: \n name,\n avatarUrl,\n avatarColorId,\n canonicalAlias: summaryData.canonicalAlias,\n timestamp: this._platform.clock.now(),\n joinRule: this._getJoinRule(inviteState),\n inviter: inviter?.serialize(),\n };\n }\n\n _createSummaryData(inviteState) {\n return inviteState.reduce((data, event) => processStateEvent(data, event, this._user.id), new SummaryData(null, this.id));\n }\n\n async _createHeroes(inviteState, log) {\n const members = inviteState.filter(e => e.type === MEMBER_EVENT_TYPE);\n const otherMembers = members.filter(e => e.state_key !== this._user.id);\n const memberChanges = otherMembers.reduce((map, e) => {\n const member = RoomMember.fromMemberEvent(this.id, e);\n map.set(member.userId, new MemberChange(member, null));\n return map;\n }, new Map());\n const otherUserIds = otherMembers.map(e => e.state_key);\n const heroes = new Heroes(this.id);\n const changes = await heroes.calculateChanges(otherUserIds, memberChanges, null);\n // we don't get an actual lazy-loading m.heroes summary on invites,\n // so just count the members by hand\n const countSummary = new SummaryData(null, this.id);\n countSummary.joinCount = members.reduce((sum, e) => sum + (e.content?.membership === \"join\" ? 1 : 0), 0);\n countSummary.inviteCount = members.reduce((sum, e) => sum + (e.content?.membership === \"invite\" ? 1 : 0), 0);\n heroes.applyChanges(changes, countSummary, log);\n return heroes;\n }\n\n _getMyInvite(inviteState) {\n return inviteState.find(e => e.type === MEMBER_EVENT_TYPE && e.state_key === this._user.id);\n }\n\n _getInviter(myInvite, inviteState) {\n const inviterMemberEvent = inviteState.find(e => e.type === MEMBER_EVENT_TYPE && e.state_key === myInvite.sender);\n if (inviterMemberEvent) {\n return RoomMember.fromMemberEvent(this.id, inviterMemberEvent);\n }\n }\n\n _getJoinRule(inviteState) {\n const event = inviteState.find(e => e.type === \"m.room.join_rules\");\n if (event) {\n return event.content?.join_rule;\n }\n return null;\n }\n}\n\nimport {NullLogItem} from \"../../logging/NullLogger\";\nimport {Clock as MockClock} from \"../../mocks/Clock.js\";\nimport {default as roomInviteFixture} from \"../../fixtures/matrix/invites/room.js\";\nimport {default as dmInviteFixture} from \"../../fixtures/matrix/invites/dm.js\";\n\nexport function tests() {\n\n function createStorage() {\n const invitesMap = new Map();\n return {\n invitesMap,\n invites: {\n set(invite) {\n invitesMap.set(invite.roomId, invite);\n },\n remove(roomId) {\n invitesMap.delete(roomId);\n }\n }\n }\n }\n\n const roomId = \"!123:hs.tld\";\n const aliceAvatarUrl = \"mxc://hs.tld/def456\";\n const roomAvatarUrl = \"mxc://hs.tld/roomavatar\";\n\n return {\n \"invite for room has correct fields\": async assert => {\n const invite = new Invite({\n roomId,\n platform: {clock: new MockClock(1001)},\n user: {id: \"@bob:hs.tld\"}\n });\n const txn = createStorage();\n const changes = await invite.writeSync(\"invite\", roomInviteFixture, txn, new NullLogItem());\n assert.equal(txn.invitesMap.get(roomId).roomId, roomId);\n invite.afterSync(changes, new NullLogItem());\n assert.equal(invite.name, \"Invite example\");\n assert.equal(invite.avatarUrl, roomAvatarUrl);\n assert.equal(invite.isPublic, false);\n assert.equal(invite.timestamp, 1001);\n assert.equal(invite.isEncrypted, false);\n assert.equal(invite.isDirectMessage, false);\n assert(invite.inviter);\n assert.equal(invite.inviter.userId, \"@alice:hs.tld\");\n assert.equal(invite.inviter.displayName, \"Alice\");\n assert.equal(invite.inviter.avatarUrl, aliceAvatarUrl);\n },\n \"invite for encrypted DM has correct fields\": async assert => {\n const invite = new Invite({\n roomId,\n platform: {clock: new MockClock(1003)},\n user: {id: \"@bob:hs.tld\"}\n });\n const txn = createStorage();\n const changes = await invite.writeSync(\"invite\", dmInviteFixture, txn, new NullLogItem());\n assert.equal(txn.invitesMap.get(roomId).roomId, roomId);\n invite.afterSync(changes, new NullLogItem());\n assert.equal(invite.name, \"Alice\");\n assert.equal(invite.avatarUrl, aliceAvatarUrl);\n assert.equal(invite.timestamp, 1003);\n assert.equal(invite.isEncrypted, true);\n assert.equal(invite.isDirectMessage, true);\n assert(invite.inviter);\n assert.equal(invite.inviter.userId, \"@alice:hs.tld\");\n assert.equal(invite.inviter.displayName, \"Alice\");\n assert.equal(invite.inviter.avatarUrl, aliceAvatarUrl);\n },\n \"load persisted invite has correct fields\": async assert => {\n const writeInvite = new Invite({\n roomId,\n platform: {clock: new MockClock(1003)},\n user: {id: \"@bob:hs.tld\"}\n });\n const txn = createStorage();\n await writeInvite.writeSync(\"invite\", dmInviteFixture, txn, new NullLogItem());\n const invite = new Invite({roomId});\n invite.load(txn.invitesMap.get(roomId), new NullLogItem());\n assert.equal(invite.name, \"Alice\");\n assert.equal(invite.avatarUrl, aliceAvatarUrl);\n assert.equal(invite.timestamp, 1003);\n assert.equal(invite.isEncrypted, true);\n assert.equal(invite.isDirectMessage, true);\n assert(invite.inviter);\n assert.equal(invite.inviter.userId, \"@alice:hs.tld\");\n assert.equal(invite.inviter.displayName, \"Alice\");\n assert.equal(invite.inviter.avatarUrl, aliceAvatarUrl);\n },\n \"syncing join sets accepted\": async assert => {\n let changeEmitCount = 0;\n const invite = new Invite({\n roomId,\n platform: {clock: new MockClock(1003)},\n user: {id: \"@bob:hs.tld\"},\n });\n invite.on(\"change\", () => { changeEmitCount += 1; });\n const txn = createStorage();\n const changes = await invite.writeSync(\"invite\", dmInviteFixture, txn, new NullLogItem());\n assert.equal(txn.invitesMap.get(roomId).roomId, roomId);\n invite.afterSync(changes, new NullLogItem());\n const joinChanges = await invite.writeSync(\"join\", null, txn, new NullLogItem());\n assert.strictEqual(changeEmitCount, 0);\n invite.afterSync(joinChanges, new NullLogItem());\n assert.strictEqual(changeEmitCount, 1);\n assert.equal(txn.invitesMap.get(roomId), undefined);\n assert.equal(invite.rejected, false);\n assert.equal(invite.accepted, true);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {HomeServerApi} from \"../net/HomeServerApi.js\";\nimport type {ILogItem} from \"../../logging/types\";\n\nexport interface IPusherDescription {\n kind: \"http\" | \"email\" | \"null\";\n lang: string;\n device_display_name: string;\n app_display_name: string;\n app_id: string;\n pushkey: string;\n data: IPusherData;\n append?: boolean;\n profile_tag?: string;\n}\n\ninterface IPusherData {\n format?: string;\n url?: string;\n endpoint?: PushSubscriptionJSON[\"endpoint\"];\n keys?: PushSubscriptionJSON[\"keys\"];\n}\n\nexport class Pusher {\n private readonly _description: IPusherDescription;\n\n constructor(description: IPusherDescription) {\n this._description = description;\n }\n\n static httpPusher(host: string, appId: string, pushkey: string, data: IPusherData): Pusher {\n return new Pusher({\n kind: \"http\",\n append: true, // as pushkeys are shared between multiple users on one origin\n data: Object.assign({}, data, {url: host + \"/_matrix/push/v1/notify\"}),\n pushkey,\n app_id: appId,\n app_display_name: \"Hydrogen\",\n device_display_name: \"Hydrogen\",\n lang: \"en\"\n });\n }\n\n static createDefaultPayload(sessionId: string): {session_id: string} {\n return {session_id: sessionId};\n }\n\n async enable(hsApi: HomeServerApi, log: ILogItem): Promise {\n try {\n log.set(\"endpoint\", new URL(this._description.data.endpoint!).host);\n } catch {\n log.set(\"endpoint\", null);\n }\n await hsApi.setPusher(this._description, {log}).response();\n }\n\n async disable(hsApi: HomeServerApi, log: ILogItem): Promise {\n const deleteDescription = Object.assign({}, this._description, {kind: null});\n await hsApi.setPusher(deleteDescription, {log}).response();\n }\n\n serialize(): IPusherDescription {\n return this._description;\n }\n\n equals(pusher): boolean {\n if (this._description.app_id !== pusher._description.app_id) {\n return false;\n }\n if (this._description.pushkey !== pusher._description.pushkey) {\n return false;\n }\n return JSON.stringify(this._description.data) === JSON.stringify(pusher._description.data);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function groupBy(array: V[], groupFn: (V) => K): Map {\n return groupByWithCreator(array, groupFn,\n () => {return [];},\n (array, value) => array.push(value)\n );\n}\n\nexport function groupByWithCreator(array: V[], groupFn: (V) => K, createCollectionFn: () => C, addCollectionFn: (C, V) => void): Map {\n return array.reduce((map, value) => {\n const key = groupFn(value);\n let collection = map.get(key);\n if (!collection) {\n collection = createCollectionFn();\n map.set(key, collection);\n }\n addCollectionFn(collection, value);\n return map;\n }, new Map());\n}\n\nexport function countBy(events: V[], mapper: (V) => string | number): { [key: string]: number } {\n return events.reduce((counts, event) => {\n const mappedValue = mapper(event);\n if (!counts[mappedValue]) {\n counts[mappedValue] = 1;\n } else {\n counts[mappedValue] += 1;\n }\n return counts;\n }, {});\n}\n\nexport function tests() {\n return {\n countBy: assert => {\n const counts = countBy([{type: \"foo\"}, {type: \"bar\"}, {type: \"foo\"}], o => o.type);\n assert.equal(Object.keys(counts).length, 2);\n assert.equal(counts.foo, 2);\n assert.equal(counts.bar, 1);\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {OLM_ALGORITHM} from \"./e2ee/common.js\";\nimport {countBy, groupBy} from \"../utils/groupBy\";\n\nexport class DeviceMessageHandler {\n constructor({storage}) {\n this._storage = storage;\n this._olmDecryption = null;\n this._megolmDecryption = null;\n }\n\n enableEncryption({olmDecryption, megolmDecryption}) {\n this._olmDecryption = olmDecryption;\n this._megolmDecryption = megolmDecryption;\n }\n\n obtainSyncLock(toDeviceEvents) {\n return this._olmDecryption?.obtainDecryptionLock(toDeviceEvents);\n }\n\n async prepareSync(toDeviceEvents, lock, txn, log) {\n log.set(\"messageTypes\", countBy(toDeviceEvents, e => e.type));\n const encryptedEvents = toDeviceEvents.filter(e => e.type === \"m.room.encrypted\");\n if (!this._olmDecryption) {\n log.log(\"can't decrypt, encryption not enabled\", log.level.Warn);\n return;\n }\n // only know olm for now\n const olmEvents = encryptedEvents.filter(e => e.content?.algorithm === OLM_ALGORITHM);\n if (olmEvents.length) {\n const olmDecryptChanges = await this._olmDecryption.decryptAll(olmEvents, lock, txn);\n log.set(\"decryptedTypes\", countBy(olmDecryptChanges.results, r => r.event?.type));\n for (const err of olmDecryptChanges.errors) {\n log.child(\"decrypt_error\").catch(err);\n }\n const newRoomKeys = this._megolmDecryption.roomKeysFromDeviceMessages(olmDecryptChanges.results, log);\n return new SyncPreparation(olmDecryptChanges, newRoomKeys);\n }\n }\n\n /** check that prep is not undefined before calling this */\n async writeSync(prep, txn) {\n // write olm changes\n prep.olmDecryptChanges.write(txn);\n const didWriteValues = await Promise.all(prep.newRoomKeys.map(key => this._megolmDecryption.writeRoomKey(key, txn)));\n return didWriteValues.some(didWrite => !!didWrite);\n }\n}\n\nclass SyncPreparation {\n constructor(olmDecryptChanges, newRoomKeys) {\n this.olmDecryptChanges = olmDecryptChanges;\n this.newRoomKeys = newRoomKeys;\n this.newKeysByRoom = groupBy(newRoomKeys, r => r.roomId);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport anotherjson from \"another-json\";\nimport {SESSION_E2EE_KEY_PREFIX, OLM_ALGORITHM, MEGOLM_ALGORITHM} from \"./common.js\";\n\n// use common prefix so it's easy to clear properties that are not e2ee related during session clear\nconst ACCOUNT_SESSION_KEY = SESSION_E2EE_KEY_PREFIX + \"olmAccount\";\nconst DEVICE_KEY_FLAG_SESSION_KEY = SESSION_E2EE_KEY_PREFIX + \"areDeviceKeysUploaded\";\nconst SERVER_OTK_COUNT_SESSION_KEY = SESSION_E2EE_KEY_PREFIX + \"serverOTKCount\";\n\nasync function initiallyStoreAccount(account, pickleKey, areDeviceKeysUploaded, serverOTKCount, storage) {\n const pickledAccount = account.pickle(pickleKey);\n const txn = await storage.readWriteTxn([\n storage.storeNames.session\n ]);\n try {\n // add will throw if the key already exists\n // we would not want to overwrite olmAccount here\n txn.session.add(ACCOUNT_SESSION_KEY, pickledAccount);\n txn.session.add(DEVICE_KEY_FLAG_SESSION_KEY, areDeviceKeysUploaded);\n txn.session.add(SERVER_OTK_COUNT_SESSION_KEY, serverOTKCount);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n}\n\nexport class Account {\n static async load({olm, pickleKey, hsApi, userId, deviceId, olmWorker, txn}) {\n const pickledAccount = await txn.session.get(ACCOUNT_SESSION_KEY);\n if (pickledAccount) {\n const account = new olm.Account();\n const areDeviceKeysUploaded = await txn.session.get(DEVICE_KEY_FLAG_SESSION_KEY);\n account.unpickle(pickleKey, pickledAccount);\n const serverOTKCount = await txn.session.get(SERVER_OTK_COUNT_SESSION_KEY);\n return new Account({pickleKey, hsApi, account, userId,\n deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker});\n }\n }\n\n static async adoptDehydratedDevice({olm, dehydratedDevice, pickleKey, hsApi, userId, olmWorker, storage}) {\n const account = dehydratedDevice.adoptUnpickledOlmAccount();\n const oneTimeKeys = JSON.parse(account.one_time_keys());\n // only one algorithm supported by olm atm, so hardcode its name\n const oneTimeKeysEntries = Object.entries(oneTimeKeys.curve25519);\n const serverOTKCount = oneTimeKeysEntries.length;\n const areDeviceKeysUploaded = true;\n await initiallyStoreAccount(account, pickleKey, areDeviceKeysUploaded, serverOTKCount, storage);\n return new Account({\n pickleKey, hsApi, account, userId,\n deviceId: dehydratedDevice.deviceId,\n areDeviceKeysUploaded, serverOTKCount, olm, olmWorker\n });\n }\n\n static async create({olm, pickleKey, hsApi, userId, deviceId, olmWorker, storage}) {\n const account = new olm.Account();\n if (olmWorker) {\n await olmWorker.createAccountAndOTKs(account, account.max_number_of_one_time_keys());\n } else {\n account.create();\n account.generate_one_time_keys(account.max_number_of_one_time_keys());\n }\n const areDeviceKeysUploaded = false;\n const serverOTKCount = 0;\n if (storage) {\n await initiallyStoreAccount(account, pickleKey, areDeviceKeysUploaded, serverOTKCount, storage);\n }\n return new Account({pickleKey, hsApi, account, userId,\n deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker});\n }\n\n constructor({pickleKey, hsApi, account, userId, deviceId, areDeviceKeysUploaded, serverOTKCount, olm, olmWorker}) {\n this._olm = olm;\n this._pickleKey = pickleKey;\n this._hsApi = hsApi;\n this._account = account;\n this._userId = userId;\n this._deviceId = deviceId;\n this._areDeviceKeysUploaded = areDeviceKeysUploaded;\n this._serverOTKCount = serverOTKCount;\n this._olmWorker = olmWorker;\n this._identityKeys = JSON.parse(this._account.identity_keys());\n }\n\n get identityKeys() {\n return this._identityKeys;\n }\n\n setDeviceId(deviceId) {\n this._deviceId = deviceId;\n }\n\n async uploadKeys(storage, isDehydratedDevice, log) {\n const oneTimeKeys = JSON.parse(this._account.one_time_keys());\n // only one algorithm supported by olm atm, so hardcode its name\n const oneTimeKeysEntries = Object.entries(oneTimeKeys.curve25519);\n if (oneTimeKeysEntries.length || !this._areDeviceKeysUploaded) {\n const payload = {};\n if (!this._areDeviceKeysUploaded) {\n log.set(\"identity\", true);\n const identityKeys = JSON.parse(this._account.identity_keys());\n payload.device_keys = this._deviceKeysPayload(identityKeys);\n }\n if (oneTimeKeysEntries.length) {\n log.set(\"otks\", true);\n payload.one_time_keys = this._oneTimeKeysPayload(oneTimeKeysEntries);\n }\n const dehydratedDeviceId = isDehydratedDevice ? this._deviceId : undefined;\n const response = await this._hsApi.uploadKeys(dehydratedDeviceId, payload, {log}).response();\n this._serverOTKCount = response?.one_time_key_counts?.signed_curve25519;\n log.set(\"serverOTKCount\", this._serverOTKCount);\n // TODO: should we not modify this in the txn like we do elsewhere?\n // we'd have to pickle and unpickle the account to clone it though ...\n // and the upload has succeed at this point, so in-memory would be correct\n // but in-storage not if the txn fails. \n await this._updateSessionStorage(storage, sessionStore => {\n if (oneTimeKeysEntries.length) {\n this._account.mark_keys_as_published();\n sessionStore?.set(ACCOUNT_SESSION_KEY, this._account.pickle(this._pickleKey));\n sessionStore?.set(SERVER_OTK_COUNT_SESSION_KEY, this._serverOTKCount);\n }\n if (!this._areDeviceKeysUploaded) {\n this._areDeviceKeysUploaded = true;\n sessionStore?.set(DEVICE_KEY_FLAG_SESSION_KEY, this._areDeviceKeysUploaded);\n }\n });\n }\n }\n\n async generateOTKsIfNeeded(storage, log) {\n // We need to keep a pool of one time public keys on the server so that\n // other devices can start conversations with us. But we can only store\n // a finite number of private keys in the olm Account object.\n // To complicate things further there can be a delay between a device\n // claiming a public one time key from the server and it sending us a\n // message. We need to keep the corresponding private key locally until\n // we receive the message.\n // But that message might never arrive leaving us stuck with duff\n // private keys clogging up our local storage.\n // So we need some kind of engineering compromise to balance all of\n // these factors.\n \n // Check how many keys we can store in the Account object.\n const maxOTKs = this._account.max_number_of_one_time_keys();\n // Try to keep at most half that number on the server. This leaves the\n // rest of the slots free to hold keys that have been claimed from the\n // server but we haven't recevied a message for.\n // If we run out of slots when generating new keys then olm will\n // discard the oldest private keys first. This will eventually clean\n // out stale private keys that won't receive a message.\n const keyLimit = Math.floor(maxOTKs / 2);\n // does the server have insufficient OTKs?\n if (this._serverOTKCount < keyLimit) {\n const oneTimeKeys = JSON.parse(this._account.one_time_keys());\n const oneTimeKeysEntries = Object.entries(oneTimeKeys.curve25519);\n const unpublishedOTKCount = oneTimeKeysEntries.length;\n // we want to end up with maxOTKs / 2 key on the server,\n // so generate any on top of the remaining ones on the server and the unpublished ones\n // (we have generated before but haven't uploaded yet for some reason)\n // to get to that number.\n const newKeyCount = keyLimit - unpublishedOTKCount - this._serverOTKCount;\n if (newKeyCount > 0) {\n await log.wrap(\"generate otks\", log => {\n log.set(\"max\", maxOTKs);\n log.set(\"server\", this._serverOTKCount);\n log.set(\"unpublished\", unpublishedOTKCount);\n log.set(\"new\", newKeyCount);\n log.set(\"limit\", keyLimit);\n this._account.generate_one_time_keys(newKeyCount);\n this._updateSessionStorage(storage, sessionStore => {\n sessionStore.set(ACCOUNT_SESSION_KEY, this._account.pickle(this._pickleKey));\n });\n });\n }\n // even though we didn't generate any keys, we still have some unpublished ones that should be published\n return true;\n }\n return false;\n }\n\n createInboundOlmSession(senderKey, body) {\n const newSession = new this._olm.Session();\n try {\n newSession.create_inbound_from(this._account, senderKey, body);\n return newSession;\n } catch (err) {\n newSession.free();\n throw err;\n }\n }\n\n async createOutboundOlmSession(theirIdentityKey, theirOneTimeKey) {\n const newSession = new this._olm.Session();\n try {\n if (this._olmWorker) {\n await this._olmWorker.createOutboundOlmSession(this._account, newSession, theirIdentityKey, theirOneTimeKey);\n } else {\n newSession.create_outbound(this._account, theirIdentityKey, theirOneTimeKey);\n }\n return newSession;\n } catch (err) {\n newSession.free();\n throw err;\n }\n }\n\n writeRemoveOneTimeKey(session, txn) {\n // this is side-effecty and will have applied the change if the txn fails,\n // but don't want to clone the account for now\n // and it is not the worst thing to think we have used a OTK when\n // decrypting the message that actually used it threw for some reason.\n this._account.remove_one_time_keys(session);\n txn.session.set(ACCOUNT_SESSION_KEY, this._account.pickle(this._pickleKey));\n }\n\n writeSync(deviceOneTimeKeysCount, txn, log) {\n // we only upload signed_curve25519 otks\n const otkCount = deviceOneTimeKeysCount.signed_curve25519;\n if (Number.isSafeInteger(otkCount) && otkCount !== this._serverOTKCount) {\n txn.session.set(SERVER_OTK_COUNT_SESSION_KEY, otkCount);\n log.set(\"otkCount\", otkCount);\n return otkCount;\n }\n }\n\n afterSync(otkCount) {\n // could also be undefined\n if (Number.isSafeInteger(otkCount)) {\n this._serverOTKCount = otkCount;\n }\n }\n\n _deviceKeysPayload(identityKeys) {\n const obj = {\n user_id: this._userId,\n device_id: this._deviceId,\n algorithms: [OLM_ALGORITHM, MEGOLM_ALGORITHM],\n keys: {}\n };\n for (const [algorithm, pubKey] of Object.entries(identityKeys)) {\n obj.keys[`${algorithm}:${this._deviceId}`] = pubKey;\n }\n this.signObject(obj);\n return obj;\n }\n\n _oneTimeKeysPayload(oneTimeKeysEntries) {\n const obj = {};\n for (const [keyId, pubKey] of oneTimeKeysEntries) {\n const keyObj = {\n key: pubKey \n };\n this.signObject(keyObj);\n obj[`signed_curve25519:${keyId}`] = keyObj;\n }\n return obj;\n }\n\n async _updateSessionStorage(storage, callback) {\n if (storage) {\n const txn = await storage.readWriteTxn([\n storage.storeNames.session\n ]);\n try {\n await callback(txn.session);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n } else {\n await callback(undefined);\n }\n }\n\n signObject(obj) {\n const sigs = obj.signatures || {};\n const unsigned = obj.unsigned;\n\n delete obj.signatures;\n delete obj.unsigned;\n\n sigs[this._userId] = sigs[this._userId] || {};\n sigs[this._userId][\"ed25519:\" + this._deviceId] = \n this._account.sign(anotherjson.stringify(obj));\n obj.signatures = sigs;\n if (unsigned !== undefined) {\n obj.unsigned = unsigned;\n }\n }\n\n pickleWithKey(key) {\n return this._account.pickle(key);\n }\n\n dispose() {\n this._account.free();\n this._account = undefined;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {Platform} from \"../../platform/web/Platform.js\";\n\nexport type KeyDescriptionData = {\n algorithm: string;\n passphrase: {\n algorithm: string;\n iterations: number;\n salt: string;\n bits?: number;\n };\n mac: string;\n iv: string;\n}\n\nexport class KeyDescription {\n private readonly _id: string;\n private readonly _keyDescription: KeyDescriptionData;\n\n constructor(id: string, keyDescription: KeyDescriptionData) {\n this._id = id;\n this._keyDescription = keyDescription;\n }\n\n get id(): string {\n return this._id;\n }\n\n get passphraseParams(): KeyDescriptionData[\"passphrase\"] {\n return this._keyDescription?.passphrase;\n }\n\n get algorithm(): string {\n return this._keyDescription?.algorithm;\n }\n\n async isCompatible(key: Key, platform: Platform): Promise {\n if (this.algorithm === \"m.secret_storage.v1.aes-hmac-sha2\") {\n const kd = this._keyDescription;\n if (kd.mac) {\n const otherMac = await calculateKeyMac(key.binaryKey, kd.iv, platform);\n return kd.mac === otherMac;\n } else if (kd.passphrase) {\n const kdOther = key.description._keyDescription;\n if (!kdOther.passphrase) {\n return false;\n }\n return kd.passphrase.algorithm === kdOther.passphrase.algorithm && \n kd.passphrase.iterations === kdOther.passphrase.iterations && \n kd.passphrase.salt === kdOther.passphrase.salt;\n }\n }\n return false;\n }\n}\n\nexport class Key {\n private readonly _keyDescription: KeyDescription;\n private readonly _binaryKey: Uint8Array;\n\n constructor(keyDescription: KeyDescription, binaryKey: Uint8Array) {\n this._keyDescription = keyDescription;\n this._binaryKey = binaryKey;\n }\n\n withDescription(description: KeyDescription): Key {\n return new Key(description, this._binaryKey);\n }\n\n get description(): KeyDescription {\n return this._keyDescription;\n }\n\n get id(): string {\n return this._keyDescription.id;\n }\n\n get binaryKey(): Uint8Array {\n return this._binaryKey;\n }\n\n get algorithm(): string {\n return this._keyDescription.algorithm;\n }\n}\n\nasync function calculateKeyMac(key: BufferSource, ivStr: string, platform: Platform): Promise {\n const {crypto, encoding} = platform;\n const {utf8, base64} = encoding;\n const {derive, aes, hmac} = crypto;\n\n const iv = base64.decode(ivStr);\n\n // salt for HKDF, with 8 bytes of zeros\n const zerosalt = new Uint8Array(8);\n const ZERO_STR = \"\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\\0\";\n \n const info = utf8.encode(\"\");\n const keybits = await derive.hkdf(key, zerosalt, info, \"SHA-256\", 512);\n const aesKey = keybits.slice(0, 32);\n const hmacKey = keybits.slice(32);\n const ciphertext = await aes.encryptCTR({key: aesKey, iv, data: utf8.encode(ZERO_STR)});\n const mac = await hmac.compute(hmacKey, ciphertext, \"SHA-256\");\n\n return base64.encode(mac);\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Key} from \"./common\";\nimport type {KeyDescription} from \"./common\";\nimport type {Platform} from \"../../platform/web/Platform.js\";\n\nconst DEFAULT_ITERATIONS = 500000;\nconst DEFAULT_BITSIZE = 256;\n\n/**\n * @param {KeyDescription} keyDescription\n * @param {string} passphrase\n * @param {Platform} platform\n * @return {Key}\n */\nexport async function keyFromPassphrase(keyDescription: KeyDescription, passphrase: string, platform: Platform): Promise {\n const {passphraseParams} = keyDescription;\n if (!passphraseParams) {\n throw new Error(\"not a passphrase key\");\n }\n if (passphraseParams.algorithm !== \"m.pbkdf2\") {\n throw new Error(`Unsupported passphrase algorithm: ${passphraseParams.algorithm}`);\n }\n const {utf8} = platform.encoding;\n const keyBits = await platform.crypto.derive.pbkdf2(\n utf8.encode(passphrase),\n passphraseParams.iterations || DEFAULT_ITERATIONS,\n // salt is just a random string, not encoded in any way\n utf8.encode(passphraseParams.salt),\n \"SHA-512\",\n passphraseParams.bits || DEFAULT_BITSIZE);\n return new Key(keyDescription, keyBits);\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {Key} from \"./common\";\nimport {KeyDescription} from \"./common\";\nimport type {Platform} from \"../../platform/web/Platform.js\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nconst OLM_RECOVERY_KEY_PREFIX = [0x8B, 0x01] as const;\n\n/**\n * @param {Olm} olm\n * @param {KeyDescription} keyDescription\n * @param {string} recoveryKey\n * @return {Key}\n */\nexport function keyFromRecoveryKey(keyDescription: KeyDescription, recoveryKey: string, olm: Olm, platform: Platform): Key {\n const result = platform.encoding.base58.decode(recoveryKey.replace(/ /g, ''));\n\n let parity = 0;\n for (const b of result) {\n parity ^= b;\n }\n if (parity !== 0) {\n throw new Error(\"Incorrect parity\");\n }\n\n for (let i = 0; i < OLM_RECOVERY_KEY_PREFIX.length; ++i) {\n if (result[i] !== OLM_RECOVERY_KEY_PREFIX[i]) {\n throw new Error(\"Incorrect prefix\");\n }\n }\n\n if (\n result.length !==\n OLM_RECOVERY_KEY_PREFIX.length + olm.PRIVATE_KEY_LENGTH + 1\n ) {\n throw new Error(\"Incorrect length\");\n }\n\n const keyBits = Uint8Array.from(result.slice(\n OLM_RECOVERY_KEY_PREFIX.length,\n OLM_RECOVERY_KEY_PREFIX.length + olm.PRIVATE_KEY_LENGTH,\n ));\n\n return new Key(keyDescription, keyBits);\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {KeyDescription, Key} from \"./common\";\nimport {keyFromPassphrase} from \"./passphrase\";\nimport {keyFromRecoveryKey} from \"./recoveryKey\";\nimport {SESSION_E2EE_KEY_PREFIX} from \"../e2ee/common.js\";\nimport type {Storage} from \"../storage/idb/Storage\";\nimport type {Transaction} from \"../storage/idb/Transaction\";\nimport type {KeyDescriptionData} from \"./common\";\nimport type {Platform} from \"../../platform/web/Platform.js\";\nimport type * as OlmNamespace from \"@matrix-org/olm\"\n\ntype Olm = typeof OlmNamespace;\n\nconst SSSS_KEY = `${SESSION_E2EE_KEY_PREFIX}ssssKey`;\nconst BACKUPVERSION_KEY = `${SESSION_E2EE_KEY_PREFIX}keyBackupVersion`;\n\nexport enum KeyType {\n \"RecoveryKey\",\n \"Passphrase\"\n}\n\nasync function readDefaultKeyDescription(storage: Storage): Promise {\n const txn = await storage.readTxn([\n storage.storeNames.accountData\n ]);\n const defaultKeyEvent = await txn.accountData.get(\"m.secret_storage.default_key\");\n const id = defaultKeyEvent?.content?.key;\n if (!id) {\n return;\n }\n const keyAccountData = await txn.accountData.get(`m.secret_storage.key.${id}`);\n if (!keyAccountData) {\n return;\n }\n return new KeyDescription(id, keyAccountData.content as KeyDescriptionData);\n}\n\nexport async function writeKey(key: Key, keyBackupVersion: number, txn: Transaction): Promise {\n const existingVersion: number | undefined = await txn.session.get(BACKUPVERSION_KEY);\n txn.session.set(BACKUPVERSION_KEY, keyBackupVersion);\n txn.session.set(SSSS_KEY, {id: key.id, binaryKey: key.binaryKey});\n return existingVersion;\n}\n\nexport async function readKey(txn: Transaction): Promise {\n const keyData = await txn.session.get(SSSS_KEY);\n if (!keyData) {\n return;\n }\n const keyAccountData = await txn.accountData.get(`m.secret_storage.key.${keyData.id}`);\n if (keyAccountData) {\n return new Key(new KeyDescription(keyData.id, keyAccountData.content as KeyDescriptionData), keyData.binaryKey);\n }\n}\n\n\nexport async function removeKey(txn: Transaction): Promise {\n txn.session.remove(SSSS_KEY);\n}\n\nexport async function keyFromCredential(type: KeyType, credential: string, storage: Storage, platform: Platform, olm: Olm): Promise {\n const keyDescription = await readDefaultKeyDescription(storage);\n if (!keyDescription) {\n throw new Error(\"Could not find a default secret storage key in account data\");\n }\n return await keyFromCredentialAndDescription(type, credential, keyDescription, platform, olm);\n}\n\nexport async function keyFromCredentialAndDescription(type: KeyType, credential: string, keyDescription: KeyDescription, platform: Platform, olm: Olm): Promise {\n let key: Key;\n if (type === KeyType.Passphrase) {\n key = await keyFromPassphrase(keyDescription, credential, platform);\n } else if (type === KeyType.RecoveryKey) {\n key = keyFromRecoveryKey(keyDescription, credential, olm, platform);\n } else {\n throw new Error(`Invalid type: ${type}`);\n }\n return key;\n}\n\nexport async function keyFromDehydratedDeviceKey(key: Key, storage: Storage, platform: Platform): Promise {\n const keyDescription = await readDefaultKeyDescription(storage);\n if (await keyDescription?.isCompatible(key, platform)) {\n return key.withDescription(keyDescription!);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nconst DEHYDRATION_LIBOLM_PICKLE_ALGORITHM = \"org.matrix.msc2697.v1.olm.libolm_pickle\"; \nimport {KeyDescription} from \"../ssss/common\";\nimport {keyFromCredentialAndDescription} from \"../ssss/index\";\n\nexport async function getDehydratedDevice(hsApi, olm, platform, log) {\n try {\n const response = await hsApi.getDehydratedDevice({log}).response();\n if (response.device_data.algorithm === DEHYDRATION_LIBOLM_PICKLE_ALGORITHM) {\n return new EncryptedDehydratedDevice(response, olm, platform);\n }\n } catch (err) {\n if (err.name !== \"HomeServerError\") {\n log.error = err;\n }\n return undefined;\n }\n}\n\nexport async function uploadAccountAsDehydratedDevice(account, hsApi, key, deviceDisplayName, log) {\n const response = await hsApi.createDehydratedDevice({\n device_data: {\n algorithm: DEHYDRATION_LIBOLM_PICKLE_ALGORITHM,\n account: account.pickleWithKey(key.binaryKey.slice()),\n passphrase: key.description?.passphraseParams || {},\n },\n initial_device_display_name: deviceDisplayName\n }).response();\n const deviceId = response.device_id;\n account.setDeviceId(deviceId);\n await account.uploadKeys(undefined, true, log);\n return deviceId;\n}\n\nclass EncryptedDehydratedDevice {\n constructor(dehydratedDevice, olm, platform) {\n this._dehydratedDevice = dehydratedDevice;\n this._olm = olm;\n this._platform = platform;\n }\n\n async decrypt(keyType, credential) {\n const keyDescription = new KeyDescription(\"dehydrated_device\", this._dehydratedDevice.device_data.passphrase);\n const key = await keyFromCredentialAndDescription(keyType, credential, keyDescription, this._platform, this._olm);\n const account = new this._olm.Account();\n try {\n const pickledAccount = this._dehydratedDevice.device_data.account;\n account.unpickle(key.binaryKey.slice(), pickledAccount);\n return new DehydratedDevice(this._dehydratedDevice, account, key);\n } catch (err) {\n account.free();\n if (err.message === \"OLM.BAD_ACCOUNT_KEY\") {\n return undefined;\n } else {\n throw err;\n }\n }\n }\n\n get deviceId() {\n return this._dehydratedDevice.device_id;\n }\n}\n\nclass DehydratedDevice {\n constructor(dehydratedDevice, account, key) {\n this._dehydratedDevice = dehydratedDevice;\n this._account = account;\n this._key = key;\n }\n\n async claim(hsApi, log) {\n try {\n const response = await hsApi.claimDehydratedDevice(this.deviceId, {log}).response();\n return response.success;\n } catch (err) {\n return false;\n }\n }\n\n // make it clear that ownership is transfered upon calling this\n adoptUnpickledOlmAccount() {\n const account = this._account;\n this._account = undefined;\n return account;\n }\n\n get deviceId() {\n return this._dehydratedDevice.device_id;\n }\n\n get key() {\n return this._key;\n }\n\n dispose() {\n this._account?.free();\n this._account = undefined;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport interface ILock {\n release(): void;\n}\n\nexport class Lock implements ILock {\n private _promise?: Promise;\n private _resolve?: (() => void);\n\n tryTake(): boolean {\n if (!this._promise) {\n this._promise = new Promise(resolve => {\n this._resolve = resolve;\n });\n return true;\n }\n return false;\n }\n\n async take(): Promise {\n while(!this.tryTake()) {\n await this.released();\n }\n }\n\n get isTaken(): boolean {\n return !!this._promise;\n }\n\n release(): void {\n if (this._resolve) {\n this._promise = undefined;\n const resolve = this._resolve;\n this._resolve = undefined;\n resolve();\n }\n }\n\n released(): Promise | undefined {\n return this._promise;\n }\n}\n\nexport class MultiLock implements ILock {\n\n constructor(public readonly locks: Lock[]) {\n }\n\n release(): void {\n for (const lock of this.locks) {\n lock.release();\n }\n }\n}\n\nexport function tests() {\n return {\n \"taking a lock twice returns false\": assert => {\n const lock = new Lock();\n assert.equal(lock.tryTake(), true);\n assert.equal(lock.isTaken, true);\n assert.equal(lock.tryTake(), false);\n },\n \"can take a released lock again\": assert => {\n const lock = new Lock();\n lock.tryTake();\n lock.release();\n assert.equal(lock.isTaken, false);\n assert.equal(lock.tryTake(), true);\n },\n \"2 waiting for lock, only first one gets it\": async assert => {\n const lock = new Lock();\n lock.tryTake();\n\n let first;\n lock.released()!.then(() => first = lock.tryTake());\n let second;\n lock.released()!.then(() => second = lock.tryTake());\n const promise = lock.released();\n lock.release();\n await promise;\n assert.strictEqual(first, true);\n assert.strictEqual(second, false);\n },\n \"await non-taken lock\": async assert => {\n const lock = new Lock();\n await lock.released();\n assert(true);\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {OlmSessionEntry} from \"../../storage/idb/stores/OlmSessionStore\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nexport function createSessionEntry(olmSession: Olm.Session, senderKey: string, timestamp: number, pickleKey: string): OlmSessionEntry {\n return {\n session: olmSession.pickle(pickleKey),\n sessionId: olmSession.session_id(),\n senderKey,\n lastUsed: timestamp,\n };\n}\n\nexport class Session {\n public isModified: boolean;\n\n constructor(\n public readonly data: OlmSessionEntry,\n private readonly pickleKey: string,\n private readonly olm: Olm,\n public isNew: boolean = false\n ) {\n this.isModified = isNew;\n }\n\n static create(senderKey: string, olmSession: Olm.Session, olm: Olm, pickleKey: string, timestamp: number): Session {\n const data = createSessionEntry(olmSession, senderKey, timestamp, pickleKey);\n return new Session(data, pickleKey, olm, true);\n }\n\n get id(): string {\n return this.data.sessionId;\n }\n\n load(): Olm.Session {\n const session = new this.olm.Session();\n session.unpickle(this.pickleKey, this.data.session);\n return session;\n }\n\n unload(olmSession: Olm.Session): void {\n olmSession.free();\n }\n\n save(olmSession: Olm.Session): void {\n this.data.session = olmSession.pickle(this.pickleKey);\n this.isModified = true;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n\n/**\n * @property {object} event the plaintext event (type and content property)\n * @property {string} senderCurve25519Key the curve25519 sender key of the olm event\n * @property {string} claimedEd25519Key The ed25519 fingerprint key retrieved from the decryption payload.\n * The sender of the olm event claims this is the ed25519 fingerprint key\n * that matches the curve25519 sender key.\n * The caller needs to check if this key does indeed match the senderKey\n * for a device with a valid signature returned from /keys/query,\n * see DeviceTracker\n */\n\nimport type {DeviceIdentity} from \"../storage/idb/stores/DeviceIdentityStore\";\n\ntype DecryptedEvent = {\n type?: string,\n content?: Record\n}\n\nexport class DecryptionResult {\n private device?: DeviceIdentity;\n private roomTracked: boolean = true;\n\n constructor(\n public readonly event: DecryptedEvent,\n public readonly senderCurve25519Key: string,\n public readonly claimedEd25519Key: string\n ) {}\n\n setDevice(device: DeviceIdentity): void {\n this.device = device;\n }\n\n setRoomNotTrackedYet(): void {\n this.roomTracked = false;\n }\n\n get isVerified(): boolean {\n if (this.device) {\n const comesFromDevice = this.device.ed25519Key === this.claimedEd25519Key;\n return comesFromDevice;\n }\n return false;\n }\n\n get isUnverified(): boolean {\n if (this.device) {\n return !this.isVerified;\n } else if (this.isVerificationUnknown) {\n return false;\n } else {\n return true;\n }\n }\n\n get isVerificationUnknown(): boolean {\n // verification is unknown if we haven't yet fetched the devices for the room\n return !this.device && !this.roomTracked;\n }\n}\n","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport const enum OlmPayloadType {\n PreKey = 0,\n Normal = 1\n}\n\nexport type OlmMessage = {\n type?: OlmPayloadType,\n body?: string\n}\n\nexport type OlmEncryptedMessageContent = {\n algorithm?: \"m.olm.v1.curve25519-aes-sha2\"\n sender_key?: string,\n ciphertext?: {\n [deviceCurve25519Key: string]: OlmMessage\n }\n}\n\nexport type OlmEncryptedEvent = {\n type?: \"m.room.encrypted\",\n content?: OlmEncryptedMessageContent\n sender?: string\n}\n\nexport type OlmPayload = {\n type?: string;\n content?: Record;\n sender?: string;\n recipient?: string;\n recipient_keys?: {ed25519?: string};\n keys?: {ed25519?: string};\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {DecryptionError} from \"../common.js\";\nimport {groupBy} from \"../../../utils/groupBy\";\nimport {MultiLock, ILock} from \"../../../utils/Lock\";\nimport {Session} from \"./Session\";\nimport {DecryptionResult} from \"../DecryptionResult\";\nimport {OlmPayloadType} from \"./types\";\n\nimport type {OlmMessage, OlmPayload} from \"./types\";\nimport type {Account} from \"../Account\";\nimport type {LockMap} from \"../../../utils/LockMap\";\nimport type {Transaction} from \"../../storage/idb/Transaction\";\nimport type {OlmEncryptedEvent} from \"./types\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nconst SESSION_LIMIT_PER_SENDER_KEY = 4;\n\ntype DecryptionResults = {\n results: DecryptionResult[],\n errors: DecryptionError[],\n senderKeyDecryption: SenderKeyDecryption\n};\n\ntype CreateAndDecryptResult = {\n session: Session,\n plaintext: string\n};\n\nfunction sortSessions(sessions: Session[]): void {\n sessions.sort((a, b) => {\n return b.data.lastUsed - a.data.lastUsed;\n });\n}\n\nexport class Decryption {\n constructor(\n private readonly account: Account,\n private readonly pickleKey: string,\n private readonly now: () => number,\n private readonly ownUserId: string,\n private readonly olm: Olm,\n private readonly senderKeyLock: LockMap\n ) {}\n \n // we need to lock because both encryption and decryption can't be done in one txn,\n // so for them not to step on each other toes, we need to lock.\n // \n // the lock is release from 1 of 3 places, whichever comes first:\n // - decryptAll below fails (to release the lock as early as we can)\n // - DecryptionChanges.write succeeds\n // - Sync finishes the writeSync phase (or an error was thrown, in case we never get to DecryptionChanges.write) \n async obtainDecryptionLock(events: OlmEncryptedEvent[]): Promise {\n const senderKeys = new Set();\n for (const event of events) {\n const senderKey = event.content?.[\"sender_key\"];\n if (senderKey) {\n senderKeys.add(senderKey);\n }\n }\n // take a lock on all senderKeys so encryption or other calls to decryptAll (should not happen)\n // don't modify the sessions at the same time\n const locks = await Promise.all(Array.from(senderKeys).map(senderKey => {\n return this.senderKeyLock.takeLock(senderKey);\n }));\n return new MultiLock(locks);\n }\n\n // we need decryptAll because there is some parallelization we can do for decrypting different sender keys at once\n // but for the same sender key we need to do one by one\n // \n // also we want to store the room key, etc ... in the same txn as we remove the pending encrypted event\n // \n // so we need to decrypt events in a batch (so we can decide which ones can run in parallel and which one one by one)\n // and also can avoid side-effects before all can be stored this way\n // \n // doing it one by one would be possible, but we would lose the opportunity for parallelization\n // \n \n /**\n * It is importants the lock obtained from obtainDecryptionLock is for the same set of events as passed in here.\n * [decryptAll description]\n * @param {[type]} events\n * @return {Promise} [description]\n */\n async decryptAll(events: OlmEncryptedEvent[], lock: ILock, txn: Transaction): Promise {\n try {\n const eventsPerSenderKey = groupBy(events, (event: OlmEncryptedEvent) => event.content?.[\"sender_key\"]);\n const timestamp = this.now();\n // decrypt events for different sender keys in parallel\n const senderKeyOperations = await Promise.all(Array.from(eventsPerSenderKey.entries()).map(([senderKey, events]) => {\n return this._decryptAllForSenderKey(senderKey!, events, timestamp, txn);\n }));\n const results = senderKeyOperations.reduce((all, r) => all.concat(r.results), [] as DecryptionResult[]);\n const errors = senderKeyOperations.reduce((all, r) => all.concat(r.errors), [] as DecryptionError[]);\n const senderKeyDecryptions = senderKeyOperations.map(r => r.senderKeyDecryption);\n return new DecryptionChanges(senderKeyDecryptions, results, errors, this.account, lock);\n } catch (err) {\n // make sure the locks are release if something throws\n // otherwise they will be released in DecryptionChanges after having written\n // or after the writeSync phase in Sync\n lock.release();\n throw err;\n }\n }\n\n async _decryptAllForSenderKey(senderKey: string, events: OlmEncryptedEvent[], timestamp: number, readSessionsTxn: Transaction): Promise {\n const sessions = await this._getSessions(senderKey, readSessionsTxn);\n const senderKeyDecryption = new SenderKeyDecryption(senderKey, sessions, timestamp);\n const results: DecryptionResult[] = [];\n const errors: DecryptionError[] = [];\n // events for a single senderKey need to be decrypted one by one\n for (const event of events) {\n try {\n const result = this._decryptForSenderKey(senderKeyDecryption, event, timestamp);\n results.push(result);\n } catch (err) {\n errors.push(err);\n }\n }\n return {results, errors, senderKeyDecryption};\n }\n\n _decryptForSenderKey(senderKeyDecryption: SenderKeyDecryption, event: OlmEncryptedEvent, timestamp: number): DecryptionResult {\n const senderKey = senderKeyDecryption.senderKey;\n const message = this._getMessageAndValidateEvent(event);\n let plaintext: string | undefined;\n try {\n plaintext = senderKeyDecryption.decrypt(message);\n } catch (err) {\n // TODO: is it ok that an error on one session prevents other sessions from being attempted?\n throw new DecryptionError(\"OLM_BAD_ENCRYPTED_MESSAGE\", event, {senderKey, error: err.message});\n }\n // could not decrypt with any existing session\n if (typeof plaintext !== \"string\" && message.type === OlmPayloadType.PreKey) {\n let createResult: CreateAndDecryptResult;\n try {\n createResult = this._createSessionAndDecrypt(senderKey, message, timestamp);\n } catch (error) {\n throw new DecryptionError(`Could not create inbound olm session: ${error.message}`, event, {senderKey, error});\n }\n senderKeyDecryption.addNewSession(createResult.session);\n plaintext = createResult.plaintext;\n }\n if (typeof plaintext === \"string\") {\n let payload: OlmPayload;\n try {\n payload = JSON.parse(plaintext);\n } catch (error) {\n throw new DecryptionError(\"PLAINTEXT_NOT_JSON\", event, {plaintext, error});\n }\n this._validatePayload(payload, event);\n return new DecryptionResult(payload, senderKey, payload.keys!.ed25519!);\n } else {\n throw new DecryptionError(\"OLM_NO_MATCHING_SESSION\", event,\n {knownSessionIds: senderKeyDecryption.sessions.map(s => s.id)});\n }\n }\n\n // only for pre-key messages after having attempted decryption with existing sessions\n _createSessionAndDecrypt(senderKey: string, message: OlmMessage, timestamp: number): CreateAndDecryptResult {\n let plaintext;\n // if we have multiple messages encrypted with the same new session,\n // this could create multiple sessions as the OTK isn't removed yet\n // (this only happens in DecryptionChanges.write)\n // This should be ok though as we'll first try to decrypt with the new session\n const olmSession = this.account.createInboundOlmSession(senderKey, message.body);\n try {\n plaintext = olmSession.decrypt(message.type, message.body);\n const session = Session.create(senderKey, olmSession, this.olm, this.pickleKey, timestamp);\n session.unload(olmSession);\n return {session, plaintext};\n } catch (err) {\n olmSession.free();\n throw err;\n }\n }\n\n _getMessageAndValidateEvent(event: OlmEncryptedEvent): OlmMessage {\n const ciphertext = event.content?.ciphertext;\n if (!ciphertext) {\n throw new DecryptionError(\"OLM_MISSING_CIPHERTEXT\", event);\n }\n const message = ciphertext?.[this.account.identityKeys.curve25519];\n if (!message) {\n throw new DecryptionError(\"OLM_NOT_INCLUDED_IN_RECIPIENTS\", event);\n }\n\n return message;\n }\n\n async _getSessions(senderKey: string, txn: Transaction): Promise {\n const sessionEntries = await txn.olmSessions.getAll(senderKey);\n // sort most recent used sessions first\n const sessions = sessionEntries.map(s => new Session(s, this.pickleKey, this.olm));\n sortSessions(sessions);\n return sessions;\n }\n\n _validatePayload(payload: OlmPayload, event: OlmEncryptedEvent): void {\n if (payload.sender !== event.sender) {\n throw new DecryptionError(\"OLM_FORWARDED_MESSAGE\", event, {sentBy: event.sender, encryptedBy: payload.sender});\n }\n if (payload.recipient !== this.ownUserId) {\n throw new DecryptionError(\"OLM_BAD_RECIPIENT\", event, {recipient: payload.recipient});\n }\n if (payload.recipient_keys?.ed25519 !== this.account.identityKeys.ed25519) {\n throw new DecryptionError(\"OLM_BAD_RECIPIENT_KEY\", event, {key: payload.recipient_keys?.ed25519});\n }\n // TODO: check room_id\n if (!payload.type) {\n throw new DecryptionError(\"missing type on payload\", event, {payload});\n }\n if (typeof payload.keys?.ed25519 !== \"string\") {\n throw new DecryptionError(\"Missing or invalid claimed ed25519 key on payload\", event, {payload});\n }\n }\n}\n\n// decryption helper for a single senderKey\nclass SenderKeyDecryption {\n constructor(\n public readonly senderKey: string,\n public readonly sessions: Session[],\n private readonly timestamp: number\n ) {}\n\n addNewSession(session: Session): void {\n // add at top as it is most recent\n this.sessions.unshift(session);\n }\n\n decrypt(message: OlmMessage): string | undefined {\n for (const session of this.sessions) {\n const plaintext = this.decryptWithSession(session, message);\n if (typeof plaintext === \"string\") {\n // keep them sorted so will try the same session first for other messages\n // and so we can assume the excess ones are at the end\n // if they grow too large\n sortSessions(this.sessions);\n return plaintext;\n }\n }\n }\n\n getModifiedSessions(): Session[] {\n return this.sessions.filter(session => session.isModified);\n }\n\n get hasNewSessions(): boolean {\n return this.sessions.some(session => session.isNew);\n }\n\n // this could internally dispatch to a web-worker\n // and is why we unpickle/pickle on each iteration\n // if this turns out to be a real cost for IE11,\n // we could look into adding a less expensive serialization mechanism\n // for olm sessions to libolm\n private decryptWithSession(session: Session, message: OlmMessage): string | undefined {\n if (message.type === undefined || message.body === undefined) {\n throw new Error(\"Invalid message without type or body\");\n }\n const olmSession = session.load();\n try {\n if (message.type === OlmPayloadType.PreKey && !olmSession.matches_inbound(message.body)) {\n return;\n }\n try {\n const plaintext = olmSession.decrypt(message.type as number, message.body!);\n session.save(olmSession);\n session.data.lastUsed = this.timestamp;\n return plaintext;\n } catch (err) {\n if (message.type === OlmPayloadType.PreKey) {\n throw new Error(`Error decrypting prekey message with existing session id ${session.id}: ${err.message}`);\n }\n // decryption failed, bail out\n return;\n }\n } finally {\n session.unload(olmSession);\n }\n }\n}\n\n/**\n * @property {Array} results\n * @property {Array} errors see DecryptionError.event to retrieve the event that failed to decrypt.\n */\nclass DecryptionChanges {\n constructor(\n private readonly senderKeyDecryptions: SenderKeyDecryption[],\n public readonly results: DecryptionResult[],\n public readonly errors: DecryptionError[],\n private readonly account: Account,\n private readonly lock: ILock\n ) {}\n\n get hasNewSessions(): boolean {\n return this.senderKeyDecryptions.some(skd => skd.hasNewSessions);\n }\n\n write(txn: Transaction): void {\n try {\n for (const senderKeyDecryption of this.senderKeyDecryptions) {\n for (const session of senderKeyDecryption.getModifiedSessions()) {\n txn.olmSessions.set(session.data);\n if (session.isNew) {\n const olmSession = session.load();\n try {\n this.account.writeRemoveOneTimeKey(olmSession, txn);\n } finally {\n session.unload(olmSession);\n }\n }\n }\n if (senderKeyDecryption.sessions.length > SESSION_LIMIT_PER_SENDER_KEY) {\n const {senderKey, sessions} = senderKeyDecryption;\n // >= because index is zero-based\n for (let i = sessions.length - 1; i >= SESSION_LIMIT_PER_SENDER_KEY ; i -= 1) {\n const session = sessions[i];\n txn.olmSessions.remove(senderKey, session.id);\n }\n }\n }\n } finally {\n this.lock.release();\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {groupByWithCreator} from \"../../../utils/groupBy\";\nimport {verifyEd25519Signature, OLM_ALGORITHM} from \"../common.js\";\nimport {createSessionEntry} from \"./Session\";\n\nimport type {OlmMessage, OlmPayload, OlmEncryptedMessageContent} from \"./types\";\nimport type {Account} from \"../Account\";\nimport type {LockMap} from \"../../../utils/LockMap\";\nimport type {Storage} from \"../../storage/idb/Storage\";\nimport type {Transaction} from \"../../storage/idb/Transaction\";\nimport type {DeviceIdentity} from \"../../storage/idb/stores/DeviceIdentityStore\";\nimport type {HomeServerApi} from \"../../net/HomeServerApi\";\nimport type {ILogItem} from \"../../../logging/types\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\ntype ClaimedOTKResponse = {\n [userId: string]: {\n [deviceId: string]: {\n [algorithmAndOtk: string]: {\n key: string,\n signatures: {\n [userId: string]: {\n [algorithmAndDevice: string]: string\n }\n }\n }\n }\n }\n};\n\nfunction findFirstSessionId(sessionIds) {\n return sessionIds.reduce((first, sessionId) => {\n if (!first || sessionId < first) {\n return sessionId;\n } else {\n return first;\n }\n }, null);\n}\n\nconst OTK_ALGORITHM = \"signed_curve25519\";\n// only encrypt this amount of olm messages at once otherwise we run out of wasm memory\n// with all the sessions loaded at the same time\n// See https://github.com/vector-im/hydrogen-web/issues/150 as well, which indicates the limit is 44,\n// but let's take a conservative limit as the megolm session cache also takes space\nconst MAX_BATCH_SIZE = 20;\n\nexport class Encryption {\n constructor(\n private readonly account: Account,\n private readonly pickleKey: string,\n private readonly olm: Olm,\n private readonly storage: Storage,\n private readonly now: () => number,\n private readonly ownUserId: string,\n private readonly olmUtil: Olm.Utility,\n private readonly senderKeyLock: LockMap\n ) {}\n\n async encrypt(type: string, content: Record, devices: DeviceIdentity[], hsApi: HomeServerApi, log: ILogItem): Promise {\n let messages: EncryptedMessage[] = [];\n for (let i = 0; i < devices.length ; i += MAX_BATCH_SIZE) {\n const batchDevices = devices.slice(i, i + MAX_BATCH_SIZE);\n const batchMessages = await this._encryptForMaxDevices(type, content, batchDevices, hsApi, log);\n messages = messages.concat(batchMessages);\n }\n return messages;\n }\n\n async _encryptForMaxDevices(type: string, content: Record, devices: DeviceIdentity[], hsApi: HomeServerApi, log: ILogItem): Promise {\n // TODO: see if we can only hold some of the locks until after the /keys/claim call (if needed) \n // take a lock on all senderKeys so decryption and other calls to encrypt (should not happen)\n // don't modify the sessions at the same time\n const locks = await Promise.all(devices.map(device => {\n return this.senderKeyLock.takeLock(device.curve25519Key);\n }));\n try {\n const {\n devicesWithoutSession,\n existingEncryptionTargets,\n } = await this._findExistingSessions(devices);\n \n const timestamp = this.now(); \n\n let encryptionTargets: EncryptionTarget[] = [];\n try {\n if (devicesWithoutSession.length) {\n const newEncryptionTargets = await log.wrap(\"create sessions\", log => this._createNewSessions(\n devicesWithoutSession, hsApi, timestamp, log));\n encryptionTargets = encryptionTargets.concat(newEncryptionTargets);\n }\n await this._loadSessions(existingEncryptionTargets);\n encryptionTargets = encryptionTargets.concat(existingEncryptionTargets);\n const encryptLog = {l: \"encrypt\", targets: encryptionTargets.length};\n const messages = log.wrap(encryptLog, () => encryptionTargets.map(target => {\n const encryptedContent = this._encryptForDevice(type, content, target);\n return new EncryptedMessage(encryptedContent, target.device);\n }));\n await this._storeSessions(encryptionTargets, timestamp);\n return messages;\n } finally {\n for (const target of encryptionTargets) {\n target.dispose();\n }\n }\n } finally {\n for (const lock of locks) {\n lock.release();\n }\n }\n }\n\n async _findExistingSessions(devices: DeviceIdentity[]): Promise<{devicesWithoutSession: DeviceIdentity[], existingEncryptionTargets: EncryptionTarget[]}> {\n const txn = await this.storage.readTxn([this.storage.storeNames.olmSessions]);\n const sessionIdsForDevice = await Promise.all(devices.map(async device => {\n return await txn.olmSessions.getSessionIds(device.curve25519Key);\n }));\n const devicesWithoutSession = devices.filter((_, i) => {\n const sessionIds = sessionIdsForDevice[i];\n return !(sessionIds?.length);\n });\n\n const existingEncryptionTargets = devices.map((device, i) => {\n const sessionIds = sessionIdsForDevice[i];\n if (sessionIds?.length > 0) {\n const sessionId = findFirstSessionId(sessionIds);\n return EncryptionTarget.fromSessionId(device, sessionId);\n }\n }).filter(target => !!target) as EncryptionTarget[];\n\n return {devicesWithoutSession, existingEncryptionTargets};\n }\n\n _encryptForDevice(type: string, content: Record, target: EncryptionTarget): OlmEncryptedMessageContent {\n const {session, device} = target;\n const plaintext = JSON.stringify(this._buildPlainTextMessageForDevice(type, content, device));\n const message = session!.encrypt(plaintext);\n const encryptedContent = {\n algorithm: OLM_ALGORITHM,\n sender_key: this.account.identityKeys.curve25519,\n ciphertext: {\n [device.curve25519Key]: message\n }\n };\n return encryptedContent;\n }\n\n _buildPlainTextMessageForDevice(type: string, content: Record, device: DeviceIdentity): OlmPayload {\n return {\n keys: {\n \"ed25519\": this.account.identityKeys.ed25519\n },\n recipient_keys: {\n \"ed25519\": device.ed25519Key\n },\n recipient: device.userId,\n sender: this.ownUserId,\n content,\n type\n }\n }\n\n async _createNewSessions(devicesWithoutSession: DeviceIdentity[], hsApi: HomeServerApi, timestamp: number, log: ILogItem): Promise {\n const newEncryptionTargets = await log.wrap(\"claim\", log => this._claimOneTimeKeys(hsApi, devicesWithoutSession, log));\n try {\n for (const target of newEncryptionTargets) {\n const {device, oneTimeKey} = target;\n target.session = await this.account.createOutboundOlmSession(device.curve25519Key, oneTimeKey);\n }\n await this._storeSessions(newEncryptionTargets, timestamp);\n } catch (err) {\n for (const target of newEncryptionTargets) {\n target.dispose();\n }\n throw err;\n }\n return newEncryptionTargets;\n }\n\n async _claimOneTimeKeys(hsApi: HomeServerApi, deviceIdentities: DeviceIdentity[], log: ILogItem): Promise {\n // create a Map>\n const devicesByUser = groupByWithCreator(deviceIdentities,\n (device: DeviceIdentity) => device.userId,\n (): Map => new Map(),\n (deviceMap: Map, device: DeviceIdentity) => deviceMap.set(device.deviceId, device)\n );\n const oneTimeKeys = Array.from(devicesByUser.entries()).reduce((usersObj, [userId, deviceMap]) => {\n usersObj[userId] = Array.from(deviceMap.values()).reduce((devicesObj, device) => {\n devicesObj[device.deviceId] = OTK_ALGORITHM;\n return devicesObj;\n }, {});\n return usersObj;\n }, {});\n const claimResponse = await hsApi.claimKeys({\n timeout: 10000,\n one_time_keys: oneTimeKeys\n }, {log}).response();\n if (Object.keys(claimResponse.failures).length) {\n log.log({l: \"failures\", servers: Object.keys(claimResponse.failures)}, log.level.Warn);\n }\n const userKeyMap = claimResponse?.[\"one_time_keys\"] as ClaimedOTKResponse;\n return this._verifyAndCreateOTKTargets(userKeyMap, devicesByUser, log);\n }\n\n _verifyAndCreateOTKTargets(userKeyMap: ClaimedOTKResponse, devicesByUser: Map>, log: ILogItem): EncryptionTarget[] {\n const verifiedEncryptionTargets: EncryptionTarget[] = [];\n for (const [userId, userSection] of Object.entries(userKeyMap)) {\n for (const [deviceId, deviceSection] of Object.entries(userSection)) {\n const [firstPropName, keySection] = Object.entries(deviceSection)[0];\n const [keyAlgorithm] = firstPropName.split(\":\");\n if (keyAlgorithm === OTK_ALGORITHM) {\n const device = devicesByUser.get(userId)?.get(deviceId);\n if (device) {\n const isValidSignature = verifyEd25519Signature(\n this.olmUtil, userId, deviceId, device.ed25519Key, keySection, log);\n if (isValidSignature) {\n const target = EncryptionTarget.fromOTK(device, keySection.key);\n verifiedEncryptionTargets.push(target);\n }\n }\n }\n } \n }\n return verifiedEncryptionTargets;\n }\n\n async _loadSessions(encryptionTargets: EncryptionTarget[]): Promise {\n const txn = await this.storage.readTxn([this.storage.storeNames.olmSessions]);\n // given we run loading in parallel, there might still be some\n // storage requests that will finish later once one has failed.\n // those should not allocate a session anymore.\n let failed = false;\n try {\n await Promise.all(encryptionTargets.map(async encryptionTarget => {\n const sessionEntry = await txn.olmSessions.get(\n encryptionTarget.device.curve25519Key, encryptionTarget.sessionId!);\n if (sessionEntry && !failed) {\n const olmSession = new this.olm.Session();\n olmSession.unpickle(this.pickleKey, sessionEntry.session);\n encryptionTarget.session = olmSession;\n }\n }));\n } catch (err) {\n failed = true;\n // clean up the sessions that did load\n for (const target of encryptionTargets) {\n target.dispose();\n }\n throw err;\n }\n }\n\n async _storeSessions(encryptionTargets: EncryptionTarget[], timestamp: number): Promise {\n const txn = await this.storage.readWriteTxn([this.storage.storeNames.olmSessions]);\n try {\n for (const target of encryptionTargets) {\n const sessionEntry = createSessionEntry(\n target.session!, target.device.curve25519Key, timestamp, this.pickleKey);\n txn.olmSessions.set(sessionEntry);\n }\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n }\n}\n\n// just a container needed to encrypt a message for a recipient device\n// it is constructed with either a oneTimeKey\n// (and later converted to a session) in case of a new session\n// or an existing session\nclass EncryptionTarget {\n \n public session: Olm.Session | null = null;\n\n constructor(\n public readonly device: DeviceIdentity, \n public readonly oneTimeKey: string | null,\n public readonly sessionId: string | null\n ) {}\n\n static fromOTK(device: DeviceIdentity, oneTimeKey: string): EncryptionTarget {\n return new EncryptionTarget(device, oneTimeKey, null);\n }\n\n static fromSessionId(device: DeviceIdentity, sessionId: string): EncryptionTarget {\n return new EncryptionTarget(device, null, sessionId);\n }\n\n dispose(): void {\n if (this.session) {\n this.session.free();\n }\n }\n}\n\nclass EncryptedMessage {\n constructor(\n public readonly content: OlmEncryptedMessageContent,\n public readonly device: DeviceIdentity\n ) {}\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {DecryptionError} from \"../../common.js\";\n\nexport class DecryptionChanges {\n constructor(roomId, results, errors, replayEntries) {\n this._roomId = roomId;\n this._results = results;\n this._errors = errors;\n this._replayEntries = replayEntries;\n }\n\n /**\n * @type MegolmBatchDecryptionResult\n * @property {Map} results a map of event id to decryption result\n * @property {Map} errors event id -> errors\n * \n * Handle replay attack detection, and return result\n * @param {[type]} txn [description]\n * @return {MegolmBatchDecryptionResult}\n */\n async write(txn) {\n await Promise.all(this._replayEntries.map(async replayEntry => {\n try {\n this._handleReplayAttack(this._roomId, replayEntry, txn);\n } catch (err) {\n this._errors.set(replayEntry.eventId, err);\n }\n }));\n return {\n results: this._results,\n errors: this._errors\n };\n }\n\n // need to handle replay attack because\n // if we redecrypted the same message twice and showed it again\n // then it could be a malicious server admin replaying the word “yes”\n // to make you respond to a msg you didn’t say “yes” to, or something\n async _handleReplayAttack(roomId, replayEntry, txn) {\n const {messageIndex, sessionId, eventId, timestamp} = replayEntry;\n const decryption = await txn.groupSessionDecryptions.get(roomId, sessionId, messageIndex);\n\n if (decryption && decryption.eventId !== eventId) {\n // the one with the newest timestamp should be the attack\n const decryptedEventIsBad = decryption.timestamp < timestamp;\n const badEventId = decryptedEventIsBad ? eventId : decryption.eventId;\n // discard result\n this._results.delete(eventId);\n\n throw new DecryptionError(\"MEGOLM_REPLAYED_INDEX\", event, {\n messageIndex,\n badEventId,\n otherEventId: decryption.eventId\n });\n }\n\n if (!decryption) {\n txn.groupSessionDecryptions.set(roomId, sessionId, messageIndex, {\n eventId,\n timestamp\n });\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function mergeMap(src: Map | undefined, dst: Map): void {\n if (src) {\n for (const [key, value] of src.entries()) {\n dst.set(key, value);\n }\n }\n}\n\nexport function tests() {\n return {\n \"mergeMap with src\": assert => {\n const src = new Map();\n src.set(1, \"a\");\n const dst = new Map();\n dst.set(2, \"b\");\n mergeMap(src, dst);\n assert.equal(dst.get(1), \"a\");\n assert.equal(dst.get(2), \"b\");\n assert.equal(src.get(2), null);\n },\n \"mergeMap without src doesn't fail\": () => {\n mergeMap(undefined, new Map());\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {DecryptionChanges} from \"./DecryptionChanges.js\";\nimport {mergeMap} from \"../../../../utils/mergeMap\";\n\n/**\n * Class that contains all the state loaded from storage to decrypt the given events\n */\nexport class DecryptionPreparation {\n constructor(roomId, sessionDecryptions, errors) {\n this._roomId = roomId;\n this._sessionDecryptions = sessionDecryptions;\n this._initialErrors = errors;\n }\n\n async decrypt() {\n try {\n const errors = this._initialErrors;\n const results = new Map();\n const replayEntries = [];\n await Promise.all(this._sessionDecryptions.map(async sessionDecryption => {\n const sessionResult = await sessionDecryption.decryptAll();\n mergeMap(sessionResult.errors, errors);\n mergeMap(sessionResult.results, results);\n replayEntries.push(...sessionResult.replayEntries);\n }));\n return new DecryptionChanges(this._roomId, results, errors, replayEntries);\n } finally {\n this.dispose();\n }\n }\n\n dispose() {\n for (const sd of this._sessionDecryptions) {\n sd.dispose();\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {TimelineEvent} from \"../../../storage/types\";\n\nexport class ReplayDetectionEntry {\n public readonly sessionId: string;\n public readonly messageIndex: number;\n public readonly event: TimelineEvent;\n\n constructor(sessionId: string, messageIndex: number, event: TimelineEvent) {\n this.sessionId = sessionId;\n this.messageIndex = messageIndex;\n this.event = event;\n }\n\n get eventId(): string {\n return this.event.event_id;\n }\n\n get timestamp(): number {\n return this.event.origin_server_ts;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {DecryptionResult} from \"../../DecryptionResult\";\nimport {DecryptionError} from \"../../common.js\";\nimport {ReplayDetectionEntry} from \"./ReplayDetectionEntry\";\nimport type {RoomKey} from \"./RoomKey\";\nimport type {KeyLoader, OlmDecryptionResult} from \"./KeyLoader\";\nimport type {OlmWorker} from \"../../OlmWorker\";\nimport type {TimelineEvent} from \"../../../storage/types\";\n\ninterface DecryptAllResult {\n readonly results: Map;\n readonly errors?: Map;\n readonly replayEntries: ReplayDetectionEntry[];\n}\n/**\n * Does the actual decryption of all events for a given megolm session in a batch\n */\nexport class SessionDecryption {\n private key: RoomKey;\n private events: TimelineEvent[];\n private keyLoader: KeyLoader;\n private olmWorker?: OlmWorker;\n private decryptionRequests?: any[];\n\n constructor(key: RoomKey, events: TimelineEvent[], olmWorker: OlmWorker | undefined, keyLoader: KeyLoader) {\n this.key = key;\n this.events = events;\n this.olmWorker = olmWorker;\n this.keyLoader = keyLoader;\n this.decryptionRequests = olmWorker ? [] : undefined;\n }\n\n async decryptAll(): Promise {\n const replayEntries: ReplayDetectionEntry[] = [];\n const results: Map = new Map();\n let errors: Map | undefined;\n\n await this.keyLoader.useKey(this.key, async session => {\n for (const event of this.events) {\n try {\n const ciphertext = event.content.ciphertext as string;\n let decryptionResult: OlmDecryptionResult | undefined;\n // TODO: pass all cipthertexts in one go to the megolm worker and don't deserialize the key until in the worker?\n if (this.olmWorker) {\n const request = this.olmWorker.megolmDecrypt(session, ciphertext);\n this.decryptionRequests!.push(request);\n decryptionResult = await request.response();\n } else {\n decryptionResult = session.decrypt(ciphertext) as OlmDecryptionResult;\n }\n const {plaintext} = decryptionResult!;\n let payload;\n try {\n payload = JSON.parse(plaintext);\n } catch (err) {\n throw new DecryptionError(\"PLAINTEXT_NOT_JSON\", event, {plaintext, err});\n }\n if (payload.room_id !== this.key.roomId) {\n throw new DecryptionError(\"MEGOLM_WRONG_ROOM\", event,\n {encryptedRoomId: payload.room_id, eventRoomId: this.key.roomId});\n }\n replayEntries.push(new ReplayDetectionEntry(this.key.sessionId, decryptionResult!.message_index, event));\n const result = new DecryptionResult(payload, this.key.senderKey, this.key.claimedEd25519Key);\n results.set(event.event_id, result);\n } catch (err) {\n // ignore AbortError from cancelling decryption requests in dispose method\n if (err.name === \"AbortError\") {\n return;\n }\n if (!errors) {\n errors = new Map();\n }\n errors.set(event.event_id, err);\n }\n }\n });\n\n return {results, errors, replayEntries};\n }\n\n dispose() {\n if (this.decryptionRequests) {\n for (const r of this.decryptionRequests) {\n r.abort();\n }\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {groupByWithCreator} from \"../../../../utils/groupBy\";\nimport type {TimelineEvent} from \"../../../storage/types\";\n\nfunction getSenderKey(event: TimelineEvent): string | undefined {\n return event.content?.[\"sender_key\"];\n}\n\nfunction getSessionId(event: TimelineEvent): string | undefined {\n return event.content?.[\"session_id\"];\n}\n\nfunction getCiphertext(event: TimelineEvent): string | undefined {\n return event.content?.ciphertext;\n}\n\nexport function validateEvent(event: TimelineEvent) {\n return typeof getSenderKey(event) === \"string\" &&\n typeof getSessionId(event) === \"string\" &&\n typeof getCiphertext(event) === \"string\";\n}\n\nexport class SessionKeyGroup {\n public readonly events: TimelineEvent[];\n constructor() {\n this.events = [];\n }\n\n get senderKey(): string | undefined {\n return getSenderKey(this.events[0]!);\n }\n\n get sessionId(): string | undefined {\n return getSessionId(this.events[0]!);\n }\n}\n\nexport function groupEventsBySession(events: TimelineEvent[]): Map {\n return groupByWithCreator(events,\n (event: TimelineEvent) => `${getSenderKey(event)}|${getSessionId(event)}`,\n () => new SessionKeyGroup(),\n (group: SessionKeyGroup, event: TimelineEvent) => group.events.push(event)\n );\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BackupStatus, KeySource} from \"../../../storage/idb/stores/InboundGroupSessionStore\";\nimport type {InboundGroupSessionEntry} from \"../../../storage/idb/stores/InboundGroupSessionStore\";\nimport type {Transaction} from \"../../../storage/idb/Transaction\";\nimport type {DecryptionResult} from \"../../DecryptionResult\";\nimport type {KeyLoader} from \"./KeyLoader\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nexport abstract class RoomKey {\n private _isBetter: boolean | undefined;\n\n isForSession(roomId: string, senderKey: string, sessionId: string) {\n return this.roomId === roomId && this.senderKey === senderKey && this.sessionId === sessionId;\n }\n\n abstract get roomId(): string;\n abstract get senderKey(): string;\n abstract get sessionId(): string;\n abstract get claimedEd25519Key(): string;\n abstract get serializationKey(): string;\n abstract get serializationType(): string;\n abstract get eventIds(): string[] | undefined;\n abstract loadInto(session: Olm.InboundGroupSession, pickleKey: string): void;\n /* Whether the key has been checked against storage (or is from storage)\n * to be the better key for a given session. Given that all keys are checked to be better\n * as part of writing, we can trust that when this returns true, it really is the best key\n * available between storage and cached keys in memory. This is why keys with this field set to\n * true are used by the key loader to return cached keys. Also see KeyOperation.isBest there. */\n get isBetter(): boolean | undefined { return this._isBetter; }\n // should only be set in key.checkBetterThanKeyInStorage\n set isBetter(value: boolean | undefined) { this._isBetter = value; }\n}\n\nexport function isBetterThan(newSession: Olm.InboundGroupSession, existingSession: Olm.InboundGroupSession) {\n return newSession.first_known_index() < existingSession.first_known_index();\n}\n\nexport abstract class IncomingRoomKey extends RoomKey {\n private _eventIds?: string[];\n \n checkBetterThanKeyInStorage(loader: KeyLoader, txn: Transaction): Promise {\n return this._checkBetterThanKeyInStorage(loader, undefined, txn);\n }\n\n async write(loader: KeyLoader, txn: Transaction): Promise {\n // we checked already and we had a better session in storage, so don't write\n let pickledSession: string | undefined;\n if (this.isBetter === undefined) {\n // if this key wasn't used to decrypt any messages in the same sync,\n // we haven't checked if this is the best key yet,\n // so do that now to not overwrite a better key.\n // while we have the key deserialized, also pickle it to store it later on here.\n await this._checkBetterThanKeyInStorage(loader, (session, pickleKey) => {\n pickledSession = session.pickle(pickleKey);\n }, txn);\n }\n if (this.isBetter === false) {\n return false;\n }\n // before calling write in parallel, we need to check loader.running is false so we are sure our transaction will not be closed\n if (!pickledSession) {\n pickledSession = await loader.useKey(this, (session, pickleKey) => session.pickle(pickleKey));\n }\n const sessionEntry = {\n roomId: this.roomId,\n senderKey: this.senderKey,\n sessionId: this.sessionId,\n session: pickledSession,\n backup: this.backupStatus,\n source: this.keySource,\n claimedKeys: {\"ed25519\": this.claimedEd25519Key},\n };\n txn.inboundGroupSessions.set(sessionEntry);\n return true;\n }\n\n get eventIds() { return this._eventIds; }\n\n private async _checkBetterThanKeyInStorage(loader: KeyLoader, callback: (((session: Olm.InboundGroupSession, pickleKey: string) => void) | undefined), txn: Transaction): Promise {\n if (this.isBetter !== undefined) {\n return this.isBetter;\n }\n let existingKey = loader.getCachedKey(this.roomId, this.senderKey, this.sessionId);\n if (!existingKey) {\n const storageKey = await keyFromStorage(this.roomId, this.senderKey, this.sessionId, txn);\n // store the event ids that can be decrypted with this key\n // before we overwrite them if called from `write`.\n if (storageKey) {\n if (storageKey.hasSession) {\n existingKey = storageKey;\n } else if (storageKey.eventIds) {\n this._eventIds = storageKey.eventIds;\n }\n }\n }\n if (existingKey) {\n const key = existingKey;\n await loader.useKey(this, async newSession => {\n await loader.useKey(key, (existingSession, pickleKey) => {\n // set isBetter as soon as possible, on both keys compared, \n // as it is is used to determine whether a key can be used for the cache\n this.isBetter = isBetterThan(newSession, existingSession);\n key.isBetter = !this.isBetter;\n if (this.isBetter && callback) {\n callback(newSession, pickleKey);\n }\n });\n });\n } else {\n // no previous key, so we're the best \\o/\n this.isBetter = true;\n }\n return this.isBetter!;\n }\n\n protected get backupStatus(): BackupStatus {\n return BackupStatus.NotBackedUp;\n }\n\n protected abstract get keySource(): KeySource;\n}\n\nclass DeviceMessageRoomKey extends IncomingRoomKey {\n private _decryptionResult: DecryptionResult;\n\n constructor(decryptionResult: DecryptionResult) {\n super();\n this._decryptionResult = decryptionResult;\n }\n\n get roomId() { return this._decryptionResult.event.content?.[\"room_id\"]; }\n get senderKey() { return this._decryptionResult.senderCurve25519Key; }\n get sessionId() { return this._decryptionResult.event.content?.[\"session_id\"]; }\n get claimedEd25519Key() { return this._decryptionResult.claimedEd25519Key; }\n get serializationKey(): string { return this._decryptionResult.event.content?.[\"session_key\"]; }\n get serializationType(): string { return \"create\"; }\n protected get keySource(): KeySource { return KeySource.DeviceMessage; }\n\n loadInto(session) {\n session.create(this.serializationKey);\n }\n}\n\n// a room key we send out ourselves,\n// here adapted to write it as an incoming key\n// as we don't send it to ourself with a to_device msg\nexport class OutboundRoomKey extends IncomingRoomKey {\n private _sessionKey: string;\n\n constructor(\n private readonly _roomId: string,\n private readonly outboundSession: Olm.OutboundGroupSession,\n private readonly identityKeys: {[algo: string]: string}\n ) {\n super();\n // this is a new key, so always better than what might be in storage, no need to check\n this.isBetter = true;\n // cache this, as it is used by key loader to find a matching key and\n // this calls into WASM so is not just reading a prop\n this._sessionKey = this.outboundSession.session_key();\n }\n\n get roomId(): string { return this._roomId; }\n get senderKey(): string { return this.identityKeys.curve25519; }\n get sessionId(): string { return this.outboundSession.session_id(); }\n get claimedEd25519Key(): string { return this.identityKeys.ed25519; }\n get serializationKey(): string { return this._sessionKey; }\n get serializationType(): string { return \"create\"; }\n protected get keySource(): KeySource { return KeySource.Outbound; }\n\n loadInto(session: Olm.InboundGroupSession) {\n session.create(this.serializationKey);\n }\n}\n\nclass BackupRoomKey extends IncomingRoomKey {\n constructor(private _roomId: string, private _sessionId: string, private _backupInfo: object) {\n super();\n }\n\n get roomId() { return this._roomId; }\n get senderKey() { return this._backupInfo[\"sender_key\"]; }\n get sessionId() { return this._sessionId; }\n get claimedEd25519Key() { return this._backupInfo[\"sender_claimed_keys\"]?.[\"ed25519\"]; }\n get serializationKey(): string { return this._backupInfo[\"session_key\"]; }\n get serializationType(): string { return \"import_session\"; }\n protected get keySource(): KeySource { return KeySource.Backup; }\n\n loadInto(session) {\n session.import_session(this.serializationKey);\n }\n\n protected get backupStatus(): BackupStatus {\n return BackupStatus.BackedUp;\n }\n}\n\nexport class StoredRoomKey extends RoomKey {\n private storageEntry: InboundGroupSessionEntry;\n\n constructor(storageEntry: InboundGroupSessionEntry) {\n super();\n this.isBetter = true; // usually the key in storage is the best until checks prove otherwise\n this.storageEntry = storageEntry;\n }\n\n get roomId() { return this.storageEntry.roomId; }\n get senderKey() { return this.storageEntry.senderKey; }\n get sessionId() { return this.storageEntry.sessionId; }\n get claimedEd25519Key() { return this.storageEntry.claimedKeys![\"ed25519\"]; }\n get eventIds() { return this.storageEntry.eventIds; }\n get serializationKey(): string { return this.storageEntry.session || \"\"; }\n get serializationType(): string { return \"unpickle\"; }\n \n loadInto(session, pickleKey) {\n session.unpickle(pickleKey, this.serializationKey);\n }\n\n get hasSession() {\n // sessions are stored before they are received\n // to keep track of events that need it to be decrypted.\n // This is used to retry decryption of those events once the session is received.\n return !!this.serializationKey;\n }\n}\n\nexport function keyFromDeviceMessage(dr: DecryptionResult): DeviceMessageRoomKey | undefined {\n const sessionKey = dr.event.content?.[\"session_key\"];\n const key = new DeviceMessageRoomKey(dr);\n if (\n typeof key.roomId === \"string\" && \n typeof key.sessionId === \"string\" && \n typeof key.senderKey === \"string\" &&\n typeof sessionKey === \"string\"\n ) {\n return key;\n }\n}\n\n/*\nsessionInfo is a response from key backup and has the following keys:\n algorithm\n forwarding_curve25519_key_chain\n sender_claimed_keys\n sender_key\n session_key\n */\nexport function keyFromBackup(roomId, sessionId, backupInfo): BackupRoomKey | undefined {\n const sessionKey = backupInfo[\"session_key\"];\n const senderKey = backupInfo[\"sender_key\"];\n // TODO: can we just trust this?\n const claimedEd25519Key = backupInfo[\"sender_claimed_keys\"]?.[\"ed25519\"];\n\n if (\n typeof roomId === \"string\" && \n typeof sessionId === \"string\" && \n typeof senderKey === \"string\" &&\n typeof sessionKey === \"string\" &&\n typeof claimedEd25519Key === \"string\"\n ) {\n return new BackupRoomKey(roomId, sessionId, backupInfo);\n }\n}\n\nexport async function keyFromStorage(roomId: string, senderKey: string, sessionId: string, txn: Transaction): Promise {\n const existingSessionEntry = await txn.inboundGroupSessions.get(roomId, senderKey, sessionId);\n if (existingSessionEntry) {\n return new StoredRoomKey(existingSessionEntry);\n }\n return;\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {DecryptionError} from \"../common.js\";\nimport {DecryptionPreparation} from \"./decryption/DecryptionPreparation.js\";\nimport {SessionDecryption} from \"./decryption/SessionDecryption\";\nimport {MEGOLM_ALGORITHM} from \"../common.js\";\nimport {validateEvent, groupEventsBySession} from \"./decryption/utils\";\nimport {keyFromStorage, keyFromDeviceMessage, keyFromBackup} from \"./decryption/RoomKey\";\nimport type {RoomKey, IncomingRoomKey} from \"./decryption/RoomKey\";\nimport type {KeyLoader} from \"./decryption/KeyLoader\";\nimport type {OlmWorker} from \"../OlmWorker\";\nimport type {Transaction} from \"../../storage/idb/Transaction\";\nimport type {TimelineEvent} from \"../../storage/types\";\nimport type {DecryptionResult} from \"../DecryptionResult\";\nimport type {ILogItem} from \"../../../logging/types\";\n\nexport class Decryption {\n private keyLoader: KeyLoader;\n private olmWorker?: OlmWorker;\n\n constructor(keyLoader: KeyLoader, olmWorker: OlmWorker | undefined) {\n this.keyLoader = keyLoader;\n this.olmWorker = olmWorker;\n }\n\n async addMissingKeyEventIds(roomId, senderKey, sessionId, eventIds, txn) {\n let sessionEntry = await txn.inboundGroupSessions.get(roomId, senderKey, sessionId);\n // we never want to overwrite an existing key\n if (sessionEntry?.session) {\n return;\n }\n if (sessionEntry) {\n const uniqueEventIds = new Set(sessionEntry.eventIds);\n for (const id of eventIds) {\n uniqueEventIds.add(id);\n }\n sessionEntry.eventIds = Array.from(uniqueEventIds);\n } else {\n sessionEntry = {roomId, senderKey, sessionId, eventIds};\n }\n txn.inboundGroupSessions.set(sessionEntry);\n }\n\n async getEventIdsForMissingKey(roomId, senderKey, sessionId, txn) {\n const sessionEntry = await txn.inboundGroupSessions.get(roomId, senderKey, sessionId);\n if (sessionEntry && !sessionEntry.session) {\n return sessionEntry.eventIds;\n }\n }\n\n async hasSession(roomId, senderKey, sessionId, txn) {\n const sessionEntry = await txn.inboundGroupSessions.get(roomId, senderKey, sessionId);\n const isValidSession = typeof sessionEntry?.session === \"string\";\n return isValidSession;\n }\n\n /**\n * Reads all the state from storage to be able to decrypt the given events.\n * Decryption can then happen outside of a storage transaction.\n * @param {[type]} roomId [description]\n * @param {[type]} events [description]\n * @param {RoomKey[]?} newKeys keys as returned from extractRoomKeys, but not yet committed to storage. May be undefined.\n * @param {[type]} sessionCache [description]\n * @param {[type]} txn [description]\n * @return {DecryptionPreparation}\n */\n async prepareDecryptAll(roomId: string, events: TimelineEvent[], newKeys: IncomingRoomKey[] | undefined, txn: Transaction) {\n const errors = new Map();\n const validEvents: TimelineEvent[] = [];\n\n for (const event of events) {\n if (validateEvent(event)) {\n validEvents.push(event);\n } else {\n errors.set(event.event_id, new DecryptionError(\"MEGOLM_INVALID_EVENT\", event))\n }\n }\n\n const eventsBySession = groupEventsBySession(validEvents);\n\n const sessionDecryptions: SessionDecryption[] = [];\n await Promise.all(Array.from(eventsBySession.values()).map(async group => {\n const key = await this.getRoomKey(roomId, group.senderKey!, group.sessionId!, newKeys, txn);\n if (key) {\n sessionDecryptions.push(new SessionDecryption(key, group.events, this.olmWorker, this.keyLoader));\n } else {\n for (const event of group.events) {\n errors.set(event.event_id, new DecryptionError(\"MEGOLM_NO_SESSION\", event));\n }\n }\n }));\n\n return new DecryptionPreparation(roomId, sessionDecryptions, errors);\n }\n\n private async getRoomKey(roomId: string, senderKey: string, sessionId: string, newKeys: IncomingRoomKey[] | undefined, txn: Transaction): Promise {\n if (newKeys) {\n const key = newKeys.find(k => k.isForSession(roomId, senderKey, sessionId));\n if (key && await key.checkBetterThanKeyInStorage(this.keyLoader, txn)) {\n return key;\n }\n }\n // look only in the cache after looking into newKeys as it may contains that are better\n const cachedKey = this.keyLoader.getCachedKey(roomId, senderKey, sessionId);\n if (cachedKey) {\n return cachedKey;\n }\n const storageKey = await keyFromStorage(roomId, senderKey, sessionId, txn);\n if (storageKey && storageKey.serializationKey) {\n return storageKey;\n }\n }\n\n /**\n * Writes the key as an inbound group session if there is not already a better key in the store\n */\n writeRoomKey(key: IncomingRoomKey, txn: Transaction): Promise {\n return key.write(this.keyLoader, txn);\n }\n\n /**\n * Extracts room keys from decrypted device messages.\n * The key won't be persisted yet, you need to call RoomKey.write for that.\n */\n roomKeysFromDeviceMessages(decryptionResults: DecryptionResult[], log: ILogItem): IncomingRoomKey[] {\n const keys: IncomingRoomKey[] = [];\n for (const dr of decryptionResults) {\n if (dr.event?.type !== \"m.room_key\" || dr.event.content?.algorithm !== MEGOLM_ALGORITHM) {\n continue;\n }\n log.wrap(\"room_key\", log => {\n const key = keyFromDeviceMessage(dr);\n if (key) {\n log.set(\"roomId\", key.roomId);\n log.set(\"id\", key.sessionId);\n keys.push(key);\n } else {\n log.logLevel = log.level.Warn;\n log.set(\"invalid\", true);\n }\n }, log.level.Detail);\n }\n return keys;\n }\n\n roomKeyFromBackup(roomId: string, sessionId: string, sessionInfo: string): IncomingRoomKey | undefined {\n return keyFromBackup(roomId, sessionId, sessionInfo);\n }\n\n dispose() {\n this.keyLoader.dispose();\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {isBetterThan, IncomingRoomKey} from \"./RoomKey\";\nimport {BaseLRUCache} from \"../../../../utils/LRUCache\";\nimport type {RoomKey} from \"./RoomKey\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nexport declare class OlmDecryptionResult {\n readonly plaintext: string;\n readonly message_index: number;\n}\n\n/*\nBecause Olm only has very limited memory available when compiled to wasm,\nwe limit the amount of sessions held in memory.\n*/\nexport class KeyLoader extends BaseLRUCache {\n\n private pickleKey: string;\n private olm: Olm;\n private resolveUnusedOperation?: () => void;\n private operationBecomesUnusedPromise?: Promise;\n\n constructor(olm: Olm, pickleKey: string, limit: number) {\n super(limit);\n this.pickleKey = pickleKey;\n this.olm = olm;\n }\n\n getCachedKey(roomId: string, senderKey: string, sessionId: string): RoomKey | undefined {\n const idx = this.findCachedKeyIndex(roomId, senderKey, sessionId);\n if (idx !== -1) {\n return this._getByIndexAndMoveUp(idx)!.key;\n }\n }\n\n async useKey(key: RoomKey, callback: (session: Olm.InboundGroupSession, pickleKey: string) => Promise | T): Promise {\n const keyOp = await this.allocateOperation(key);\n try {\n return await callback(keyOp.session, this.pickleKey);\n } finally {\n this.releaseOperation(keyOp);\n }\n }\n\n get running() {\n return this._entries.some(op => op.refCount !== 0);\n }\n\n dispose() {\n for (let i = 0; i < this._entries.length; i += 1) {\n this._entries[i].dispose();\n }\n // remove all entries\n this._entries.splice(0, this._entries.length);\n }\n\n private async allocateOperation(key: RoomKey): Promise {\n let idx;\n while((idx = this.findIndexForAllocation(key)) === -1) {\n await this.operationBecomesUnused();\n }\n if (idx < this.size) {\n const op = this._getByIndexAndMoveUp(idx)!;\n // cache hit\n if (op.isForKey(key)) {\n op.refCount += 1;\n return op;\n } else {\n // refCount should be 0 here\n op.refCount = 1;\n op.key = key;\n key.loadInto(op.session, this.pickleKey);\n }\n return op;\n } else {\n // create new operation\n const session = new this.olm.InboundGroupSession();\n key.loadInto(session, this.pickleKey);\n const op = new KeyOperation(key, session);\n this._set(op);\n return op;\n }\n }\n\n private releaseOperation(op: KeyOperation) {\n op.refCount -= 1;\n if (op.refCount <= 0 && this.resolveUnusedOperation) {\n this.resolveUnusedOperation();\n // promise is resolved now, we'll need a new one for next await so clear\n this.operationBecomesUnusedPromise = this.resolveUnusedOperation = undefined;\n }\n }\n\n private operationBecomesUnused(): Promise {\n if (!this.operationBecomesUnusedPromise) {\n this.operationBecomesUnusedPromise = new Promise(resolve => {\n this.resolveUnusedOperation = resolve;\n });\n }\n return this.operationBecomesUnusedPromise;\n }\n\n private findIndexForAllocation(key: RoomKey) {\n let idx = this.findIndexSameKey(key); // cache hit\n if (idx === -1) {\n if (this.size < this.limit) {\n idx = this.size;\n } else {\n idx = this.findIndexSameSessionUnused(key);\n if (idx === -1) {\n idx = this.findIndexOldestUnused();\n }\n }\n }\n return idx;\n }\n\n private findCachedKeyIndex(roomId: string, senderKey: string, sessionId: string): number {\n return this._entries.reduce((bestIdx, op, i, arr) => {\n const bestOp = bestIdx === -1 ? undefined : arr[bestIdx];\n // only operations that are the \"best\" for their session can be used, see comment on isBest\n if (op.isBest === true && op.isForSameSession(roomId, senderKey, sessionId)) {\n if (!bestOp || op.isBetter(bestOp)) {\n return i;\n }\n }\n return bestIdx;\n }, -1);\n }\n\n private findIndexSameKey(key: RoomKey): number {\n return this._entries.findIndex(op => {\n return op.isForSameSession(key.roomId, key.senderKey, key.sessionId) && op.isForKey(key);\n });\n }\n\n private findIndexSameSessionUnused(key: RoomKey): number {\n return this._entries.reduce((worstIdx, op, i, arr) => {\n const worst = worstIdx === -1 ? undefined : arr[worstIdx];\n // we try to pick the worst operation to overwrite, so the best one stays in the cache\n if (op.refCount === 0 && op.isForSameSession(key.roomId, key.senderKey, key.sessionId)) {\n if (!worst || !op.isBetter(worst)) {\n return i;\n }\n }\n return worstIdx;\n }, -1);\n }\n\n private findIndexOldestUnused(): number {\n for (let i = this._entries.length - 1; i >= 0; i -= 1) {\n const op = this._entries[i];\n if (op.refCount === 0) {\n return i;\n }\n }\n return -1;\n }\n}\n\nclass KeyOperation {\n session: Olm.InboundGroupSession;\n key: RoomKey;\n refCount: number;\n\n constructor(key: RoomKey, session: Olm.InboundGroupSession) {\n this.key = key;\n this.session = session;\n this.refCount = 1;\n }\n\n isForSameSession(roomId: string, senderKey: string, sessionId: string): boolean {\n return this.key.roomId === roomId && this.key.senderKey === senderKey && this.key.sessionId === sessionId;\n }\n\n // assumes isForSameSession is true\n isBetter(other: KeyOperation) {\n return isBetterThan(this.session, other.session);\n }\n\n isForKey(key: RoomKey) {\n return this.key.serializationKey === key.serializationKey &&\n this.key.serializationType === key.serializationType;\n }\n\n dispose() {\n this.session.free();\n this.session = undefined as any;\n }\n\n /** returns whether the key for this operation has been checked at some point against storage\n * and was determined to be the better key, undefined if it hasn't been checked yet.\n * Only keys that are the best keys can be returned by getCachedKey as returning a cache hit\n * will usually not check for a better session in storage. Also see RoomKey.isBetter. */\n get isBest(): boolean | undefined {\n return this.key.isBetter;\n }\n}\n\nimport {KeySource} from \"../../../storage/idb/stores/InboundGroupSessionStore\";\n\n\nexport function tests() {\n let instances = 0;\n\n class MockRoomKey extends IncomingRoomKey {\n private _roomId: string;\n private _senderKey: string;\n private _sessionId: string;\n private _firstKnownIndex: number;\n\n constructor(roomId: string, senderKey: string, sessionId: string, firstKnownIndex: number) {\n super();\n this._roomId = roomId;\n this._senderKey = senderKey;\n this._sessionId = sessionId;\n this._firstKnownIndex = firstKnownIndex;\n }\n\n get roomId(): string { return this._roomId; }\n get senderKey(): string { return this._senderKey; }\n get sessionId(): string { return this._sessionId; }\n get claimedEd25519Key(): string { return \"claimedEd25519Key\"; }\n get serializationKey(): string { return `key-${this.sessionId}-${this._firstKnownIndex}`; }\n get serializationType(): string { return \"type\"; }\n get eventIds(): string[] | undefined { return undefined; }\n get keySource(): KeySource { return KeySource.DeviceMessage; }\n\n loadInto(session: Olm.InboundGroupSession) {\n const mockSession = session as MockInboundSession;\n mockSession.sessionId = this.sessionId;\n mockSession.firstKnownIndex = this._firstKnownIndex;\n }\n }\n\n class MockInboundSession {\n public sessionId: string = \"\";\n public firstKnownIndex: number = 0;\n\n constructor() {\n instances += 1;\n }\n\n free(): void { instances -= 1; }\n pickle(key: string | Uint8Array): string { return `${this.sessionId}-pickled-session`; }\n unpickle(key: string | Uint8Array, pickle: string) {}\n create(session_key: string): string { return `${this.sessionId}-created-session`; }\n import_session(session_key: string): string { return \"\"; }\n decrypt(message: string): OlmDecryptionResult { return {} as OlmDecryptionResult; }\n session_id(): string { return this.sessionId; }\n first_known_index(): number { return this.firstKnownIndex; }\n export_session(message_index: number): string { return `${this.sessionId}-exported-session`; }\n }\n\n const PICKLE_KEY = \"🥒🔑\";\n const olm = {InboundGroupSession: MockInboundSession};\n const roomId = \"!abc:hs.tld\";\n const aliceSenderKey = \"abc\";\n const bobSenderKey = \"def\";\n const sessionId1 = \"s123\";\n const sessionId2 = \"s456\";\n \n return {\n \"load key gives correct session\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n let callback1Called = false;\n let callback2Called = false;\n const p1 = loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1), async session => {\n callback1Called = true;\n assert.equal(session.session_id(), sessionId1);\n assert.equal(session.first_known_index(), 1);\n await Promise.resolve(); // make sure they are busy in parallel\n });\n const p2 = loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId2, 2), async session => {\n callback2Called = true;\n assert.equal(session.session_id(), sessionId2);\n assert.equal(session.first_known_index(), 2);\n await Promise.resolve(); // make sure they are busy in parallel\n });\n assert.equal(loader.size, 2);\n await Promise.all([p1, p2]);\n assert(callback1Called);\n assert(callback2Called);\n },\n \"keys with different first index are kept separate\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n let callback1Called = false;\n let callback2Called = false;\n const p1 = loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1), async session => {\n callback1Called = true;\n assert.equal(session.session_id(), sessionId1);\n assert.equal(session.first_known_index(), 1);\n await Promise.resolve(); // make sure they are busy in parallel\n });\n const p2 = loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId1, 2), async session => {\n callback2Called = true;\n assert.equal(session.session_id(), sessionId1);\n assert.equal(session.first_known_index(), 2);\n await Promise.resolve(); // make sure they are busy in parallel\n });\n assert.equal(loader.size, 2);\n await Promise.all([p1, p2]);\n assert(callback1Called);\n assert(callback2Called);\n },\n \"useKey blocks as long as no free sessions are available\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 1);\n let resolve;\n let callbackCalled = false;\n loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1), async session => {\n await new Promise(r => resolve = r);\n });\n await Promise.resolve();\n assert.equal(loader.size, 1);\n const promise = loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId2, 1), session => {\n callbackCalled = true;\n });\n assert.equal(callbackCalled, false);\n resolve();\n await promise;\n assert.equal(callbackCalled, true);\n },\n \"cache hit while key in use, then replace (check refCount works properly)\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 1);\n let resolve1, resolve2;\n const key1 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1);\n const p1 = loader.useKey(key1, async session => {\n await new Promise(r => resolve1 = r);\n });\n const p2 = loader.useKey(key1, async session => {\n await new Promise(r => resolve2 = r);\n });\n await Promise.resolve();\n assert.equal(loader.size, 1);\n assert.equal(loader.running, true);\n resolve1();\n await p1;\n assert.equal(loader.running, true);\n resolve2();\n await p2;\n assert.equal(loader.running, false);\n let callbackCalled = false;\n await loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId2, 1), async session => {\n callbackCalled = true;\n assert.equal(session.session_id(), sessionId2);\n assert.equal(session.first_known_index(), 1);\n });\n assert.equal(loader.size, 1);\n assert.equal(callbackCalled, true);\n },\n \"cache hit while key not in use\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n let resolve1, resolve2, invocations = 0;\n const key1 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1);\n await loader.useKey(key1, async session => { invocations += 1; });\n key1.isBetter = true;\n assert.equal(loader.size, 1);\n const cachedKey = loader.getCachedKey(roomId, aliceSenderKey, sessionId1)!;\n assert.equal(cachedKey, key1);\n await loader.useKey(cachedKey, async session => { invocations += 1; });\n assert.equal(loader.size, 1);\n assert.equal(invocations, 2);\n },\n \"dispose calls free on all sessions\": async assert => {\n instances = 0;\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n await loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1), async session => {});\n await loader.useKey(new MockRoomKey(roomId, aliceSenderKey, sessionId2, 1), async session => {});\n assert.equal(instances, 2);\n assert.equal(loader.size, 2);\n loader.dispose();\n assert.strictEqual(instances, 0, \"instances\");\n assert.strictEqual(loader.size, 0, \"loader.size\");\n },\n \"checkBetterThanKeyInStorage false with cache\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n const key1 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 2);\n await loader.useKey(key1, async session => {});\n // fake we've checked with storage that this is the best key,\n // and as long is it remains the best key with newly added keys,\n // it will be returned from getCachedKey (as called from checkBetterThanKeyInStorage)\n key1.isBetter = true;\n const key2 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 3);\n // this will hit cache of key 1 so we pass in null as txn\n const isBetter = await key2.checkBetterThanKeyInStorage(loader, null as any);\n assert.strictEqual(isBetter, false);\n assert.strictEqual(key2.isBetter, false);\n },\n \"checkBetterThanKeyInStorage true with cache\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n const key1 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 2);\n key1.isBetter = true; // fake we've check with storage so far (not including key2) this is the best key\n await loader.useKey(key1, async session => {});\n const key2 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 1);\n // this will hit cache of key 1 so we pass in null as txn\n const isBetter = await key2.checkBetterThanKeyInStorage(loader, null as any);\n assert.strictEqual(isBetter, true);\n assert.strictEqual(key2.isBetter, true);\n },\n \"prefer to remove worst key for a session from cache\": async assert => {\n const loader = new KeyLoader(olm as any as Olm, PICKLE_KEY, 2);\n const key1 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 2);\n await loader.useKey(key1, async session => {});\n key1.isBetter = true; // set to true just so it gets returned from getCachedKey\n const key2 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 4);\n await loader.useKey(key2, async session => {});\n const key3 = new MockRoomKey(roomId, aliceSenderKey, sessionId1, 3);\n await loader.useKey(key3, async session => {});\n assert.strictEqual(loader.getCachedKey(roomId, aliceSenderKey, sessionId1), key1);\n },\n }\n}\n","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MEGOLM_ALGORITHM} from \"../../common\";\nimport type {RoomKey} from \"../decryption/RoomKey\";\n\nimport type {BaseBackupInfo, SignatureMap, SessionKeyInfo} from \"./types\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nexport const Algorithm = \"m.megolm_backup.v1.curve25519-aes-sha2\";\n\nexport type BackupInfo = BaseBackupInfo & {\n algorithm: typeof Algorithm,\n auth_data: AuthData,\n}\n\ntype AuthData = {\n public_key: string,\n signatures: SignatureMap\n}\n\nexport type SessionData = {\n ciphertext: string,\n mac: string,\n ephemeral: string,\n}\n\nexport class BackupEncryption {\n constructor(\n private encryption?: Olm.PkEncryption,\n private decryption?: Olm.PkDecryption\n ) {}\n\n static fromAuthData(authData: AuthData, privateKey: Uint8Array, olm: Olm): BackupEncryption {\n const expectedPubKey = authData.public_key;\n const decryption = new olm.PkDecryption();\n const encryption = new olm.PkEncryption();\n try {\n const pubKey = decryption.init_with_private_key(privateKey);\n if (pubKey !== expectedPubKey) {\n throw new Error(`Bad backup key, public key does not match. Calculated ${pubKey} but expected ${expectedPubKey}`);\n }\n encryption.set_recipient_key(pubKey);\n } catch(err) {\n decryption.free();\n throw err;\n }\n return new BackupEncryption(encryption, decryption);\n }\n\n decryptRoomKey(sessionData: SessionData): SessionKeyInfo {\n const sessionInfo = this.decryption!.decrypt(\n sessionData.ephemeral,\n sessionData.mac,\n sessionData.ciphertext,\n );\n return JSON.parse(sessionInfo) as SessionKeyInfo;\n }\n\n encryptRoomKey(key: RoomKey, sessionKey: string): SessionData {\n const sessionInfo: SessionKeyInfo = {\n algorithm: MEGOLM_ALGORITHM,\n sender_key: key.senderKey,\n sender_claimed_keys: {ed25519: key.claimedEd25519Key},\n forwarding_curve25519_key_chain: [],\n session_key: sessionKey\n };\n return this.encryption!.encrypt(JSON.stringify(sessionInfo)) as SessionData;\n }\n\n dispose() {\n this.decryption?.free();\n this.decryption = undefined;\n this.encryption?.free();\n this.encryption = undefined;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {StoreNames} from \"../../../storage/common\";\nimport {StoredRoomKey, keyFromBackup} from \"../decryption/RoomKey\";\nimport {MEGOLM_ALGORITHM} from \"../../common\";\nimport * as Curve25519 from \"./Curve25519\";\nimport {AbortableOperation} from \"../../../../utils/AbortableOperation\";\nimport {ObservableValue} from \"../../../../observable/ObservableValue\";\n\nimport {SetAbortableFn} from \"../../../../utils/AbortableOperation\";\nimport type {BackupInfo, SessionData, SessionKeyInfo, SessionInfo, KeyBackupPayload} from \"./types\";\nimport type {HomeServerApi} from \"../../../net/HomeServerApi\";\nimport type {IncomingRoomKey, RoomKey} from \"../decryption/RoomKey\";\nimport type {KeyLoader} from \"../decryption/KeyLoader\";\nimport type {SecretStorage} from \"../../../ssss/SecretStorage\";\nimport type {Storage} from \"../../../storage/idb/Storage\";\nimport type {ILogItem} from \"../../../../logging/types\";\nimport type {Platform} from \"../../../../platform/web/Platform\";\nimport type {Transaction} from \"../../../storage/idb/Transaction\";\nimport type * as OlmNamespace from \"@matrix-org/olm\";\ntype Olm = typeof OlmNamespace;\n\nconst KEYS_PER_REQUEST = 200;\n\nexport class KeyBackup {\n public readonly operationInProgress = new ObservableValue, Progress> | undefined>(undefined);\n\n private _stopped = false;\n private _needsNewKey = false;\n private _hasBackedUpAllKeys = false;\n private _error?: Error;\n\n constructor(\n private readonly backupInfo: BackupInfo,\n private readonly crypto: Curve25519.BackupEncryption,\n private readonly hsApi: HomeServerApi,\n private readonly keyLoader: KeyLoader,\n private readonly storage: Storage,\n private readonly platform: Platform,\n private readonly maxDelay: number = 10000\n ) {}\n\n get hasStopped(): boolean { return this._stopped; }\n get error(): Error | undefined { return this._error; }\n get version(): string { return this.backupInfo.version; }\n get needsNewKey(): boolean { return this._needsNewKey; }\n get hasBackedUpAllKeys(): boolean { return this._hasBackedUpAllKeys; }\n\n async getRoomKey(roomId: string, sessionId: string, log: ILogItem): Promise {\n const sessionResponse = await this.hsApi.roomKeyForRoomAndSession(this.backupInfo.version, roomId, sessionId, {log}).response();\n if (!sessionResponse.session_data) {\n return;\n }\n const sessionKeyInfo = this.crypto.decryptRoomKey(sessionResponse.session_data as SessionData);\n if (sessionKeyInfo?.algorithm === MEGOLM_ALGORITHM) {\n return keyFromBackup(roomId, sessionId, sessionKeyInfo);\n } else if (sessionKeyInfo?.algorithm) {\n log.set(\"unknown algorithm\", sessionKeyInfo.algorithm);\n }\n }\n\n markAllForBackup(txn: Transaction): Promise {\n return txn.inboundGroupSessions.markAllAsNotBackedUp();\n }\n\n flush(log: ILogItem): void {\n if (!this.operationInProgress.get()) {\n log.wrapDetached(\"flush key backup\", async log => {\n if (this._needsNewKey) {\n log.set(\"needsNewKey\", this._needsNewKey);\n return;\n }\n this._stopped = false;\n this._error = undefined;\n this._hasBackedUpAllKeys = false;\n const operation = this._runFlushOperation(log);\n this.operationInProgress.set(operation);\n try {\n await operation.result;\n this._hasBackedUpAllKeys = true;\n } catch (err) {\n this._stopped = true;\n if (err.name === \"HomeServerError\" && (err.errcode === \"M_WRONG_ROOM_KEYS_VERSION\" || err.errcode === \"M_NOT_FOUND\")) {\n log.set(\"wrong_version\", true);\n this._needsNewKey = true;\n } else {\n // TODO should really also use AbortError in storage\n if (err.name !== \"AbortError\" || (err.name === \"StorageError\" && err.errcode === \"AbortError\")) {\n this._error = err;\n }\n }\n log.catch(err);\n }\n this.operationInProgress.set(undefined);\n });\n }\n }\n\n private _runFlushOperation(log: ILogItem): AbortableOperation, Progress> {\n return new AbortableOperation(async (setAbortable, setProgress) => {\n let total = 0;\n let amountFinished = 0;\n while (true) {\n const waitMs = this.platform.random() * this.maxDelay;\n const timeout = this.platform.clock.createTimeout(waitMs);\n setAbortable(timeout);\n await timeout.elapsed();\n const txn = await this.storage.readTxn([StoreNames.inboundGroupSessions]);\n setAbortable(txn);\n // fetch total again on each iteration as while we are flushing, sync might be adding keys\n total = amountFinished + await txn.inboundGroupSessions.countNonBackedUpSessions();\n setProgress(new Progress(total, amountFinished));\n const keysNeedingBackup = (await txn.inboundGroupSessions.getFirstNonBackedUpSessions(KEYS_PER_REQUEST))\n .map(entry => new StoredRoomKey(entry));\n if (keysNeedingBackup.length === 0) {\n log.set(\"total\", total);\n return;\n }\n const payload = await this.encodeKeysForBackup(keysNeedingBackup);\n const uploadRequest = this.hsApi.uploadRoomKeysToBackup(this.backupInfo.version, payload, {log});\n setAbortable(uploadRequest);\n await uploadRequest.response();\n await this.markKeysAsBackedUp(keysNeedingBackup, setAbortable);\n amountFinished += keysNeedingBackup.length;\n setProgress(new Progress(total, amountFinished));\n }\n });\n }\n\n private async encodeKeysForBackup(roomKeys: RoomKey[]): Promise {\n const payload: KeyBackupPayload = { rooms: {} };\n const payloadRooms = payload.rooms;\n for (const key of roomKeys) {\n let roomPayload = payloadRooms[key.roomId];\n if (!roomPayload) {\n roomPayload = payloadRooms[key.roomId] = { sessions: {} };\n }\n roomPayload.sessions[key.sessionId] = await this.encodeRoomKey(key);\n }\n return payload;\n }\n\n private async markKeysAsBackedUp(roomKeys: RoomKey[], setAbortable: SetAbortableFn) {\n const txn = await this.storage.readWriteTxn([\n StoreNames.inboundGroupSessions,\n ]);\n setAbortable(txn);\n try {\n await Promise.all(roomKeys.map(key => {\n return txn.inboundGroupSessions.markAsBackedUp(key.roomId, key.senderKey, key.sessionId);\n }));\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n }\n\n private async encodeRoomKey(roomKey: RoomKey): Promise {\n return await this.keyLoader.useKey(roomKey, session => {\n const firstMessageIndex = session.first_known_index();\n const sessionKey = session.export_session(firstMessageIndex);\n return {\n first_message_index: firstMessageIndex,\n forwarded_count: 0,\n is_verified: false,\n session_data: this.crypto.encryptRoomKey(roomKey, sessionKey)\n };\n });\n }\n\n dispose() {\n this.crypto.dispose();\n }\n\n static async fromSecretStorage(platform: Platform, olm: Olm, secretStorage: SecretStorage, hsApi: HomeServerApi, keyLoader: KeyLoader, storage: Storage, txn: Transaction): Promise {\n const base64PrivateKey = await secretStorage.readSecret(\"m.megolm_backup.v1\", txn);\n if (base64PrivateKey) {\n const privateKey = new Uint8Array(platform.encoding.base64.decode(base64PrivateKey));\n const backupInfo = await hsApi.roomKeysVersion().response() as BackupInfo;\n if (backupInfo.algorithm === Curve25519.Algorithm) {\n const crypto = Curve25519.BackupEncryption.fromAuthData(backupInfo.auth_data, privateKey, olm);\n return new KeyBackup(backupInfo, crypto, hsApi, keyLoader, storage, platform);\n } else {\n throw new Error(`Unknown backup algorithm: ${backupInfo.algorithm}`);\n }\n }\n }\n}\n\nexport class Progress {\n constructor(\n public readonly total: number,\n public readonly finished: number\n ) {}\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MEGOLM_ALGORITHM} from \"../common.js\";\nimport {OutboundRoomKey} from \"./decryption/RoomKey\";\n\nexport class Encryption {\n constructor({pickleKey, olm, account, keyLoader, storage, now, ownDeviceId}) {\n this._pickleKey = pickleKey;\n this._olm = olm;\n this._account = account;\n this._keyLoader = keyLoader;\n this._storage = storage;\n this._now = now;\n this._ownDeviceId = ownDeviceId;\n }\n\n discardOutboundSession(roomId, txn) {\n txn.outboundGroupSessions.remove(roomId);\n }\n\n async createRoomKeyMessage(roomId, txn) {\n let sessionEntry = await txn.outboundGroupSessions.get(roomId);\n if (sessionEntry) {\n const session = new this._olm.OutboundGroupSession();\n try {\n session.unpickle(this._pickleKey, sessionEntry.session);\n return this._createRoomKeyMessage(session, roomId);\n } finally {\n session.free();\n }\n }\n }\n\n createWithheldMessage(roomMessage, code, reason) {\n return {\n algorithm: roomMessage.algorithm,\n code,\n reason,\n room_id: roomMessage.room_id,\n sender_key: this._account.identityKeys.curve25519,\n session_id: roomMessage.session_id\n };\n }\n\n async ensureOutboundSession(roomId, encryptionParams) {\n let session = new this._olm.OutboundGroupSession();\n try {\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.inboundGroupSessions,\n this._storage.storeNames.outboundGroupSessions,\n ]);\n let roomKeyMessage;\n try {\n let sessionEntry = await txn.outboundGroupSessions.get(roomId);\n roomKeyMessage = await this._readOrCreateSession(session, sessionEntry, roomId, encryptionParams, txn);\n if (roomKeyMessage) {\n this._writeSession(this._now(), session, roomId, txn);\n }\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n return roomKeyMessage;\n } finally {\n session.free();\n }\n }\n\n async _readOrCreateSession(session, sessionEntry, roomId, encryptionParams, txn) {\n if (sessionEntry) {\n session.unpickle(this._pickleKey, sessionEntry.session);\n }\n if (!sessionEntry || this._needsToRotate(session, sessionEntry.createdAt, encryptionParams)) {\n // in the case of rotating, recreate a session as we already unpickled into it\n if (sessionEntry) {\n session.free();\n session = new this._olm.OutboundGroupSession();\n }\n session.create();\n const roomKeyMessage = this._createRoomKeyMessage(session, roomId);\n const roomKey = new OutboundRoomKey(roomId, session, this._account.identityKeys);\n await roomKey.write(this._keyLoader, txn);\n return roomKeyMessage;\n }\n }\n\n _writeSession(createdAt, session, roomId, txn) {\n txn.outboundGroupSessions.set({\n roomId,\n session: session.pickle(this._pickleKey),\n createdAt,\n });\n }\n\n /**\n * Encrypts a message with megolm\n * @param {string} roomId \n * @param {string} type event type to encrypt\n * @param {string} content content to encrypt\n * @param {object} encryptionParams the content of the m.room.encryption event\n * @return {Promise}\n */\n async encrypt(roomId, type, content, encryptionParams) {\n let session = new this._olm.OutboundGroupSession();\n try {\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.inboundGroupSessions,\n this._storage.storeNames.outboundGroupSessions,\n ]);\n let roomKeyMessage;\n let encryptedContent;\n try {\n let sessionEntry = await txn.outboundGroupSessions.get(roomId);\n roomKeyMessage = await this._readOrCreateSession(session, sessionEntry, roomId, encryptionParams, txn);\n encryptedContent = this._encryptContent(roomId, session, type, content);\n // update timestamp when a new session is created\n const createdAt = roomKeyMessage ? this._now() : sessionEntry.createdAt;\n this._writeSession(createdAt, session, roomId, txn);\n\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n return new EncryptionResult(encryptedContent, roomKeyMessage);\n } finally {\n if (session) {\n session.free();\n }\n }\n }\n\n _needsToRotate(session, createdAt, encryptionParams) {\n let rotationPeriodMs = 604800000; // default\n if (Number.isSafeInteger(encryptionParams?.rotation_period_ms)) {\n rotationPeriodMs = encryptionParams?.rotation_period_ms;\n }\n let rotationPeriodMsgs = 100; // default\n if (Number.isSafeInteger(encryptionParams?.rotation_period_msgs)) {\n rotationPeriodMsgs = encryptionParams?.rotation_period_msgs;\n }\n\n if (this._now() > (createdAt + rotationPeriodMs)) {\n return true;\n }\n if (session.message_index() >= rotationPeriodMsgs) {\n return true;\n } \n }\n\n _encryptContent(roomId, session, type, content) {\n const plaintext = JSON.stringify({\n room_id: roomId,\n type,\n content\n });\n const ciphertext = session.encrypt(plaintext);\n\n const encryptedContent = {\n algorithm: MEGOLM_ALGORITHM,\n sender_key: this._account.identityKeys.curve25519,\n ciphertext,\n session_id: session.session_id(),\n device_id: this._ownDeviceId\n };\n\n return encryptedContent;\n }\n\n _createRoomKeyMessage(session, roomId) {\n return {\n room_id: roomId,\n session_id: session.session_id(),\n session_key: session.session_key(),\n algorithm: MEGOLM_ALGORITHM,\n // chain_index is ignored by element-web if not all clients\n // but let's send it anyway, as element-web does so\n chain_index: session.message_index()\n }\n }\n}\n\n/**\n * @property {object?} roomKeyMessage if encrypting this message\n * created a new outbound session,\n * this contains the content of the m.room_key message\n * that should be sent out over olm.\n * @property {object} content the encrypted message as the content of\n * the m.room.encrypted event that should be sent out \n */\nclass EncryptionResult {\n constructor(content, roomKeyMessage) {\n this.content = content;\n this.roomKeyMessage = roomKeyMessage;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {LogLevel, LogFilter} from \"./LogFilter\";\nimport type {BaseLogger} from \"./BaseLogger\";\nimport type {ISerializedItem, ILogItem, LogItemValues, LabelOrValues, FilterCreator, LogCallback} from \"./types\";\n\nexport class LogItem implements ILogItem {\n public readonly start: number;\n public logLevel: LogLevel;\n public error?: Error;\n public end?: number;\n private _values: LogItemValues;\n private _logger: BaseLogger;\n private _filterCreator?: FilterCreator;\n private _children?: Array;\n\n constructor(labelOrValues: LabelOrValues, logLevel: LogLevel, logger: BaseLogger, filterCreator?: FilterCreator) {\n this._logger = logger;\n this.start = logger._now();\n // (l)abel\n this._values = typeof labelOrValues === \"string\" ? {l: labelOrValues} : labelOrValues;\n this.logLevel = logLevel;\n this._filterCreator = filterCreator;\n }\n\n /** start a new root log item and run it detached mode, see BaseLogger.runDetached */\n runDetached(labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem {\n return this._logger.runDetached(labelOrValues, callback, logLevel, filterCreator);\n }\n\n /** start a new detached root log item and log a reference to it from this item */\n wrapDetached(labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): void {\n this.refDetached(this.runDetached(labelOrValues, callback, logLevel, filterCreator));\n }\n\n /** logs a reference to a different log item, usually obtained from runDetached.\n This is useful if the referenced operation can't be awaited. */\n refDetached(logItem: ILogItem, logLevel?: LogLevel): void {\n logItem.ensureRefId();\n this.log({ref: logItem.values.refId}, logLevel);\n }\n\n ensureRefId(): void {\n if (!this._values.refId) {\n this.set(\"refId\", this._logger._createRefId());\n }\n }\n\n /**\n * Creates a new child item and runs it in `callback`.\n */\n wrap(labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): T {\n const item = this.child(labelOrValues, logLevel, filterCreator);\n return item.run(callback);\n }\n\n get duration(): number | undefined {\n if (this.end) {\n return this.end - this.start;\n } else {\n return undefined;\n }\n }\n\n durationWithoutType(type: string): number | undefined {\n const durationOfType = this.durationOfType(type);\n if (this.duration && durationOfType) {\n return this.duration - durationOfType;\n }\n }\n\n durationOfType(type: string): number | undefined {\n if (this._values.t === type) {\n return this.duration;\n } else if (this._children) {\n return this._children.reduce((sum, c) => {\n const duration = c.durationOfType(type);\n return sum + (duration ?? 0);\n }, 0);\n } else {\n return 0;\n }\n }\n \n /**\n * Creates a new child item that finishes immediately\n * Finished items should not be modified anymore as they can be serialized\n * at any stage, but using `set` on the return value in a synchronous way should still be safe.\n */\n log(labelOrValues: LabelOrValues, logLevel?: LogLevel): ILogItem {\n const item = this.child(labelOrValues, logLevel);\n item.end = item.start;\n return item;\n }\n\n set(key: string | object, value?: unknown): ILogItem {\n if(typeof key === \"object\") {\n const values = key;\n Object.assign(this._values, values);\n } else {\n this._values[key] = value;\n }\n return this;\n }\n\n serialize(filter: LogFilter, parentStartTime: number | undefined, forced: boolean): ISerializedItem | undefined {\n if (this._filterCreator) {\n try {\n filter = this._filterCreator(new LogFilter(filter), this);\n } catch (err) {\n console.error(\"Error creating log filter\", err);\n }\n }\n let children: Array | null = null;\n if (this._children) {\n children = this._children.reduce((array: Array, c) => {\n const s = c.serialize(filter, this.start, false);\n if (s) {\n if (array === null) {\n array = [];\n }\n array.push(s);\n }\n return array;\n }, null);\n }\n if (filter && !filter.filter(this, children)) {\n return;\n }\n // in (v)alues, (l)abel and (t)ype are also reserved.\n const item: ISerializedItem = {\n // (s)tart\n s: typeof parentStartTime === \"number\" ? this.start - parentStartTime : this.start,\n // (d)uration\n d: this.duration,\n // (v)alues\n v: this._values,\n // (l)evel\n l: this.logLevel\n };\n if (this.error) {\n // (e)rror\n item.e = {\n stack: this.error.stack,\n name: this.error.name,\n message: this.error.message.split(\"\\n\")[0]\n };\n }\n if (forced) {\n item.f = true; //(f)orced\n }\n if (children) {\n // (c)hildren\n item.c = children;\n }\n return item;\n }\n\n /**\n * You probably want to use `wrap` instead of this.\n * \n * Runs a callback passing this log item,\n * recording the timing and any error.\n *\n * callback can return a Promise.\n *\n * Should only be called once.\n * \n * @param {Function} callback [description]\n * @return {[type]} [description]\n */\n run(callback: LogCallback): T {\n if (this.end !== undefined) {\n console.trace(\"log item is finished, additional logs will likely not be recorded\");\n }\n try {\n const result = callback(this);\n if (result instanceof Promise) {\n return result.then(promiseResult => {\n this.finish();\n return promiseResult;\n }, err => {\n throw this.catch(err);\n }) as unknown as T;\n } else {\n this.finish();\n return result;\n }\n } catch (err) {\n throw this.catch(err);\n }\n }\n\n /**\n * finished the item, recording the end time. After finishing, an item can't be modified anymore as it will be persisted.\n * @internal shouldn't typically be called by hand. allows to force finish if a promise is still running when closing the app\n */\n finish(): void {\n if (this.end === undefined) {\n if (this._children) {\n for(const c of this._children) {\n c.finish();\n }\n }\n this.end = this._logger._now();\n }\n }\n\n // expose log level without needing import everywhere\n get level(): typeof LogLevel {\n return LogLevel;\n }\n\n catch(err: Error): Error {\n this.error = err;\n this.logLevel = LogLevel.Error;\n this.finish();\n return err;\n }\n\n child(labelOrValues: LabelOrValues, logLevel?: LogLevel, filterCreator?: FilterCreator): LogItem {\n if (this.end) {\n console.trace(\"log item is finished, additional logs will likely not be recorded\");\n }\n if (!logLevel) {\n logLevel = this.logLevel || LogLevel.Info;\n }\n const item = new LogItem(labelOrValues, logLevel, this._logger, filterCreator);\n if (!this._children) {\n this._children = [];\n }\n this._children.push(item);\n return item;\n }\n\n get logger(): BaseLogger {\n return this._logger;\n }\n\n get values(): LogItemValues {\n return this._values;\n }\n\n get children(): Array | undefined {\n return this._children;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {LogItem} from \"./LogItem\";\nimport {LogLevel, LogFilter} from \"./LogFilter\";\nimport type {ILogger, ILogExport, FilterCreator, LabelOrValues, LogCallback, ILogItem, ISerializedItem} from \"./types\";\nimport type {Platform} from \"../platform/web/Platform.js\";\n\nexport abstract class BaseLogger implements ILogger {\n protected _openItems: Set = new Set();\n protected _platform: Platform;\n protected _serializedTransformer: (item: ISerializedItem) => ISerializedItem;\n\n constructor({platform, serializedTransformer = (item: ISerializedItem) => item}) {\n this._platform = platform;\n this._serializedTransformer = serializedTransformer;\n }\n\n log(labelOrValues: LabelOrValues, logLevel: LogLevel = LogLevel.Info): void {\n const item = new LogItem(labelOrValues, logLevel, this);\n item.end = item.start;\n this._persistItem(item, undefined, false);\n }\n\n /** if item is a log item, wrap the callback in a child of it, otherwise start a new root log item. */\n wrapOrRun(item: ILogItem | undefined, labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): T {\n if (item) {\n return item.wrap(labelOrValues, callback, logLevel, filterCreator);\n } else {\n return this.run(labelOrValues, callback, logLevel, filterCreator);\n }\n }\n\n /** run a callback in detached mode,\n where the (async) result or errors are not propagated but still logged.\n Useful to pair with LogItem.refDetached.\n\n @return {ILogItem} the log item added, useful to pass to LogItem.refDetached */\n runDetached(labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): ILogItem {\n if (!logLevel) {\n logLevel = LogLevel.Info;\n }\n const item = new LogItem(labelOrValues, logLevel, this);\n this._run(item, callback, logLevel, false /* don't throw, nobody is awaiting */, filterCreator);\n return item;\n }\n\n /** run a callback wrapped in a log operation.\n Errors and duration are transparently logged, also for async operations.\n Whatever the callback returns is returned here. */\n run(labelOrValues: LabelOrValues, callback: LogCallback, logLevel?: LogLevel, filterCreator?: FilterCreator): T {\n if (logLevel === undefined) {\n logLevel = LogLevel.Info;\n }\n const item = new LogItem(labelOrValues, logLevel, this);\n return this._run(item, callback, logLevel, true, filterCreator);\n }\n\n _run(item: LogItem, callback: LogCallback, logLevel: LogLevel, wantResult: true, filterCreator?: FilterCreator): T;\n // we don't return if we don't throw, as we don't have anything to return when an error is caught but swallowed for the fire-and-forget case.\n _run(item: LogItem, callback: LogCallback, logLevel: LogLevel, wantResult: false, filterCreator?: FilterCreator): void;\n _run(item: LogItem, callback: LogCallback, logLevel: LogLevel, wantResult: boolean, filterCreator?: FilterCreator): T | void {\n this._openItems.add(item);\n\n const finishItem = () => {\n let filter = new LogFilter();\n if (filterCreator) {\n try {\n filter = filterCreator(filter, item);\n } catch (err) {\n console.error(\"Error while creating log filter\", err);\n }\n } else {\n // if not filter is specified, filter out anything lower than the initial log level\n filter = filter.minLevel(logLevel);\n }\n try {\n this._persistItem(item, filter, false);\n } catch (err) {\n console.error(\"Could not persist log item\", err);\n }\n this._openItems.delete(item);\n };\n\n try {\n let result = item.run(callback);\n if (result instanceof Promise) {\n result = result.then(promiseResult => {\n finishItem();\n return promiseResult;\n }, err => {\n finishItem();\n if (wantResult) {\n throw err;\n }\n }) as unknown as T;\n if (wantResult) {\n return result;\n }\n } else {\n finishItem();\n if(wantResult) {\n return result;\n }\n }\n } catch (err) {\n finishItem();\n if (wantResult) {\n throw err;\n }\n }\n }\n\n _finishOpenItems() {\n for (const openItem of this._openItems) {\n openItem.finish();\n try {\n // for now, serialize with an all-permitting filter\n // as the createFilter function would get a distorted image anyway\n // about the duration of the item, etc ...\n // true for force finish\n this._persistItem(openItem, new LogFilter(), true);\n } catch (err) {\n console.error(\"Could not serialize log item\", err);\n }\n }\n this._openItems.clear();\n }\n\n abstract _persistItem(item: LogItem, filter?: LogFilter, forced?: boolean): void;\n\n abstract export(): Promise;\n\n // expose log level without needing \n get level(): typeof LogLevel {\n return LogLevel;\n }\n\n _now(): number {\n return this._platform.clock.now();\n }\n\n _createRefId(): number {\n return Math.round(this._platform.random() * Number.MAX_SAFE_INTEGER);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {BaseLogger} from \"./BaseLogger\";\nimport {LogItem} from \"./LogItem\";\nimport type {ILogItem, LogItemValues, ILogExport} from \"./types\";\n\nexport class ConsoleLogger extends BaseLogger {\n _persistItem(item: LogItem): void {\n printToConsole(item);\n }\n\n async export(): Promise {\n return undefined;\n }\n}\n\nconst excludedKeysFromTable = [\"l\", \"id\"];\nfunction filterValues(values: LogItemValues): LogItemValues | null {\n return Object.entries(values)\n .filter(([key]) => !excludedKeysFromTable.includes(key))\n .reduce((obj: LogItemValues, [key, value]) => {\n obj = obj || {};\n obj[key] = value;\n return obj;\n }, null);\n}\n\nfunction printToConsole(item: LogItem): void {\n const label = `${itemCaption(item)} (${item.duration}ms)`;\n const filteredValues = filterValues(item.values);\n const shouldGroup = item.children || filteredValues;\n if (shouldGroup) {\n if (item.error) {\n console.group(label);\n } else {\n console.groupCollapsed(label);\n }\n if (item.error) {\n console.error(item.error);\n }\n } else {\n if (item.error) {\n console.error(item.error);\n } else {\n console.log(label);\n }\n }\n if (filteredValues) {\n console.table(filteredValues);\n }\n if (item.children) {\n for(const c of item.children) {\n printToConsole(c);\n }\n }\n if (shouldGroup) {\n console.groupEnd();\n }\n}\n\nfunction itemCaption(item: ILogItem): string {\n if (item.values.t === \"network\") {\n return `${item.values.method} ${item.values.url}`;\n } else if (item.values.l && typeof item.values.id !== \"undefined\") {\n return `${item.values.l} ${item.values.id}`;\n } else if (item.values.l && typeof item.values.status !== \"undefined\") {\n return `${item.values.l} (${item.values.status})`;\n } else if (item.values.l && item.error) {\n return `${item.values.l} failed`;\n } else if (typeof item.values.ref !== \"undefined\") {\n return `ref ${item.values.ref}`;\n } else {\n return item.values.l || item.values.type;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {MEGOLM_ALGORITHM, DecryptionSource} from \"./common.js\";\nimport {groupEventsBySession} from \"./megolm/decryption/utils\";\nimport {mergeMap} from \"../../utils/mergeMap\";\nimport {groupBy} from \"../../utils/groupBy\";\nimport {makeTxnId} from \"../common.js\";\nimport {iterateResponseStateEvents} from \"../room/common\";\n\nconst ENCRYPTED_TYPE = \"m.room.encrypted\";\nconst ROOM_HISTORY_VISIBILITY_TYPE = \"m.room.history_visibility\";\n// how often ensureMessageKeyIsShared can check if it needs to\n// create a new outbound session\n// note that encrypt could still create a new session\nconst MIN_PRESHARE_INTERVAL = 60 * 1000; // 1min\n\n// TODO: this class is a good candidate for splitting up into encryption and decryption, there doesn't seem to be much overlap\nexport class RoomEncryption {\n constructor({room, deviceTracker, olmEncryption, megolmEncryption, megolmDecryption, encryptionParams, storage, keyBackup, notifyMissingMegolmSession, clock}) {\n this._room = room;\n this._deviceTracker = deviceTracker;\n this._olmEncryption = olmEncryption;\n this._megolmEncryption = megolmEncryption;\n this._megolmDecryption = megolmDecryption;\n // content of the m.room.encryption event\n this._encryptionParams = encryptionParams;\n // caches devices to verify events\n this._senderDeviceCache = new Map();\n this._storage = storage;\n this._keyBackup = keyBackup;\n this._notifyMissingMegolmSession = notifyMissingMegolmSession;\n this._clock = clock;\n this._isFlushingRoomKeyShares = false;\n this._lastKeyPreShareTime = null;\n this._keySharePromise = null;\n this._historyVisibility = undefined;\n this._disposed = false;\n }\n\n enableKeyBackup(keyBackup) {\n if (this._keyBackup && !!keyBackup) {\n return;\n }\n this._keyBackup = keyBackup;\n }\n\n async restoreMissingSessionsFromBackup(entries, log) {\n const events = entries.filter(e => e.isEncrypted && !e.isDecrypted && e.event).map(e => e.event);\n const eventsBySession = groupEventsBySession(events);\n const groups = Array.from(eventsBySession.values());\n const txn = await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);\n const hasSessions = await Promise.all(groups.map(async group => {\n return this._megolmDecryption.hasSession(this._room.id, group.senderKey, group.sessionId, txn);\n }));\n const missingSessions = groups.filter((_, i) => !hasSessions[i]);\n if (missingSessions.length) {\n // start with last sessions which should be for the last items in the timeline\n for (var i = missingSessions.length - 1; i >= 0; i--) {\n const session = missingSessions[i];\n await log.wrap(\"session\", log => this._requestMissingSessionFromBackup(session.senderKey, session.sessionId, log));\n }\n }\n }\n\n notifyTimelineClosed() {\n this._senderDeviceCache = new Map(); // purge the sender device cache\n }\n\n async writeSync(roomResponse, memberChanges, txn, log) {\n let historyVisibility = await this._loadHistoryVisibilityIfNeeded(this._historyVisibility, txn);\n const addedMembers = [];\n const removedMembers = [];\n // update the historyVisibility if needed\n await iterateResponseStateEvents(roomResponse, event => {\n // TODO: can the same state event appear twice? Hence we would be rewriting the useridentities twice...\n // we'll see in the logs\n if(event.state_key === \"\" && event.type === ROOM_HISTORY_VISIBILITY_TYPE) {\n const newHistoryVisibility = event?.content?.history_visibility;\n if (newHistoryVisibility !== historyVisibility) {\n return log.wrap({\n l: \"history_visibility changed\",\n from: historyVisibility,\n to: newHistoryVisibility\n }, async log => {\n historyVisibility = newHistoryVisibility;\n const result = await this._deviceTracker.writeHistoryVisibility(this._room, historyVisibility, txn, log);\n addedMembers.push(...result.added);\n removedMembers.push(...result.removed);\n });\n }\n }\n });\n // process member changes\n if (memberChanges.size) {\n const result = await this._deviceTracker.writeMemberChanges(\n this._room, memberChanges, historyVisibility, txn);\n addedMembers.push(...result.added);\n removedMembers.push(...result.removed);\n }\n // discard key if somebody (including ourselves) left\n if (removedMembers.length) {\n log.log({\n l: \"discardOutboundSession\",\n leftUsers: removedMembers,\n });\n this._megolmEncryption.discardOutboundSession(this._room.id, txn);\n }\n let shouldFlush = false;\n // add room to userIdentities if needed, and share the current key with them\n if (addedMembers.length) {\n shouldFlush = await this._addShareRoomKeyOperationForMembers(addedMembers, txn, log);\n }\n return {shouldFlush, historyVisibility};\n }\n\n afterSync({historyVisibility}) {\n this._historyVisibility = historyVisibility;\n }\n\n async _loadHistoryVisibilityIfNeeded(historyVisibility, txn = undefined) {\n if (!historyVisibility) {\n if (!txn) {\n txn = await this._storage.readTxn([this._storage.storeNames.roomState]);\n }\n const visibilityEntry = await txn.roomState.get(this._room.id, ROOM_HISTORY_VISIBILITY_TYPE, \"\");\n if (visibilityEntry) {\n return visibilityEntry.event?.content?.history_visibility;\n }\n }\n return historyVisibility;\n }\n\n async prepareDecryptAll(events, newKeys, source, txn) {\n const errors = new Map();\n const validEvents = [];\n for (const event of events) {\n if (event.redacted_because || event.unsigned?.redacted_because) {\n continue;\n }\n if (event.content?.algorithm !== MEGOLM_ALGORITHM) {\n errors.set(event.event_id, new Error(\"Unsupported algorithm: \" + event.content?.algorithm));\n }\n validEvents.push(event);\n }\n const preparation = await this._megolmDecryption.prepareDecryptAll(\n this._room.id, validEvents, newKeys, txn);\n return new DecryptionPreparation(preparation, errors, source, this, events);\n }\n\n async _processDecryptionResults(events, results, errors, source, txn, log) {\n const missingSessionEvents = events.filter(event => {\n const error = errors.get(event.event_id);\n return error?.code === \"MEGOLM_NO_SESSION\";\n });\n if (!missingSessionEvents.length) {\n return;\n }\n // store missing event ids if received from sync\n const missingEventsBySession = groupEventsBySession(missingSessionEvents);\n if (source === DecryptionSource.Sync) {\n await Promise.all(Array.from(missingEventsBySession.values()).map(async group => {\n const eventIds = group.events.map(e => e.event_id);\n return this._megolmDecryption.addMissingKeyEventIds(\n this._room.id, group.senderKey, group.sessionId, eventIds, txn);\n }));\n }\n \n if (!this._keyBackup) {\n return;\n }\n\n log.wrapDetached(\"check key backup\", async log => {\n // if the message came from sync, wait 10s to see if the room key arrives late,\n // and only after that proceed to request from backup\n log.set(\"source\", source);\n log.set(\"events\", missingSessionEvents.length);\n log.set(\"sessions\", missingEventsBySession.size);\n if (source === DecryptionSource.Sync) {\n await this._clock.createTimeout(10000).elapsed();\n if (this._disposed) {\n return;\n }\n // now check which sessions have been received already\n const txn = await this._storage.readTxn([this._storage.storeNames.inboundGroupSessions]);\n await Promise.all(Array.from(missingEventsBySession).map(async ([key, group]) => {\n if (await this._megolmDecryption.hasSession(this._room.id, group.senderKey, group.sessionId, txn)) {\n missingEventsBySession.delete(key);\n }\n }));\n }\n await Promise.all(Array.from(missingEventsBySession.values()).map(group => {\n return log.wrap(\"session\", log => this._requestMissingSessionFromBackup(group.senderKey, group.sessionId, log));\n }));\n });\n }\n\n async _verifyDecryptionResult(result, txn) {\n let device = this._senderDeviceCache.get(result.senderCurve25519Key);\n if (!device) {\n device = await this._deviceTracker.getDeviceByCurve25519Key(result.senderCurve25519Key, txn);\n this._senderDeviceCache.set(result.senderCurve25519Key, device);\n }\n if (device) {\n result.setDevice(device);\n } else if (!this._room.isTrackingMembers) {\n result.setRoomNotTrackedYet();\n }\n }\n\n async _requestMissingSessionFromBackup(senderKey, sessionId, log) {\n // show prompt to enable secret storage\n if (!this._keyBackup) {\n log.set(\"enabled\", false);\n this._notifyMissingMegolmSession();\n return;\n }\n log.set(\"id\", sessionId);\n log.set(\"senderKey\", senderKey);\n try {\n const roomKey = await this._keyBackup.getRoomKey(this._room.id, sessionId, log);\n if (roomKey) {\n if (roomKey.senderKey !== senderKey) {\n log.set(\"wrong_sender_key\", roomKey.senderKey);\n log.logLevel = log.level.Warn;\n return;\n }\n let keyIsBestOne = false;\n let retryEventIds;\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.inboundGroupSessions]);\n try {\n keyIsBestOne = await this._megolmDecryption.writeRoomKey(roomKey, txn);\n log.set(\"isBetter\", keyIsBestOne);\n if (keyIsBestOne) {\n retryEventIds = roomKey.eventIds;\n }\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n if (keyIsBestOne) {\n await log.wrap(\"retryDecryption\", log => this._room.notifyRoomKey(roomKey, retryEventIds || [], log));\n }\n }\n } catch (err) {\n if (!(err.name === \"HomeServerError\" && err.errcode === \"M_NOT_FOUND\")) {\n log.set(\"not_found\", true);\n } else {\n log.error = err;\n log.logLevel = log.level.Error;\n }\n }\n }\n\n /**\n * @param {RoomKey} roomKeys\n * @param {Transaction} txn\n * @return {Promise>} the event ids that should be retried to decrypt\n */\n getEventIdsForMissingKey(roomKey, txn) {\n return this._megolmDecryption.getEventIdsForMissingKey(this._room.id, roomKey.senderKey, roomKey.sessionId, txn);\n }\n\n /** shares the encryption key for the next message if needed */\n async ensureMessageKeyIsShared(hsApi, log) {\n if (this._lastKeyPreShareTime?.measure() < MIN_PRESHARE_INTERVAL) {\n return;\n }\n this._lastKeyPreShareTime = this._clock.createMeasure();\n try {\n this._keySharePromise = (async () => {\n const roomKeyMessage = await this._megolmEncryption.ensureOutboundSession(this._room.id, this._encryptionParams);\n if (roomKeyMessage) {\n this._keyBackup?.flush(log);\n await log.wrap(\"share key\", log => this._shareNewRoomKey(roomKeyMessage, hsApi, log));\n }\n })();\n await this._keySharePromise;\n } finally {\n this._keySharePromise = null;\n }\n }\n\n async encrypt(type, content, hsApi, log) {\n // ensureMessageKeyIsShared is still running,\n // wait for it to create and share a key if needed\n if (this._keySharePromise) {\n log.set(\"waitForRunningKeyShare\", true);\n await this._keySharePromise;\n }\n const megolmResult = await log.wrap(\"megolm encrypt\", () => this._megolmEncryption.encrypt(this._room.id, type, content, this._encryptionParams));\n if (megolmResult.roomKeyMessage) {\n this._keyBackup?.flush(log);\n await log.wrap(\"share key\", log => this._shareNewRoomKey(megolmResult.roomKeyMessage, hsApi, log));\n }\n return {\n type: ENCRYPTED_TYPE,\n content: megolmResult.content\n };\n }\n\n needsToShareKeys(memberChanges) {\n for (const m of memberChanges.values()) {\n if (m.hasJoined) {\n return true;\n }\n }\n return false;\n }\n\n async _shareNewRoomKey(roomKeyMessage, hsApi, log) {\n this._historyVisibility = await this._loadHistoryVisibilityIfNeeded(this._historyVisibility);\n await this._deviceTracker.trackRoom(this._room, this._historyVisibility, log);\n const devices = await this._deviceTracker.devicesForTrackedRoom(this._room.id, hsApi, log);\n const userIds = Array.from(devices.reduce((set, device) => set.add(device.userId), new Set()));\n \n let writeOpTxn = await this._storage.readWriteTxn([this._storage.storeNames.operations]);\n let operation;\n try {\n operation = this._writeRoomKeyShareOperation(roomKeyMessage, userIds, writeOpTxn);\n } catch (err) {\n writeOpTxn.abort();\n throw err;\n }\n // TODO: at this point we have the room key stored, and the rest is sort of optional\n // it would be nice if we could signal SendQueue that any error from here on is non-fatal and\n // return the encrypted payload.\n await this._processShareRoomKeyOperation(operation, hsApi, log);\n }\n\n async _addShareRoomKeyOperationForMembers(userIds, txn, log) {\n const roomKeyMessage = await this._megolmEncryption.createRoomKeyMessage(\n this._room.id, txn);\n if (roomKeyMessage) {\n log.log({\n l: \"share key for new members\", userIds,\n id: roomKeyMessage.session_id,\n chain_index: roomKeyMessage.chain_index\n });\n this._writeRoomKeyShareOperation(roomKeyMessage, userIds, txn);\n return true;\n }\n return false;\n }\n\n async flushPendingRoomKeyShares(hsApi, operations, log) {\n // this has to be reentrant as it can be called from Room.start while still running\n if (this._isFlushingRoomKeyShares) {\n return;\n }\n this._isFlushingRoomKeyShares = true;\n try {\n if (!operations) {\n const txn = await this._storage.readTxn([this._storage.storeNames.operations]);\n operations = await txn.operations.getAllByTypeAndScope(\"share_room_key\", this._room.id);\n }\n for (const operation of operations) {\n // just to be sure\n if (operation.type !== \"share_room_key\") {\n continue;\n }\n await log.wrap(\"operation\", log => this._processShareRoomKeyOperation(operation, hsApi, log));\n }\n } finally {\n this._isFlushingRoomKeyShares = false;\n }\n }\n\n _writeRoomKeyShareOperation(roomKeyMessage, userIds, txn) {\n const id = Math.floor(Math.random() * Number.MAX_SAFE_INTEGER).toString();\n const operation = {\n id,\n type: \"share_room_key\",\n scope: this._room.id,\n userIds,\n roomKeyMessage,\n };\n txn.operations.add(operation);\n return operation;\n }\n\n async _processShareRoomKeyOperation(operation, hsApi, log) {\n log.set(\"id\", operation.id);\n this._historyVisibility = await this._loadHistoryVisibilityIfNeeded(this._historyVisibility);\n await this._deviceTracker.trackRoom(this._room, this._historyVisibility, log);\n const devices = await this._deviceTracker.devicesForRoomMembers(this._room.id, operation.userIds, hsApi, log);\n const messages = await log.wrap(\"olm encrypt\", log => this._olmEncryption.encrypt(\n \"m.room_key\", operation.roomKeyMessage, devices, hsApi, log));\n const missingDevices = devices.filter(d => !messages.some(m => m.device === d));\n await log.wrap(\"send\", log => this._sendMessagesToDevices(ENCRYPTED_TYPE, messages, hsApi, log));\n if (missingDevices.length) {\n await log.wrap(\"missingDevices\", async log => {\n log.set(\"devices\", missingDevices.map(d => d.deviceId));\n const unsentUserIds = operation.userIds.filter(userId => missingDevices.some(d => d.userId === userId));\n log.set(\"unsentUserIds\", unsentUserIds);\n operation.userIds = unsentUserIds;\n // first remove the users that we've sent the keys already from the operation,\n // so if anything fails, we don't send them again\n await this._updateOperationsStore(operations => operations.update(operation));\n // now, let the devices we could not claim their key\n const withheldMessage = this._megolmEncryption.createWithheldMessage(operation.roomKeyMessage, \"m.no_olm\", \"OTKs exhausted\");\n await this._sendSharedMessageToDevices(\"org.matrix.room_key.withheld\", withheldMessage, missingDevices, hsApi, log);\n });\n }\n await this._updateOperationsStore(operations => operations.remove(operation.id));\n }\n\n async _updateOperationsStore(callback) {\n const writeTxn = await this._storage.readWriteTxn([this._storage.storeNames.operations]);\n try {\n callback(writeTxn.operations);\n } catch (err) {\n writeTxn.abort();\n throw err;\n }\n await writeTxn.complete();\n }\n\n async _sendSharedMessageToDevices(type, message, devices, hsApi, log) {\n const devicesByUser = groupBy(devices, device => device.userId);\n const payload = {\n messages: Array.from(devicesByUser.entries()).reduce((userMap, [userId, devices]) => {\n userMap[userId] = devices.reduce((deviceMap, device) => {\n deviceMap[device.deviceId] = message;\n return deviceMap;\n }, {});\n return userMap;\n }, {})\n };\n const txnId = makeTxnId();\n await hsApi.sendToDevice(type, payload, txnId, {log}).response();\n }\n\n async _sendMessagesToDevices(type, messages, hsApi, log) {\n log.set(\"messages\", messages.length);\n const messagesByUser = groupBy(messages, message => message.device.userId);\n const payload = {\n messages: Array.from(messagesByUser.entries()).reduce((userMap, [userId, messages]) => {\n userMap[userId] = messages.reduce((deviceMap, message) => {\n deviceMap[message.device.deviceId] = message.content;\n return deviceMap;\n }, {});\n return userMap;\n }, {})\n };\n const txnId = makeTxnId();\n await hsApi.sendToDevice(type, payload, txnId, {log}).response();\n }\n\n filterUndecryptedEventEntriesForKeys(entries, keys) {\n return entries.filter(entry => {\n if (entry.isEncrypted && !entry.isDecrypted) {\n const {event} = entry;\n if (event) {\n const senderKey = event.content?.[\"sender_key\"];\n const sessionId = event.content?.[\"session_id\"];\n return keys.some(key => senderKey === key.senderKey && sessionId === key.sessionId);\n }\n }\n return false;\n });\n }\n\n dispose() {\n this._disposed = true;\n }\n}\n\n/**\n * wrappers around megolm decryption classes to be able to post-process\n * the decryption results before turning them\n */\nclass DecryptionPreparation {\n constructor(megolmDecryptionPreparation, extraErrors, source, roomEncryption, events) {\n this._megolmDecryptionPreparation = megolmDecryptionPreparation;\n this._extraErrors = extraErrors;\n this._source = source;\n this._roomEncryption = roomEncryption;\n this._events = events;\n }\n\n async decrypt() {\n return new DecryptionChanges(\n await this._megolmDecryptionPreparation.decrypt(),\n this._extraErrors,\n this._source,\n this._roomEncryption,\n this._events);\n }\n\n dispose() {\n this._megolmDecryptionPreparation.dispose();\n }\n}\n\nclass DecryptionChanges {\n constructor(megolmDecryptionChanges, extraErrors, source, roomEncryption, events) {\n this._megolmDecryptionChanges = megolmDecryptionChanges;\n this._extraErrors = extraErrors;\n this._source = source;\n this._roomEncryption = roomEncryption;\n this._events = events;\n }\n\n async write(txn, log) {\n const {results, errors} = await this._megolmDecryptionChanges.write(txn);\n mergeMap(this._extraErrors, errors);\n await this._roomEncryption._processDecryptionResults(this._events, results, errors, this._source, txn, log);\n return new BatchDecryptionResult(results, errors, this._roomEncryption);\n }\n}\n\nclass BatchDecryptionResult {\n constructor(results, errors, roomEncryption) {\n this.results = results;\n this.errors = errors;\n this._roomEncryption = roomEncryption;\n }\n\n applyToEntries(entries) {\n for (const entry of entries) {\n const result = this.results.get(entry.id);\n if (result) {\n entry.setDecryptionResult(result);\n } else {\n const error = this.errors.get(entry.id);\n if (error) {\n entry.setDecryptionError(error);\n }\n }\n }\n }\n\n verifySenders(txn) {\n return Promise.all(Array.from(this.results.values()).map(result => {\n return this._roomEncryption._verifyDecryptionResult(result, txn);\n }));\n }\n}\n\nimport {createMockStorage} from \"../../mocks/Storage\";\nimport {Clock as MockClock} from \"../../mocks/Clock\";\nimport {poll} from \"../../mocks/poll\";\nimport {Instance as NullLoggerInstance} from \"../../logging/NullLogger\";\nimport {ConsoleLogger} from \"../../logging/ConsoleLogger\";\nimport {HomeServer as MockHomeServer} from \"../../mocks/HomeServer.js\";\n\nexport function tests() {\n const roomId = \"!abc:hs.tld\";\n return {\n \"ensureMessageKeyIsShared tracks room and passes correct history visibility to deviceTracker\": async assert => {\n const storage = await createMockStorage();\n const megolmMock = {\n async ensureOutboundSession() { return { }; }\n };\n const olmMock = {\n async encrypt() { return []; }\n }\n let isRoomTracked = false;\n let isDevicesRequested = false;\n const deviceTracker = {\n async trackRoom(room, historyVisibility) {\n // only assert on first call\n if (isRoomTracked) { return; }\n assert(!isDevicesRequested);\n assert.equal(room.id, roomId);\n assert.equal(historyVisibility, \"invited\");\n isRoomTracked = true;\n },\n async devicesForTrackedRoom() {\n assert(isRoomTracked);\n isDevicesRequested = true;\n return [];\n },\n async devicesForRoomMembers() {\n return [];\n }\n }\n const writeTxn = await storage.readWriteTxn([storage.storeNames.roomState]);\n writeTxn.roomState.set(roomId, {state_key: \"\", type: ROOM_HISTORY_VISIBILITY_TYPE, content: {\n history_visibility: \"invited\"\n }});\n await writeTxn.complete();\n const roomEncryption = new RoomEncryption({\n room: {id: roomId},\n megolmEncryption: megolmMock,\n olmEncryption: olmMock,\n storage,\n deviceTracker,\n clock: new MockClock()\n });\n const homeServer = new MockHomeServer();\n const promise = roomEncryption.ensureMessageKeyIsShared(homeServer.api, NullLoggerInstance.item);\n // need to poll because sendToDevice isn't first async step\n const request = await poll(() => homeServer.requests.sendToDevice?.[0]);\n request.respond({});\n await promise;\n assert(isRoomTracked);\n assert(isDevicesRequested);\n },\n \"encrypt tracks room and passes correct history visibility to deviceTracker\": async assert => {\n const storage = await createMockStorage();\n const megolmMock = {\n async encrypt() { return { roomKeyMessage: {} }; }\n };\n const olmMock = {\n async encrypt() { return []; }\n }\n let isRoomTracked = false;\n let isDevicesRequested = false;\n const deviceTracker = {\n async trackRoom(room, historyVisibility) {\n // only assert on first call\n if (isRoomTracked) { return; }\n assert(!isDevicesRequested);\n assert.equal(room.id, roomId);\n assert.equal(historyVisibility, \"invited\");\n isRoomTracked = true;\n },\n async devicesForTrackedRoom() {\n assert(isRoomTracked);\n isDevicesRequested = true;\n return [];\n },\n async devicesForRoomMembers() {\n return [];\n }\n }\n const writeTxn = await storage.readWriteTxn([storage.storeNames.roomState]);\n writeTxn.roomState.set(roomId, {state_key: \"\", type: ROOM_HISTORY_VISIBILITY_TYPE, content: {\n history_visibility: \"invited\"\n }});\n await writeTxn.complete();\n const roomEncryption = new RoomEncryption({\n room: {id: roomId},\n megolmEncryption: megolmMock,\n olmEncryption: olmMock,\n storage,\n deviceTracker\n });\n const homeServer = new MockHomeServer();\n const promise = roomEncryption.encrypt(\"m.room.message\", {body: \"hello\"}, homeServer.api, NullLoggerInstance.item);\n // need to poll because sendToDevice isn't first async step\n const request = await poll(() => homeServer.requests.sendToDevice?.[0]);\n request.respond({});\n await promise;\n assert(isRoomTracked);\n assert(isDevicesRequested);\n },\n \"writeSync passes correct history visibility to deviceTracker\": async assert => {\n const storage = await createMockStorage();\n let isMemberChangesCalled = false;\n const deviceTracker = {\n async writeMemberChanges(room, memberChanges, historyVisibility, txn) {\n assert.equal(historyVisibility, \"invited\");\n isMemberChangesCalled = true;\n return {removed: [], added: []};\n },\n async devicesForRoomMembers() {\n return [];\n }\n }\n const writeTxn = await storage.readWriteTxn([storage.storeNames.roomState]);\n writeTxn.roomState.set(roomId, {state_key: \"\", type: ROOM_HISTORY_VISIBILITY_TYPE, content: {\n history_visibility: \"invited\"\n }});\n const memberChanges = new Map([[\"@alice:hs.tld\", {}]]);\n const roomEncryption = new RoomEncryption({\n room: {id: roomId},\n storage,\n deviceTracker\n });\n const roomResponse = {};\n const txn = await storage.readWriteTxn([storage.storeNames.roomState]);\n await roomEncryption.writeSync(roomResponse, memberChanges, txn, NullLoggerInstance.item);\n assert(isMemberChangesCalled);\n },\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {verifyEd25519Signature, SIGNATURE_ALGORITHM} from \"./common.js\";\nimport {HistoryVisibility, shouldShareKey} from \"./common.js\";\nimport {RoomMember} from \"../room/members/RoomMember.js\";\n\nconst TRACKING_STATUS_OUTDATED = 0;\nconst TRACKING_STATUS_UPTODATE = 1;\n\nfunction addRoomToIdentity(identity, userId, roomId) {\n if (!identity) {\n identity = {\n userId: userId,\n roomIds: [roomId],\n deviceTrackingStatus: TRACKING_STATUS_OUTDATED,\n };\n return identity;\n } else {\n if (!identity.roomIds.includes(roomId)) {\n identity.roomIds.push(roomId);\n return identity;\n }\n }\n}\n\n// map 1 device from /keys/query response to DeviceIdentity\nfunction deviceKeysAsDeviceIdentity(deviceSection) {\n const deviceId = deviceSection[\"device_id\"];\n const userId = deviceSection[\"user_id\"];\n return {\n userId,\n deviceId,\n ed25519Key: deviceSection.keys[`ed25519:${deviceId}`],\n curve25519Key: deviceSection.keys[`curve25519:${deviceId}`],\n algorithms: deviceSection.algorithms,\n displayName: deviceSection.unsigned?.device_display_name,\n };\n}\n\nexport class DeviceTracker {\n constructor({storage, getSyncToken, olmUtil, ownUserId, ownDeviceId}) {\n this._storage = storage;\n this._getSyncToken = getSyncToken;\n this._identityChangedForRoom = null;\n this._olmUtil = olmUtil;\n this._ownUserId = ownUserId;\n this._ownDeviceId = ownDeviceId;\n }\n\n async writeDeviceChanges(changed, txn, log) {\n const {userIdentities} = txn;\n // TODO: should we also look at left here to handle this?:\n // the usual problem here is that you share a room with a user,\n // go offline, the remote user leaves the room, changes their devices,\n // then rejoins the room you share (or another room).\n // At which point you come online, all of this happens in the gap, \n // and you don't notice that they ever left, \n // and so the client doesn't invalidate their device cache for the user\n log.set(\"changed\", changed.length);\n await Promise.all(changed.map(async userId => {\n const user = await userIdentities.get(userId);\n if (user) {\n log.log({l: \"outdated\", id: userId});\n user.deviceTrackingStatus = TRACKING_STATUS_OUTDATED;\n userIdentities.set(user);\n }\n }));\n }\n\n /** @return Promise<{added: string[], removed: string[]}> the user ids for who the room was added or removed to the userIdentity,\n * and with who a key should be now be shared\n **/\n async writeMemberChanges(room, memberChanges, historyVisibility, txn) {\n const added = [];\n const removed = [];\n await Promise.all(Array.from(memberChanges.values()).map(async memberChange => {\n // keys should now be shared with this member?\n // add the room to the userIdentity if so\n if (shouldShareKey(memberChange.membership, historyVisibility)) {\n if (await this._addRoomToUserIdentity(memberChange.roomId, memberChange.userId, txn)) {\n added.push(memberChange.userId);\n }\n } else if (shouldShareKey(memberChange.previousMembership, historyVisibility)) {\n // try to remove room we were previously sharing the key with the member but not anymore\n const {roomId} = memberChange;\n // if we left the room, remove room from all user identities in the room\n if (memberChange.userId === this._ownUserId) {\n const userIds = await txn.roomMembers.getAllUserIds(roomId);\n await Promise.all(userIds.map(userId => {\n return this._removeRoomFromUserIdentity(roomId, userId, txn);\n }));\n } else {\n await this._removeRoomFromUserIdentity(roomId, memberChange.userId, txn);\n }\n removed.push(memberChange.userId);\n }\n }));\n return {added, removed};\n }\n\n async trackRoom(room, historyVisibility, log) {\n if (room.isTrackingMembers || !room.isEncrypted) {\n return;\n }\n const memberList = await room.loadMemberList(undefined, log);\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.roomSummary,\n this._storage.storeNames.userIdentities,\n ]);\n try {\n let isTrackingChanges;\n try {\n isTrackingChanges = room.writeIsTrackingMembers(true, txn);\n const members = Array.from(memberList.members.values());\n log.set(\"members\", members.length);\n await Promise.all(members.map(async member => {\n if (shouldShareKey(member.membership, historyVisibility)) {\n await this._addRoomToUserIdentity(member.roomId, member.userId, txn);\n }\n }));\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n room.applyIsTrackingMembersChanges(isTrackingChanges);\n } finally {\n memberList.release();\n }\n }\n\n async writeHistoryVisibility(room, historyVisibility, syncTxn, log) {\n const added = [];\n const removed = [];\n if (room.isTrackingMembers && room.isEncrypted) {\n await log.wrap(\"rewriting userIdentities\", async log => {\n const memberList = await room.loadMemberList(syncTxn, log);\n try {\n const members = Array.from(memberList.members.values());\n log.set(\"members\", members.length);\n await Promise.all(members.map(async member => {\n if (shouldShareKey(member.membership, historyVisibility)) {\n if (await this._addRoomToUserIdentity(member.roomId, member.userId, syncTxn)) {\n added.push(member.userId);\n }\n } else {\n if (await this._removeRoomFromUserIdentity(member.roomId, member.userId, syncTxn)) {\n removed.push(member.userId);\n }\n }\n }));\n } finally {\n memberList.release();\n }\n });\n }\n return {added, removed};\n }\n\n async _addRoomToUserIdentity(roomId, userId, txn) {\n const {userIdentities} = txn;\n const identity = await userIdentities.get(userId);\n const updatedIdentity = addRoomToIdentity(identity, userId, roomId);\n if (updatedIdentity) {\n userIdentities.set(updatedIdentity);\n return true;\n }\n return false;\n }\n\n async _removeRoomFromUserIdentity(roomId, userId, txn) {\n const {userIdentities, deviceIdentities} = txn;\n const identity = await userIdentities.get(userId);\n if (identity) {\n identity.roomIds = identity.roomIds.filter(id => id !== roomId);\n // no more encrypted rooms with this user, remove\n if (identity.roomIds.length === 0) {\n userIdentities.remove(userId);\n deviceIdentities.removeAllForUser(userId);\n } else {\n userIdentities.set(identity);\n }\n return true;\n }\n return false;\n }\n\n async _queryKeys(userIds, hsApi, log) {\n // TODO: we need to handle the race here between /sync and /keys/query just like we need to do for the member list ...\n // there are multiple requests going out for /keys/query though and only one for /members\n\n const deviceKeyResponse = await hsApi.queryKeys({\n \"timeout\": 10000,\n \"device_keys\": userIds.reduce((deviceKeysMap, userId) => {\n deviceKeysMap[userId] = [];\n return deviceKeysMap;\n }, {}),\n \"token\": this._getSyncToken()\n }, {log}).response();\n\n const verifiedKeysPerUser = log.wrap(\"verify\", log => this._filterVerifiedDeviceKeys(deviceKeyResponse[\"device_keys\"], log));\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.userIdentities,\n this._storage.storeNames.deviceIdentities,\n ]);\n let deviceIdentities;\n try {\n const devicesIdentitiesPerUser = await Promise.all(verifiedKeysPerUser.map(async ({userId, verifiedKeys}) => {\n const deviceIdentities = verifiedKeys.map(deviceKeysAsDeviceIdentity);\n return await this._storeQueriedDevicesForUserId(userId, deviceIdentities, txn);\n }));\n deviceIdentities = devicesIdentitiesPerUser.reduce((all, devices) => all.concat(devices), []);\n log.set(\"devices\", deviceIdentities.length);\n } catch (err) {\n txn.abort();\n throw err;\n }\n await txn.complete();\n return deviceIdentities;\n }\n\n async _storeQueriedDevicesForUserId(userId, deviceIdentities, txn) {\n const knownDeviceIds = await txn.deviceIdentities.getAllDeviceIds(userId);\n // delete any devices that we know off but are not in the response anymore.\n // important this happens before checking if the ed25519 key changed,\n // otherwise we would end up deleting existing devices with changed keys.\n for (const deviceId of knownDeviceIds) {\n if (deviceIdentities.every(di => di.deviceId !== deviceId)) {\n txn.deviceIdentities.remove(userId, deviceId);\n }\n }\n\n // all the device identities as we will have them in storage\n const allDeviceIdentities = [];\n const deviceIdentitiesToStore = [];\n // filter out devices that have changed their ed25519 key since last time we queried them\n await Promise.all(deviceIdentities.map(async deviceIdentity => {\n if (knownDeviceIds.includes(deviceIdentity.deviceId)) {\n const existingDevice = await txn.deviceIdentities.get(deviceIdentity.userId, deviceIdentity.deviceId);\n if (existingDevice.ed25519Key !== deviceIdentity.ed25519Key) {\n allDeviceIdentities.push(existingDevice);\n return;\n }\n }\n allDeviceIdentities.push(deviceIdentity);\n deviceIdentitiesToStore.push(deviceIdentity);\n }));\n // store devices\n for (const deviceIdentity of deviceIdentitiesToStore) {\n txn.deviceIdentities.set(deviceIdentity);\n }\n // mark user identities as up to date\n const identity = await txn.userIdentities.get(userId);\n identity.deviceTrackingStatus = TRACKING_STATUS_UPTODATE;\n txn.userIdentities.set(identity);\n\n return allDeviceIdentities;\n }\n\n /**\n * @return {Array<{userId, verifiedKeys: Array>}\n */\n _filterVerifiedDeviceKeys(keyQueryDeviceKeysResponse, parentLog) {\n const curve25519Keys = new Set();\n const verifiedKeys = Object.entries(keyQueryDeviceKeysResponse).map(([userId, keysByDevice]) => {\n const verifiedEntries = Object.entries(keysByDevice).filter(([deviceId, deviceKeys]) => {\n const deviceIdOnKeys = deviceKeys[\"device_id\"];\n const userIdOnKeys = deviceKeys[\"user_id\"];\n if (userIdOnKeys !== userId) {\n return false;\n }\n if (deviceIdOnKeys !== deviceId) {\n return false;\n }\n const ed25519Key = deviceKeys.keys?.[`ed25519:${deviceId}`];\n const curve25519Key = deviceKeys.keys?.[`curve25519:${deviceId}`];\n if (typeof ed25519Key !== \"string\" || typeof curve25519Key !== \"string\") {\n return false;\n }\n if (curve25519Keys.has(curve25519Key)) {\n parentLog.log({\n l: \"ignore device with duplicate curve25519 key\",\n keys: deviceKeys\n }, parentLog.level.Warn);\n return false;\n }\n curve25519Keys.add(curve25519Key);\n const isValid = this._hasValidSignature(deviceKeys, parentLog);\n if (!isValid) {\n parentLog.log({\n l: \"ignore device with invalid signature\",\n keys: deviceKeys\n }, parentLog.level.Warn);\n }\n return isValid;\n });\n const verifiedKeys = verifiedEntries.map(([, deviceKeys]) => deviceKeys);\n return {userId, verifiedKeys};\n });\n return verifiedKeys;\n }\n\n _hasValidSignature(deviceSection, parentLog) {\n const deviceId = deviceSection[\"device_id\"];\n const userId = deviceSection[\"user_id\"];\n const ed25519Key = deviceSection?.keys?.[`${SIGNATURE_ALGORITHM}:${deviceId}`];\n return verifyEd25519Signature(this._olmUtil, userId, deviceId, ed25519Key, deviceSection, parentLog);\n }\n\n /**\n * Gives all the device identities for a room that is already tracked.\n * Assumes room is already tracked. Call `trackRoom` first if unsure.\n * @param {String} roomId [description]\n * @return {[type]} [description]\n */\n async devicesForTrackedRoom(roomId, hsApi, log) {\n const txn = await this._storage.readTxn([\n this._storage.storeNames.roomMembers,\n this._storage.storeNames.userIdentities,\n ]);\n\n // because we don't have multiEntry support in IE11, we get a set of userIds that is pretty close to what we\n // need as a good first filter (given that non-join memberships will be in there). After fetching the identities,\n // we check which ones have the roomId for the room we're looking at.\n \n // So, this will also contain non-joined memberships\n const userIds = await txn.roomMembers.getAllUserIds(roomId);\n\n return await this._devicesForUserIds(roomId, userIds, txn, hsApi, log);\n }\n\n async devicesForRoomMembers(roomId, userIds, hsApi, log) {\n const txn = await this._storage.readTxn([\n this._storage.storeNames.userIdentities,\n ]);\n return await this._devicesForUserIds(roomId, userIds, txn, hsApi, log);\n }\n\n /**\n * @param {string} roomId [description]\n * @param {Array} userIds a set of user ids to try and find the identity for. Will be check to belong to roomId.\n * @param {Transaction} userIdentityTxn to read the user identities\n * @param {HomeServerApi} hsApi\n * @return {Array}\n */\n async _devicesForUserIds(roomId, userIds, userIdentityTxn, hsApi, log) {\n const allMemberIdentities = await Promise.all(userIds.map(userId => userIdentityTxn.userIdentities.get(userId)));\n const identities = allMemberIdentities.filter(identity => {\n // identity will be missing for any userIds that don't have \n // membership join in any of your encrypted rooms\n return identity && identity.roomIds.includes(roomId);\n });\n const upToDateIdentities = identities.filter(i => i.deviceTrackingStatus === TRACKING_STATUS_UPTODATE);\n const outdatedIdentities = identities.filter(i => i.deviceTrackingStatus === TRACKING_STATUS_OUTDATED);\n log.set(\"uptodate\", upToDateIdentities.length);\n log.set(\"outdated\", outdatedIdentities.length);\n let queriedDevices;\n if (outdatedIdentities.length) {\n // TODO: ignore the race between /sync and /keys/query for now,\n // where users could get marked as outdated or added/removed from the room while\n // querying keys\n queriedDevices = await this._queryKeys(outdatedIdentities.map(i => i.userId), hsApi, log);\n }\n\n const deviceTxn = await this._storage.readTxn([\n this._storage.storeNames.deviceIdentities,\n ]);\n const devicesPerUser = await Promise.all(upToDateIdentities.map(identity => {\n return deviceTxn.deviceIdentities.getAllForUserId(identity.userId);\n }));\n let flattenedDevices = devicesPerUser.reduce((all, devicesForUser) => all.concat(devicesForUser), []);\n if (queriedDevices && queriedDevices.length) {\n flattenedDevices = flattenedDevices.concat(queriedDevices);\n }\n // filter out our own device\n const devices = flattenedDevices.filter(device => {\n const isOwnDevice = device.userId === this._ownUserId && device.deviceId === this._ownDeviceId;\n return !isOwnDevice;\n });\n return devices;\n }\n\n async getDeviceByCurve25519Key(curve25519Key, txn) {\n return await txn.deviceIdentities.getByCurve25519Key(curve25519Key);\n }\n}\n\nimport {createMockStorage} from \"../../mocks/Storage\";\nimport {Instance as NullLoggerInstance} from \"../../logging/NullLogger\";\nimport {MemberChange} from \"../room/members/RoomMember\";\n\nexport function tests() {\n\n function createUntrackedRoomMock(roomId, joinedUserIds, invitedUserIds = []) {\n return {\n id: roomId,\n isTrackingMembers: false,\n isEncrypted: true,\n loadMemberList: () => {\n const joinedMembers = joinedUserIds.map(userId => {return RoomMember.fromUserId(roomId, userId, \"join\");});\n const invitedMembers = invitedUserIds.map(userId => {return RoomMember.fromUserId(roomId, userId, \"invite\");});\n const members = joinedMembers.concat(invitedMembers);\n const memberMap = members.reduce((map, member) => {\n map.set(member.userId, member);\n return map;\n }, new Map());\n return {members: memberMap, release() {}}\n },\n writeIsTrackingMembers(isTrackingMembers) {\n if (this.isTrackingMembers !== isTrackingMembers) {\n return isTrackingMembers;\n }\n return undefined;\n },\n applyIsTrackingMembersChanges(isTrackingMembers) {\n if (isTrackingMembers !== undefined) {\n this.isTrackingMembers = isTrackingMembers;\n }\n },\n }\n }\n\n function createQueryKeysHSApiMock(createKey = (algorithm, userId, deviceId) => `${algorithm}:${userId}:${deviceId}:key`) {\n return {\n queryKeys(payload) {\n const {device_keys: deviceKeys} = payload;\n const userKeys = Object.entries(deviceKeys).reduce((userKeys, [userId, deviceIds]) => {\n if (deviceIds.length === 0) {\n deviceIds = [\"device1\"];\n }\n userKeys[userId] = deviceIds.filter(d => d === \"device1\").reduce((deviceKeys, deviceId) => {\n deviceKeys[deviceId] = {\n \"algorithms\": [\n \"m.olm.v1.curve25519-aes-sha2\",\n \"m.megolm.v1.aes-sha2\"\n ],\n \"device_id\": deviceId,\n \"keys\": {\n [`curve25519:${deviceId}`]: createKey(\"curve25519\", userId, deviceId),\n [`ed25519:${deviceId}`]: createKey(\"ed25519\", userId, deviceId),\n },\n \"signatures\": {\n [userId]: {\n [`ed25519:${deviceId}`]: `ed25519:${userId}:${deviceId}:signature`\n }\n },\n \"unsigned\": {\n \"device_display_name\": `${userId} Phone`\n },\n \"user_id\": userId\n };\n return deviceKeys;\n }, {});\n return userKeys;\n }, {});\n const response = {device_keys: userKeys};\n return {\n async response() {\n return response;\n }\n };\n }\n };\n }\n\n async function writeMemberListToStorage(room, storage) {\n const txn = await storage.readWriteTxn([\n storage.storeNames.roomMembers,\n ]);\n const memberList = await room.loadMemberList(txn);\n try {\n for (const member of memberList.members.values()) {\n txn.roomMembers.set(member.serialize());\n }\n } catch (err) {\n txn.abort();\n throw err;\n } finally {\n memberList.release();\n }\n await txn.complete();\n }\n\n const roomId = \"!abc:hs.tld\";\n\n return {\n \"trackRoom only writes joined members with history visibility of joined\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n const room = createUntrackedRoomMock(roomId, [\"@alice:hs.tld\", \"@bob:hs.tld\"], [\"@charly:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Joined, NullLoggerInstance.item);\n const txn = await storage.readTxn([storage.storeNames.userIdentities]);\n assert.deepEqual(await txn.userIdentities.get(\"@alice:hs.tld\"), {\n userId: \"@alice:hs.tld\",\n roomIds: [roomId],\n deviceTrackingStatus: TRACKING_STATUS_OUTDATED\n });\n assert.deepEqual(await txn.userIdentities.get(\"@bob:hs.tld\"), {\n userId: \"@bob:hs.tld\",\n roomIds: [roomId],\n deviceTrackingStatus: TRACKING_STATUS_OUTDATED\n });\n assert.equal(await txn.userIdentities.get(\"@charly:hs.tld\"), undefined);\n },\n \"getting devices for tracked room yields correct keys\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n const room = createUntrackedRoomMock(roomId, [\"@alice:hs.tld\", \"@bob:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Joined, NullLoggerInstance.item);\n const hsApi = createQueryKeysHSApiMock();\n const devices = await tracker.devicesForRoomMembers(roomId, [\"@alice:hs.tld\", \"@bob:hs.tld\"], hsApi, NullLoggerInstance.item);\n assert.equal(devices.length, 2);\n assert.equal(devices.find(d => d.userId === \"@alice:hs.tld\").ed25519Key, \"ed25519:@alice:hs.tld:device1:key\");\n assert.equal(devices.find(d => d.userId === \"@bob:hs.tld\").ed25519Key, \"ed25519:@bob:hs.tld:device1:key\");\n },\n \"device with changed key is ignored\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n const room = createUntrackedRoomMock(roomId, [\"@alice:hs.tld\", \"@bob:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Joined, NullLoggerInstance.item);\n const hsApi = createQueryKeysHSApiMock();\n // query devices first time\n await tracker.devicesForRoomMembers(roomId, [\"@alice:hs.tld\", \"@bob:hs.tld\"], hsApi, NullLoggerInstance.item);\n const txn = await storage.readWriteTxn([storage.storeNames.userIdentities]);\n // mark alice as outdated, so keys will be fetched again\n tracker.writeDeviceChanges([\"@alice:hs.tld\"], txn, NullLoggerInstance.item);\n await txn.complete();\n const hsApiWithChangedAliceKey = createQueryKeysHSApiMock((algo, userId, deviceId) => {\n return `${algo}:${userId}:${deviceId}:${userId === \"@alice:hs.tld\" ? \"newKey\" : \"key\"}`;\n });\n const devices = await tracker.devicesForRoomMembers(roomId, [\"@alice:hs.tld\", \"@bob:hs.tld\"], hsApiWithChangedAliceKey, NullLoggerInstance.item);\n assert.equal(devices.length, 2);\n assert.equal(devices.find(d => d.userId === \"@alice:hs.tld\").ed25519Key, \"ed25519:@alice:hs.tld:device1:key\");\n assert.equal(devices.find(d => d.userId === \"@bob:hs.tld\").ed25519Key, \"ed25519:@bob:hs.tld:device1:key\");\n const txn2 = await storage.readTxn([storage.storeNames.deviceIdentities]);\n // also check the modified key was not stored\n assert.equal((await txn2.deviceIdentities.get(\"@alice:hs.tld\", \"device1\")).ed25519Key, \"ed25519:@alice:hs.tld:device1:key\");\n },\n \"change history visibility from joined to invited adds invitees\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n // alice is joined, bob is invited\n const room = await createUntrackedRoomMock(roomId, \n [\"@alice:hs.tld\"], [\"@bob:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Joined, NullLoggerInstance.item);\n const txn = await storage.readWriteTxn([storage.storeNames.userIdentities, storage.storeNames.deviceIdentities]);\n assert.equal(await txn.userIdentities.get(\"@bob:hs.tld\"), undefined);\n const {added, removed} = await tracker.writeHistoryVisibility(room, HistoryVisibility.Invited, txn, NullLoggerInstance.item);\n assert.equal((await txn.userIdentities.get(\"@bob:hs.tld\")).userId, \"@bob:hs.tld\");\n assert.deepEqual(added, [\"@bob:hs.tld\"]);\n assert.deepEqual(removed, []);\n },\n \"change history visibility from invited to joined removes invitees\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n // alice is joined, bob is invited\n const room = await createUntrackedRoomMock(roomId, \n [\"@alice:hs.tld\"], [\"@bob:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Invited, NullLoggerInstance.item);\n const txn = await storage.readWriteTxn([storage.storeNames.userIdentities, storage.storeNames.deviceIdentities]);\n assert.equal((await txn.userIdentities.get(\"@bob:hs.tld\")).userId, \"@bob:hs.tld\");\n const {added, removed} = await tracker.writeHistoryVisibility(room, HistoryVisibility.Joined, txn, NullLoggerInstance.item);\n assert.equal(await txn.userIdentities.get(\"@bob:hs.tld\"), undefined);\n assert.deepEqual(added, []);\n assert.deepEqual(removed, [\"@bob:hs.tld\"]);\n },\n \"adding invitee with history visibility of invited adds room to userIdentities\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n const room = await createUntrackedRoomMock(roomId, [\"@alice:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Invited, NullLoggerInstance.item);\n const txn = await storage.readWriteTxn([storage.storeNames.userIdentities, storage.storeNames.deviceIdentities]);\n // inviting a new member\n const inviteChange = new MemberChange(RoomMember.fromUserId(roomId, \"@bob:hs.tld\", \"invite\"));\n const {added, removed} = await tracker.writeMemberChanges(room, [inviteChange], HistoryVisibility.Invited, txn);\n assert.deepEqual(added, [\"@bob:hs.tld\"]);\n assert.deepEqual(removed, []);\n assert.equal((await txn.userIdentities.get(\"@bob:hs.tld\")).userId, \"@bob:hs.tld\");\n },\n \"adding invitee with history visibility of joined doesn't add room\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n const room = await createUntrackedRoomMock(roomId, [\"@alice:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Joined, NullLoggerInstance.item);\n const txn = await storage.readWriteTxn([storage.storeNames.userIdentities, storage.storeNames.deviceIdentities]);\n // inviting a new member\n const inviteChange = new MemberChange(RoomMember.fromUserId(roomId, \"@bob:hs.tld\", \"invite\"));\n const memberChanges = new Map([[inviteChange.userId, inviteChange]]);\n const {added, removed} = await tracker.writeMemberChanges(room, memberChanges, HistoryVisibility.Joined, txn);\n assert.deepEqual(added, []);\n assert.deepEqual(removed, []);\n assert.equal(await txn.userIdentities.get(\"@bob:hs.tld\"), undefined);\n },\n \"getting all devices after changing history visibility now includes invitees\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n const room = createUntrackedRoomMock(roomId, [\"@alice:hs.tld\"], [\"@bob:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Invited, NullLoggerInstance.item);\n const hsApi = createQueryKeysHSApiMock();\n // write memberlist from room mock to mock storage,\n // as devicesForTrackedRoom reads directly from roomMembers store.\n await writeMemberListToStorage(room, storage);\n const devices = await tracker.devicesForTrackedRoom(roomId, hsApi, NullLoggerInstance.item);\n assert.equal(devices.length, 2);\n assert.equal(devices.find(d => d.userId === \"@alice:hs.tld\").ed25519Key, \"ed25519:@alice:hs.tld:device1:key\");\n assert.equal(devices.find(d => d.userId === \"@bob:hs.tld\").ed25519Key, \"ed25519:@bob:hs.tld:device1:key\");\n },\n \"rejecting invite with history visibility of invited removes room from user identity\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n // alice is joined, bob is invited\n const room = await createUntrackedRoomMock(roomId, [\"@alice:hs.tld\"], [\"@bob:hs.tld\"]);\n await tracker.trackRoom(room, HistoryVisibility.Invited, NullLoggerInstance.item);\n const txn = await storage.readWriteTxn([storage.storeNames.userIdentities, storage.storeNames.deviceIdentities]);\n // reject invite\n const inviteChange = new MemberChange(RoomMember.fromUserId(roomId, \"@bob:hs.tld\", \"leave\"), \"invite\");\n const memberChanges = new Map([[inviteChange.userId, inviteChange]]);\n const {added, removed} = await tracker.writeMemberChanges(room, memberChanges, HistoryVisibility.Invited, txn);\n assert.deepEqual(added, []);\n assert.deepEqual(removed, [\"@bob:hs.tld\"]);\n assert.equal(await txn.userIdentities.get(\"@bob:hs.tld\"), undefined);\n },\n \"remove room from user identity sharing multiple rooms with us preserves other room\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n // alice is joined, bob is invited\n const room1 = await createUntrackedRoomMock(\"!abc:hs.tld\", [\"@alice:hs.tld\", \"@bob:hs.tld\"]);\n const room2 = await createUntrackedRoomMock(\"!def:hs.tld\", [\"@alice:hs.tld\", \"@bob:hs.tld\"]);\n await tracker.trackRoom(room1, HistoryVisibility.Joined, NullLoggerInstance.item);\n await tracker.trackRoom(room2, HistoryVisibility.Joined, NullLoggerInstance.item);\n const txn1 = await storage.readTxn([storage.storeNames.userIdentities]);\n assert.deepEqual((await txn1.userIdentities.get(\"@bob:hs.tld\")).roomIds, [\"!abc:hs.tld\", \"!def:hs.tld\"]);\n const leaveChange = new MemberChange(RoomMember.fromUserId(room2.id, \"@bob:hs.tld\", \"leave\"), \"join\");\n const memberChanges = new Map([[leaveChange.userId, leaveChange]]);\n const txn2 = await storage.readWriteTxn([storage.storeNames.userIdentities, storage.storeNames.deviceIdentities]);\n await tracker.writeMemberChanges(room2, memberChanges, HistoryVisibility.Joined, txn2);\n await txn2.complete();\n const txn3 = await storage.readTxn([storage.storeNames.userIdentities]);\n assert.deepEqual((await txn3.userIdentities.get(\"@bob:hs.tld\")).roomIds, [\"!abc:hs.tld\"]);\n },\n \"add room to user identity sharing multiple rooms with us preserves other room\": async assert => {\n const storage = await createMockStorage();\n const tracker = new DeviceTracker({\n storage,\n getSyncToken: () => \"token\",\n olmUtil: {ed25519_verify: () => {}}, // valid if it does not throw\n ownUserId: \"@alice:hs.tld\",\n ownDeviceId: \"ABCD\",\n });\n // alice is joined, bob is invited\n const room1 = await createUntrackedRoomMock(\"!abc:hs.tld\", [\"@alice:hs.tld\", \"@bob:hs.tld\"]);\n const room2 = await createUntrackedRoomMock(\"!def:hs.tld\", [\"@alice:hs.tld\", \"@bob:hs.tld\"]);\n await tracker.trackRoom(room1, HistoryVisibility.Joined, NullLoggerInstance.item);\n const txn1 = await storage.readTxn([storage.storeNames.userIdentities]);\n assert.deepEqual((await txn1.userIdentities.get(\"@bob:hs.tld\")).roomIds, [\"!abc:hs.tld\"]);\n await tracker.trackRoom(room2, HistoryVisibility.Joined, NullLoggerInstance.item);\n const txn2 = await storage.readTxn([storage.storeNames.userIdentities]);\n assert.deepEqual((await txn2.userIdentities.get(\"@bob:hs.tld\")).roomIds, [\"!abc:hs.tld\", \"!def:hs.tld\"]);\n },\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Lock} from \"./Lock\";\n\nexport class LockMap {\n private readonly _map: Map = new Map();\n\n async takeLock(key: T): Promise {\n let lock = this._map.get(key);\n if (lock) {\n await lock.take();\n } else {\n lock = new Lock();\n lock.tryTake();\n this._map.set(key, lock);\n }\n // don't leave old locks lying around\n lock.released()!.then(() => {\n // give others a chance to take the lock first\n Promise.resolve().then(() => {\n if (!lock!.isTaken) {\n this._map.delete(key);\n }\n });\n });\n return lock;\n }\n}\n\nexport function tests() {\n return {\n \"taking a lock on the same key blocks\": async assert => {\n const lockMap = new LockMap();\n const lock = await lockMap.takeLock(\"foo\");\n let second = false;\n const prom = lockMap.takeLock(\"foo\").then(() => {\n second = true;\n });\n assert.equal(second, false);\n // do a delay to make sure prom does not resolve on its own\n await Promise.resolve();\n lock.release();\n await prom;\n assert.equal(second, true);\n },\n \"lock is not cleaned up with second request\": async assert => {\n const lockMap = new LockMap();\n const lock = await lockMap.takeLock(\"foo\");\n let ranSecond = false;\n const prom = lockMap.takeLock(\"foo\").then(returnedLock => {\n ranSecond = true;\n assert.equal(returnedLock.isTaken, true);\n // peek into internals, naughty\n // @ts-ignore\n assert.equal(lockMap._map.get(\"foo\"), returnedLock);\n });\n lock.release();\n await prom;\n // double delay to make sure cleanup logic ran\n await Promise.resolve();\n await Promise.resolve();\n assert.equal(ranSecond, true);\n },\n \"lock is cleaned up without other request\": async assert => {\n const lockMap = new LockMap();\n const lock = await lockMap.takeLock(\"foo\");\n await Promise.resolve();\n lock.release();\n // double delay to make sure cleanup logic ran\n await Promise.resolve();\n await Promise.resolve();\n // @ts-ignore\n assert.equal(lockMap._map.has(\"foo\"), false);\n },\n \n };\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport type {Key} from \"./common\";\nimport type {Platform} from \"../../platform/web/Platform.js\";\nimport type {Transaction} from \"../storage/idb/Transaction\";\n\ntype EncryptedData = {\n iv: string;\n ciphertext: string;\n mac: string;\n}\n\nexport class SecretStorage {\n private readonly _key: Key;\n private readonly _platform: Platform;\n\n constructor({key, platform}: {key: Key, platform: Platform}) {\n this._key = key;\n this._platform = platform;\n }\n\n async readSecret(name: string, txn: Transaction): Promise {\n const accountData = await txn.accountData.get(name);\n if (!accountData) {\n return;\n }\n const encryptedData = accountData?.content?.encrypted?.[this._key.id] as EncryptedData;\n if (!encryptedData) {\n throw new Error(`Secret ${accountData.type} is not encrypted for key ${this._key.id}`);\n }\n\n if (this._key.algorithm === \"m.secret_storage.v1.aes-hmac-sha2\") {\n return await this._decryptAESSecret(accountData.type, encryptedData);\n } else {\n throw new Error(`Unsupported algorithm for key ${this._key.id}: ${this._key.algorithm}`);\n }\n }\n\n async _decryptAESSecret(type: string, encryptedData: EncryptedData): Promise {\n const {base64, utf8} = this._platform.encoding;\n // now derive the aes and mac key from the 4s key\n const hkdfKey = await this._platform.crypto.derive.hkdf(\n this._key.binaryKey,\n new Uint8Array(8).buffer, //zero salt\n utf8.encode(type), // info\n \"SHA-256\",\n 512 // 512 bits or 64 bytes\n );\n const aesKey = hkdfKey.slice(0, 32);\n const hmacKey = hkdfKey.slice(32);\n const ciphertextBytes = base64.decode(encryptedData.ciphertext);\n\n const isVerified = await this._platform.crypto.hmac.verify(\n hmacKey, base64.decode(encryptedData.mac),\n ciphertextBytes, \"SHA-256\");\n\n if (!isVerified) {\n throw new Error(\"Bad MAC\");\n }\n\n const plaintextBytes = await this._platform.crypto.aes.decryptCTR({\n key: aesKey,\n iv: base64.decode(encryptedData.iv),\n data: ciphertextBytes\n });\n\n return utf8.decode(plaintextBytes);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Room} from \"./room/Room.js\";\nimport {ArchivedRoom} from \"./room/ArchivedRoom.js\";\nimport {RoomStatus} from \"./room/common\";\nimport {RoomBeingCreated} from \"./room/RoomBeingCreated\";\nimport {Invite} from \"./room/Invite.js\";\nimport {Pusher} from \"./push/Pusher\";\nimport { ObservableMap } from \"../observable/index.js\";\nimport {User} from \"./User.js\";\nimport {DeviceMessageHandler} from \"./DeviceMessageHandler.js\";\nimport {Account as E2EEAccount} from \"./e2ee/Account.js\";\nimport {uploadAccountAsDehydratedDevice} from \"./e2ee/Dehydration.js\";\nimport {Decryption as OlmDecryption} from \"./e2ee/olm/Decryption\";\nimport {Encryption as OlmEncryption} from \"./e2ee/olm/Encryption\";\nimport {Decryption as MegOlmDecryption} from \"./e2ee/megolm/Decryption\";\nimport {KeyLoader as MegOlmKeyLoader} from \"./e2ee/megolm/decryption/KeyLoader\";\nimport {KeyBackup} from \"./e2ee/megolm/keybackup/KeyBackup\";\nimport {Encryption as MegOlmEncryption} from \"./e2ee/megolm/Encryption.js\";\nimport {MEGOLM_ALGORITHM} from \"./e2ee/common.js\";\nimport {RoomEncryption} from \"./e2ee/RoomEncryption.js\";\nimport {DeviceTracker} from \"./e2ee/DeviceTracker.js\";\nimport {LockMap} from \"../utils/LockMap\";\nimport {groupBy} from \"../utils/groupBy\";\nimport {\n keyFromCredential as ssssKeyFromCredential,\n readKey as ssssReadKey,\n writeKey as ssssWriteKey,\n removeKey as ssssRemoveKey,\n keyFromDehydratedDeviceKey as createSSSSKeyFromDehydratedDeviceKey\n} from \"./ssss/index\";\nimport {SecretStorage} from \"./ssss/SecretStorage\";\nimport {ObservableValue, RetainedObservableValue} from \"../observable/ObservableValue\";\n\nconst PICKLE_KEY = \"DEFAULT_KEY\";\nconst PUSHER_KEY = \"pusher\";\n\nexport class Session {\n // sessionInfo contains deviceId, userId and homeserver\n constructor({storage, hsApi, sessionInfo, olm, olmWorker, platform, mediaRepository}) {\n this._platform = platform;\n this._storage = storage;\n this._hsApi = hsApi;\n this._mediaRepository = mediaRepository;\n this._syncInfo = null;\n this._sessionInfo = sessionInfo;\n this._rooms = new ObservableMap();\n this._roomUpdateCallback = (room, params) => this._rooms.update(room.id, params);\n this._activeArchivedRooms = new Map();\n this._invites = new ObservableMap();\n this._inviteUpdateCallback = (invite, params) => this._invites.update(invite.id, params);\n this._roomsBeingCreatedUpdateCallback = (rbc, params) => {\n if (rbc.isCancelled) {\n this._roomsBeingCreated.remove(rbc.id);\n } else {\n this._roomsBeingCreated.update(rbc.id, params)\n }\n };\n this._roomsBeingCreated = new ObservableMap();\n this._user = new User(sessionInfo.userId);\n this._deviceMessageHandler = new DeviceMessageHandler({storage});\n this._olm = olm;\n this._olmUtil = null;\n this._e2eeAccount = null;\n this._deviceTracker = null;\n this._olmEncryption = null;\n this._keyLoader = null;\n this._megolmEncryption = null;\n this._megolmDecryption = null;\n this._getSyncToken = () => this.syncToken;\n this._olmWorker = olmWorker;\n this._keyBackup = new ObservableValue(undefined);\n this._observedRoomStatus = new Map();\n\n if (olm) {\n this._olmUtil = new olm.Utility();\n this._deviceTracker = new DeviceTracker({\n storage,\n getSyncToken: this._getSyncToken,\n olmUtil: this._olmUtil,\n ownUserId: sessionInfo.userId,\n ownDeviceId: sessionInfo.deviceId,\n });\n }\n this._createRoomEncryption = this._createRoomEncryption.bind(this);\n this._forgetArchivedRoom = this._forgetArchivedRoom.bind(this);\n this.needsKeyBackup = new ObservableValue(false);\n }\n\n get fingerprintKey() {\n return this._e2eeAccount?.identityKeys.ed25519;\n }\n\n get hasSecretStorageKey() {\n return this._hasSecretStorageKey;\n }\n\n get deviceId() {\n return this._sessionInfo.deviceId;\n }\n\n get userId() {\n return this._sessionInfo.userId;\n }\n\n // called once this._e2eeAccount is assigned\n _setupEncryption() {\n // TODO: this should all go in a wrapper in e2ee/ that is bootstrapped by passing in the account\n // and can create RoomEncryption objects and handle encrypted to_device messages and device list changes.\n const senderKeyLock = new LockMap();\n const olmDecryption = new OlmDecryption(\n this._e2eeAccount,\n PICKLE_KEY,\n this._platform.clock.now,\n this._user.id,\n this._olm,\n senderKeyLock\n );\n this._olmEncryption = new OlmEncryption(\n this._e2eeAccount,\n PICKLE_KEY,\n this._olm,\n this._storage,\n this._platform.clock.now,\n this._user.id,\n this._olmUtil,\n senderKeyLock\n );\n this._keyLoader = new MegOlmKeyLoader(this._olm, PICKLE_KEY, 20);\n this._megolmEncryption = new MegOlmEncryption({\n account: this._e2eeAccount,\n pickleKey: PICKLE_KEY,\n olm: this._olm,\n storage: this._storage,\n keyLoader: this._keyLoader,\n now: this._platform.clock.now,\n ownDeviceId: this._sessionInfo.deviceId,\n });\n this._megolmDecryption = new MegOlmDecryption(this._keyLoader, this._olmWorker);\n this._deviceMessageHandler.enableEncryption({olmDecryption, megolmDecryption: this._megolmDecryption});\n }\n\n _createRoomEncryption(room, encryptionParams) {\n // TODO: this will actually happen when users start using the e2ee version for the first time\n\n // this should never happen because either a session was already synced once\n // and thus an e2ee account was created as well and _setupEncryption is called from load\n // OR\n // this is a new session and loading it will load zero rooms, thus not calling this method.\n // in this case _setupEncryption is called from beforeFirstSync, right after load,\n // so any incoming synced rooms won't be there yet\n if (!this._olmEncryption) {\n throw new Error(\"creating room encryption before encryption got globally enabled\");\n }\n // only support megolm\n if (encryptionParams.algorithm !== MEGOLM_ALGORITHM) {\n return null;\n }\n return new RoomEncryption({\n room,\n deviceTracker: this._deviceTracker,\n olmEncryption: this._olmEncryption,\n megolmEncryption: this._megolmEncryption,\n megolmDecryption: this._megolmDecryption,\n storage: this._storage,\n keyBackup: this._keyBackup?.get(),\n encryptionParams,\n notifyMissingMegolmSession: () => {\n if (!this._keyBackup.get()) {\n this.needsKeyBackup.set(true)\n }\n },\n clock: this._platform.clock\n });\n }\n\n /**\n * Enable secret storage by providing the secret storage credential.\n * This will also see if there is a megolm key backup and try to enable that if so.\n * \n * @param {string} type either \"passphrase\" or \"recoverykey\"\n * @param {string} credential either the passphrase or the recovery key, depending on the type\n * @return {Promise} resolves or rejects after having tried to enable secret storage\n */\n enableSecretStorage(type, credential, log = undefined) {\n return this._platform.logger.wrapOrRun(log, \"enable secret storage\", async log => {\n if (!this._olm) {\n throw new Error(\"olm required\");\n }\n if (this._keyBackup.get()) {\n this._keyBackup.get().dispose();\n this._keyBackup.set(null);\n }\n const key = await ssssKeyFromCredential(type, credential, this._storage, this._platform, this._olm);\n // and create key backup, which needs to read from accountData\n const readTxn = await this._storage.readTxn([\n this._storage.storeNames.accountData,\n ]);\n if (await this._createKeyBackup(key, readTxn, log)) {\n // only after having read a secret, write the key\n // as we only find out if it was good if the MAC verification succeeds\n await this._writeSSSSKey(key, log);\n this._keyBackup.get().flush(log);\n return key;\n } else {\n throw new Error(\"Could not read key backup with the given key\");\n }\n });\n }\n\n async _writeSSSSKey(key, log) {\n // we're going to write the 4S key, and also the backup version.\n // this way, we can detect when we enter a key for a new backup version\n // and mark all inbound sessions to be backed up again\n const keyBackup = this._keyBackup.get();\n if (!keyBackup) {\n return;\n }\n const backupVersion = keyBackup.version;\n const writeTxn = await this._storage.readWriteTxn([\n this._storage.storeNames.session,\n this._storage.storeNames.inboundGroupSessions,\n ]);\n try {\n const previousBackupVersion = await ssssWriteKey(key, backupVersion, writeTxn);\n log.set(\"previousBackupVersion\", previousBackupVersion);\n log.set(\"backupVersion\", backupVersion);\n if (!!previousBackupVersion && previousBackupVersion !== backupVersion) {\n const amountMarked = await keyBackup.markAllForBackup(writeTxn);\n log.set(\"amountMarkedForBackup\", amountMarked);\n }\n } catch (err) {\n writeTxn.abort();\n throw err;\n }\n await writeTxn.complete();\n }\n\n async disableSecretStorage() {\n const writeTxn = await this._storage.readWriteTxn([\n this._storage.storeNames.session,\n ]);\n try {\n ssssRemoveKey(writeTxn);\n } catch (err) {\n writeTxn.abort();\n throw err;\n }\n await writeTxn.complete();\n if (this._keyBackup.get()) {\n for (const room of this._rooms.values()) {\n if (room.isEncrypted) {\n room.enableKeyBackup(undefined);\n }\n }\n this._keyBackup.get().dispose();\n this._keyBackup.set(null);\n }\n }\n\n _createKeyBackup(ssssKey, txn, log) {\n return log.wrap(\"enable key backup\", async log => {\n try {\n const secretStorage = new SecretStorage({key: ssssKey, platform: this._platform});\n const keyBackup = await KeyBackup.fromSecretStorage(\n this._platform,\n this._olm,\n secretStorage,\n this._hsApi,\n this._keyLoader,\n this._storage,\n txn\n );\n if (keyBackup) {\n for (const room of this._rooms.values()) {\n if (room.isEncrypted) {\n room.enableKeyBackup(keyBackup);\n }\n }\n this._keyBackup.set(keyBackup);\n return true;\n }\n } catch (err) {\n log.catch(err);\n }\n return false;\n });\n }\n\n /**\n * @type {ObservableValue this._e2eeAccount.uploadKeys(this._storage, false, log));\n }\n }\n\n /** @internal */\n async dehydrateIdentity(dehydratedDevice, log) {\n log.set(\"deviceId\", dehydratedDevice.deviceId);\n if (!this._olm) {\n log.set(\"no_olm\", true);\n return false;\n }\n if (dehydratedDevice.deviceId !== this.deviceId) {\n log.set(\"wrong_device\", true);\n return false;\n }\n if (this._e2eeAccount) {\n log.set(\"account_already_setup\", true);\n return false;\n }\n if (!await dehydratedDevice.claim(this._hsApi, log)) {\n log.set(\"already_claimed\", true);\n return false;\n }\n this._e2eeAccount = await E2EEAccount.adoptDehydratedDevice({\n dehydratedDevice,\n hsApi: this._hsApi,\n olm: this._olm,\n pickleKey: PICKLE_KEY,\n userId: this._sessionInfo.userId,\n olmWorker: this._olmWorker,\n deviceId: this.deviceId,\n storage: this._storage,\n });\n log.set(\"keys\", this._e2eeAccount.identityKeys);\n this._setupEncryption();\n return true;\n }\n\n _createNewAccount(deviceId, storage = undefined) {\n // storage is optional and if omitted the account won't be persisted (useful for dehydrating devices)\n return E2EEAccount.create({\n hsApi: this._hsApi,\n olm: this._olm,\n pickleKey: PICKLE_KEY,\n userId: this._sessionInfo.userId,\n olmWorker: this._olmWorker,\n deviceId,\n storage,\n });\n }\n\n setupDehydratedDevice(key, log = null) {\n return this._platform.logger.wrapOrRun(log, \"setupDehydratedDevice\", async log => {\n const dehydrationAccount = await this._createNewAccount(\"temp-device-id\");\n try {\n const deviceId = await uploadAccountAsDehydratedDevice(\n dehydrationAccount, this._hsApi, key, \"Dehydrated device\", log);\n log.set(\"deviceId\", deviceId);\n return deviceId;\n } finally {\n dehydrationAccount.dispose();\n }\n });\n }\n\n /** @internal */\n async load(log) {\n const txn = await this._storage.readTxn([\n this._storage.storeNames.session,\n this._storage.storeNames.roomSummary,\n this._storage.storeNames.invites,\n this._storage.storeNames.roomMembers,\n this._storage.storeNames.timelineEvents,\n this._storage.storeNames.timelineFragments,\n this._storage.storeNames.pendingEvents,\n ]);\n // restore session object\n this._syncInfo = await txn.session.get(\"sync\");\n // restore e2ee account, if any\n if (this._olm) {\n this._e2eeAccount = await E2EEAccount.load({\n hsApi: this._hsApi,\n olm: this._olm,\n pickleKey: PICKLE_KEY,\n userId: this._sessionInfo.userId,\n deviceId: this._sessionInfo.deviceId,\n olmWorker: this._olmWorker,\n txn\n });\n if (this._e2eeAccount) {\n log.set(\"keys\", this._e2eeAccount.identityKeys);\n this._setupEncryption();\n }\n }\n const pendingEventsByRoomId = await this._getPendingEventsByRoom(txn);\n // load invites\n const invites = await txn.invites.getAll();\n const inviteLoadPromise = Promise.all(invites.map(async inviteData => {\n const invite = this.createInvite(inviteData.roomId);\n log.wrap(\"invite\", log => invite.load(inviteData, log));\n this._invites.add(invite.id, invite);\n }));\n // load rooms\n const rooms = await txn.roomSummary.getAll();\n const roomLoadPromise = Promise.all(rooms.map(async summary => {\n const room = this.createJoinedRoom(summary.roomId, pendingEventsByRoomId.get(summary.roomId));\n await log.wrap(\"room\", log => room.load(summary, txn, log));\n this._rooms.add(room.id, room);\n }));\n // load invites and rooms in parallel\n await Promise.all([inviteLoadPromise, roomLoadPromise]);\n for (const [roomId, invite] of this.invites) {\n const room = this.rooms.get(roomId);\n if (room) {\n room.setInvite(invite);\n }\n }\n }\n\n dispose() {\n this._olmWorker?.dispose();\n this._olmWorker = undefined;\n this._keyBackup.get()?.dispose();\n this._keyBackup.set(undefined);\n this._megolmDecryption?.dispose();\n this._megolmDecryption = undefined;\n this._e2eeAccount?.dispose();\n this._e2eeAccount = undefined;\n for (const room of this._rooms.values()) {\n room.dispose();\n }\n this._rooms = undefined;\n }\n\n /**\n * @internal called from session container when coming back online and catchup syncs have finished.\n * @param {Object} lastVersionResponse a response from /versions, which is polled while offline,\n * and useful to store so we can later tell what capabilities\n * our homeserver has.\n */\n async start(lastVersionResponse, dehydratedDevice, log) {\n if (lastVersionResponse) {\n // store /versions response\n const txn = await this._storage.readWriteTxn([\n this._storage.storeNames.session\n ]);\n txn.session.set(\"serverVersions\", lastVersionResponse);\n // TODO: what can we do if this throws?\n await txn.complete();\n }\n // enable session backup, this requests the latest backup version\n if (!this._keyBackup.get()) {\n if (dehydratedDevice) {\n await log.wrap(\"SSSSKeyFromDehydratedDeviceKey\", async log => {\n const ssssKey = await createSSSSKeyFromDehydratedDeviceKey(dehydratedDevice.key, this._storage, this._platform);\n if (ssssKey) {\n log.set(\"success\", true);\n await this._writeSSSSKey(ssssKey);\n }\n });\n }\n const txn = await this._storage.readTxn([\n this._storage.storeNames.session,\n this._storage.storeNames.accountData,\n ]);\n // try set up session backup if we stored the ssss key\n const ssssKey = await ssssReadKey(txn);\n if (ssssKey) {\n // txn will end here as this does a network request\n if (await this._createKeyBackup(ssssKey, txn, log)) {\n this._keyBackup.get()?.flush(log);\n }\n }\n if (!this._keyBackup.get()) {\n // null means key backup isn't configured yet\n // as opposed to undefined, which means we're still checking\n this._keyBackup.set(null);\n }\n }\n // restore unfinished operations, like sending out room keys\n const opsTxn = await this._storage.readWriteTxn([\n this._storage.storeNames.operations\n ]);\n const operations = await opsTxn.operations.getAll();\n const operationsByScope = groupBy(operations, o => o.scope);\n\n for (const room of this._rooms.values()) {\n let roomOperationsByType;\n const roomOperations = operationsByScope.get(room.id);\n if (roomOperations) {\n roomOperationsByType = groupBy(roomOperations, r => r.type);\n }\n room.start(roomOperationsByType, log);\n }\n }\n\n async _getPendingEventsByRoom(txn) {\n const pendingEvents = await txn.pendingEvents.getAll();\n return pendingEvents.reduce((groups, pe) => {\n const group = groups.get(pe.roomId);\n if (group) {\n group.push(pe);\n } else {\n groups.set(pe.roomId, [pe]);\n }\n return groups;\n }, new Map());\n }\n\n get rooms() {\n return this._rooms;\n }\n\n findDirectMessageForUserId(userId) {\n for (const [,room] of this._rooms) {\n if (room.isDirectMessageForUserId(userId)) {\n return room;\n }\n }\n for (const [,invite] of this._invites) {\n if (invite.isDirectMessageForUserId(userId)) {\n return invite;\n }\n }\n }\n\n /** @internal */\n createJoinedRoom(roomId, pendingEvents) {\n return new Room({\n roomId,\n getSyncToken: this._getSyncToken,\n storage: this._storage,\n emitCollectionChange: this._roomUpdateCallback,\n hsApi: this._hsApi,\n mediaRepository: this._mediaRepository,\n pendingEvents,\n user: this._user,\n createRoomEncryption: this._createRoomEncryption,\n platform: this._platform\n });\n }\n\n /** @internal */\n _createArchivedRoom(roomId) {\n const room = new ArchivedRoom({\n roomId,\n getSyncToken: this._getSyncToken,\n storage: this._storage,\n emitCollectionChange: () => {},\n releaseCallback: () => this._activeArchivedRooms.delete(roomId),\n forgetCallback: this._forgetArchivedRoom,\n hsApi: this._hsApi,\n mediaRepository: this._mediaRepository,\n user: this._user,\n createRoomEncryption: this._createRoomEncryption,\n platform: this._platform\n });\n this._activeArchivedRooms.set(roomId, room);\n return room;\n }\n\n get invites() {\n return this._invites;\n }\n\n /** @internal */\n createInvite(roomId) {\n return new Invite({\n roomId,\n hsApi: this._hsApi,\n emitCollectionUpdate: this._inviteUpdateCallback,\n mediaRepository: this._mediaRepository,\n user: this._user,\n platform: this._platform,\n });\n }\n\n get roomsBeingCreated() {\n return this._roomsBeingCreated;\n }\n\n createRoom(options) {\n let roomBeingCreated;\n this._platform.logger.runDetached(\"create room\", async log => {\n const id = `local-${Math.floor(this._platform.random() * Number.MAX_SAFE_INTEGER)}`;\n roomBeingCreated = new RoomBeingCreated(\n id, options, this._roomsBeingCreatedUpdateCallback,\n this._mediaRepository, this._platform, log);\n this._roomsBeingCreated.set(id, roomBeingCreated);\n const promises = [roomBeingCreated.create(this._hsApi, log)];\n const loadProfiles = options.loadProfiles !== false; // default to true\n if (loadProfiles) {\n promises.push(roomBeingCreated.loadProfiles(this._hsApi, log));\n }\n await Promise.all(promises);\n // we should now know the roomId, check if the room was synced before we received\n // the room id. Replace the room being created with the synced room.\n if (roomBeingCreated.roomId) {\n if (this.rooms.get(roomBeingCreated.roomId)) {\n this._tryReplaceRoomBeingCreated(roomBeingCreated.roomId, log);\n }\n await roomBeingCreated.adjustDirectMessageMapIfNeeded(this._user, this._storage, this._hsApi, log);\n }\n });\n return roomBeingCreated;\n }\n\n async obtainSyncLock(syncResponse) {\n const toDeviceEvents = syncResponse.to_device?.events;\n if (Array.isArray(toDeviceEvents) && toDeviceEvents.length) {\n return await this._deviceMessageHandler.obtainSyncLock(toDeviceEvents);\n }\n }\n\n async prepareSync(syncResponse, lock, txn, log) {\n const toDeviceEvents = syncResponse.to_device?.events;\n if (Array.isArray(toDeviceEvents) && toDeviceEvents.length) {\n return await log.wrap(\"deviceMsgs\", log => this._deviceMessageHandler.prepareSync(toDeviceEvents, lock, txn, log));\n }\n }\n\n /** @internal */\n async writeSync(syncResponse, syncFilterId, preparation, txn, log) {\n const changes = {\n syncInfo: null,\n e2eeAccountChanges: null\n };\n const syncToken = syncResponse.next_batch;\n if (syncToken !== this.syncToken) {\n const syncInfo = {token: syncToken, filterId: syncFilterId};\n // don't modify `this` because transaction might still fail\n txn.session.set(\"sync\", syncInfo);\n changes.syncInfo = syncInfo;\n }\n\n const deviceOneTimeKeysCount = syncResponse.device_one_time_keys_count;\n if (this._e2eeAccount && deviceOneTimeKeysCount) {\n changes.e2eeAccountChanges = this._e2eeAccount.writeSync(deviceOneTimeKeysCount, txn, log);\n }\n \n const deviceLists = syncResponse.device_lists;\n if (this._deviceTracker && Array.isArray(deviceLists?.changed) && deviceLists.changed.length) {\n await log.wrap(\"deviceLists\", log => this._deviceTracker.writeDeviceChanges(deviceLists.changed, txn, log));\n }\n\n if (preparation) {\n changes.hasNewRoomKeys = await log.wrap(\"deviceMsgs\", log => this._deviceMessageHandler.writeSync(preparation, txn, log));\n }\n\n // store account data\n const accountData = syncResponse[\"account_data\"];\n if (Array.isArray(accountData?.events)) {\n for (const event of accountData.events) {\n if (typeof event.type === \"string\") {\n txn.accountData.set(event);\n }\n }\n }\n return changes;\n }\n\n /** @internal */\n afterSync({syncInfo, e2eeAccountChanges}) {\n if (syncInfo) {\n // sync transaction succeeded, modify object state now\n this._syncInfo = syncInfo;\n }\n if (this._e2eeAccount) {\n this._e2eeAccount.afterSync(e2eeAccountChanges);\n }\n }\n\n /** @internal */\n async afterSyncCompleted(changes, isCatchupSync, log) {\n // we don't start uploading one-time keys until we've caught up with\n // to-device messages, to help us avoid throwing away one-time-keys that we\n // are about to receive messages for\n // (https://github.com/vector-im/riot-web/issues/2782).\n if (!isCatchupSync) {\n const needsToUploadOTKs = await this._e2eeAccount.generateOTKsIfNeeded(this._storage, log);\n if (needsToUploadOTKs) {\n await log.wrap(\"uploadKeys\", log => this._e2eeAccount.uploadKeys(this._storage, false, log));\n }\n }\n if (changes.hasNewRoomKeys) {\n this._keyBackup.get()?.flush(log);\n }\n }\n\n _tryReplaceRoomBeingCreated(roomId, log) {\n for (const [,roomBeingCreated] of this._roomsBeingCreated) {\n if (roomBeingCreated.roomId === roomId) {\n const observableStatus = this._observedRoomStatus.get(roomBeingCreated.id);\n if (observableStatus) {\n log.log(`replacing room being created`)\n .set(\"localId\", roomBeingCreated.id)\n .set(\"roomId\", roomBeingCreated.roomId);\n observableStatus.set(observableStatus.get() | RoomStatus.Replaced);\n }\n roomBeingCreated.dispose();\n this._roomsBeingCreated.remove(roomBeingCreated.id);\n return;\n }\n }\n }\n\n applyRoomCollectionChangesAfterSync(inviteStates, roomStates, archivedRoomStates, log) {\n // update the collections after sync\n for (const rs of roomStates) {\n if (rs.shouldAdd) {\n this._rooms.add(rs.id, rs.room);\n this._tryReplaceRoomBeingCreated(rs.id, log);\n } else if (rs.shouldRemove) {\n this._rooms.remove(rs.id);\n }\n }\n for (const is of inviteStates) {\n if (is.shouldAdd) {\n this._invites.add(is.id, is.invite);\n } else if (is.shouldRemove) {\n this._invites.remove(is.id);\n }\n }\n // now all the collections are updated, update the room status\n // so any listeners to the status will find the collections\n // completely up to date\n if (this._observedRoomStatus.size !== 0) {\n for (const ars of archivedRoomStates) {\n if (ars.shouldAdd) {\n this._observedRoomStatus.get(ars.id)?.set(RoomStatus.Archived);\n }\n }\n for (const rs of roomStates) {\n if (rs.shouldAdd) {\n this._observedRoomStatus.get(rs.id)?.set(RoomStatus.Joined);\n }\n }\n for (const is of inviteStates) {\n const statusObservable = this._observedRoomStatus.get(is.id);\n if (statusObservable) {\n const withInvited = statusObservable.get() | RoomStatus.Invited;\n if (is.shouldAdd) {\n statusObservable.set(withInvited);\n } else if (is.shouldRemove) {\n const withoutInvited = withInvited ^ RoomStatus.Invited;\n statusObservable.set(withoutInvited);\n }\n }\n }\n }\n }\n\n _forgetArchivedRoom(roomId) {\n const statusObservable = this._observedRoomStatus.get(roomId);\n if (statusObservable) {\n statusObservable.set((statusObservable.get() | RoomStatus.Archived) ^ RoomStatus.Archived);\n }\n }\n\n /** @internal */\n get syncToken() {\n return this._syncInfo?.token;\n }\n\n /** @internal */\n get syncFilterId() {\n return this._syncInfo?.filterId;\n }\n\n get user() {\n return this._user;\n }\n\n get mediaRepository() {\n return this._mediaRepository;\n }\n\n enablePushNotifications(enable) {\n if (enable) {\n return this._enablePush();\n } else {\n return this._disablePush();\n }\n }\n\n async _enablePush() {\n return this._platform.logger.run(\"enablePush\", async log => {\n const defaultPayload = Pusher.createDefaultPayload(this._sessionInfo.id);\n const pusher = await this._platform.notificationService.enablePush(Pusher, defaultPayload);\n if (!pusher) {\n log.set(\"no_pusher\", true);\n return false;\n }\n await pusher.enable(this._hsApi, log);\n // store pusher data, so we know we enabled it across reloads,\n // and we can disable it without too much hassle\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.session]);\n txn.session.set(PUSHER_KEY, pusher.serialize());\n await txn.complete();\n return true;\n });\n }\n\n\n async _disablePush() {\n return this._platform.logger.run(\"disablePush\", async log => {\n await this._platform.notificationService.disablePush();\n const readTxn = await this._storage.readTxn([this._storage.storeNames.session]);\n const pusherData = await readTxn.session.get(PUSHER_KEY);\n if (!pusherData) {\n // we've disabled push in the notif service at least\n return true;\n }\n const pusher = new Pusher(pusherData);\n await pusher.disable(this._hsApi, log);\n const txn = await this._storage.readWriteTxn([this._storage.storeNames.session]);\n txn.session.remove(PUSHER_KEY);\n await txn.complete();\n return true;\n });\n }\n\n async arePushNotificationsEnabled() {\n if (!await this._platform.notificationService.isPushEnabled()) {\n return false;\n }\n const readTxn = await this._storage.readTxn([this._storage.storeNames.session]);\n const pusherData = await readTxn.session.get(PUSHER_KEY);\n return !!pusherData;\n }\n\n async checkPusherEnabledOnHomeserver() {\n const readTxn = await this._storage.readTxn([this._storage.storeNames.session]);\n const pusherData = await readTxn.session.get(PUSHER_KEY);\n if (!pusherData) {\n return false;\n }\n const myPusher = new Pusher(pusherData);\n const serverPushersData = await this._hsApi.getPushers().response();\n const serverPushers = (serverPushersData?.pushers || []).map(data => new Pusher(data));\n return serverPushers.some(p => p.equals(myPusher));\n }\n\n async getRoomStatus(roomId) {\n const isBeingCreated = !!this._roomsBeingCreated.get(roomId);\n if (isBeingCreated) {\n return RoomStatus.BeingCreated;\n }\n const isJoined = !!this._rooms.get(roomId);\n if (isJoined) {\n return RoomStatus.Joined;\n } else {\n const isInvited = !!this._invites.get(roomId);\n const txn = await this._storage.readTxn([this._storage.storeNames.archivedRoomSummary]);\n const isArchived = await txn.archivedRoomSummary.has(roomId);\n if (isInvited && isArchived) {\n return RoomStatus.Invited | RoomStatus.Archived;\n } else if (isInvited) {\n return RoomStatus.Invited;\n } else if (isArchived) {\n return RoomStatus.Archived;\n } else {\n return RoomStatus.None;\n }\n }\n }\n\n async observeRoomStatus(roomId) {\n let observable = this._observedRoomStatus.get(roomId);\n if (!observable) {\n const status = await this.getRoomStatus(roomId);\n observable = new RetainedObservableValue(status, () => {\n this._observedRoomStatus.delete(roomId);\n });\n\n this._observedRoomStatus.set(roomId, observable);\n }\n return observable;\n }\n\n /**\n Creates an empty (summary isn't loaded) the archived room if it isn't\n loaded already, assuming sync will either remove it (when rejoining) or\n write a full summary adopting it from the joined room when leaving\n \n @internal\n */\n createOrGetArchivedRoomForSync(roomId) {\n let archivedRoom = this._activeArchivedRooms.get(roomId);\n if (archivedRoom) {\n archivedRoom.retain();\n } else {\n archivedRoom = this._createArchivedRoom(roomId);\n }\n return archivedRoom;\n }\n\n loadArchivedRoom(roomId, log = null) {\n return this._platform.logger.wrapOrRun(log, \"loadArchivedRoom\", async log => {\n log.set(\"id\", roomId);\n const activeArchivedRoom = this._activeArchivedRooms.get(roomId);\n if (activeArchivedRoom) {\n activeArchivedRoom.retain();\n return activeArchivedRoom;\n }\n const txn = await this._storage.readTxn([\n this._storage.storeNames.archivedRoomSummary,\n this._storage.storeNames.roomMembers,\n ]);\n const summary = await txn.archivedRoomSummary.get(roomId);\n if (summary) {\n const room = this._createArchivedRoom(roomId);\n await room.load(summary, txn, log);\n return room;\n }\n });\n }\n\n joinRoom(roomIdOrAlias, log = null) {\n return this._platform.logger.wrapOrRun(log, \"joinRoom\", async log => {\n const body = await this._hsApi.joinIdOrAlias(roomIdOrAlias, {log}).response();\n return body.room_id;\n });\n }\n}\n\nexport function tests() {\n function createStorageMock(session, pendingEvents = []) {\n return {\n readTxn() {\n return {\n session: {\n get(key) {\n return Promise.resolve(session[key]);\n }\n },\n pendingEvents: {\n getAll() {\n return Promise.resolve(pendingEvents);\n }\n },\n roomSummary: {\n getAll() {\n return Promise.resolve([]);\n }\n },\n invites: {\n getAll() {\n return Promise.resolve([]);\n }\n }\n };\n },\n storeNames: {}\n };\n }\n\n return {\n \"session data is not modified until after sync\": async (assert) => {\n const session = new Session({storage: createStorageMock({\n sync: {token: \"a\", filterId: 5}\n }), sessionInfo: {userId: \"\"}});\n await session.load();\n let syncSet = false;\n const syncTxn = {\n session: {\n set(key, value) {\n if (key === \"sync\") {\n assert.equal(value.token, \"b\");\n assert.equal(value.filterId, 6);\n syncSet = true;\n }\n }\n }\n };\n const newSessionData = await session.writeSync({next_batch: \"b\"}, 6, null, syncTxn, {});\n assert(syncSet);\n assert.equal(session.syncToken, \"a\");\n assert.equal(session.syncFilterId, 5);\n session.afterSync(newSessionData);\n assert.equal(session.syncToken, \"b\");\n assert.equal(session.syncFilterId, 6);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ILogItem} from \"../../logging/types\";\nimport {ILoginMethod} from \"./LoginMethod\";\nimport {HomeServerApi} from \"../net/HomeServerApi.js\";\n\nexport class PasswordLoginMethod implements ILoginMethod {\n private readonly _username: string;\n private readonly _password: string;\n public readonly homeserver: string;\n\n constructor({username, password, homeserver}: {username: string, password: string, homeserver: string}) {\n this._username = username;\n this._password = password;\n this.homeserver = homeserver;\n }\n\n async login(hsApi: HomeServerApi, deviceName: string, log: ILogItem): Promise> {\n return await hsApi.passwordLogin(this._username, this._password, deviceName, {log}).response();\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {makeTxnId} from \"../common.js\";\nimport {ILogItem} from \"../../logging/types\";\nimport {ILoginMethod} from \"./LoginMethod\";\nimport {HomeServerApi} from \"../net/HomeServerApi.js\";\n\nexport class TokenLoginMethod implements ILoginMethod {\n private readonly _loginToken: string;\n public readonly homeserver: string;\n\n constructor({ homeserver, loginToken }: { homeserver: string, loginToken: string}) {\n this.homeserver = homeserver;\n this._loginToken = loginToken;\n }\n\n async login(hsApi: HomeServerApi, deviceName: string, log: ILogItem): Promise> {\n return await hsApi.tokenLogin(this._loginToken, makeTxnId(), deviceName, {log}).response();\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class SSOLoginHelper{\n private _homeserver: string;\n\n constructor(homeserver: string) {\n this._homeserver = homeserver;\n }\n\n get homeserver(): string { return this._homeserver; }\n\n createSSORedirectURL(returnURL: string): string {\n return `${this._homeserver}/_matrix/client/r0/login/sso/redirect?redirectUrl=${returnURL}`;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {AuthenticationData, RegistrationParams} from \"../types\";\n\nexport abstract class BaseRegistrationStage {\n protected _session: string;\n protected _nextStage: BaseRegistrationStage;\n protected readonly _params?: Record\n\n constructor(session: string, params?: RegistrationParams) {\n this._session = session;\n this._params = params;\n }\n\n /**\n * eg: m.login.recaptcha or m.login.dummy\n */\n abstract get type(): string;\n\n /**\n * This method should return auth part that must be provided to\n * /register endpoint to successfully complete this stage\n */\n /** @internal */\n abstract generateAuthenticationData(): AuthenticationData;\n\n setNextStage(stage: BaseRegistrationStage) {\n this._nextStage = stage;\n }\n\n get nextStage(): BaseRegistrationStage {\n return this._nextStage;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AuthenticationData} from \"../types\";\nimport {BaseRegistrationStage} from \"./BaseRegistrationStage\";\n\nexport class DummyAuth extends BaseRegistrationStage {\n generateAuthenticationData(): AuthenticationData {\n return {\n session: this._session,\n type: this.type,\n }; \n }\n\n get type(): string {\n return \"m.login.dummy\";\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AuthenticationData} from \"../types\";\nimport {BaseRegistrationStage} from \"./BaseRegistrationStage\";\n\nexport class TermsAuth extends BaseRegistrationStage {\n generateAuthenticationData(): AuthenticationData {\n return {\n session: this._session,\n type: this.type,\n // No other auth data needed for m.login.terms\n }; \n }\n\n get type(): string {\n return \"m.login.terms\";\n }\n\n get privacyPolicy() {\n return this._params?.policies[\"privacy_policy\"];\n }\n\n get termsOfService() {\n return this._params?.policies[\"terms_of_service\"];\n }\n}\n","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AuthenticationData, RegistrationParams} from \"../types\";\nimport {BaseRegistrationStage} from \"./BaseRegistrationStage\";\n\nexport class TokenAuth extends BaseRegistrationStage {\n private _token?: string;\n private readonly _type: string;\n\n constructor(session: string, params: RegistrationParams | undefined, type: string) {\n super(session, params);\n this._type = type;\n }\n\n\n generateAuthenticationData(): AuthenticationData {\n if (!this._token) {\n throw new Error(\"No token provided for TokenAuth\");\n }\n return {\n session: this._session,\n type: this._type,\n token: this._token,\n }; \n }\n\n setToken(token: string) {\n this._token = token;\n }\n\n get type(): string {\n return this._type;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {HomeServerApi} from \"../net/HomeServerApi\";\nimport type {BaseRegistrationStage} from \"./stages/BaseRegistrationStage\";\nimport {DummyAuth} from \"./stages/DummyAuth\";\nimport {TermsAuth} from \"./stages/TermsAuth\";\nimport {TokenAuth} from \"./stages/TokenAuth\";\nimport type {\n AccountDetails,\n RegistrationFlow,\n RegistrationResponseMoreDataNeeded,\n RegistrationResponse,\n RegistrationResponseSuccess,\n RegistrationParams,\n} from \"./types\";\n\ntype FlowSelector = (flows: RegistrationFlow[]) => RegistrationFlow | void;\n\nexport class Registration {\n private readonly _hsApi: HomeServerApi;\n private readonly _accountDetails: AccountDetails;\n private readonly _flowSelector: FlowSelector;\n private _sessionInfo?: RegistrationResponseSuccess\n\n constructor(hsApi: HomeServerApi, accountDetails: AccountDetails, flowSelector?: FlowSelector) {\n this._hsApi = hsApi;\n this._accountDetails = accountDetails;\n this._flowSelector = flowSelector ?? (flows => flows[0]);\n }\n\n async start(): Promise {\n const response = await this._hsApi.register(\n this._accountDetails.username,\n this._accountDetails.password,\n this._accountDetails.initialDeviceDisplayName,\n undefined,\n this._accountDetails.inhibitLogin).response();\n return this.parseStagesFromResponse(response);\n }\n\n /**\n * Finish a registration stage, return value is:\n * - the next stage if this stage was completed successfully\n * - undefined if registration is completed\n */\n async submitStage(stage: BaseRegistrationStage): Promise {\n const auth = stage.generateAuthenticationData();\n const { username, password, initialDeviceDisplayName, inhibitLogin } = this._accountDetails;\n const request = this._hsApi.register(username, password, initialDeviceDisplayName, auth, inhibitLogin);\n const response = await request.response();\n const status = await request.responseCode();\n const registrationResponse: RegistrationResponse = { ...response, status };\n return this.parseRegistrationResponse(registrationResponse, stage);\n }\n\n private parseStagesFromResponse(response: RegistrationResponseMoreDataNeeded): BaseRegistrationStage {\n const { session, params } = response;\n const flow = this._flowSelector(response.flows);\n if (!flow) {\n throw new Error(\"flowSelector did not return any flow!\");\n }\n let firstStage: BaseRegistrationStage | undefined;\n let lastStage: BaseRegistrationStage | undefined;\n for (const stage of flow.stages) {\n const registrationStage = this._createRegistrationStage(stage, session, params);\n if (!firstStage) {\n firstStage = registrationStage;\n lastStage = registrationStage;\n } else {\n lastStage!.setNextStage(registrationStage);\n lastStage = registrationStage;\n }\n }\n return firstStage!;\n }\n\n private async parseRegistrationResponse(response: RegistrationResponse, currentStage: BaseRegistrationStage) {\n switch (response.status) {\n case 200:\n this._sessionInfo = response;\n return undefined;\n case 401:\n if (response.completed?.includes(currentStage.type)) {\n return currentStage.nextStage;\n }\n else {\n throw new Error(\"This stage could not be completed!\");\n }\n }\n }\n\n private _createRegistrationStage(type: string, session: string, params?: RegistrationParams) {\n switch (type) {\n case \"m.login.dummy\":\n return new DummyAuth(session, params?.[type]);\n case \"m.login.terms\":\n return new TermsAuth(session, params?.[type]);\n case \"org.matrix.msc3231.login.registration_token\":\n case \"m.login.registration_token\":\n return new TokenAuth(session, params?.[type], type);\n default:\n throw new Error(`Unknown stage: ${type}`);\n }\n }\n\n get sessionInfo(): RegistrationResponseSuccess | undefined {\n return this._sessionInfo;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {createEnum} from \"../utils/enum\";\nimport {lookupHomeserver} from \"./well-known.js\";\nimport {AbortableOperation} from \"../utils/AbortableOperation\";\nimport {ObservableValue} from \"../observable/ObservableValue\";\nimport {HomeServerApi} from \"./net/HomeServerApi\";\nimport {Reconnector, ConnectionStatus} from \"./net/Reconnector\";\nimport {ExponentialRetryDelay} from \"./net/ExponentialRetryDelay\";\nimport {MediaRepository} from \"./net/MediaRepository\";\nimport {RequestScheduler} from \"./net/RequestScheduler\";\nimport {Sync, SyncStatus} from \"./Sync.js\";\nimport {Session} from \"./Session.js\";\nimport {PasswordLoginMethod} from \"./login/PasswordLoginMethod\";\nimport {TokenLoginMethod} from \"./login/TokenLoginMethod\";\nimport {SSOLoginHelper} from \"./login/SSOLoginHelper\";\nimport {getDehydratedDevice} from \"./e2ee/Dehydration.js\";\nimport {Registration} from \"./registration/Registration\";\n\nexport const LoadStatus = createEnum(\n \"NotLoading\",\n \"Login\",\n \"LoginFailed\",\n \"QueryAccount\", // check for dehydrated device after login\n \"AccountSetup\", // asked to restore from dehydrated device if present, call sc.accountSetup.finish() to progress to the next stage\n \"Loading\",\n \"SessionSetup\", // upload e2ee keys, ...\n \"Migrating\", // not used atm, but would fit here\n \"FirstSync\",\n \"Error\",\n \"Ready\",\n);\n\nexport const LoginFailure = createEnum(\n \"Connection\",\n \"Credentials\",\n \"Unknown\",\n);\n\nexport class Client {\n constructor(platform) {\n this._platform = platform;\n this._sessionStartedByReconnector = false;\n this._status = new ObservableValue(LoadStatus.NotLoading);\n this._error = null;\n this._loginFailure = null;\n this._reconnector = null;\n this._session = null;\n this._sync = null;\n this._sessionId = null;\n this._storage = null;\n this._requestScheduler = null;\n this._olmPromise = platform.loadOlm();\n this._workerPromise = platform.loadOlmWorker();\n this._accountSetup = undefined;\n }\n\n createNewSessionId() {\n return (Math.floor(this._platform.random() * Number.MAX_SAFE_INTEGER)).toString();\n }\n\n get sessionId() {\n return this._sessionId;\n }\n\n async startWithExistingSession(sessionId) {\n if (this._status.get() !== LoadStatus.NotLoading) {\n return;\n }\n this._status.set(LoadStatus.Loading);\n await this._platform.logger.run(\"load session\", async log => {\n log.set(\"id\", sessionId);\n try {\n const sessionInfo = await this._platform.sessionInfoStorage.get(sessionId);\n if (!sessionInfo) {\n throw new Error(\"Invalid session id: \" + sessionId);\n }\n await this._loadSessionInfo(sessionInfo, null, log);\n log.set(\"status\", this._status.get());\n } catch (err) {\n log.catch(err);\n this._error = err;\n this._status.set(LoadStatus.Error);\n }\n });\n }\n\n // TODO: When converted to typescript this should return the same type\n // as this._loginOptions is in LoginViewModel.ts (LoginOptions).\n _parseLoginOptions(options, homeserver) {\n /*\n Take server response and return new object which has two props password and sso which\n implements LoginMethod\n */\n const flows = options.flows;\n const result = {homeserver};\n for (const flow of flows) {\n if (flow.type === \"m.login.password\") {\n result.password = (username, password) => new PasswordLoginMethod({homeserver, username, password});\n }\n else if (flow.type === \"m.login.sso\" && flows.find(flow => flow.type === \"m.login.token\")) {\n result.sso = new SSOLoginHelper(homeserver);\n }\n else if (flow.type === \"m.login.token\") {\n result.token = loginToken => new TokenLoginMethod({homeserver, loginToken});\n }\n }\n return result;\n }\n\n queryLogin(homeserver) {\n return new AbortableOperation(async setAbortable => {\n homeserver = await lookupHomeserver(homeserver, (url, options) => {\n return setAbortable(this._platform.request(url, options));\n });\n const hsApi = new HomeServerApi({homeserver, request: this._platform.request});\n const response = await setAbortable(hsApi.getLoginFlows()).response();\n return this._parseLoginOptions(response, homeserver);\n });\n }\n\n async startRegistration(homeserver, username, password, initialDeviceDisplayName, flowSelector) {\n const request = this._platform.request;\n const hsApi = new HomeServerApi({homeserver, request});\n const registration = new Registration(hsApi, {\n username,\n password,\n initialDeviceDisplayName,\n },\n flowSelector);\n return registration;\n }\n\n async startWithLogin(loginMethod, {inspectAccountSetup} = {}) {\n const currentStatus = this._status.get();\n if (currentStatus !== LoadStatus.LoginFailed &&\n currentStatus !== LoadStatus.NotLoading &&\n currentStatus !== LoadStatus.Error) {\n return;\n }\n this._resetStatus();\n await this._platform.logger.run(\"login\", async log => {\n this._status.set(LoadStatus.Login);\n const clock = this._platform.clock;\n let sessionInfo;\n try {\n const request = this._platform.request;\n const hsApi = new HomeServerApi({homeserver: loginMethod.homeserver, request});\n const loginData = await loginMethod.login(hsApi, \"Hydrogen\", log);\n const sessionId = this.createNewSessionId();\n sessionInfo = {\n id: sessionId,\n deviceId: loginData.device_id,\n userId: loginData.user_id,\n homeServer: loginMethod.homeserver, // deprecate this over time\n homeserver: loginMethod.homeserver,\n accessToken: loginData.access_token,\n lastUsed: clock.now()\n };\n log.set(\"id\", sessionId);\n } catch (err) {\n this._error = err;\n if (err.name === \"HomeServerError\") {\n if (err.errcode === \"M_FORBIDDEN\") {\n this._loginFailure = LoginFailure.Credentials;\n } else {\n this._loginFailure = LoginFailure.Unknown;\n }\n log.set(\"loginFailure\", this._loginFailure);\n this._status.set(LoadStatus.LoginFailed);\n } else if (err.name === \"ConnectionError\") {\n this._loginFailure = LoginFailure.Connection;\n this._status.set(LoadStatus.LoginFailed);\n } else {\n this._status.set(LoadStatus.Error);\n }\n return;\n }\n let dehydratedDevice;\n if (inspectAccountSetup) {\n dehydratedDevice = await this._inspectAccountAfterLogin(sessionInfo, log);\n if (dehydratedDevice) {\n sessionInfo.deviceId = dehydratedDevice.deviceId;\n }\n }\n await this._platform.sessionInfoStorage.add(sessionInfo);\n // loading the session can only lead to\n // LoadStatus.Error in case of an error,\n // so separate try/catch\n try {\n await this._loadSessionInfo(sessionInfo, dehydratedDevice, log);\n log.set(\"status\", this._status.get());\n } catch (err) {\n log.catch(err);\n // free olm Account that might be contained\n dehydratedDevice?.dispose();\n this._error = err;\n this._status.set(LoadStatus.Error);\n }\n });\n }\n\n async _loadSessionInfo(sessionInfo, dehydratedDevice, log) {\n log.set(\"appVersion\", this._platform.version);\n const clock = this._platform.clock;\n this._sessionStartedByReconnector = false;\n this._status.set(LoadStatus.Loading);\n this._reconnector = new Reconnector({\n onlineStatus: this._platform.onlineStatus,\n retryDelay: new ExponentialRetryDelay(clock.createTimeout),\n createMeasure: clock.createMeasure\n });\n const hsApi = new HomeServerApi({\n homeserver: sessionInfo.homeServer,\n accessToken: sessionInfo.accessToken,\n request: this._platform.request,\n reconnector: this._reconnector,\n });\n this._sessionId = sessionInfo.id;\n this._storage = await this._platform.storageFactory.create(sessionInfo.id, log);\n // no need to pass access token to session\n const filteredSessionInfo = {\n id: sessionInfo.id,\n deviceId: sessionInfo.deviceId,\n userId: sessionInfo.userId,\n homeserver: sessionInfo.homeServer,\n };\n const olm = await this._olmPromise;\n let olmWorker = null;\n if (this._workerPromise) {\n olmWorker = await this._workerPromise;\n }\n this._requestScheduler = new RequestScheduler({hsApi, clock});\n this._requestScheduler.start();\n const mediaRepository = new MediaRepository({\n homeserver: sessionInfo.homeServer,\n platform: this._platform,\n });\n this._session = new Session({\n storage: this._storage,\n sessionInfo: filteredSessionInfo,\n hsApi: this._requestScheduler.hsApi,\n olm,\n olmWorker,\n mediaRepository,\n platform: this._platform,\n });\n await this._session.load(log);\n if (dehydratedDevice) {\n await log.wrap(\"dehydrateIdentity\", log => this._session.dehydrateIdentity(dehydratedDevice, log));\n await this._session.setupDehydratedDevice(dehydratedDevice.key, log);\n } else if (!this._session.hasIdentity) {\n this._status.set(LoadStatus.SessionSetup);\n await log.wrap(\"createIdentity\", log => this._session.createIdentity(log));\n }\n\n this._sync = new Sync({hsApi: this._requestScheduler.hsApi, storage: this._storage, session: this._session, logger: this._platform.logger});\n // notify sync and session when back online\n this._reconnectSubscription = this._reconnector.connectionStatus.subscribe(state => {\n if (state === ConnectionStatus.Online) {\n this._platform.logger.runDetached(\"reconnect\", async log => {\n // needs to happen before sync and session or it would abort all requests\n this._requestScheduler.start();\n this._sync.start();\n this._sessionStartedByReconnector = true;\n const d = dehydratedDevice;\n dehydratedDevice = undefined;\n await log.wrap(\"session start\", log => this._session.start(this._reconnector.lastVersionsResponse, d, log));\n });\n }\n });\n await log.wrap(\"wait first sync\", () => this._waitForFirstSync());\n if (this._isDisposed) {\n return;\n }\n this._status.set(LoadStatus.Ready);\n\n // if the sync failed, and then the reconnector\n // restored the connection, it would have already\n // started to session, so check first\n // to prevent an extra /versions request\n if (!this._sessionStartedByReconnector) {\n const lastVersionsResponse = await hsApi.versions({timeout: 10000, log}).response();\n if (this._isDisposed) {\n return;\n }\n const d = dehydratedDevice;\n dehydratedDevice = undefined;\n // log as ref as we don't want to await it\n await log.wrap(\"session start\", log => this._session.start(lastVersionsResponse, d, log));\n }\n }\n\n async _waitForFirstSync() {\n this._sync.start();\n this._status.set(LoadStatus.FirstSync);\n // only transition into Ready once the first sync has succeeded\n this._waitForFirstSyncHandle = this._sync.status.waitFor(s => {\n if (s === SyncStatus.Stopped) {\n // keep waiting if there is a ConnectionError\n // as the reconnector above will call\n // sync.start again to retry in this case\n return this._sync.error?.name !== \"ConnectionError\";\n }\n return s === SyncStatus.Syncing;\n });\n try {\n await this._waitForFirstSyncHandle.promise;\n if (this._sync.status.get() === SyncStatus.Stopped && this._sync.error) {\n throw this._sync.error;\n }\n } catch (err) {\n // if dispose is called from stop, bail out\n if (err.name === \"AbortError\") {\n return;\n }\n throw err;\n } finally {\n this._waitForFirstSyncHandle = null;\n }\n }\n\n _inspectAccountAfterLogin(sessionInfo, log) {\n return log.wrap(\"inspectAccount\", async log => {\n this._status.set(LoadStatus.QueryAccount);\n const hsApi = new HomeServerApi({\n homeserver: sessionInfo.homeServer,\n accessToken: sessionInfo.accessToken,\n request: this._platform.request,\n });\n const olm = await this._olmPromise;\n let encryptedDehydratedDevice;\n try {\n encryptedDehydratedDevice = await getDehydratedDevice(hsApi, olm, this._platform, log);\n } catch (err) {\n if (err.name === \"HomeServerError\") {\n log.set(\"not_supported\", true);\n } else {\n throw err;\n }\n }\n if (encryptedDehydratedDevice) {\n let resolveStageFinish;\n const promiseStageFinish = new Promise(r => resolveStageFinish = r);\n this._accountSetup = new AccountSetup(encryptedDehydratedDevice, resolveStageFinish);\n this._status.set(LoadStatus.AccountSetup);\n await promiseStageFinish;\n const dehydratedDevice = this._accountSetup?._dehydratedDevice;\n this._accountSetup = null;\n return dehydratedDevice;\n }\n });\n }\n\n get accountSetup() {\n return this._accountSetup;\n }\n\n get loadStatus() {\n return this._status;\n }\n\n get loadError() {\n return this._error;\n }\n\n get loginFailure() {\n return this._loginFailure;\n }\n\n /** only set at loadStatus InitialSync, CatchupSync or Ready */\n get sync() {\n return this._sync;\n }\n\n /** only set at loadStatus InitialSync, CatchupSync or Ready */\n get session() {\n return this._session;\n }\n\n get reconnector() {\n return this._reconnector;\n }\n\n get _isDisposed() {\n return !this._reconnector;\n }\n\n startLogout(sessionId) {\n return this._platform.logger.run(\"logout\", async log => {\n this._sessionId = sessionId;\n log.set(\"id\", this._sessionId);\n const sessionInfo = await this._platform.sessionInfoStorage.get(this._sessionId);\n if (!sessionInfo) {\n throw new Error(`Could not find session for id ${this._sessionId}`);\n }\n try {\n const hsApi = new HomeServerApi({\n homeserver: sessionInfo.homeServer,\n accessToken: sessionInfo.accessToken,\n request: this._platform.request\n });\n await hsApi.logout({log}).response();\n } catch (err) {}\n await this.deleteSession(log);\n });\n }\n\n dispose() {\n if (this._reconnectSubscription) {\n this._reconnectSubscription();\n this._reconnectSubscription = null;\n }\n this._reconnector = null;\n if (this._requestScheduler) {\n this._requestScheduler.stop();\n this._requestScheduler = null;\n }\n if (this._sync) {\n this._sync.stop();\n this._sync = null;\n }\n if (this._session) {\n this._session.dispose();\n this._session = null;\n }\n if (this._waitForFirstSyncHandle) {\n this._waitForFirstSyncHandle.dispose();\n this._waitForFirstSyncHandle = null;\n }\n if (this._storage) {\n this._storage.close();\n this._storage = null;\n }\n }\n\n async deleteSession(log) {\n if (this._sessionId) {\n // need to dispose first, so the storage is closed,\n // and also first sync finishing won't call Session.start anymore,\n // which assumes that the storage works.\n this.dispose();\n // if one fails, don't block the other from trying\n // also, run in parallel\n await Promise.all([\n log.wrap(\"storageFactory\", () => this._platform.storageFactory.delete(this._sessionId)),\n log.wrap(\"sessionInfoStorage\", () => this._platform.sessionInfoStorage.delete(this._sessionId)),\n ]);\n this._sessionId = null;\n }\n }\n\n _resetStatus() {\n this._status.set(LoadStatus.NotLoading);\n this._error = null;\n this._loginFailure = null;\n }\n}\n\nclass AccountSetup {\n constructor(encryptedDehydratedDevice, finishStage) {\n this._encryptedDehydratedDevice = encryptedDehydratedDevice;\n this._dehydratedDevice = undefined;\n this._finishStage = finishStage;\n }\n\n get encryptedDehydratedDevice() {\n return this._encryptedDehydratedDevice;\n }\n\n finish(dehydratedDevice) {\n this._dehydratedDevice = dehydratedDevice;\n this._finishStage();\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// ViewModel should just be an eventemitter, not an ObservableValue\n// as in some cases it would really be more convenient to have multiple events (like telling the timeline to scroll down)\n// we do need to return a disposable from EventEmitter.on, or at least have a method here to easily track a subscription to an EventEmitter\n\nimport {EventEmitter} from \"../utils/EventEmitter\";\nimport {Disposables} from \"../utils/Disposables\";\n\nimport type {Disposable} from \"../utils/Disposables\";\nimport type {Platform} from \"../platform/web/Platform\";\nimport type {Clock} from \"../platform/web/dom/Clock\";\nimport type {ILogger} from \"../logging/types\";\nimport type {Navigation} from \"./navigation/Navigation\";\nimport type {SegmentType} from \"./navigation/index\";\nimport type {IURLRouter} from \"./navigation/URLRouter\";\n\nexport type Options = {\n platform: Platform;\n logger: ILogger;\n urlCreator: IURLRouter;\n navigation: Navigation;\n emitChange?: (params: any) => void;\n}\n\n\nexport class ViewModel = Options> extends EventEmitter<{change: never}> {\n private disposables?: Disposables;\n private _isDisposed = false;\n private _options: Readonly;\n\n constructor(options: Readonly) {\n super();\n this._options = options;\n }\n\n childOptions(explicitOptions: T): T & Options {\n return Object.assign({}, this._options, explicitOptions);\n }\n\n get options(): Readonly { return this._options; }\n\n // makes it easier to pass through dependencies of a sub-view model\n getOption(name: N): O[N] {\n return this._options[name];\n }\n\n observeNavigation(type: T, onChange: (value: N[T], type: T) => void): void {\n const segmentObservable = this.navigation.observe(type);\n const unsubscribe = segmentObservable.subscribe((value: N[T]) => {\n onChange(value, type);\n });\n this.track(unsubscribe);\n }\n\n track(disposable: D): D {\n if (!this.disposables) {\n this.disposables = new Disposables();\n }\n return this.disposables.track(disposable);\n }\n\n untrack(disposable: Disposable): undefined {\n if (this.disposables) {\n return this.disposables.untrack(disposable);\n }\n return undefined;\n }\n\n dispose(): void {\n if (this.disposables) {\n this.disposables.dispose();\n }\n this._isDisposed = true;\n }\n\n get isDisposed(): boolean {\n return this._isDisposed;\n }\n\n disposeTracked(disposable: Disposable | undefined): undefined {\n if (this.disposables) {\n return this.disposables.disposeTracked(disposable);\n }\n return undefined;\n }\n\n // TODO: this will need to support binding\n // if any of the expr is a function, assume the function is a binding, and return a binding function ourselves\n //\n // translated string should probably always be bindings, unless we're fine with a refresh when changing the language?\n // we probably are, if we're using routing with a url, we could just refresh.\n i18n(parts: TemplateStringsArray, ...expr: any[]): string {\n // just concat for now\n let result = \"\";\n for (let i = 0; i < parts.length; ++i) {\n result = result + parts[i];\n if (i < expr.length) {\n result = result + expr[i];\n }\n }\n return result;\n }\n\n emitChange(changedProps: any): void {\n if (this._options.emitChange) {\n this._options.emitChange(changedProps);\n } else {\n this.emit(\"change\", changedProps);\n }\n }\n\n get platform(): Platform {\n return this._options.platform;\n }\n\n get clock(): Clock {\n return this._options.platform.clock;\n }\n\n get logger(): ILogger {\n return this.platform.logger;\n }\n\n get urlCreator(): IURLRouter {\n return this._options.urlCreator;\n }\n\n get navigation(): Navigation {\n // typescript needs a little help here\n return this._options.navigation as unknown as Navigation;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { Platform } from \"../platform/web/Platform\";\nimport { MediaRepository } from \"../matrix/net/MediaRepository\";\n\nexport function avatarInitials(name: string): string {\n let firstChar = name.charAt(0);\n if (firstChar === \"!\" || firstChar === \"@\" || firstChar === \"#\") {\n firstChar = name.charAt(1);\n }\n return firstChar.toUpperCase();\n}\n\n/**\n * calculates a numeric hash for a given string\n *\n * @param {string} str string to hash\n *\n * @return {number}\n */\nfunction hashCode(str: string): number {\n let hash = 0;\n let i: number;\n let chr: number;\n if (str.length === 0) {\n return hash;\n }\n for (i = 0; i < str.length; i++) {\n chr = str.charCodeAt(i);\n hash = ((hash << 5) - hash) + chr;\n hash |= 0;\n }\n return Math.abs(hash);\n}\n\nexport function getIdentifierColorNumber(id: string): number {\n return (hashCode(id) % 8) + 1;\n}\n\nexport function getAvatarHttpUrl(avatarUrl: string, cssSize: number, platform: Platform, mediaRepository: MediaRepository): string | null {\n if (avatarUrl) {\n const imageSize = cssSize * platform.devicePixelRatio;\n return mediaRepository.mxcUrlThumbnail(avatarUrl, imageSize, imageSize, \"crop\");\n }\n return null;\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\nimport {ViewModel} from \"../../ViewModel\";\n\nconst KIND_ORDER = [\"roomBeingCreated\", \"invite\", \"room\"];\n\nexport class BaseTileViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._isOpen = false;\n this._hidden = false;\n }\n\n get hidden() {\n return this._hidden;\n }\n\n set hidden(value) {\n if (value !== this._hidden) {\n this._hidden = value;\n this.emitChange(\"hidden\");\n }\n }\n\n close() {\n if (this._isOpen) {\n this._isOpen = false;\n this.emitChange(\"isOpen\");\n }\n }\n\n open() {\n if (!this._isOpen) {\n this._isOpen = true;\n this.emitChange(\"isOpen\");\n }\n }\n\n get isOpen() {\n return this._isOpen;\n }\n\n compare(other) {\n if (other.kind !== this.kind) {\n return KIND_ORDER.indexOf(this.kind) - KIND_ORDER.indexOf(other.kind);\n }\n return 0;\n }\n\n // Avatar view model contract\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._avatarSource.avatarColorId);\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._avatarSource.avatarUrl, size, this.platform, this._avatarSource.mediaRepository);\n }\n\n get avatarTitle() {\n return this.name;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseTileViewModel} from \"./BaseTileViewModel.js\";\n\nexport class RoomTileViewModel extends BaseTileViewModel {\n constructor(options) {\n super(options);\n const {room} = options;\n this._room = room;\n this._url = this.urlCreator.openRoomActionUrl(this._room.id);\n }\n\n get kind() {\n return \"room\";\n }\n\n get url() {\n return this._url;\n }\n\n /** very important that sorting order is stable and that comparing\n * to itself always returns 0, otherwise SortedMapList will\n * remove the wrong children, etc ... */\n compare(other) {\n const parentComparison = super.compare(other);\n if (parentComparison !== 0) {\n return parentComparison;\n }\n /*\n put unread rooms first\n then put rooms with a timestamp first, and sort by name\n then sort by name for rooms without a timestamp\n */\n const myRoom = this._room;\n const theirRoom = other._room;\n\n if (myRoom.isLowPriority !== theirRoom.isLowPriority) {\n if (myRoom.isLowPriority) {\n return 1;\n }\n return -1;\n }\n const myTimestamp = myRoom.lastMessageTimestamp;\n const theirTimestamp = theirRoom.lastMessageTimestamp;\n const myTimestampValid = Number.isSafeInteger(myTimestamp);\n const theirTimestampValid = Number.isSafeInteger(theirTimestamp);\n // if either does not have a timestamp, put the one with a timestamp first\n if (myTimestampValid !== theirTimestampValid) {\n if (!theirTimestampValid) {\n return -1;\n }\n return 1;\n }\n const timeDiff = theirTimestamp - myTimestamp;\n if (timeDiff === 0 || !theirTimestampValid || !myTimestampValid) {\n // sort alphabetically\n const nameCmp = this.name.localeCompare(other.name);\n if (nameCmp === 0) {\n return this._room.id.localeCompare(other._room.id);\n }\n return nameCmp;\n }\n return timeDiff;\n }\n\n get isUnread() {\n return this._room.isUnread;\n }\n\n get name() {\n return this._room.name || this.i18n`Empty Room`;\n }\n\n get badgeCount() {\n return this._room.notificationCount;\n }\n\n get isHighlighted() {\n return this._room.highlightCount !== 0;\n }\n\n get _avatarSource() {\n return this._room;\n }\n}\n","/*\nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function comparePrimitive(a, b) {\n if (a === b) {\n return 0;\n } else {\n return a < b ? -1 : 1;\n }\n}\n","/*\nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseTileViewModel} from \"./BaseTileViewModel.js\";\nimport {comparePrimitive} from \"./common\";\n\nexport class InviteTileViewModel extends BaseTileViewModel {\n constructor(options) {\n super(options);\n const {invite} = options;\n this._invite = invite;\n this._url = this.urlCreator.openRoomActionUrl(this._invite.id);\n }\n\n get busy() { return this._invite.accepting || this._invite.rejecting; }\n get kind() { return \"invite\"; }\n get url() { return this._url; }\n get name() { return this._invite.name; }\n get isHighlighted() { return true; }\n get isUnread() { return true; }\n get badgeCount() { return this.i18n`!`; }\n get _avatarSource() { return this._invite; }\n\n /** very important that sorting order is stable and that comparing\n * to itself always returns 0, otherwise SortedMapList will\n * remove the wrong children, etc ... */\n compare(other) {\n const parentComparison = super.compare(other);\n if (parentComparison !== 0) {\n return parentComparison;\n }\n const timeDiff = other._invite.timestamp - this._invite.timestamp;\n if (timeDiff !== 0) {\n return timeDiff;\n }\n return comparePrimitive(this._invite.id, other._invite.id);\n }\n}\n\nexport function tests() {\n return {\n \"test compare with timestamp\": assert => {\n const urlCreator = {openRoomActionUrl() { return \"\";}}\n const vm1 = new InviteTileViewModel({invite: {timestamp: 500, id: \"1\"}, urlCreator});\n const vm2 = new InviteTileViewModel({invite: {timestamp: 250, id: \"2\"}, urlCreator});\n assert(vm1.compare(vm2) < 0);\n assert(vm2.compare(vm1) > 0);\n assert.equal(vm1.compare(vm1), 0);\n },\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseTileViewModel} from \"./BaseTileViewModel.js\";\nimport {comparePrimitive} from \"./common\";\n\nexport class RoomBeingCreatedTileViewModel extends BaseTileViewModel {\n constructor(options) {\n super(options);\n const {roomBeingCreated} = options;\n this._roomBeingCreated = roomBeingCreated;\n this._url = this.urlCreator.openRoomActionUrl(this._roomBeingCreated.id);\n }\n\n get busy() { return !this._roomBeingCreated.error; }\n get kind() { return \"roomBeingCreated\"; }\n get isHighlighted() { return !this.busy; }\n get badgeCount() { return !this.busy && this.i18n`Failed`; }\n get url() { return this._url; }\n get name() { return this._roomBeingCreated.name; }\n get _avatarSource() { return this._roomBeingCreated; }\n\n /** very important that sorting order is stable and that comparing\n * to itself always returns 0, otherwise SortedMapList will\n * remove the wrong children, etc ... */\n compare(other) {\n const parentCmp = super.compare(other);\n if (parentCmp !== 0) {\n return parentCmp;\n }\n const nameCmp = comparePrimitive(this.name, other.name);\n if (nameCmp === 0) {\n return comparePrimitive(this._roomBeingCreated.id, other._roomBeingCreated.id);\n } else {\n return nameCmp;\n }\n }\n\n avatarUrl(size) {\n // allow blob url which doesn't need mxc => http resolution\n return this._roomBeingCreated.avatarBlobUrl ?? super.avatarUrl(size);\n }\n}\n\nexport function tests() {\n return {\n \"test compare with names\": assert => {\n const urlCreator = {openRoomActionUrl() { return \"\";}}\n const vm1 = new RoomBeingCreatedTileViewModel({roomBeingCreated: {name: \"A\", id: \"1\"}, urlCreator});\n const vm2 = new RoomBeingCreatedTileViewModel({roomBeingCreated: {name: \"B\", id: \"2\"}, urlCreator});\n assert(vm1.compare(vm2) < 0);\n assert(vm2.compare(vm1) > 0);\n assert.equal(vm1.compare(vm1), 0);\n },\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class RoomFilter {\n constructor(query) {\n this._parts = query.split(\" \").map(s => s.toLowerCase().trim());\n }\n\n matches(roomTileVM) {\n const name = roomTileVM.name.toLowerCase();\n return this._parts.every(p => name.includes(p));\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableMap} from \"./BaseObservableMap\";\n\nexport class ApplyMap extends BaseObservableMap {\n constructor(source, apply) {\n super();\n this._source = source;\n this._apply = apply;\n this._subscription = null;\n }\n\n hasApply() {\n return !!this._apply;\n }\n\n setApply(apply) {\n this._apply = apply;\n if (apply) {\n this.applyOnce(this._apply);\n }\n }\n\n applyOnce(apply) {\n for (const [key, value] of this._source) {\n apply(key, value);\n }\n }\n\n onAdd(key, value) {\n if (this._apply) {\n this._apply(key, value);\n }\n this.emitAdd(key, value);\n }\n\n onRemove(key, value) {\n this.emitRemove(key, value);\n }\n\n onUpdate(key, value, params) {\n if (this._apply) {\n this._apply(key, value, params);\n }\n this.emitUpdate(key, value, params);\n }\n\n onSubscribeFirst() {\n this._subscription = this._source.subscribe(this);\n if (this._apply) {\n this.applyOnce(this._apply);\n }\n super.onSubscribeFirst();\n }\n\n onUnsubscribeLast() {\n super.onUnsubscribeLast();\n this._subscription = this._subscription();\n }\n\n onReset() {\n if (this._apply) {\n this.applyOnce(this._apply);\n }\n this.emitReset();\n }\n\n [Symbol.iterator]() {\n return this._source[Symbol.iterator]();\n }\n\n get size() {\n return this._source.size;\n }\n\n get(key) {\n return this._source.get(key);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableValue, ObservableValue} from \"../../observable/ObservableValue\";\n\n\ntype AllowsChild = (parent: Segment | undefined, child: Segment) => boolean;\n\n/**\n * OptionalValue is basically stating that if SegmentType[type] = true:\n * - Allow this type to be optional\n * - Give it a default value of undefined\n * - Also allow it to be true\n * This lets us do:\n * const s: Segment = new Segment(\"create-room\");\n * instead of\n * const s: Segment = new Segment(\"create-room\", undefined);\n */\nexport type OptionalValue = T extends true? [(undefined | true)?]: [T];\n\nexport class Navigation {\n private readonly _allowsChild: AllowsChild;\n private _path: Path;\n private readonly _observables: Map> = new Map();\n private readonly _pathObservable: ObservableValue>;\n\n constructor(allowsChild: AllowsChild) {\n this._allowsChild = allowsChild;\n this._path = new Path([], allowsChild);\n this._pathObservable = new ObservableValue(this._path);\n }\n\n get pathObservable(): ObservableValue> {\n return this._pathObservable;\n }\n\n get path(): Path {\n return this._path;\n }\n\n push(type: K, ...value: OptionalValue): void {\n const newPath = this.path.with(new Segment(type, ...value));\n if (newPath) {\n this.applyPath(newPath);\n }\n }\n\n applyPath(path: Path): void {\n // Path is not exported, so you can only create a Path through Navigation,\n // so we assume it respects the allowsChild rules\n const oldPath = this._path;\n this._path = path;\n // clear values not in the new path in reverse order of path\n for (let i = oldPath.segments.length - 1; i >= 0; i -= 1) {\n const segment = oldPath.segments[i];\n if (!this._path.get(segment.type)) {\n const observable = this._observables.get(segment.type);\n observable?.emitIfChanged();\n }\n }\n // change values in order of path\n for (const segment of this._path.segments) {\n const observable = this._observables.get(segment.type);\n observable?.emitIfChanged();\n }\n // to observe the whole path having changed\n // Since paths are immutable,\n // we can just use set here which will compare the references\n this._pathObservable.set(this._path);\n }\n\n observe(type: keyof T): SegmentObservable {\n let observable = this._observables.get(type);\n if (!observable) {\n observable = new SegmentObservable(this, type);\n this._observables.set(type, observable);\n }\n return observable;\n }\n\n pathFrom(segments: Segment[]): Path {\n let parent: Segment | undefined;\n let i: number;\n for (i = 0; i < segments.length; i += 1) {\n if (!this._allowsChild(parent, segments[i])) {\n return new Path(segments.slice(0, i), this._allowsChild);\n }\n parent = segments[i];\n }\n return new Path(segments, this._allowsChild);\n }\n\n segment(type: K, ...value: OptionalValue): Segment {\n return new Segment(type, ...value);\n }\n}\n\nfunction segmentValueEqual(a?: T[keyof T], b?: T[keyof T]): boolean {\n if (a === b) {\n return true;\n }\n // allow (sparse) arrays\n if (Array.isArray(a) && Array.isArray(b)) {\n const len = Math.max(a.length, b.length);\n for (let i = 0; i < len; i += 1) {\n if (a[i] !== b[i]) {\n return false;\n }\n }\n return true;\n }\n return false;\n}\n\n\nexport class Segment {\n public value: T[K];\n\n constructor(public type: K, ...value: OptionalValue) {\n this.value = (value[0] === undefined ? true : value[0]) as unknown as T[K];\n }\n}\n\nclass Path {\n private readonly _segments: Segment[];\n private readonly _allowsChild: AllowsChild;\n\n constructor(segments: Segment[] = [], allowsChild: AllowsChild) {\n this._segments = segments;\n this._allowsChild = allowsChild;\n }\n\n clone(): Path {\n return new Path(this._segments.slice(), this._allowsChild);\n }\n\n with(segment: Segment): Path | undefined {\n let index = this._segments.length - 1;\n do {\n if (this._allowsChild(this._segments[index], segment)) {\n // pop the elements that didn't allow the new segment as a child\n const newSegments = this._segments.slice(0, index + 1);\n newSegments.push(segment);\n return new Path(newSegments, this._allowsChild);\n }\n index -= 1;\n } while(index >= -1);\n // allow -1 as well so we check if the segment is allowed as root\n return undefined;\n }\n\n until(type: keyof T): Path {\n const index = this._segments.findIndex(s => s.type === type);\n if (index !== -1) {\n return new Path(this._segments.slice(0, index + 1), this._allowsChild)\n }\n return new Path([], this._allowsChild);\n }\n\n get(type: keyof T): Segment | undefined {\n return this._segments.find(s => s.type === type);\n }\n\n replace(segment: Segment): Path | undefined {\n const index = this._segments.findIndex(s => s.type === segment.type);\n if (index !== -1) {\n const parent = this._segments[index - 1];\n if (this._allowsChild(parent, segment)) {\n const child = this._segments[index + 1];\n if (!child || this._allowsChild(segment, child)) {\n const newSegments = this._segments.slice();\n newSegments[index] = segment;\n return new Path(newSegments, this._allowsChild);\n }\n }\n }\n return undefined;\n }\n\n get segments(): Segment[] {\n return this._segments;\n }\n}\n\n/**\n * custom observable so it always returns what is in navigation.path, even if we haven't emitted the change yet.\n * This ensures that observers of a segment can also read the most recent value of other segments.\n */\nclass SegmentObservable extends BaseObservableValue {\n private readonly _navigation: Navigation;\n private _type: keyof T;\n private _lastSetValue?: T[keyof T];\n \n constructor(navigation: Navigation, type: keyof T) {\n super();\n this._navigation = navigation;\n this._type = type;\n this._lastSetValue = navigation.path.get(type)?.value;\n }\n\n get(): T[keyof T] | undefined {\n const path = this._navigation.path;\n const segment = path.get(this._type);\n const value = segment?.value;\n return value;\n }\n\n emitIfChanged(): void {\n const newValue = this.get();\n if (!segmentValueEqual(newValue, this._lastSetValue)) {\n this._lastSetValue = newValue;\n this.emit(newValue);\n }\n }\n}\n\nexport type {Path};\n\nexport function tests() {\n\n function createMockNavigation() {\n return new Navigation((parent, {type}) => {\n switch (parent?.type) {\n case undefined:\n return type === \"1\" || type === \"2\";\n case \"1\":\n return type === \"1.1\";\n case \"1.1\":\n return type === \"1.1.1\";\n case \"2\":\n return type === \"2.1\" || type === \"2.2\";\n default:\n return false;\n }\n });\n }\n\n function observeTypes(nav, types) {\n const changes: {type:string, value:any}[] = [];\n for (const type of types) {\n nav.observe(type).subscribe(value => {\n changes.push({type, value});\n });\n }\n return changes;\n }\n\n type SegmentType = {\n \"foo\": number;\n \"bar\": number;\n \"baz\": number;\n }\n\n return {\n \"applying a path emits an event on the observable\": assert => {\n const nav = createMockNavigation();\n const path = nav.pathFrom([\n new Segment(\"2\", 7),\n new Segment(\"2.2\", 8),\n ]);\n assert.equal(path.segments.length, 2);\n let changes = observeTypes(nav, [\"2\", \"2.2\"]);\n nav.applyPath(path);\n assert.equal(changes.length, 2);\n assert.equal(changes[0].type, \"2\");\n assert.equal(changes[0].value, 7);\n assert.equal(changes[1].type, \"2.2\");\n assert.equal(changes[1].value, 8);\n },\n \"path.get\": assert => {\n const path = new Path([new Segment(\"foo\", 5), new Segment(\"bar\", 6)], () => true);\n assert.equal(path.get(\"foo\")!.value, 5);\n assert.equal(path.get(\"bar\")!.value, 6);\n },\n \"path.replace success\": assert => {\n const path = new Path([new Segment(\"foo\", 5), new Segment(\"bar\", 6)], () => true);\n const newPath = path.replace(new Segment(\"foo\", 1));\n assert.equal(newPath!.get(\"foo\")!.value, 1);\n assert.equal(newPath!.get(\"bar\")!.value, 6);\n },\n \"path.replace not found\": assert => {\n const path = new Path([new Segment(\"foo\", 5), new Segment(\"bar\", 6)], () => true);\n const newPath = path.replace(new Segment(\"baz\", 1));\n assert.equal(newPath, null);\n }\n };\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {History} from \"../../platform/web/dom/History.js\";\nimport type {Navigation, Segment, Path, OptionalValue} from \"./Navigation\";\nimport type {SubscriptionHandle} from \"../../observable/BaseObservable\";\n\ntype ParseURLPath = (urlPath: string, currentNavPath: Path, defaultSessionId?: string) => Segment[];\ntype StringifyPath = (path: Path) => string;\n\nexport interface IURLRouter {\n attach(): void;\n dispose(): void;\n pushUrl(url: string): void;\n tryRestoreLastUrl(): boolean;\n urlForSegments(segments: Segment[]): string | undefined;\n urlForSegment(type: K, ...value: OptionalValue): string | undefined;\n urlUntilSegment(type: keyof T): string;\n urlForPath(path: Path): string;\n openRoomActionUrl(roomId: string): string;\n createSSOCallbackURL(): string;\n normalizeUrl(): void;\n}\n\nexport class URLRouter implements IURLRouter {\n private readonly _history: History;\n private readonly _navigation: Navigation;\n private readonly _parseUrlPath: ParseURLPath;\n private readonly _stringifyPath: StringifyPath;\n private _subscription?: SubscriptionHandle;\n private _pathSubscription?: SubscriptionHandle;\n private _isApplyingUrl: boolean = false;\n private _defaultSessionId?: string;\n\n constructor(history: History, navigation: Navigation, parseUrlPath: ParseURLPath, stringifyPath: StringifyPath) {\n this._history = history;\n this._navigation = navigation;\n this._parseUrlPath = parseUrlPath;\n this._stringifyPath = stringifyPath;\n this._defaultSessionId = this._getLastSessionId();\n }\n\n private _getLastSessionId(): string | undefined {\n const navPath = this._urlAsNavPath(this._history.getLastSessionUrl() || \"\");\n const sessionId = navPath.get(\"session\")?.value;\n if (typeof sessionId === \"string\") {\n return sessionId;\n }\n return undefined;\n }\n\n attach(): void {\n this._subscription = this._history.subscribe(url => this._applyUrl(url));\n // subscribe to path before applying initial url\n // so redirects in _applyNavPathToHistory are reflected in url bar\n this._pathSubscription = this._navigation.pathObservable.subscribe(path => this._applyNavPathToHistory(path));\n this._applyUrl(this._history.get());\n }\n\n dispose(): void {\n if (this._subscription) { this._subscription = this._subscription(); }\n if (this._pathSubscription) { this._pathSubscription = this._pathSubscription(); }\n }\n\n private _applyNavPathToHistory(path: Path): void {\n const url = this.urlForPath(path);\n if (url !== this._history.get()) {\n if (this._isApplyingUrl) {\n // redirect\n this._history.replaceUrlSilently(url);\n } else {\n this._history.pushUrlSilently(url);\n }\n }\n }\n\n private _applyNavPathToNavigation(navPath: Path): void {\n // this will cause _applyNavPathToHistory to be called,\n // so set a flag whether this request came from ourselves\n // (in which case it is a redirect if the url does not match the current one)\n this._isApplyingUrl = true;\n this._navigation.applyPath(navPath);\n this._isApplyingUrl = false;\n }\n\n private _urlAsNavPath(url: string): Path {\n const urlPath = this._history.urlAsPath(url);\n return this._navigation.pathFrom(this._parseUrlPath(urlPath, this._navigation.path, this._defaultSessionId));\n }\n\n private _applyUrl(url: string): void {\n const navPath = this._urlAsNavPath(url);\n this._applyNavPathToNavigation(navPath);\n }\n\n pushUrl(url: string): void {\n this._history.pushUrl(url);\n }\n\n tryRestoreLastUrl(): boolean {\n const lastNavPath = this._urlAsNavPath(this._history.getLastSessionUrl() || \"\");\n if (lastNavPath.segments.length !== 0) {\n this._applyNavPathToNavigation(lastNavPath);\n return true;\n }\n return false;\n }\n\n urlForSegments(segments: Segment[]): string | undefined {\n let path: Path | undefined = this._navigation.path;\n for (const segment of segments) {\n path = path.with(segment);\n if (!path) {\n return;\n }\n }\n return this.urlForPath(path);\n }\n\n urlForSegment(type: K, ...value: OptionalValue): string | undefined {\n return this.urlForSegments([this._navigation.segment(type, ...value)]);\n }\n\n urlUntilSegment(type: keyof T): string {\n return this.urlForPath(this._navigation.path.until(type));\n }\n\n urlForPath(path: Path): string {\n return this._history.pathAsUrl(this._stringifyPath(path));\n }\n\n openRoomActionUrl(roomId: string): string {\n // not a segment to navigation knowns about, so append it manually\n const urlPath = `${this._stringifyPath(this._navigation.path.until(\"session\"))}/open-room/${roomId}`;\n return this._history.pathAsUrl(urlPath);\n }\n\n createSSOCallbackURL(): string {\n return window.location.origin;\n }\n\n normalizeUrl(): void {\n // Remove any queryParameters from the URL\n // Gets rid of the loginToken after SSO\n this._history.replaceUrlSilently(`${window.location.origin}/${window.location.hash}`);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Navigation, Segment} from \"./Navigation\";\nimport {URLRouter} from \"./URLRouter\";\nimport type {Path, OptionalValue} from \"./Navigation\";\n\nexport type SegmentType = {\n \"login\": true;\n \"session\": string | boolean;\n \"sso\": string;\n \"logout\": true;\n \"room\": string;\n \"rooms\": string[];\n \"settings\": true;\n \"create-room\": true;\n \"empty-grid-tile\": number;\n \"lightbox\": string;\n \"right-panel\": true;\n \"details\": true;\n \"members\": true;\n \"member\": string;\n};\n\nexport function createNavigation(): Navigation {\n return new Navigation(allowsChild);\n}\n\nexport function createRouter({history, navigation}: {history: History, navigation: Navigation}): URLRouter {\n return new URLRouter(history, navigation, parseUrlPath, stringifyPath);\n}\n\nfunction allowsChild(parent: Segment | undefined, child: Segment): boolean {\n const {type} = child;\n switch (parent?.type) {\n case undefined:\n // allowed root segments\n return type === \"login\" || type === \"session\" || type === \"sso\" || type === \"logout\";\n case \"session\":\n return type === \"room\" || type === \"rooms\" || type === \"settings\" || type === \"create-room\";\n case \"rooms\":\n // downside of the approach: both of these will control which tile is selected\n return type === \"room\" || type === \"empty-grid-tile\";\n case \"room\":\n return type === \"lightbox\" || type === \"right-panel\";\n case \"right-panel\":\n return type === \"details\"|| type === \"members\" || type === \"member\";\n default:\n return false;\n }\n}\n\nexport function removeRoomFromPath(path: Path, roomId: string): Path | undefined {\n let newPath: Path | undefined = path;\n const rooms = newPath.get(\"rooms\");\n let roomIdGridIndex = -1;\n // first delete from rooms segment\n if (rooms) {\n roomIdGridIndex = rooms.value.indexOf(roomId);\n if (roomIdGridIndex !== -1) {\n const idsWithoutRoom = rooms.value.slice();\n idsWithoutRoom[roomIdGridIndex] = \"\";\n newPath = newPath.replace(new Segment(\"rooms\", idsWithoutRoom));\n }\n }\n const room = newPath!.get(\"room\");\n // then from room (which occurs with or without rooms)\n if (room && room.value === roomId) {\n if (roomIdGridIndex !== -1) {\n newPath = newPath!.with(new Segment(\"empty-grid-tile\", roomIdGridIndex));\n } else {\n newPath = newPath!.until(\"session\");\n }\n }\n return newPath;\n}\n\nfunction roomsSegmentWithRoom(rooms: Segment, roomId: string, path: Path): Segment {\n if(!rooms.value.includes(roomId)) {\n const emptyGridTile = path.get(\"empty-grid-tile\");\n const oldRoom = path.get(\"room\");\n let index = 0;\n if (emptyGridTile) {\n index = emptyGridTile.value;\n } else if (oldRoom) {\n index = rooms.value.indexOf(oldRoom.value);\n }\n const roomIds = rooms.value.slice();\n roomIds[index] = roomId;\n return new Segment(\"rooms\", roomIds);\n } else {\n return rooms;\n }\n}\n\nfunction pushRightPanelSegment(array: Segment[], segment: T, ...value: OptionalValue): void {\n array.push(new Segment(\"right-panel\"));\n array.push(new Segment(segment, ...value));\n}\n\nexport function addPanelIfNeeded(navigation: Navigation, path: Path): Path {\n const segments = navigation.path.segments;\n const i = segments.findIndex(segment => segment.type === \"right-panel\");\n let _path = path;\n if (i !== -1) {\n _path = path.until(\"room\");\n _path = _path.with(segments[i])!;\n _path = _path.with(segments[i + 1])!;\n }\n return _path;\n}\n\nexport function parseUrlPath(urlPath: string, currentNavPath: Path, defaultSessionId?: string): Segment[] {\n // substring(1) to take of initial /\n const parts = urlPath.substring(1).split(\"/\");\n const iterator = parts[Symbol.iterator]();\n const segments: Segment[] = [];\n let next; \n while (!(next = iterator.next()).done) {\n const type = next.value;\n if (type === \"rooms\") {\n const roomsValue = iterator.next().value;\n if (roomsValue === undefined) { break; }\n const roomIds = roomsValue.split(\",\");\n segments.push(new Segment(type, roomIds));\n const selectedIndex = parseInt(iterator.next().value || \"0\", 10);\n const roomId = roomIds[selectedIndex];\n if (roomId) {\n segments.push(new Segment(\"room\", roomId));\n } else {\n segments.push(new Segment(\"empty-grid-tile\", selectedIndex));\n }\n } else if (type === \"open-room\") {\n const roomId = iterator.next().value;\n if (!roomId) { break; }\n const rooms = currentNavPath.get(\"rooms\");\n if (rooms) {\n segments.push(roomsSegmentWithRoom(rooms, roomId, currentNavPath));\n }\n segments.push(new Segment(\"room\", roomId));\n const openRoomPartIndex = parts.findIndex(part => part === \"open-room\");\n const hasOnlyRoomIdAfterPart = openRoomPartIndex >= parts.length - 2;\n if (hasOnlyRoomIdAfterPart) {\n // Copy right-panel segments from previous path only if there are no other parts after open-room\n // fixes memberlist -> member details closing/opening grid view\n const previousSegments = currentNavPath.segments;\n const i = previousSegments.findIndex(s => s.type === \"right-panel\");\n if (i !== -1) {\n segments.push(...previousSegments.slice(i));\n }\n }\n } else if (type === \"last-session\") {\n let sessionSegment = currentNavPath.get(\"session\");\n if (typeof sessionSegment?.value !== \"string\" && defaultSessionId) {\n sessionSegment = new Segment(\"session\", defaultSessionId);\n }\n if (sessionSegment) {\n segments.push(sessionSegment);\n }\n } else if (type === \"details\" || type === \"members\") {\n pushRightPanelSegment(segments, type);\n } else if (type === \"member\") {\n const userId = iterator.next().value;\n if (!userId) { break; }\n pushRightPanelSegment(segments, type, userId);\n } else if (type.includes(\"loginToken\")) {\n // Special case for SSO-login with query parameter loginToken=\n const loginToken = type.split(\"=\").pop();\n segments.push(new Segment(\"sso\", loginToken));\n } else {\n // might be undefined, which will be turned into true by Segment \n const value = iterator.next().value;\n segments.push(new Segment(type, value));\n }\n }\n return segments;\n}\n\nexport function stringifyPath(path: Path): string {\n let urlPath = \"\";\n let prevSegment: Segment | undefined;\n for (const segment of path.segments) {\n switch (segment.type) {\n case \"rooms\":\n urlPath += `/rooms/${segment.value.join(\",\")}`;\n break;\n case \"empty-grid-tile\":\n urlPath += `/${segment.value}`;\n break;\n case \"room\":\n if (prevSegment?.type === \"rooms\") {\n const index = prevSegment.value.indexOf(segment.value);\n urlPath += `/${index}`;\n } else {\n urlPath += `/${segment.type}/${segment.value}`;\n }\n break;\n case \"right-panel\":\n case \"sso\":\n // Do not put these segments in URL\n continue;\n default:\n urlPath += `/${segment.type}`;\n if (segment.value && segment.value !== true) {\n urlPath += `/${segment.value}`;\n }\n }\n prevSegment = segment;\n }\n return urlPath;\n}\n\nexport function tests() {\n function createEmptyPath() {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([]);\n return path;\n }\n\n return {\n \"stringify grid url with focused empty tile\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"empty-grid-tile\", 3)\n ]);\n const urlPath = stringifyPath(path);\n assert.equal(urlPath, \"/session/1/rooms/a,b,c/3\");\n },\n \"stringify grid url with focused room\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\")\n ]);\n const urlPath = stringifyPath(path);\n assert.equal(urlPath, \"/session/1/rooms/a,b,c/1\");\n },\n \"stringify url with right-panel and details segment\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\"),\n new Segment(\"right-panel\"),\n new Segment(\"details\")\n ]);\n const urlPath = stringifyPath(path);\n assert.equal(urlPath, \"/session/1/rooms/a,b,c/1/details\");\n },\n \"Parse loginToken query parameter into SSO segment\": assert => {\n const path = createEmptyPath();\n const segments = parseUrlPath(\"?loginToken=a1232aSD123\", path);\n assert.equal(segments.length, 1);\n assert.equal(segments[0].type, \"sso\");\n assert.equal(segments[0].value, \"a1232aSD123\");\n },\n \"parse grid url path with focused empty tile\": assert => {\n const path = createEmptyPath();\n const segments = parseUrlPath(\"/session/1/rooms/a,b,c/3\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"b\", \"c\"]);\n assert.equal(segments[2].type, \"empty-grid-tile\");\n assert.equal(segments[2].value, 3);\n },\n \"parse grid url path with focused room\": assert => {\n const path = createEmptyPath();\n const segments = parseUrlPath(\"/session/1/rooms/a,b,c/1\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"b\", \"c\"]);\n assert.equal(segments[2].type, \"room\");\n assert.equal(segments[2].value, \"b\");\n },\n \"parse empty grid url\": assert => {\n const path = createEmptyPath();\n const segments = parseUrlPath(\"/session/1/rooms/\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"\"]);\n assert.equal(segments[2].type, \"empty-grid-tile\");\n assert.equal(segments[2].value, 0);\n },\n \"parse empty grid url with focus\": assert => {\n const path = createEmptyPath();\n const segments = parseUrlPath(\"/session/1/rooms//1\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"\"]);\n assert.equal(segments[2].type, \"empty-grid-tile\");\n assert.equal(segments[2].value, 1);\n },\n \"parse open-room action replacing the current focused room\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\")\n ]);\n const segments = parseUrlPath(\"/session/1/open-room/d\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"d\", \"c\"]);\n assert.equal(segments[2].type, \"room\");\n assert.equal(segments[2].value, \"d\");\n },\n \"parse open-room action changing focus to an existing room\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\")\n ]);\n const segments = parseUrlPath(\"/session/1/open-room/a\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"b\", \"c\"]);\n assert.equal(segments[2].type, \"room\");\n assert.equal(segments[2].value, \"a\");\n },\n \"parse open-room action changing focus to an existing room with details open\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\"),\n new Segment(\"right-panel\", true),\n new Segment(\"details\", true)\n ]);\n const segments = parseUrlPath(\"/session/1/open-room/a\", path);\n assert.equal(segments.length, 5);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"b\", \"c\"]);\n assert.equal(segments[2].type, \"room\");\n assert.equal(segments[2].value, \"a\");\n assert.equal(segments[3].type, \"right-panel\");\n assert.equal(segments[3].value, true);\n assert.equal(segments[4].type, \"details\");\n assert.equal(segments[4].value, true);\n },\n \"open-room action should only copy over previous segments if there are no parts after open-room\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\"),\n new Segment(\"right-panel\", true),\n new Segment(\"members\", true)\n ]);\n const segments = parseUrlPath(\"/session/1/open-room/a/member/foo\", path);\n assert.equal(segments.length, 5);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"b\", \"c\"]);\n assert.equal(segments[2].type, \"room\");\n assert.equal(segments[2].value, \"a\");\n assert.equal(segments[3].type, \"right-panel\");\n assert.equal(segments[3].value, true);\n assert.equal(segments[4].type, \"member\");\n assert.equal(segments[4].value, \"foo\");\n },\n \"parse open-room action setting a room in an empty tile\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"empty-grid-tile\", 4)\n ]);\n const segments = parseUrlPath(\"/session/1/open-room/d\", path);\n assert.equal(segments.length, 3);\n assert.equal(segments[0].type, \"session\");\n assert.equal(segments[0].value, \"1\");\n assert.equal(segments[1].type, \"rooms\");\n assert.deepEqual(segments[1].value, [\"a\", \"b\", \"c\", , \"d\"]); //eslint-disable-line no-sparse-arrays\n assert.equal(segments[2].type, \"room\");\n assert.equal(segments[2].value, \"d\");\n },\n \"parse session url path without id\": assert => {\n const path = createEmptyPath();\n const segments = parseUrlPath(\"/session\", path);\n assert.equal(segments.length, 1);\n assert.equal(segments[0].type, \"session\");\n assert.strictEqual(segments[0].value, true);\n },\n \"remove active room from grid path turns it into empty tile\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\")\n ]);\n const newPath = removeRoomFromPath(path, \"b\");\n assert.equal(newPath?.segments.length, 3);\n assert.equal(newPath?.segments[0].type, \"session\");\n assert.equal(newPath?.segments[0].value, 1);\n assert.equal(newPath?.segments[1].type, \"rooms\");\n assert.deepEqual(newPath?.segments[1].value, [\"a\", \"\", \"c\"]);\n assert.equal(newPath?.segments[2].type, \"empty-grid-tile\");\n assert.equal(newPath?.segments[2].value, 1);\n },\n \"remove inactive room from grid path\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"c\"]),\n new Segment(\"room\", \"b\")\n ]);\n const newPath = removeRoomFromPath(path, \"a\");\n assert.equal(newPath?.segments.length, 3);\n assert.equal(newPath?.segments[0].type, \"session\");\n assert.equal(newPath?.segments[0].value, 1);\n assert.equal(newPath?.segments[1].type, \"rooms\");\n assert.deepEqual(newPath?.segments[1].value, [\"\", \"b\", \"c\"]);\n assert.equal(newPath?.segments[2].type, \"room\");\n assert.equal(newPath?.segments[2].value, \"b\");\n },\n \"remove inactive room from grid path with empty tile\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"rooms\", [\"a\", \"b\", \"\"]),\n new Segment(\"empty-grid-tile\", 3)\n ]);\n const newPath = removeRoomFromPath(path, \"b\");\n assert.equal(newPath?.segments.length, 3);\n assert.equal(newPath?.segments[0].type, \"session\");\n assert.equal(newPath?.segments[0].value, 1);\n assert.equal(newPath?.segments[1].type, \"rooms\");\n assert.deepEqual(newPath?.segments[1].value, [\"a\", \"\", \"\"]);\n assert.equal(newPath?.segments[2].type, \"empty-grid-tile\");\n assert.equal(newPath?.segments[2].value, 3);\n },\n \"remove active room\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"room\", \"b\")\n ]);\n const newPath = removeRoomFromPath(path, \"b\");\n assert.equal(newPath?.segments.length, 1);\n assert.equal(newPath?.segments[0].type, \"session\");\n assert.equal(newPath?.segments[0].value, 1);\n },\n \"remove inactive room doesn't do anything\": assert => {\n const nav: Navigation = new Navigation(allowsChild);\n const path = nav.pathFrom([\n new Segment(\"session\", 1),\n new Segment(\"room\", \"b\")\n ]);\n const newPath = removeRoomFromPath(path, \"a\");\n assert.equal(newPath?.segments.length, 2);\n assert.equal(newPath?.segments[0].type, \"session\");\n assert.equal(newPath?.segments[0].value, 1);\n assert.equal(newPath?.segments[1].type, \"room\");\n assert.equal(newPath?.segments[1].value, \"b\");\n },\n \n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {RoomTileViewModel} from \"./RoomTileViewModel.js\";\nimport {InviteTileViewModel} from \"./InviteTileViewModel.js\";\nimport {RoomBeingCreatedTileViewModel} from \"./RoomBeingCreatedTileViewModel.js\";\nimport {RoomFilter} from \"./RoomFilter.js\";\nimport {ApplyMap} from \"../../../observable/map/ApplyMap.js\";\nimport {addPanelIfNeeded} from \"../../navigation/index\";\n\nexport class LeftPanelViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {session} = options;\n this._tileViewModelsMap = this._mapTileViewModels(session.roomsBeingCreated, session.invites, session.rooms);\n this._tileViewModelsFilterMap = new ApplyMap(this._tileViewModelsMap);\n this._tileViewModels = this._tileViewModelsFilterMap.sortValues((a, b) => a.compare(b));\n this._currentTileVM = null;\n this._setupNavigation();\n this._closeUrl = this.urlCreator.urlForSegment(\"session\");\n this._settingsUrl = this.urlCreator.urlForSegment(\"settings\");\n this._createRoomUrl = this.urlCreator.urlForSegment(\"create-room\");\n }\n\n _mapTileViewModels(roomsBeingCreated, invites, rooms) {\n // join is not commutative, invites will take precedence over rooms\n const allTiles = invites.join(roomsBeingCreated, rooms).mapValues((item, emitChange) => {\n let vm;\n if (item.isBeingCreated) {\n vm = new RoomBeingCreatedTileViewModel(this.childOptions({roomBeingCreated: item, emitChange}));\n } else if (item.isInvite) {\n vm = new InviteTileViewModel(this.childOptions({invite: item, emitChange}));\n } else {\n vm = new RoomTileViewModel(this.childOptions({room: item, emitChange}));\n }\n const isOpen = this.navigation.path.get(\"room\")?.value === item.id;\n if (isOpen) {\n vm.open();\n this._updateCurrentVM(vm);\n }\n return vm;\n });\n return allTiles;\n }\n\n _updateCurrentVM(vm) {\n // need to also update the current vm here as\n // we can't call `_open` from the ctor as the map\n // is only populated when the view subscribes.\n this._currentTileVM?.close();\n this._currentTileVM = vm;\n }\n\n get closeUrl() {\n return this._closeUrl;\n }\n\n get settingsUrl() {\n return this._settingsUrl;\n }\n\n get createRoomUrl() { return this._createRoomUrl; }\n\n _setupNavigation() {\n const roomObservable = this.navigation.observe(\"room\");\n this.track(roomObservable.subscribe(roomId => this._open(roomId)));\n\n const gridObservable = this.navigation.observe(\"rooms\");\n this.gridEnabled = !!gridObservable.get();\n this.track(gridObservable.subscribe(roomIds => {\n const changed = this.gridEnabled ^ !!roomIds;\n this.gridEnabled = !!roomIds;\n if (changed) {\n this.emitChange(\"gridEnabled\");\n }\n }));\n }\n\n _open(roomId) {\n this._currentTileVM?.close();\n this._currentTileVM = null;\n if (roomId) {\n this._currentTileVM = this._tileViewModelsMap.get(roomId);\n this._currentTileVM?.open();\n }\n }\n\n toggleGrid() {\n const room = this.navigation.path.get(\"room\");\n let path = this.navigation.path.until(\"session\");\n if (this.gridEnabled) {\n if (room) {\n path = path.with(room);\n path = addPanelIfNeeded(this.navigation, path);\n }\n } else {\n if (room) {\n path = path.with(this.navigation.segment(\"rooms\", [room.value]));\n path = path.with(room);\n path = addPanelIfNeeded(this.navigation, path);\n } else {\n path = path.with(this.navigation.segment(\"rooms\", []));\n path = path.with(this.navigation.segment(\"empty-grid-tile\", 0));\n }\n }\n this.navigation.applyPath(path);\n }\n\n get tileViewModels() {\n return this._tileViewModels;\n }\n\n clearFilter() {\n this._tileViewModelsFilterMap.setApply(null);\n this._tileViewModelsFilterMap.applyOnce((roomId, vm) => vm.hidden = false);\n }\n\n setFilter(query) {\n query = query.trim();\n if (query.length === 0) {\n this.clearFilter();\n return false;\n } else {\n const startFiltering = !this._tileViewModelsFilterMap.hasApply();\n const filter = new RoomFilter(query);\n this._tileViewModelsFilterMap.setApply((roomId, vm) => {\n vm.hidden = !filter.matches(vm);\n });\n return startFiltering;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class UpdateAction {\n constructor(remove, update, replace, updateParams) {\n this._remove = remove;\n this._update = update;\n this._replace = replace;\n this._updateParams = updateParams;\n }\n\n get shouldReplace() {\n return this._replace;\n }\n\n get shouldRemove() {\n return this._remove;\n }\n\n get shouldUpdate() {\n return this._update;\n }\n\n get updateParams() {\n return this._updateParams;\n }\n\n static Remove() {\n return new UpdateAction(true, false, false, null);\n }\n\n static Update(newParams) {\n return new UpdateAction(false, true, false, newParams);\n }\n\n static Nothing() {\n return new UpdateAction(false, false, false, null);\n }\n\n static Replace(params) {\n return new UpdateAction(false, false, true, params);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableList} from \"../../../../observable/list/BaseObservableList\";\nimport {sortedIndex} from \"../../../../utils/sortedIndex\";\n\n// maps 1..n entries to 0..1 tile. Entries are what is stored in the timeline, either an event or fragmentboundary\n// for now, tileClassForEntry should be stable in whether it returns a tile or not.\n// e.g. the decision to create a tile or not should be based on properties\n// not updated later on (e.g. event type)\n// also see big comment in onUpdate\nexport class TilesCollection extends BaseObservableList {\n constructor(entries, tileOptions) {\n super();\n this._entries = entries;\n this._tiles = null;\n this._entrySubscription = null;\n this._tileOptions = tileOptions;\n this._emitSpontanousUpdate = this._emitSpontanousUpdate.bind(this);\n }\n\n _createTile(entry) {\n const Tile = this._tileOptions.tileClassForEntry(entry);\n if (Tile) {\n return new Tile(entry, this._tileOptions);\n }\n }\n\n _emitSpontanousUpdate(tile, params) {\n const entry = tile.lowerEntry;\n const tileIdx = this._findTileIdx(entry);\n this.emitUpdate(tileIdx, tile, params);\n }\n\n onSubscribeFirst() {\n this._entrySubscription = this._entries.subscribe(this);\n this._populateTiles();\n }\n\n _populateTiles() {\n this._tiles = [];\n let currentTile = null;\n for (let entry of this._entries) {\n if (!currentTile || !currentTile.tryIncludeEntry(entry)) {\n currentTile = this._createTile(entry);\n if (currentTile) {\n this._tiles.push(currentTile);\n }\n }\n }\n let prevTile = null;\n for (let tile of this._tiles) {\n if (prevTile) {\n prevTile.updateNextSibling(tile);\n }\n tile.updatePreviousSibling(prevTile);\n prevTile = tile;\n }\n if (prevTile) {\n prevTile.updateNextSibling(null);\n }\n // now everything is wired up,\n // allow tiles to emit updates\n for (const tile of this._tiles) {\n tile.setUpdateEmit(this._emitSpontanousUpdate);\n }\n }\n\n _findTileIdx(entry) {\n return sortedIndex(this._tiles, entry, (entry, tile) => {\n // negate result because we're switching the order of the params\n return -tile.compareEntry(entry);\n });\n }\n\n _findTileAtIdx(entry, idx) {\n const tile = this._getTileAtIdx(idx);\n if (tile && tile.compareEntry(entry) === 0) {\n return tile;\n }\n }\n\n _getTileAtIdx(tileIdx) {\n if (tileIdx >= 0 && tileIdx < this._tiles.length) {\n return this._tiles[tileIdx];\n }\n return null;\n }\n\n onUnsubscribeLast() {\n this._entrySubscription = this._entrySubscription();\n for(let i = 0; i < this._tiles.length; i+= 1) {\n this._tiles[i].dispose();\n }\n this._tiles = null;\n }\n\n onReset() {\n // if TileViewModel were disposable, dispose here, or is that for views to do? views I suppose ...\n this._buildInitialTiles();\n this.emitReset();\n }\n\n onAdd(index, entry) {\n const tileIdx = this._findTileIdx(entry);\n const prevTile = this._getTileAtIdx(tileIdx - 1);\n if (prevTile && prevTile.tryIncludeEntry(entry)) {\n this.emitUpdate(tileIdx - 1, prevTile);\n return;\n }\n // not + 1 because this entry hasn't been added yet\n const nextTile = this._getTileAtIdx(tileIdx);\n if (nextTile && nextTile.tryIncludeEntry(entry)) {\n this.emitUpdate(tileIdx, nextTile);\n return;\n }\n\n const newTile = this._createTile(entry);\n if (newTile) {\n if (prevTile) {\n prevTile.updateNextSibling(newTile);\n // this emits an update while the add hasn't been emitted yet\n newTile.updatePreviousSibling(prevTile);\n }\n if (nextTile) {\n newTile.updateNextSibling(nextTile);\n nextTile.updatePreviousSibling(newTile);\n }\n this._tiles.splice(tileIdx, 0, newTile);\n this.emitAdd(tileIdx, newTile);\n // add event is emitted, now the tile\n // can emit updates\n newTile.setUpdateEmit(this._emitSpontanousUpdate);\n }\n // find position by sort key\n // ask siblings to be included? both? yes, twice: a (insert c here) b, ask a(c), if yes ask b(a), else ask b(c)? if yes then b(a)?\n }\n\n onUpdate(index, entry, params) {\n // if an update is emitted while calling source.subscribe() from onSubscribeFirst, ignore it\n if (!this._tiles) {\n return;\n }\n const tileIdx = this._findTileIdx(entry);\n const tile = this._findTileAtIdx(entry, tileIdx);\n if (tile) {\n const action = tile.updateEntry(entry, params);\n if (action.shouldReplace) {\n const newTile = this._createTile(entry);\n if (newTile) {\n this._replaceTile(tileIdx, tile, newTile, action.updateParams);\n newTile.setUpdateEmit(this._emitSpontanousUpdate);\n } else {\n this._removeTile(tileIdx, tile);\n }\n }\n if (action.shouldRemove) {\n this._removeTile(tileIdx, tile);\n }\n if (action.shouldUpdate) {\n this.emitUpdate(tileIdx, tile, action.updateParams);\n }\n }\n // technically we should handle adding a tile here as well\n // in case before we didn't have a tile for it but now we do\n // but in reality we don't have this use case as the type and msgtype\n // doesn't change. Decryption maybe is the exception?\n\n\n // outcomes here can be\n // tiles should be removed (got redacted and we don't want it in the timeline)\n // tile should be added where there was none before ... ?\n // entry should get it's own tile now\n // merge with neighbours? ... hard to imagine use case for this ...\n }\n\n _replaceTile(tileIdx, existingTile, newTile, updateParams) {\n existingTile.dispose();\n const prevTile = this._getTileAtIdx(tileIdx - 1);\n const nextTile = this._getTileAtIdx(tileIdx + 1);\n this._tiles[tileIdx] = newTile;\n prevTile?.updateNextSibling(newTile);\n newTile.updatePreviousSibling(prevTile);\n newTile.updateNextSibling(nextTile);\n nextTile?.updatePreviousSibling(newTile);\n this.emitUpdate(tileIdx, newTile, updateParams);\n }\n\n _removeTile(tileIdx, tile) {\n const prevTile = this._getTileAtIdx(tileIdx - 1);\n const nextTile = this._getTileAtIdx(tileIdx + 1);\n // applying and emitting the remove should happen\n // atomically, as updateNext/PreviousSibling might\n // emit an update with the wrong index otherwise \n this._tiles.splice(tileIdx, 1);\n tile.dispose();\n this.emitRemove(tileIdx, tile);\n prevTile?.updateNextSibling(nextTile);\n nextTile?.updatePreviousSibling(prevTile);\n }\n\n // would also be called when unloading a part of the timeline\n onRemove(index, entry) {\n const tileIdx = this._findTileIdx(entry);\n const tile = this._findTileAtIdx(entry, tileIdx);\n if (tile) {\n const removeTile = tile.removeEntry(entry);\n if (removeTile) {\n this._removeTile(tileIdx, tile);\n } else {\n this.emitUpdate(tileIdx, tile);\n }\n }\n }\n\n onMove(/*fromIdx, toIdx, value*/) {\n // this ... cannot happen in the timeline?\n // perhaps we can use this event to support a local echo (in a different fragment)\n // to be moved to the key of the remote echo, so we don't loose state ... ?\n }\n\n [Symbol.iterator]() {\n return this._tiles.values();\n }\n\n get length() {\n return this._tiles.length;\n }\n\n getFirst() {\n return this._tiles[0];\n }\n\n getTileIndex(searchTile) {\n const idx = sortedIndex(this._tiles, searchTile, (searchTile, tile) => {\n return searchTile.compare(tile);\n });\n const foundTile = this._tiles[idx];\n if (foundTile?.compare(searchTile) === 0) {\n return idx;\n }\n return -1;\n }\n\n sliceIterator(start, end) {\n return this._tiles.slice(start, end)[Symbol.iterator]();\n }\n}\n\nimport {ObservableArray} from \"../../../../observable/list/ObservableArray\";\nimport {UpdateAction} from \"./UpdateAction.js\";\n\nexport function tests() {\n class TestTile {\n constructor(entry) {\n this.entry = entry;\n this.update = null;\n }\n setUpdateEmit(update) {\n this.update = update;\n }\n tryIncludeEntry() {\n return false;\n }\n compareEntry(b) {\n return this.entry.n - b.n;\n }\n removeEntry() {\n return true;\n }\n get upperEntry() {\n return this.entry;\n }\n\n get lowerEntry() {\n return this.entry;\n }\n updateNextSibling() {}\n updatePreviousSibling() {}\n updateEntry() {\n return UpdateAction.Nothing;\n }\n\n dispose() {}\n }\n\n return {\n \"don't emit update before add\": assert => {\n class UpdateOnSiblingTile extends TestTile {\n updateNextSibling() {\n // this happens with isContinuation\n this.update && this.update(this, \"next\");\n }\n updatePreviousSibling() {\n // this happens with isContinuation\n this.update && this.update(this, \"previous\");\n }\n }\n const entries = new ObservableArray([{n: 5}, {n: 10}]);\n const tileOptions = {\n tileClassForEntry: () => UpdateOnSiblingTile,\n };\n const tiles = new TilesCollection(entries, tileOptions);\n let receivedAdd = false;\n tiles.subscribe({\n onAdd(idx, tile) {\n assert(tile.entry.n, 7);\n receivedAdd = true;\n },\n onUpdate(idx, tile) {\n if (tile.entry.n === 7) {\n assert(!receivedAdd, \"receiving update before add\");\n }\n }\n });\n entries.insert(1, {n: 7});\n assert(receivedAdd);\n },\n \"emit update with correct index in updatePreviousSibling during remove\": assert => {\n class UpdateOnSiblingTile extends TestTile {\n updatePreviousSibling() {\n this.update?.(this, \"previous\");\n }\n }\n const entries = new ObservableArray([{n: 5}, {n: 10}, {n: 15}]);\n const tileOptions = {\n tileClassForEntry: () => UpdateOnSiblingTile,\n };\n const tiles = new TilesCollection(entries, tileOptions);\n const events = [];\n tiles.subscribe({\n onUpdate(idx, tile) {\n assert.equal(idx, 1);\n assert.equal(tile.entry.n, 15);\n events.push(\"update\");\n },\n onRemove(idx, tile) {\n assert.equal(idx, 1);\n assert.equal(tile.entry.n, 10);\n events.push(\"remove\");\n }\n });\n entries.remove(1);\n assert.deepEqual(events, [\"remove\", \"update\"]);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nneed better naming, but\nentry = event or gap from matrix layer\ntile = item on visual timeline like event, date separator?, group of joined events\n\n\nshall we put date separators as marker in EventViewItem or separate item? binary search will be complicated ...\n\n\npagination ...\n\non the timeline viewmodel (containing the TilesCollection?) we'll have a method to (un)load a tail or head of\nthe timeline (counted in tiles), which results to a range in sortKeys we want on the screen. We pass that range\nto the room timeline, which unload entries from memory.\nwhen loading, it just reads events from a sortkey backwards or forwards...\n*/\nimport {TilesCollection} from \"./TilesCollection.js\";\nimport {ViewModel} from \"../../../ViewModel\";\n\nexport class TimelineViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {timeline, tileOptions} = options;\n this._timeline = this.track(timeline);\n this._tiles = new TilesCollection(timeline.entries, tileOptions);\n this._startTile = null;\n this._endTile = null;\n this._topLoadingPromise = null;\n this._requestedStartTile = null;\n this._requestedEndTile = null;\n this._requestScheduled = false;\n this._showJumpDown = false;\n }\n\n /** if this.tiles is empty, call this with undefined for both startTile and endTile */\n setVisibleTileRange(startTile, endTile) {\n // don't clear these once done as they are used to check\n // for more tiles once loadAtTop finishes\n this._requestedStartTile = startTile;\n this._requestedEndTile = endTile;\n if (!this._requestScheduled) {\n Promise.resolve().then(() => {\n this._setVisibleTileRange(this._requestedStartTile, this._requestedEndTile);\n this._requestScheduled = false;\n });\n this._requestScheduled = true;\n }\n }\n\n _setVisibleTileRange(startTile, endTile) {\n let loadTop;\n if (startTile && endTile) {\n // old tiles could have been removed from tilescollection once we support unloading\n this._startTile = startTile;\n this._endTile = endTile;\n const startIndex = this._tiles.getTileIndex(this._startTile);\n const endIndex = this._tiles.getTileIndex(this._endTile);\n for (const tile of this._tiles.sliceIterator(startIndex, endIndex + 1)) {\n tile.notifyVisible();\n }\n loadTop = startIndex < 10;\n this._setShowJumpDown(endIndex < (this._tiles.length - 1));\n } else {\n // tiles collection is empty, load more at top\n loadTop = true;\n this._setShowJumpDown(false);\n }\n\n if (loadTop && !this._topLoadingPromise) {\n this._topLoadingPromise = this._timeline.loadAtTop(10).then(hasReachedEnd => {\n this._topLoadingPromise = null;\n if (!hasReachedEnd) {\n // check if more items need to be loaded by recursing\n // use the requested start / end tile,\n // so we don't end up overwriting a newly requested visible range here\n this.setVisibleTileRange(this._requestedStartTile, this._requestedEndTile);\n }\n });\n }\n }\n\n get tiles() {\n return this._tiles;\n }\n\n _setShowJumpDown(show) {\n if (this._showJumpDown !== show) {\n this._showJumpDown = show;\n this.emitChange(\"showJumpDown\");\n }\n }\n\n get showJumpDown() {\n return this._showJumpDown;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\n\nexport class ComposerViewModel extends ViewModel {\n constructor(roomVM) {\n super(roomVM.options);\n this._roomVM = roomVM;\n this._isEmpty = true;\n this._replyVM = null;\n }\n\n setReplyingTo(entry) {\n const changed = new Boolean(entry) !== new Boolean(this._replyVM) || !this._replyVM?.id.equals(entry.asEventKey());\n if (changed) {\n this._replyVM = this.disposeTracked(this._replyVM);\n if (entry) {\n this._replyVM = this.track(this._roomVM._createTile(entry));\n this._replyVM.notifyVisible();\n }\n this.emitChange(\"replyViewModel\");\n this.emit(\"focus\");\n }\n }\n\n clearReplyingTo() {\n this.setReplyingTo(null);\n }\n\n get replyViewModel() {\n return this._replyVM;\n }\n\n get isEncrypted() {\n return this._roomVM.isEncrypted;\n }\n\n async sendMessage(message) {\n const success = await this._roomVM._sendMessage(message, this._replyVM);\n if (success) {\n this._isEmpty = true;\n this.emitChange(\"canSend\");\n this.clearReplyingTo();\n }\n return success;\n }\n\n sendPicture() {\n this._roomVM._pickAndSendPicture();\n }\n\n sendFile() {\n this._roomVM._pickAndSendFile();\n }\n\n sendVideo() {\n this._roomVM._pickAndSendVideo();\n }\n\n get canSend() {\n return !this._isEmpty;\n }\n\n async setInput(text) {\n const wasEmpty = this._isEmpty;\n this._isEmpty = text.length === 0;\n if (wasEmpty && !this._isEmpty) {\n this._roomVM._room.ensureMessageKeyIsShared();\n }\n if (wasEmpty !== this._isEmpty) {\n this.emitChange(\"canSend\");\n }\n }\n\n get kind() {\n return \"composer\";\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function imageToInfo(image) {\n return {\n w: image.width,\n h: image.height,\n mimetype: image.blob.mimeType,\n size: image.blob.size\n };\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {UpdateAction} from \"../UpdateAction.js\";\nimport {ViewModel} from \"../../../../ViewModel\";\nimport {SendStatus} from \"../../../../../matrix/room/sending/PendingEvent.js\";\n\nexport class SimpleTile extends ViewModel {\n constructor(entry, options) {\n super(options);\n this._entry = entry;\n this._emitUpdate = undefined;\n }\n // view model props for all subclasses\n // hmmm, could also do instanceof ... ?\n get shape() {\n return null;\n // \"gap\" | \"message\" | \"image\" | ... ?\n }\n\n // don't show display name / avatar\n // probably only for BaseMessageTiles of some sort?\n get isContinuation() {\n return false;\n }\n\n get hasDateSeparator() {\n return false;\n }\n\n get id() {\n return this._entry.asEventKey();\n }\n\n get eventId() {\n return this._entry.id;\n }\n\n get isPending() {\n return this._entry.isPending;\n }\n\n get isUnsent() {\n return this._entry.isPending && this._entry.pendingEvent.status !== SendStatus.Sent;\n }\n\n get canAbortSending() {\n return this._entry.isPending &&\n !this._entry.pendingEvent.hasStartedSending;\n }\n\n abortSending() {\n this._entry.pendingEvent?.abort();\n }\n\n // TilesCollection contract below\n setUpdateEmit(emitUpdate) {\n this._emitUpdate = emitUpdate;\n }\n\n /** overrides the emitChange in ViewModel to also emit the update over the tiles collection */\n emitChange(changedProps) {\n if (this._emitUpdate) {\n // it can happen that after some network call\n // we switched away from the room and the response\n // comes in, triggering an emitChange in a tile that\n // has been disposed already (and hence the change\n // callback has been cleared by dispose) We should just ignore this.\n this._emitUpdate(this, changedProps);\n }\n super.emitChange(changedProps);\n }\n\n get upperEntry() {\n return this._entry;\n }\n\n get lowerEntry() {\n return this._entry;\n }\n\n compare(tile) {\n return this.upperEntry.compare(tile.upperEntry);\n }\n\n compareEntry(entry) {\n return this._entry.compare(entry);\n }\n\n // update received for already included (falls within sort keys) entry\n updateEntry(entry, param) {\n const renderedAsRedacted = this.shape === \"redacted\";\n if (!entry.isGap && entry.isRedacted !== renderedAsRedacted) {\n // recreate the tile if the entry becomes redacted\n return UpdateAction.Replace(\"shape\");\n } else {\n this._entry = entry;\n return UpdateAction.Update(param);\n }\n }\n\n // return whether the tile should be removed\n // as SimpleTile only has one entry, the tile should be removed\n removeEntry(/*entry*/) {\n return true;\n }\n\n // SimpleTile can only contain 1 entry\n tryIncludeEntry() {\n return false;\n }\n // let item know it has a new sibling\n updatePreviousSibling(/*prev*/) {\n\n }\n\n // let item know it has a new sibling\n updateNextSibling(/*next*/) {\n \n }\n\n notifyVisible() {}\n\n dispose() {\n this.setUpdateEmit(null);\n super.dispose();\n }\n // TilesCollection contract above\n\n get _room() {\n return this._roomVM.room;\n }\n\n get _roomVM() {\n return this._options.roomVM;\n }\n\n get _timeline() {\n return this._options.timeline;\n }\n\n get _powerLevels() {\n return this._timeline.powerLevels;\n }\n\n get _ownMember() {\n return this._options.timeline.me;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SimpleTile} from \"./SimpleTile.js\";\nimport {UpdateAction} from \"../UpdateAction.js\";\n\nexport class GapTile extends SimpleTile {\n constructor(entry, options) {\n super(entry, options);\n this._loading = false;\n this._error = null;\n this._isAtTop = true;\n this._siblingChanged = false;\n }\n\n async fill() {\n if (!this._loading && !this._entry.edgeReached) {\n this._loading = true;\n this.emitChange(\"isLoading\");\n try {\n await this._room.fillGap(this._entry, 10);\n } catch (err) {\n console.error(`room.fillGap(): ${err.message}:\\n${err.stack}`);\n this._error = err;\n this.emitChange(\"error\");\n // rethrow so caller of this method\n // knows not to keep calling this for now\n throw err;\n } finally {\n this._loading = false;\n this.emitChange(\"isLoading\");\n }\n return true;\n }\n return false;\n }\n\n async notifyVisible() {\n // we do (up to 10) backfills while no new tiles have been added to the timeline\n // because notifyVisible won't be called again until something gets added to the timeline\n let depth = 0;\n let canFillMore;\n this._siblingChanged = false;\n do {\n canFillMore = await this.fill();\n depth = depth + 1;\n } while (depth < 10 && !this._siblingChanged && canFillMore && !this.isDisposed);\n }\n\n get isAtTop() {\n return this._isAtTop;\n }\n\n updatePreviousSibling(prev) {\n super.updatePreviousSibling(prev);\n const isAtTop = !prev;\n if (this._isAtTop !== isAtTop) {\n this._isAtTop = isAtTop;\n this.emitChange(\"isAtTop\");\n }\n this._siblingChanged = true;\n }\n\n updateNextSibling() {\n // if the sibling of the gap changed while calling room.fill(),\n // we intepret this as at least one new tile has been added to\n // the timeline. See notifyVisible why this is important.\n this._siblingChanged = true;\n }\n\n updateEntry(entry, params) {\n super.updateEntry(entry, params);\n if (!entry.isGap) {\n return UpdateAction.Remove();\n } else {\n return UpdateAction.Nothing();\n }\n }\n\n get shape() {\n return \"gap\";\n }\n\n get isLoading() {\n return this._loading;\n }\n\n get error() {\n if (this._error) {\n const dir = this._entry.prev_batch ? \"previous\" : \"next\";\n return `Could not load ${dir} messages: ${this._error.message}`;\n }\n return null;\n }\n}\n\nimport {FragmentBoundaryEntry} from \"../../../../../matrix/room/timeline/entries/FragmentBoundaryEntry.js\";\nexport function tests() {\n return {\n \"uses updated token to fill\": async assert => {\n let currentToken = 5;\n const fragment = {\n id: 0,\n previousToken: currentToken,\n roomId: \"!abc\"\n };\n const room = {\n async fillGap(entry) {\n assert.equal(entry.token, currentToken);\n currentToken += 1;\n const newEntry = entry.withUpdatedFragment(Object.assign({}, fragment, {previousToken: currentToken}));\n tile.updateEntry(newEntry);\n }\n };\n const tile = new GapTile(new FragmentBoundaryEntry(fragment, true), {roomVM: {room}});\n await tile.fill();\n await tile.fill();\n await tile.fill();\n assert.equal(currentToken, 8);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {ObservableMap} from \"../../../../observable/map/ObservableMap\";\n\nexport class ReactionsViewModel {\n constructor(parentTile) {\n this._parentTile = parentTile;\n this._map = new ObservableMap();\n this._reactions = this._map.sortValues((a, b) => a._compare(b));\n }\n\n /** @package */\n update(annotations, pendingAnnotations) {\n if (annotations) {\n for (const key in annotations) {\n if (annotations.hasOwnProperty(key)) {\n const annotation = annotations[key];\n const reaction = this._map.get(key);\n if (reaction) {\n if (reaction._tryUpdate(annotation)) {\n this._map.update(key);\n }\n } else {\n this._map.add(key, new ReactionViewModel(key, annotation, null, this._parentTile));\n }\n }\n }\n }\n if (pendingAnnotations) {\n for (const [key, annotation] of pendingAnnotations.entries()) {\n const reaction = this._map.get(key);\n if (reaction) {\n reaction._tryUpdatePending(annotation);\n this._map.update(key);\n } else {\n this._map.add(key, new ReactionViewModel(key, null, annotation, this._parentTile));\n }\n }\n }\n for (const existingKey of this._map.keys()) {\n const hasPending = pendingAnnotations?.has(existingKey);\n const hasRemote = annotations?.hasOwnProperty(existingKey);\n if (!hasRemote && !hasPending) {\n this._map.remove(existingKey);\n } else if (!hasRemote) {\n if (this._map.get(existingKey)._tryUpdate(null)) {\n this._map.update(existingKey);\n }\n } else if (!hasPending) {\n if (this._map.get(existingKey)._tryUpdatePending(null)) {\n this._map.update(existingKey);\n }\n }\n }\n }\n\n get reactions() {\n return this._reactions;\n }\n\n getReaction(key) {\n return this._map.get(key);\n }\n}\n\nclass ReactionViewModel {\n constructor(key, annotation, pending, parentTile) {\n this._key = key;\n this._annotation = annotation;\n this._pending = pending;\n this._parentTile = parentTile;\n this._isToggling = false;\n }\n\n _tryUpdate(annotation) {\n const oneSetAndOtherNot = !!this._annotation !== !!annotation;\n const bothSet = this._annotation && annotation;\n const areDifferent = bothSet && (\n annotation.me !== this._annotation.me ||\n annotation.count !== this._annotation.count ||\n annotation.firstTimestamp !== this._annotation.firstTimestamp\n );\n if (oneSetAndOtherNot || areDifferent) {\n this._annotation = annotation;\n return true;\n }\n return false;\n }\n\n _tryUpdatePending(pending) {\n if (!pending && !this._pending) {\n return false;\n }\n this._pending = pending;\n return true;\n }\n\n get key() {\n return this._key;\n }\n\n get count() {\n return (this._pending?.count || 0) + (this._annotation?.count || 0);\n }\n\n get isPending() {\n return this._pending !== null;\n }\n\n /** @returns {boolean} true if the user has a (pending) reaction\n * already for this key, or they have a pending redaction for\n * the reaction, false if there is nothing pending and\n * the user has not reacted yet. */\n get isActive() {\n return this._annotation?.me || this.isPending;\n }\n\n get firstTimestamp() {\n let ts = Number.MAX_SAFE_INTEGER;\n if (this._annotation) {\n ts = Math.min(ts, this._annotation.firstTimestamp);\n }\n if (this._pending) {\n ts = Math.min(ts, this._pending.firstTimestamp);\n }\n return ts;\n }\n\n _compare(other) {\n // the comparator is also used to test for equality by sortValues, if the comparison returns 0\n // given that the firstTimestamp isn't set anymore when the last reaction is removed,\n // the remove event wouldn't be able to find the correct index anymore. So special case equality.\n if (other === this) {\n return 0;\n }\n if (this.count !== other.count) {\n return other.count - this.count;\n } else {\n const cmp = this.firstTimestamp - other.firstTimestamp;\n if (cmp === 0) {\n return this.key < other.key ? -1 : 1;\n }\n return cmp;\n }\n }\n\n async toggle(log = null) {\n if (this._isToggling) {\n console.log(\"busy toggling reaction already\");\n return;\n }\n this._isToggling = true;\n try {\n await this._parentTile.toggleReaction(this.key, log);\n } finally {\n this._isToggling = false;\n }\n }\n}\n\n// matrix classes uses in the integration test below\nimport {User} from \"../../../../matrix/User.js\";\nimport {SendQueue} from \"../../../../matrix/room/sending/SendQueue.js\";\nimport {Timeline} from \"../../../../matrix/room/timeline/Timeline.js\";\nimport {EventEntry} from \"../../../../matrix/room/timeline/entries/EventEntry.js\";\nimport {RelationWriter} from \"../../../../matrix/room/timeline/persistence/RelationWriter.js\";\nimport {FragmentIdComparer} from \"../../../../matrix/room/timeline/FragmentIdComparer.js\";\nimport {createAnnotation} from \"../../../../matrix/room/timeline/relations.js\";\n// mocks\nimport {Clock as MockClock} from \"../../../../mocks/Clock.js\";\nimport {createMockStorage} from \"../../../../mocks/Storage\";\nimport {ListObserver} from \"../../../../mocks/ListObserver.js\";\nimport {createEvent, withTextBody, withContent} from \"../../../../mocks/event.js\";\nimport {NullLogItem, NullLogger} from \"../../../../logging/NullLogger\";\nimport {HomeServer as MockHomeServer} from \"../../../../mocks/HomeServer.js\";\n// other imports\nimport {BaseMessageTile} from \"./tiles/BaseMessageTile.js\";\nimport {MappedList} from \"../../../../observable/list/MappedList\";\nimport {ObservableValue} from \"../../../../observable/ObservableValue\";\nimport {PowerLevels} from \"../../../../matrix/room/PowerLevels.js\";\n\nexport function tests() {\n const fragmentIdComparer = new FragmentIdComparer([]);\n const roomId = \"$abc\";\n const alice = \"@alice:hs.tld\";\n const bob = \"@bob:hs.tld\";\n const logger = new NullLogger();\n\n function findInIterarable(it, predicate) {\n let i = 0;\n for (const item of it) {\n if (predicate(item, i)) {\n return item;\n }\n i += 1;\n }\n throw new Error(\"not found\");\n }\n\n function mapMessageEntriesToBaseMessageTile(timeline, queue) {\n const room = {\n id: roomId,\n sendEvent(eventType, content, attachments, log) {\n return queue.enqueueEvent(eventType, content, attachments, log);\n },\n sendRedaction(eventIdOrTxnId, reason, log) {\n return queue.enqueueRedaction(eventIdOrTxnId, reason, log);\n }\n };\n const tiles = new MappedList(timeline.entries, entry => {\n if (entry.eventType === \"m.room.message\") {\n return new BaseMessageTile(entry, {roomVM: {room}, timeline, platform: {logger}});\n }\n return null;\n }, (tile, params, entry) => tile?.updateEntry(entry, params, function () {}));\n return tiles;\n }\n\n return {\n // these are more an integration test than unit tests,\n // but fully test the local echo when toggling and\n // the correct send queue modifications happen\n \"toggling reaction with own remote reaction\": async assert => {\n // 1. put message and reaction in storage\n const messageEvent = withTextBody(\"Dogs > Cats\", createEvent(\"m.room.message\", \"!abc\", bob));\n const myReactionEvent = withContent(createAnnotation(messageEvent.event_id, \"🐶\"), createEvent(\"m.reaction\", \"!def\", alice));\n myReactionEvent.origin_server_ts = 5;\n const myReactionEntry = new EventEntry({event: myReactionEvent, roomId}, fragmentIdComparer);\n const relationWriter = new RelationWriter({roomId, ownUserId: alice, fragmentIdComparer});\n const storage = await createMockStorage();\n const txn = await storage.readWriteTxn([\n storage.storeNames.timelineEvents,\n storage.storeNames.timelineRelations,\n storage.storeNames.timelineFragments\n ]);\n txn.timelineFragments.add({id: 1, roomId});\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 2, event: messageEvent, roomId}, new NullLogItem());\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 3, event: myReactionEvent, roomId}, new NullLogItem());\n await relationWriter.writeRelation(myReactionEntry, txn, new NullLogItem());\n await txn.complete();\n // 2. setup queue & timeline\n const queue = new SendQueue({roomId, storage, hsApi: new MockHomeServer().api});\n const powerLevelsObservable = new ObservableValue(new PowerLevels({ ownUserId: alice, membership: \"join\" }));\n const timeline = new Timeline({\n roomId,\n storage,\n fragmentIdComparer,\n clock: new MockClock(),\n pendingEvents: queue.pendingEvents,\n powerLevelsObservable\n });\n // 3. load the timeline, which will load the message with the reaction\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n const tiles = mapMessageEntriesToBaseMessageTile(timeline, queue);\n // 4. subscribe to the queue to observe, and the tiles (so we can safely iterate)\n const queueObserver = new ListObserver();\n queue.pendingEvents.subscribe(queueObserver);\n tiles.subscribe(new ListObserver());\n const messageTile = findInIterarable(tiles, e => !!e); // the other entries are mapped to null\n const reactionVM = messageTile.reactions.getReaction(\"🐶\");\n // 5. test toggling\n // make sure the preexisting reaction is counted\n assert.equal(reactionVM.count, 1);\n // 5.1. unset reaction, should redact the pre-existing reaction\n await reactionVM.toggle();\n {\n assert.equal(reactionVM.count, 0);\n const {value: redaction, type} = await queueObserver.next();\n assert.equal(\"add\", type);\n assert.equal(redaction.eventType, \"m.room.redaction\");\n assert.equal(redaction.relatedEventId, myReactionEntry.id);\n // SendQueue puts redaction in sending status, as it is first in the queue\n assert.equal(\"update\", (await queueObserver.next()).type);\n }\n // 5.2. set reaction, should send a new reaction as the redaction is already sending\n await reactionVM.toggle();\n let reactionIndex;\n {\n assert.equal(reactionVM.count, 1);\n const {value: reaction, type, index} = await queueObserver.next();\n assert.equal(\"add\", type);\n assert.equal(reaction.eventType, \"m.reaction\");\n assert.equal(reaction.relatedEventId, messageEvent.event_id);\n reactionIndex = index;\n }\n // 5.3. unset reaction, should abort the previous pending reaction as it hasn't started sending yet\n await reactionVM.toggle();\n {\n assert.equal(reactionVM.count, 0);\n const {index, type} = await queueObserver.next();\n assert.equal(\"remove\", type);\n assert.equal(reactionIndex, index);\n }\n },\n \"toggling reaction without own remote reaction\": async assert => {\n // 1. put message in storage\n const messageEvent = withTextBody(\"Dogs > Cats\", createEvent(\"m.room.message\", \"!abc\", bob));\n const storage = await createMockStorage();\n\n const txn = await storage.readWriteTxn([\n storage.storeNames.timelineEvents,\n storage.storeNames.timelineFragments\n ]);\n txn.timelineFragments.add({id: 1, roomId});\n txn.timelineEvents.tryInsert({fragmentId: 1, eventIndex: 2, event: messageEvent, roomId}, new NullLogItem());\n await txn.complete();\n // 2. setup queue & timeline\n const queue = new SendQueue({roomId, storage, hsApi: new MockHomeServer().api});\n const powerLevelsObservable = new ObservableValue(new PowerLevels({ ownUserId: alice, membership: \"join\" }));\n const timeline = new Timeline({roomId, storage, fragmentIdComparer,\n clock: new MockClock(), pendingEvents: queue.pendingEvents, powerLevelsObservable});\n\n // 3. load the timeline, which will load the message with the reaction\n await timeline.load(new User(alice), \"join\", new NullLogItem());\n const tiles = mapMessageEntriesToBaseMessageTile(timeline, queue);\n // 4. subscribe to the queue to observe, and the tiles (so we can safely iterate)\n const queueObserver = new ListObserver();\n queue.pendingEvents.subscribe(queueObserver);\n tiles.subscribe(new ListObserver());\n const messageTile = findInIterarable(tiles, e => !!e); // the other entries are mapped to null\n // 5. test toggling\n assert.equal(messageTile.reactions, null);\n // 5.1. set reaction, should send a new reaction as there is none yet\n await messageTile.react(\"🐶\");\n // now there should be a reactions view model\n const reactionVM = messageTile.reactions.getReaction(\"🐶\");\n let reactionTxnId;\n {\n assert.equal(reactionVM.count, 1);\n const {value: reaction, type} = await queueObserver.next();\n assert.equal(\"add\", type);\n assert.equal(reaction.eventType, \"m.reaction\");\n assert.equal(reaction.relatedEventId, messageEvent.event_id);\n // SendQueue puts reaction in sending status, as it is first in the queue\n assert.equal(\"update\", (await queueObserver.next()).type);\n reactionTxnId = reaction.txnId;\n }\n // 5.2. unset reaction, should redact the previous pending reaction as it has started sending already\n let redactionIndex;\n await reactionVM.toggle();\n {\n assert.equal(reactionVM.count, 0);\n const {value: redaction, type, index} = await queueObserver.next();\n assert.equal(\"add\", type);\n assert.equal(redaction.eventType, \"m.room.redaction\");\n assert.equal(redaction.relatedTxnId, reactionTxnId);\n redactionIndex = index;\n }\n // 5.3. set reaction, should abort the previous pending redaction as it hasn't started sending yet\n await reactionVM.toggle();\n {\n assert.equal(reactionVM.count, 1);\n const {index, type} = await queueObserver.next();\n assert.equal(\"remove\", type);\n assert.equal(redactionIndex, index);\n redactionIndex = index;\n }\n },\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SimpleTile} from \"./SimpleTile.js\";\nimport {ReactionsViewModel} from \"../ReactionsViewModel.js\";\nimport {getIdentifierColorNumber, avatarInitials, getAvatarHttpUrl} from \"../../../../avatar\";\n\nexport class BaseMessageTile extends SimpleTile {\n constructor(entry, options) {\n super(entry, options);\n this._date = this._entry.timestamp ? new Date(this._entry.timestamp) : null;\n this._isContinuation = false;\n this._reactions = null;\n this._replyTile = null;\n if (this._entry.annotations || this._entry.pendingAnnotations) {\n this._updateReactions();\n }\n this._updateReplyTileIfNeeded(undefined);\n }\n\n notifyVisible() {\n super.notifyVisible();\n this._replyTile?.notifyVisible();\n }\n\n\n get _mediaRepository() {\n return this._room.mediaRepository;\n }\n\n get permaLink() {\n return `https://matrix.to/#/${encodeURIComponent(this._room.id)}/${encodeURIComponent(this._entry.id)}`;\n }\n\n get senderProfileLink() {\n return `https://matrix.to/#/${encodeURIComponent(this.sender)}`;\n }\n\n get displayName() {\n return this._entry.displayName || this.sender;\n }\n\n get sender() {\n return this._entry.sender;\n }\n\n get memberPanelLink() {\n return `${this.urlCreator.urlUntilSegment(\"room\")}/member/${this.sender}`;\n }\n\n // Avatar view model contract\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._entry.sender);\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._entry.avatarUrl, size, this.platform, this._mediaRepository);\n }\n\n get avatarLetter() {\n return avatarInitials(this.sender);\n }\n\n get avatarTitle() {\n return this.displayName;\n }\n\n get date() {\n return this._date && this._date.toLocaleDateString({}, {month: \"numeric\", day: \"numeric\"});\n }\n\n get time() {\n return this._date && this._date.toLocaleTimeString({}, {hour: \"numeric\", minute: \"2-digit\"});\n }\n\n get isOwn() {\n return this._entry.sender === this._ownMember.userId;\n }\n\n get isContinuation() {\n return this._isContinuation;\n }\n\n get isUnverified() {\n return this._entry.isUnverified;\n }\n\n get isReply() {\n return this._entry.isReply;\n }\n\n _getContent() {\n return this._entry.content;\n }\n\n updatePreviousSibling(prev) {\n super.updatePreviousSibling(prev);\n let isContinuation = false;\n if (prev && prev instanceof BaseMessageTile && prev.sender === this.sender) {\n // timestamp is null for pending events\n const myTimestamp = this._entry.timestamp;\n const otherTimestamp = prev._entry.timestamp;\n // other message was sent less than 5min ago\n isContinuation = (myTimestamp - otherTimestamp) < (5 * 60 * 1000);\n }\n if (isContinuation !== this._isContinuation) {\n this._isContinuation = isContinuation;\n this.emitChange(\"isContinuation\");\n }\n }\n\n updateEntry(entry, param) {\n const action = super.updateEntry(entry, param);\n if (action.shouldUpdate) {\n this._updateReactions();\n }\n this._updateReplyTileIfNeeded(param);\n return action;\n }\n\n _updateReplyTileIfNeeded(param) {\n const replyEntry = this._entry.contextEntry;\n if (replyEntry) {\n // this is an update to contextEntry used for replyPreview\n const action = this._replyTile?.updateEntry(replyEntry, param);\n if (action?.shouldReplace || !this._replyTile) {\n this.disposeTracked(this._replyTile);\n const tileClassForEntry = this._options.tileClassForEntry;\n const ReplyTile = tileClassForEntry(replyEntry);\n if (ReplyTile) {\n this._replyTile = new ReplyTile(replyEntry, this._options);\n }\n }\n if(action?.shouldUpdate) {\n this._replyTile?.emitChange();\n }\n }\n }\n\n startReply() {\n this._roomVM.startReply(this._entry);\n }\n\n reply(msgtype, body, log = null) {\n return this._room.sendEvent(\"m.room.message\", this._entry.reply(msgtype, body), null, log);\n }\n\n redact(reason, log) {\n return this._room.sendRedaction(this._entry.id, reason, log);\n }\n\n get canRedact() {\n return this._powerLevels.canRedactFromSender(this._entry.sender);\n }\n\n get reactions() {\n if (this.shape !== \"redacted\") {\n return this._reactions;\n }\n return null;\n }\n\n get canReact() {\n return this._powerLevels.canSendType(\"m.reaction\");\n }\n\n react(key, log = null) {\n return this.logger.wrapOrRun(log, \"react\", async log => {\n if (!this.canReact) {\n log.set(\"powerlevel_lacking\", true);\n return;\n }\n if (this._entry.haveAnnotation(key)) {\n log.set(\"already_reacted\", true);\n return;\n }\n const redaction = this._entry.pendingAnnotations?.get(key)?.redactionEntry;\n if (redaction && !redaction.pendingEvent.hasStartedSending) {\n log.set(\"abort_redaction\", true);\n await redaction.pendingEvent.abort();\n } else {\n await this._room.sendEvent(\"m.reaction\", this._entry.annotate(key), null, log);\n }\n });\n }\n\n redactReaction(key, log = null) {\n return this.logger.wrapOrRun(log, \"redactReaction\", async log => {\n if (!this._powerLevels.canRedactFromSender(this._ownMember.userId)) {\n log.set(\"powerlevel_lacking\", true);\n return;\n }\n if (!this._entry.haveAnnotation(key)) {\n log.set(\"not_yet_reacted\", true);\n return;\n }\n let entry = this._entry.pendingAnnotations?.get(key)?.annotationEntry;\n if (!entry) {\n entry = await this._timeline.getOwnAnnotationEntry(this._entry.id, key);\n }\n if (entry) {\n await this._room.sendRedaction(entry.id, null, log);\n } else {\n log.set(\"no_reaction\", true);\n }\n });\n }\n\n toggleReaction(key, log = null) {\n return this.logger.wrapOrRun(log, \"toggleReaction\", async log => {\n if (this._entry.haveAnnotation(key)) {\n await this.redactReaction(key, log);\n } else {\n await this.react(key, log);\n }\n });\n }\n\n _updateReactions() {\n const {annotations, pendingAnnotations} = this._entry;\n if (!annotations && !pendingAnnotations) {\n if (this._reactions) {\n this._reactions = null;\n }\n } else {\n if (!this._reactions) {\n this._reactions = new ReactionsViewModel(this);\n }\n this._reactions.update(annotations, pendingAnnotations);\n }\n }\n\n get replyTile() {\n if (!this._entry.contextEventId) {\n return null;\n }\n return this._replyTile;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n/*\nThe regex is split into component strings;\nmeaning that any escapes (\\) must also\nbe escaped.\n*/\nconst scheme = \"(?:https|http|ftp):\\\\/\\\\/\";\nconst noSpaceNorPunctuation = \"[^\\\\s.,?!)]\";\nconst hostCharacter = \"[a-zA-Z0-9:.\\\\[\\\\]-]\";\n\n/*\nUsing non-consuming group here to combine two criteria for the last character.\nSee point 1 below.\n*/\nconst host = `${hostCharacter}*(?=${hostCharacter})${noSpaceNorPunctuation}`;\n\n/*\nUse sub groups so we accept just / or #; but if anything comes after it,\nit should not end with punctuation or space.\n*/\nconst pathOrFragment = `(?:[\\\\/#](?:[^\\\\s]*${noSpaceNorPunctuation})?)`;\n\n/*\nThings to keep in mind:\n1. URL must not contain non-ascii characters in host but may contain\n them in path or fragment components.\n https://matrix.org/ - valid\n https://matrix.org - invalid\n2. Do not treat punctuation at the end as a part of the URL (.,?!)\n3. Path/fragment is optional.\n*/\nconst urlRegex = `${scheme}${host}${pathOrFragment}?`;\n\nexport const regex = new RegExp(urlRegex, \"gi\");\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { regex } from \"./regex.js\";\n\n/**\n * Splits text into links and non-links.\n * For each such separated token, callback is called\n * with the token and a boolean passed as argument.\n * The boolean indicates whether the token is a link or not.\n * @param {string} text Text to split\n * @param {function(string, boolean)} callback A function to call with split tokens\n */\nexport function linkify(text, callback) {\n const matches = text.matchAll(regex);\n let curr = 0;\n for (let match of matches) {\n const precedingText = text.slice(curr, match.index);\n callback(precedingText, false);\n callback(match[0], true);\n const len = match[0].length;\n curr = match.index + len;\n }\n const remainingText = text.slice(curr);\n callback(remainingText, false);\n}\n\nexport function tests() {\n\n class MockCallback {\n mockCallback(text, isLink) {\n if (!text.length) {\n return;\n }\n if (!this.result) {\n this.result = [];\n }\n const type = isLink ? \"link\" : \"text\";\n this.result.push({ type: type, text: text });\n }\n }\n\n function test(assert, input, output) {\n const m = new MockCallback;\n linkify(input, m.mockCallback.bind(m));\n assert.deepEqual(output, m.result);\n }\n\n function testLink(assert, link, expectFail = false) {\n const input = link;\n const output = expectFail ? [{ type: \"text\", text: input }] :\n [{ type: \"link\", text: input }];\n test(assert, input, output);\n }\n\n return {\n \"Link with host\": assert => {\n testLink(assert, \"https://matrix.org\");\n },\n\n \"Link with host & path\": assert => {\n testLink(assert, \"https://matrix.org/docs/develop\");\n },\n\n \"Link with host & fragment\": assert => {\n testLink(assert, \"https://matrix.org#test\");\n },\n\n \"Link with host & query\": assert => {\n testLink(assert, \"https://matrix.org/?foo=bar\");\n },\n\n \"Complex link\": assert => {\n const link = \"https://www.foobar.com/url?sa=t&rct=j&q=&esrc=s&source\" +\n \"=web&cd=&cad=rja&uact=8&ved=2ahUKEwjyu7DJ-LHwAhUQyzgGHc\" +\n \"OKA70QFjAAegQIBBAD&url=https%3A%2F%2Fmatrix.org%2Fdocs%\" +\n \"2Fprojects%2Fclient%2Felement%2F&usg=AOvVaw0xpENrPHv_R-\" +\n \"ERkyacR2Bd\";\n testLink(assert, link);\n },\n\n \"Localhost link\": assert => {\n testLink(assert, \"http://localhost\");\n testLink(assert, \"http://localhost:3000\");\n },\n\n \"IPV4 link\": assert => {\n testLink(assert, \"https://192.0.0.1\");\n testLink(assert, \"https://250.123.67.23:5924\");\n },\n\n \"IPV6 link\": assert => {\n testLink(assert, \"http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]\");\n testLink(assert, \"http://[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:7000\");\n },\n\n \"Missing scheme must not linkify\": assert => {\n testLink(assert, \"matrix.org/foo/bar\", true);\n },\n\n \"Punctuation at end of link must not linkify\": assert => {\n const link = \"https://foo.bar/?nenjil=lal810\";\n const end = \".,? \";\n for (const char of end) {\n const out = [{ type: \"link\", text: link }, { type: \"text\", text: char }];\n test(assert, link + char, out);\n }\n },\n\n \"Link doesn't adopt closing parenthesis\": assert => {\n const link = \"(https://matrix.org)\";\n const out = [{ type: \"text\", text: \"(\" }, { type: \"link\", text: \"https://matrix.org\" }, { type: \"text\", text: \")\" }];\n test(assert, link, out);\n },\n\n \"Unicode in hostname must not linkify\": assert => {\n const link = \"https://foo.bar\\uD83D\\uDE03.com\";\n const out = [{ type: \"link\", text: \"https://foo.bar\" },\n { type: \"text\", text: \"\\uD83D\\uDE03.com\" }];\n test(assert, link, out);\n },\n\n \"Link with unicode only after / must linkify\": assert => {\n testLink(assert, \"https://foo.bar.com/\\uD83D\\uDE03\");\n },\n\n \"Link with unicode after fragment without path must linkify\": assert => {\n testLink(assert, \"https://foo.bar.com#\\uD83D\\uDE03\");\n },\n\n \"Link ends with <\": assert => {\n const link = \"https://matrix.org<\";\n const out = [{ type: \"link\", text: \"https://matrix.org\" }, { type: \"text\", text: \"<\" }];\n test(assert, link, out);\n }\n };\n}\n","import { linkify } from \"./linkify/linkify.js\";\nimport { getIdentifierColorNumber, avatarInitials } from \"../../../avatar\";\n\n/**\n * Parse text into parts such as newline, links and text.\n * @param {string} body A string to parse into parts\n * @returns {MessageBody} Parsed result\n */\nexport function parsePlainBody(body) {\n const parts = [];\n const lines = body.split(\"\\n\");\n\n // create callback outside of loop\n const linkifyCallback = (text, isLink) => {\n if (isLink) {\n parts.push(new LinkPart(text, [new TextPart(text)]));\n } else {\n parts.push(new TextPart(text));\n }\n };\n\n for (let i = 0; i < lines.length; i += 1) {\n const line = lines[i];\n if (line.length) {\n linkify(line, linkifyCallback);\n }\n const isLastLine = i >= (lines.length - 1);\n if (!isLastLine) {\n parts.push(new NewLinePart());\n }\n }\n\n return new MessageBody(body, parts);\n}\n\nexport function stringAsBody(body) {\n return new MessageBody(body, [new TextPart(body)]);\n}\n\nexport class HeaderBlock {\n constructor(level, inlines) {\n this.level = level;\n this.inlines = inlines;\n }\n\n get type() { return \"header\"; }\n}\n\nexport class CodeBlock {\n constructor(language, text) {\n this.language = language;\n this.text = text;\n }\n\n get type() { return \"codeblock\"; }\n}\n\nexport class ListBlock {\n constructor(startOffset, items) {\n this.items = items;\n this.startOffset = startOffset;\n }\n\n get type() { return \"list\"; }\n}\n\nexport class TableBlock {\n constructor(head, body) {\n this.head = head;\n this.body = body;\n }\n\n get type() { return \"table\"; }\n}\n\nexport class RulePart {\n get type() { return \"rule\"; }\n}\n\nexport class NewLinePart {\n get type() { return \"newline\"; }\n}\n\nexport class FormatPart {\n constructor(format, children) {\n this.format = format.toLowerCase();\n this.children = children;\n }\n\n get type() { return \"format\"; }\n}\n\nexport class ImagePart {\n constructor(src, width, height, alt, title) {\n this.src = src;\n this.width = width;\n this.height = height;\n this.alt = alt;\n this.title = title;\n }\n\n get type() { return \"image\"; }\n}\n\nexport class PillPart {\n constructor(id, href, children) {\n this.id = id;\n this.href = href;\n this.children = children;\n }\n\n get type() { return \"pill\"; }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this.id);\n }\n\n get avatarInitials() {\n return avatarInitials(this.id);\n }\n}\n\nexport class LinkPart {\n constructor(url, inlines) {\n this.url = url;\n this.inlines = inlines;\n }\n\n get type() { return \"link\"; }\n}\n\nexport class TextPart {\n constructor(text) {\n this.text = text;\n }\n\n get type() { return \"text\"; }\n}\n\nfunction isBlockquote(part){\n return part.type === \"format\" && part.format === \"blockquote\";\n}\n\nexport class MessageBody {\n constructor(sourceString, parts) {\n this.sourceString = sourceString;\n this.parts = parts;\n }\n\n insertEmote(string) {\n // We want to skip quotes introduced by replies when emoting.\n // We assume that such quotes are not TextParts, because replies\n // must have a formatted body.\n let i = 0;\n for (; i < this.parts.length && isBlockquote(this.parts[i]); i++);\n this.parts.splice(i, 0, new TextPart(string));\n }\n}\n\nexport function tests() {\n\n function test(assert, input, output) {\n assert.deepEqual(parsePlainBody(input), new MessageBody(input, output));\n }\n\n return {\n // Tests for text\n \"Text only\": assert => {\n const input = \"This is a sentence\";\n const output = [new TextPart(input)];\n test(assert, input, output);\n },\n\n \"Text with newline\": assert => {\n const input = \"This is a sentence.\\nThis is another sentence.\";\n const output = [\n new TextPart(\"This is a sentence.\"),\n new NewLinePart(),\n new TextPart(\"This is another sentence.\")\n ];\n test(assert, input, output);\n },\n\n \"Text with newline & trailing newline\": assert => {\n const input = \"This is a sentence.\\nThis is another sentence.\\n\";\n const output = [\n new TextPart(\"This is a sentence.\"),\n new NewLinePart(),\n new TextPart(\"This is another sentence.\"),\n new NewLinePart()\n ];\n test(assert, input, output);\n }\n };\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageTile} from \"./BaseMessageTile.js\";\nimport {stringAsBody} from \"../MessageBody.js\";\nimport {createEnum} from \"../../../../../utils/enum\";\n\nexport const BodyFormat = createEnum(\"Plain\", \"Html\");\n\nexport class BaseTextTile extends BaseMessageTile {\n constructor(entry, options) {\n super(entry, options);\n this._messageBody = null;\n this._format = null\n }\n\n get shape() {\n return \"message\";\n }\n\n _parseBody(body) {\n return stringAsBody(body);\n }\n\n _getBodyFormat() {\n return BodyFormat.Plain;\n }\n\n get body() {\n const body = this._getBody();\n const format = this._getBodyFormat();\n // body is a string, so we can check for difference by just\n // doing an equality check\n // Even if the body hasn't changed, but the format has, we need\n // to re-fill our cache.\n if (!this._messageBody || this._messageBody.sourceString !== body || this._format !== format) {\n // body with markup is an array of parts,\n // so we should not recreate it for the same body string,\n // or else the equality check in the binding will always fail.\n // So cache it here.\n this._messageBody = this._parseBody(body, format);\n this._format = format;\n }\n return this._messageBody;\n }\n\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { MessageBody, HeaderBlock, TableBlock, ListBlock, CodeBlock, PillPart, FormatPart, NewLinePart, RulePart, TextPart, LinkPart, ImagePart } from \"./MessageBody.js\"\nimport { linkify } from \"./linkify/linkify.js\";\n\n/* At the time of writing (Jul 1 2021), Matrix Spec recommends\n * allowing the following HTML tags:\n * font, del, h1, h2, h3, h4, h5, h6, blockquote, p, a, ul, ol, sup, sub, li, b, i, u,\n * strong, em, strike, code, hr, br, div, table, thead, tbody, tr, th, td, caption, pre, span, img\n */\n\n/**\n * Nodes that don't have any properties to them other than their tag.\n * While has `href`, and has `src`, these have... themselves.\n */\nconst basicInline = [\"EM\", \"STRONG\", \"CODE\", \"DEL\", \"SPAN\" ];\nconst basicBlock = [\"DIV\", \"BLOCKQUOTE\"];\nconst safeSchemas = [\"https\", \"http\", \"ftp\", \"mailto\", \"magnet\"].map(name => `${name}://`);\nconst baseUrl = 'https://matrix.to';\nconst linkPrefix = `${baseUrl}/#/`;\n\nclass Deserializer {\n constructor(result, mediaRepository) {\n this.result = result;\n this.mediaRepository = mediaRepository;\n }\n\n parsePillLink(link) {\n if (!link.startsWith(linkPrefix)) {\n return null;\n }\n const contents = link.substring(linkPrefix.length);\n if (contents[0] === '@') {\n return contents;\n }\n return null;\n }\n\n parseLink(node, children) {\n const href = this.result.getAttributeValue(node, \"href\");\n const lcUrl = href?.toLowerCase();\n // urls should be absolute and with a safe schema, as listed in the spec\n if (!lcUrl || !safeSchemas.some(schema => lcUrl.startsWith(schema))) {\n return new FormatPart(\"span\", children);\n }\n const pillId = this.parsePillLink(href);\n if (pillId) {\n return new PillPart(pillId, href, children);\n }\n return new LinkPart(href, children);\n }\n\n parseList(node) {\n const result = this.result;\n let start = null;\n if (result.getNodeElementName(node) === \"OL\") {\n // Will return 1 for, say, '1A', which may not be intended?\n start = parseInt(result.getAttributeValue(node, \"start\")) || 1;\n }\n const items = [];\n for (const child of result.getChildNodes(node)) {\n if (result.getNodeElementName(child) !== \"LI\") {\n continue;\n }\n const item = this.parseAnyNodes(result.getChildNodes(child));\n items.push(item);\n }\n return new ListBlock(start, items);\n }\n\n _ensureElement(node, tag) {\n return node &&\n this.result.isElementNode(node) &&\n this.result.getNodeElementName(node) === tag;\n }\n\n parseCodeBlock(node) {\n const result = this.result;\n let codeNode;\n for (const child of result.getChildNodes(node)) {\n codeNode = child;\n break;\n }\n let language = null;\n if (!this._ensureElement(codeNode, \"CODE\")) {\n return new CodeBlock(language, this.result.getNodeText(node));\n }\n const cl = result.getAttributeValue(codeNode, \"class\") || \"\"\n for (const clname of cl.split(\" \")) {\n if (clname.startsWith(\"language-\") && !clname.startsWith(\"language-_\")) {\n language = clname.substring(9) // \"language-\".length\n break;\n }\n }\n return new CodeBlock(language, this.result.getNodeText(codeNode));\n }\n\n parseImage(node) {\n const result = this.result;\n const src = result.getAttributeValue(node, \"src\") || \"\";\n const url = this.mediaRepository.mxcUrl(src);\n // We just ignore non-mxc `src` attributes.\n if (!url) {\n return null;\n }\n const width = parseInt(result.getAttributeValue(node, \"width\")) || null;\n const height = parseInt(result.getAttributeValue(node, \"height\")) || null;\n const alt = result.getAttributeValue(node, \"alt\");\n const title = result.getAttributeValue(node, \"title\");\n return new ImagePart(url, width, height, alt, title);\n }\n\n parseTableRow(row, tag) {\n const cells = [];\n for (const node of this.result.getChildNodes(row)) {\n if(!this._ensureElement(node, tag)) {\n continue;\n }\n const children = this.result.getChildNodes(node);\n const inlines = this.parseInlineNodes(children);\n cells.push(inlines);\n }\n return cells;\n }\n\n parseTableHead(head) {\n let headRow = null;\n for (const node of this.result.getChildNodes(head)) {\n headRow = node;\n break;\n }\n if (this._ensureElement(headRow, \"TR\")) {\n return this.parseTableRow(headRow, \"TH\");\n }\n return null;\n }\n\n parseTableBody(body) {\n const rows = [];\n for (const node of this.result.getChildNodes(body)) {\n if(!this._ensureElement(node, \"TR\")) {\n continue;\n }\n rows.push(this.parseTableRow(node, \"TD\"));\n }\n return rows;\n }\n\n parseTable(node) {\n // We are only assuming iterable, so convert to arrary for indexing.\n const children = Array.from(this.result.getChildNodes(node));\n let head, body;\n if (this._ensureElement(children[0], \"THEAD\") && this._ensureElement(children[1], \"TBODY\")) {\n head = this.parseTableHead(children[0]);\n body = this.parseTableBody(children[1]);\n } else if (this._ensureElement(children[0], \"TBODY\")) {\n head = null;\n body = this.parseTableBody(children[0]);\n }\n return new TableBlock(head, body);\n }\n\n /** Once a node is known to be an element,\n * attempt to interpret it as an inline element.\n *\n * @returns the inline message part, or null if the element\n * is not inline or not allowed.\n */\n parseInlineElement(node) {\n const result = this.result;\n const tag = result.getNodeElementName(node);\n const children = result.getChildNodes(node);\n switch (tag) {\n case \"A\": {\n const inlines = this.parseInlineNodes(children);\n return this.parseLink(node, inlines);\n }\n case \"BR\":\n return new NewLinePart();\n default: {\n if (!basicInline.includes(tag)) {\n return null;\n }\n const inlines = this.parseInlineNodes(children);\n return new FormatPart(tag, inlines);\n }\n }\n }\n\n /** Attempt to interpret a node as inline.\n *\n * @returns the inline message part, or null if the\n * element is not inline or not allowed.\n */\n parseInlineNode(node) {\n if (this.result.isElementNode(node)) {\n return this.parseInlineElement(node);\n }\n return null;\n }\n\n /** Once a node is known to be an element, attempt\n * to interpret it as a block element.\n *\n * @returns the block message part, or null of the\n * element is not a block or not allowed.\n */\n parseBlockElement(node) {\n const result = this.result;\n const tag = result.getNodeElementName(node);\n const children = result.getChildNodes(node);\n switch (tag) {\n case \"H1\":\n case \"H2\":\n case \"H3\":\n case \"H4\":\n case \"H5\":\n case \"H6\": {\n const inlines = this.parseInlineNodes(children);\n return new HeaderBlock(parseInt(tag[1]), inlines)\n }\n case \"UL\":\n case \"OL\":\n return this.parseList(node);\n case \"PRE\":\n return this.parseCodeBlock(node);\n case \"HR\":\n return new RulePart();\n case \"IMG\":\n return this.parseImage(node);\n case \"P\": {\n const inlines = this.parseInlineNodes(children);\n return new FormatPart(tag, inlines);\n }\n case \"TABLE\":\n return this.parseTable(node);\n default: {\n if (!basicBlock.includes(tag)) {\n return null;\n }\n const blocks = this.parseAnyNodes(children);\n return new FormatPart(tag, blocks);\n }\n }\n }\n\n /** Attempt to parse a node as a block.\n *\n * @return the block message part, or null if the node\n * is not a block element.\n */\n parseBlockNode(node) {\n if (this.result.isElementNode(node)) {\n return this.parseBlockElement(node);\n }\n return null;\n }\n\n _parseTextParts(node, into) {\n if(!this.result.isTextNode(node)) {\n return false;\n }\n\n // XXX pretty much identical to `MessageBody`'s.\n const linkifyCallback = (text, isLink) => {\n if (isLink) {\n into.push(new LinkPart(text, [new TextPart(text)]));\n } else {\n into.push(new TextPart(text));\n }\n };\n linkify(this.result.getNodeText(node), linkifyCallback);\n return true;\n }\n\n _isAllowedNode(node) {\n return !this._ensureElement(node, \"MX-REPLY\");\n }\n\n _parseInlineNodes(nodes, into) {\n for (const htmlNode of nodes) {\n if (this._parseTextParts(htmlNode, into)) {\n // This was a text node, and we already\n // dumped its parts into our list.\n continue;\n }\n const node = this.parseInlineNode(htmlNode);\n if (node) {\n into.push(node);\n continue;\n }\n // Node is either block or unrecognized. In\n // both cases, just move on to its children.\n if (this._isAllowedNode(htmlNode)) {\n this._parseInlineNodes(this.result.getChildNodes(htmlNode), into);\n }\n }\n }\n\n parseInlineNodes(nodes) {\n const into = [];\n this._parseInlineNodes(nodes, into);\n return into;\n }\n\n // XXX very similar to `_parseInlineNodes`.\n _parseAnyNodes(nodes, into) {\n for (const htmlNode of nodes) {\n if (this._parseTextParts(htmlNode, into)) {\n // This was a text node, and we already\n // dumped its parts into our list.\n continue;\n }\n const node = this.parseInlineNode(htmlNode) || this.parseBlockNode(htmlNode);\n if (node) {\n into.push(node);\n continue;\n }\n // Node is unrecognized. Just move on to its children.\n if (this._isAllowedNode(htmlNode)) {\n this._parseAnyNodes(this.result.getChildNodes(htmlNode), into);\n }\n }\n }\n\n parseAnyNodes(nodes) {\n const into = [];\n this._parseAnyNodes(nodes, into);\n return into;\n }\n}\n\nexport function parseHTMLBody(platform, mediaRepository, html) {\n const parseResult = platform.parseHTML(html);\n const deserializer = new Deserializer(parseResult, mediaRepository);\n const parts = deserializer.parseAnyNodes(parseResult.rootNodes);\n return new MessageBody(html, parts);\n}\n\n\nexport async function tests() {\n // don't import node-html-parser until it's safe to assume we're actually in a unit test,\n // as this is a devDependency\n const nodeHtmlParser = await import(\"node-html-parser\");\n const {parse} = nodeHtmlParser.default;\n\n class HTMLParseResult {\n constructor(bodyNode) {\n this._bodyNode = bodyNode;\n }\n\n get rootNodes() {\n return this._bodyNode.childNodes;\n }\n\n getChildNodes(node) {\n return node.childNodes;\n }\n\n getAttributeNames(node) {\n return node.getAttributeNames();\n }\n\n getAttributeValue(node, attr) {\n return node.getAttribute(attr);\n }\n\n isTextNode(node) {\n return !node.tagName;\n }\n\n getNodeText(node) {\n return node.text;\n }\n\n isElementNode(node) {\n return !!node.tagName;\n }\n\n getNodeElementName(node) {\n return node.tagName;\n }\n }\n\n const platform = {\n parseHTML: (html) => new HTMLParseResult(parse(html))\n };\n\n function test(assert, input, output) {\n assert.deepEqual(parseHTMLBody(platform, null, input), new MessageBody(input, output));\n }\n\n return {\n \"Text only\": assert => {\n const input = \"This is a sentence\";\n const output = [new TextPart(input)];\n test(assert, input, output);\n },\n \"Text with inline code format\": assert => {\n const input = \"Here's some code!\";\n const output = [\n new TextPart(\"Here's \"),\n new FormatPart(\"em\", [new TextPart(\"some\")]),\n new TextPart(\" \"),\n new FormatPart(\"code\", [new TextPart(\"code\")]),\n new TextPart(\"!\")\n ];\n test(assert, input, output);\n },\n \"Text with ordered list with no attributes\": assert => {\n const input = \"
  1. Lorem
  2. Ipsum
\";\n const output = [\n new ListBlock(1, [\n [ new TextPart(\"Lorem\") ],\n [ new TextPart(\"Ipsum\") ]\n ])\n ];\n test(assert, input, output);\n },\n \"Text with ordered list starting at 3\": assert => {\n const input = '
  1. Lorem
  2. Ipsum
';\n const output = [\n new ListBlock(3, [\n [ new TextPart(\"Lorem\") ],\n [ new TextPart(\"Ipsum\") ]\n ])\n ];\n test(assert, input, output);\n },\n \"Text with unordered list\": assert => {\n const input = '
  • Lorem
  • Ipsum
';\n const output = [\n new ListBlock(null, [\n [ new TextPart(\"Lorem\") ],\n [ new TextPart(\"Ipsum\") ]\n ])\n ];\n test(assert, input, output);\n },\n \"Auto-closed tags\": assert => {\n const input = '

hello

world

';\n const output = [\n new FormatPart(\"p\", [new TextPart(\"hello\")]),\n new FormatPart(\"p\", [new TextPart(\"world\")])\n ];\n test(assert, input, output);\n },\n \"Block elements ignored inside inline elements\": assert => {\n const input = '

Hello

';\n const output = [\n new FormatPart(\"span\", [new FormatPart(\"code\", [new TextPart(\"Hello\")])])\n ];\n test(assert, input, output);\n },\n \"Unknown tags are ignored, but their children are kept\": assert => {\n const input = 'Hello
World
';\n const output = [\n new FormatPart(\"span\", [\n new FormatPart(\"code\", [new TextPart(\"Hello\")]),\n new FormatPart(\"em\", [new TextPart(\"World\")])\n ])\n ];\n test(assert, input, output);\n },\n \"Unknown and invalid attributes are stripped\": assert => {\n const input = 'Hello';\n const output = [\n new FormatPart(\"em\", [new TextPart(\"Hello\")])\n ];\n test(assert, input, output);\n },\n \"Text with code block but no tag\": assert => {\n const code = 'main :: IO ()\\nmain = putStrLn \"Hello\"'\n const input = `
${code}
`;\n const output = [\n new CodeBlock(null, code)\n ];\n test(assert, input, output);\n },\n \"Text with code block and 'unsupported' tag\": assert => {\n const code = 'Hello, world'\n const input = `
${code}
`;\n const output = [\n new CodeBlock(null, code)\n ];\n test(assert, input, output);\n },\n \"Reply fallback is always stripped\": assert => {\n const input = 'Hello, World!';\n const output = [\n new TextPart('Hello, '),\n new FormatPart(\"em\", []),\n new TextPart('!'),\n ];\n assert.deepEqual(parseHTMLBody(platform, null, input), new MessageBody(input, output));\n }\n /* Doesnt work: HTML library doesn't handle
 properly.\n        \"Text with code block\": assert => {\n            const code = 'main :: IO ()\\nmain = putStrLn \"Hello\"'\n            const input = `
${code}
`;\n const output = [\n new CodeBlock(null, code)\n ];\n test(assert, input, output);\n }\n */\n };\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseTextTile, BodyFormat} from \"./BaseTextTile.js\";\nimport {parsePlainBody} from \"../MessageBody.js\";\nimport {parseHTMLBody} from \"../deserialize.js\";\n\nexport class TextTile extends BaseTextTile {\n _getContentString(key) {\n return this._getContent()?.[key] || \"\";\n }\n\n _getPlainBody() {\n return this._getContentString(\"body\");\n }\n\n _getFormattedBody() {\n return this._getContentString(\"formatted_body\");\n }\n\n _getBody() {\n if (this._getBodyFormat() === BodyFormat.Html) {\n return this._getFormattedBody();\n } else {\n return this._getPlainBody();\n }\n }\n\n _getBodyFormat() {\n if (this._getContent()?.format === \"org.matrix.custom.html\") {\n return BodyFormat.Html;\n } else {\n return BodyFormat.Plain;\n }\n }\n\n _parseBody(body, format) {\n let messageBody;\n if (format === BodyFormat.Html) {\n messageBody = parseHTMLBody(this.platform, this._mediaRepository, body);\n } else {\n messageBody = parsePlainBody(body);\n }\n if (this._getContent()?.msgtype === \"m.emote\") {\n messageBody.insertEmote(`* ${this.displayName} `);\n }\n return messageBody;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageTile} from \"./BaseMessageTile.js\";\n\nexport class RedactedTile extends BaseMessageTile {\n get shape() {\n return \"redacted\";\n }\n\n get description() {\n const {redactionReason} = this._entry;\n if (this.isRedacting) {\n if (redactionReason) {\n return this.i18n`This message is being deleted (${redactionReason})…`;\n } else {\n return this.i18n`This message is being deleted…`;\n }\n } else {\n if (redactionReason) {\n return this.i18n`This message has been deleted (${redactionReason}).`;\n } else {\n return this.i18n`This message has been deleted.`;\n }\n }\n }\n\n get isRedacting() {\n return this._entry.isRedacting;\n }\n \n /** override parent property to disable redacting, even if still pending */\n get canRedact() {\n return false;\n }\n\n abortPendingRedaction() {\n return this._entry.abortPendingRedaction();\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageTile} from \"./BaseMessageTile.js\";\nimport {SendStatus} from \"../../../../../matrix/room/sending/PendingEvent.js\";\nconst MAX_HEIGHT = 300;\nconst MAX_WIDTH = 400;\n\nexport class BaseMediaTile extends BaseMessageTile {\n constructor(entry, options) {\n super(entry, options);\n this._decryptedThumbnail = null;\n this._decryptedFile = null;\n this._isVisible = false;\n this._error = null;\n this._downloading = false;\n this._downloadError = null;\n }\n\n async downloadMedia() {\n if (this._downloading || this.isPending) {\n return;\n }\n const content = this._getContent();\n const filename = content.body;\n this._downloading = true;\n this.emitChange(\"status\");\n let blob;\n try {\n blob = await this._mediaRepository.downloadAttachment(content);\n this.platform.saveFileAs(blob, filename);\n } catch (err) {\n this._downloadError = err;\n } finally {\n blob?.dispose();\n this._downloading = false;\n }\n this.emitChange(\"status\");\n }\n\n get isUploading() {\n return this.isPending && this._entry.pendingEvent.status === SendStatus.UploadingAttachments;\n }\n\n get uploadPercentage() {\n const {pendingEvent} = this._entry;\n return pendingEvent && Math.round((pendingEvent.attachmentsSentBytes / pendingEvent.attachmentsTotalBytes) * 100);\n }\n\n get status() {\n const {pendingEvent} = this._entry;\n switch (pendingEvent?.status) {\n case SendStatus.Waiting:\n return this.i18n`Waiting…`;\n case SendStatus.EncryptingAttachments:\n case SendStatus.Encrypting:\n return this.i18n`Encrypting…`;\n case SendStatus.UploadingAttachments:\n return this.i18n`Uploading…`;\n case SendStatus.Sending:\n return this.i18n`Sending…`;\n case SendStatus.Error:\n return this.i18n`Error: ${pendingEvent.error.message}`;\n default:\n if (this._downloadError) {\n return `Download failed`;\n }\n if (this._downloading) {\n return this.i18n`Downloading…`;\n }\n return \"\";\n }\n }\n\n get thumbnailUrl() {\n if (!this._isVisible) {\n return \"\";\n }\n if (this._decryptedThumbnail) {\n return this._decryptedThumbnail.url;\n } else {\n const thumbnailMxc = this._getContent().info?.thumbnail_url;\n if (thumbnailMxc) {\n return this._mediaRepository.mxcUrlThumbnail(thumbnailMxc, this.width, this.height, \"scale\");\n }\n }\n if (this._entry.isPending) {\n const attachment = this._entry.pendingEvent.getAttachment(\"info.thumbnail_url\");\n return attachment && attachment.localPreview.url;\n }\n if (this._isMainResourceImage()) {\n if (this._decryptedFile) {\n return this._decryptedFile.url;\n } else {\n const mxcUrl = this._getContent()?.url;\n if (typeof mxcUrl === \"string\") {\n return this._mediaRepository.mxcUrlThumbnail(mxcUrl, this.width, this.height, \"scale\");\n }\n }\n }\n return \"\";\n }\n\n notifyVisible() {\n super.notifyVisible();\n this._isVisible = true;\n this.emitChange(\"thumbnailUrl\");\n if (!this.isPending) {\n this._tryLoadEncryptedThumbnail();\n }\n }\n\n get width() {\n const info = this._getContent()?.info;\n return Math.round(info?.w * this._scaleFactor());\n }\n\n get height() {\n const info = this._getContent()?.info;\n return Math.round(info?.h * this._scaleFactor());\n }\n\n get mimeType() {\n const info = this._getContent()?.info;\n return info?.mimetype;\n }\n\n get label() {\n return this._getContent().body;\n }\n\n get error() {\n if (this._error) {\n return `Could not load media: ${this._error.message}`;\n }\n return null;\n }\n\n setViewError(err) {\n this._error = err;\n this.emitChange(\"error\");\n }\n\n async _loadEncryptedFile(file) {\n const blob = await this._mediaRepository.downloadEncryptedFile(file, true);\n if (this.isDisposed) {\n blob.dispose();\n return;\n }\n return this.track(blob);\n }\n\n async _tryLoadEncryptedThumbnail() {\n try {\n const thumbnailFile = this._getContent().info?.thumbnail_file;\n const file = this._getContent().file;\n if (thumbnailFile) {\n this._decryptedThumbnail = await this._loadEncryptedFile(thumbnailFile);\n this.emitChange(\"thumbnailUrl\");\n } else if (file && this._isMainResourceImage()) { // is the main resource an image? then try that for a thumbnail\n this._decryptedFile = await this._loadEncryptedFile(file);\n this.emitChange(\"thumbnailUrl\");\n }\n } catch (err) {\n this._error = err;\n this.emitChange(\"error\");\n }\n }\n\n _scaleFactor() {\n const info = this._getContent()?.info;\n const scaleHeightFactor = MAX_HEIGHT / info?.h;\n const scaleWidthFactor = MAX_WIDTH / info?.w;\n // take the smallest scale factor, to respect all constraints\n // we should not upscale images, so limit scale factor to 1 upwards\n return Math.min(scaleWidthFactor, scaleHeightFactor, 1);\n }\n\n _isMainResourceImage() {\n return true; // overwritten in VideoTile\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMediaTile} from \"./BaseMediaTile.js\";\n\nexport class ImageTile extends BaseMediaTile {\n constructor(entry, options) {\n super(entry, options);\n this._lightboxUrl = this.urlCreator.urlForSegments([\n // ensure the right room is active if in grid view\n this.navigation.segment(\"room\", this._room.id),\n this.navigation.segment(\"lightbox\", this._entry.id)\n ]);\n }\n\n get lightboxUrl() {\n if (!this.isPending) {\n return this._lightboxUrl;\n }\n return \"\";\n }\n\n get shape() {\n return \"image\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMediaTile} from \"./BaseMediaTile.js\";\n\nexport class VideoTile extends BaseMediaTile {\n async loadVideo() {\n const file = this._getContent().file;\n if (file && !this._decryptedFile) {\n this._decryptedFile = await this._loadEncryptedFile(file);\n this.emitChange(\"videoUrl\");\n }\n }\n\n get videoUrl() {\n if (this._decryptedFile) {\n return this._decryptedFile.url;\n }\n const mxcUrl = this._getContent()?.url;\n if (typeof mxcUrl === \"string\") {\n return this._mediaRepository.mxcUrl(mxcUrl);\n }\n return \"\";\n }\n\n get shape() {\n return \"video\";\n }\n\n _isMainResourceImage() {\n return false;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n\nexport function formatSize(size: number, decimals: number = 2): string {\n if (Number.isSafeInteger(size)) {\n const base = Math.min(3, Math.floor(Math.log(size) / Math.log(1024)));\n const formattedSize = Math.round(size / Math.pow(1024, base)).toFixed(decimals);\n switch (base) {\n case 0: return `${formattedSize} bytes`;\n case 1: return `${formattedSize} KB`;\n case 2: return `${formattedSize} MB`;\n case 3: return `${formattedSize} GB`;\n }\n }\n return \"\";\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageTile} from \"./BaseMessageTile.js\";\nimport {formatSize} from \"../../../../../utils/formatSize\";\nimport {SendStatus} from \"../../../../../matrix/room/sending/PendingEvent.js\";\n\nexport class FileTile extends BaseMessageTile {\n constructor(entry, options) {\n super(entry, options);\n this._downloadError = null;\n this._downloading = false;\n }\n\n async download() {\n if (this._downloading || this.isPending) {\n return;\n }\n const content = this._getContent();\n const filename = content.body;\n this._downloading = true;\n this.emitChange(\"label\");\n let blob;\n try {\n blob = await this._mediaRepository.downloadAttachment(content);\n this.platform.saveFileAs(blob, filename);\n } catch (err) {\n this._downloadError = err;\n } finally {\n blob?.dispose();\n this._downloading = false;\n }\n this.emitChange(\"label\");\n }\n\n get label() {\n if (this._downloadError) {\n return `Could not download file: ${this._downloadError.message}`;\n }\n const content = this._getContent();\n const filename = content.body;\n\n if (this._entry.isPending) {\n const {pendingEvent} = this._entry;\n switch (pendingEvent?.status) {\n case SendStatus.Waiting:\n return this.i18n`Waiting to send ${filename}…`;\n case SendStatus.EncryptingAttachments:\n case SendStatus.Encrypting:\n return this.i18n`Encrypting ${filename}…`;\n case SendStatus.UploadingAttachments:{\n const percent = Math.round((pendingEvent.attachmentsSentBytes / pendingEvent.attachmentsTotalBytes) * 100);\n return this.i18n`Uploading ${filename}: ${percent}%`;\n }\n case SendStatus.Sending:\n case SendStatus.Sent:\n return this.i18n`Sending ${filename}…`;\n case SendStatus.Error:\n return this.i18n`Error: could not send ${filename}: ${pendingEvent.error.message}`;\n default:\n return `Unknown send status for ${filename}`;\n }\n } else {\n const size = formatSize(this._getContent().info?.size);\n if (this._downloading) {\n return this.i18n`Downloading ${filename} (${size})…`;\n } else {\n return this.i18n`Download ${filename} (${size})`;\n } \n }\n }\n\n get shape() {\n return \"file\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageTile} from \"./BaseMessageTile.js\";\n\nexport class LocationTile extends BaseMessageTile {\n get shape() {\n return \"location\";\n }\n\n get mapsLink() {\n try {\n const url = new URL(this._getContent().geo_uri);\n if (url.protocol !== \"geo:\") {\n return \"\";\n }\n const [locationStr, ...namedParams] = url.pathname.split(\";\");\n const [latStr, longStr] = locationStr.split(\",\");\n const lat = parseFloat(latStr);\n const long = parseFloat(longStr);\n let uncertainty;\n for (const namedParam of namedParams) {\n const [name, value] = namedParam.split(\"=\");\n if (name === \"u\") {\n uncertainty = parseFloat(value);\n }\n }\n if (this.platform.isIOS) {\n return `http://maps.apple.com/?ll=${lat},${long}`;\n } else {\n let uri = `geo:${lat},${long}`;\n if (uncertainty) {\n uri = uri + `;u=${uncertainty}`;\n }\n return uri;\n }\n } catch {\n return \"\";\n }\n }\n\n get label() {\n return this.i18n`${this.displayName} sent their location`;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SimpleTile} from \"./SimpleTile.js\";\n\nexport class RoomNameTile extends SimpleTile {\n \n get shape() {\n return \"announcement\";\n }\n\n get announcement() {\n const content = this._entry.content;\n return `${this._entry.displayName || this._entry.sender} named the room \"${content?.name}\"`\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SimpleTile} from \"./SimpleTile.js\";\n\nexport class RoomMemberTile extends SimpleTile {\n\n get shape() {\n return \"announcement\";\n }\n\n get announcement() {\n const {sender, content, prevContent, stateKey} = this._entry;\n const senderName = this._entry.displayName || sender;\n const targetName = sender === stateKey ? senderName : (this._entry.content?.displayname || stateKey);\n const membership = content && content.membership;\n const prevMembership = prevContent && prevContent.membership;\n\n if (prevMembership === \"join\" && membership === \"join\") {\n if (content.avatar_url !== prevContent.avatar_url) {\n return `${senderName} changed their avatar`; \n } else if (content.displayname !== prevContent.displayname) {\n if (!content.displayname) {\n return `${stateKey} removed their name (${prevContent.displayname})`;\n }\n return `${prevContent.displayname ?? stateKey} changed their name to ${content.displayname}`; \n }\n } else if (membership === \"join\") {\n return `${targetName} joined the room`;\n } else if (membership === \"invite\") {\n return `${targetName} was invited to the room by ${senderName}`;\n } else if (prevMembership === \"invite\") {\n if (membership === \"join\") {\n return `${targetName} accepted the invitation to join the room`;\n } else if (membership === \"leave\") {\n return `${targetName} declined the invitation to join the room`;\n }\n } else if (membership === \"leave\") {\n if (stateKey === sender) {\n return `${targetName} left the room`;\n } else {\n const reason = content.reason;\n return `${targetName} was kicked from the room by ${senderName}${reason ? `: ${reason}` : \"\"}`;\n }\n } else if (membership === \"ban\") {\n return `${targetName} was banned from the room by ${senderName}`;\n }\n \n return `${sender} membership changed to ${content.membership}`;\n }\n}\n\nexport function tests() {\n return {\n \"user removes display name\": (assert) => {\n const tile = new RoomMemberTile(\n {\n prevContent: {displayname: \"foo\", membership: \"join\"},\n content: {membership: \"join\"},\n stateKey: \"foo@bar.com\",\n },\n {}\n );\n assert.strictEqual(tile.announcement, \"foo@bar.com removed their name (foo)\");\n },\n \"user without display name sets a new display name\": (assert) => {\n const tile = new RoomMemberTile(\n {\n prevContent: {membership: \"join\"},\n content: {displayname: \"foo\", membership: \"join\" },\n stateKey: \"foo@bar.com\",\n },\n {}\n );\n assert.strictEqual(tile.announcement, \"foo@bar.com changed their name to foo\");\n },\n };\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseTextTile} from \"./BaseTextTile.js\";\nimport {UpdateAction} from \"../UpdateAction.js\";\n\nexport class EncryptedEventTile extends BaseTextTile {\n updateEntry(entry, params) {\n const parentResult = super.updateEntry(entry, params);\n // event got decrypted, recreate the tile and replace this one with it\n if (entry.eventType !== \"m.room.encrypted\") {\n // the \"shape\" parameter trigger tile recreation in TimelineView\n return UpdateAction.Replace(\"shape\");\n } else {\n return parentResult;\n }\n }\n\n get shape() {\n return \"message-status\"\n }\n\n _getBody() {\n const decryptionError = this._entry.decryptionError;\n const code = decryptionError?.code;\n let string;\n if (code === \"MEGOLM_NO_SESSION\") {\n string = this.i18n`The sender hasn't sent us the key for this message yet.`;\n } else {\n string = decryptionError?.message || this.i18n`Could not decrypt message because of unknown reason.`;\n }\n return string;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SimpleTile} from \"./SimpleTile.js\";\n\nexport class EncryptionEnabledTile extends SimpleTile {\n get shape() {\n return \"announcement\";\n }\n\n get announcement() {\n const senderName = this._entry.displayName || this._entry.sender;\n return this.i18n`${senderName} has enabled end-to-end encryption`;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageTile} from \"./BaseMessageTile.js\";\n\nexport class MissingAttachmentTile extends BaseMessageTile {\n get shape() {\n return \"missing-attachment\"\n }\n\n get label() {\n const name = this._getContent().body;\n const msgtype = this._getContent().msgtype;\n if (msgtype === \"m.image\") {\n return this.i18n`The image ${name} wasn't fully sent previously and could not be recovered.`;\n } else {\n return this.i18n`The file ${name} wasn't fully sent previously and could not be recovered.`;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {GapTile} from \"./GapTile.js\";\nimport {TextTile} from \"./TextTile.js\";\nimport {RedactedTile} from \"./RedactedTile.js\";\nimport {ImageTile} from \"./ImageTile.js\";\nimport {VideoTile} from \"./VideoTile.js\";\nimport {FileTile} from \"./FileTile.js\";\nimport {LocationTile} from \"./LocationTile.js\";\nimport {RoomNameTile} from \"./RoomNameTile.js\";\nimport {RoomMemberTile} from \"./RoomMemberTile.js\";\nimport {EncryptedEventTile} from \"./EncryptedEventTile.js\";\nimport {EncryptionEnabledTile} from \"./EncryptionEnabledTile.js\";\nimport {MissingAttachmentTile} from \"./MissingAttachmentTile.js\";\n\nimport type {SimpleTile} from \"./SimpleTile.js\";\nimport type {Room} from \"../../../../../matrix/room/Room\";\nimport type {Timeline} from \"../../../../../matrix/room/timeline/Timeline\";\nimport type {FragmentBoundaryEntry} from \"../../../../../matrix/room/timeline/entries/FragmentBoundaryEntry\";\nimport type {EventEntry} from \"../../../../../matrix/room/timeline/entries/EventEntry\";\nimport type {PendingEventEntry} from \"../../../../../matrix/room/timeline/entries/PendingEventEntry\";\nimport type {Options as ViewModelOptions} from \"../../../../ViewModel\";\n\nexport type TimelineEntry = FragmentBoundaryEntry | EventEntry | PendingEventEntry;\nexport type TileClassForEntryFn = (entry: TimelineEntry) => TileConstructor | undefined;\nexport type Options = ViewModelOptions & {\n room: Room,\n timeline: Timeline\n tileClassForEntry: TileClassForEntryFn;\n};\nexport type TileConstructor = new (entry: TimelineEntry, options: Options) => SimpleTile;\n\nexport function tileClassForEntry(entry: TimelineEntry): TileConstructor | undefined {\n if (entry.isGap) {\n return GapTile;\n } else if (entry.isPending && entry.pendingEvent.isMissingAttachments) {\n return MissingAttachmentTile;\n } else if (entry.eventType) {\n switch (entry.eventType) {\n case \"m.room.message\": {\n if (entry.isRedacted) {\n return RedactedTile;\n }\n const content = entry.content;\n const msgtype = content && content.msgtype;\n switch (msgtype) {\n case \"m.text\":\n case \"m.notice\":\n case \"m.emote\":\n return TextTile;\n case \"m.image\":\n return ImageTile;\n case \"m.video\":\n return VideoTile;\n case \"m.file\":\n return FileTile;\n case \"m.location\":\n return LocationTile;\n default:\n // unknown msgtype not rendered\n return undefined;\n }\n }\n case \"m.room.name\":\n return RoomNameTile;\n case \"m.room.member\":\n return RoomMemberTile;\n case \"m.room.encrypted\":\n if (entry.isRedacted) {\n return RedactedTile;\n }\n return EncryptedEventTile;\n case \"m.room.encryption\":\n return EncryptionEnabledTile;\n default:\n // unknown type not rendered\n return undefined;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TimelineViewModel} from \"./timeline/TimelineViewModel.js\";\nimport {ComposerViewModel} from \"./ComposerViewModel.js\"\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\nimport {ViewModel} from \"../../ViewModel\";\nimport {imageToInfo} from \"../common.js\";\n// TODO: remove fallback so default isn't included in bundle for SDK users that have their custom tileClassForEntry\n// this is a breaking SDK change though to make this option mandatory\nimport {tileClassForEntry as defaultTileClassForEntry} from \"./timeline/tiles/index\";\nimport {RoomStatus} from \"../../../matrix/room/common\";\n\nexport class RoomViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {room, tileClassForEntry} = options;\n this._room = room;\n this._timelineVM = null;\n this._tileClassForEntry = tileClassForEntry ?? defaultTileClassForEntry;\n this._tileOptions = undefined;\n this._onRoomChange = this._onRoomChange.bind(this);\n this._timelineError = null;\n this._sendError = null;\n this._composerVM = null;\n if (room.isArchived) {\n this._composerVM = this.track(new ArchivedViewModel(this.childOptions({archivedRoom: room})));\n } else {\n this._recreateComposerOnPowerLevelChange();\n }\n this._clearUnreadTimout = null;\n this._closeUrl = this.urlCreator.urlUntilSegment(\"session\");\n }\n\n async load() {\n this._room.on(\"change\", this._onRoomChange);\n try {\n const timeline = await this._room.openTimeline();\n this._tileOptions = this.childOptions({\n roomVM: this,\n timeline,\n tileClassForEntry: this._tileClassForEntry,\n });\n this._timelineVM = this.track(new TimelineViewModel(this.childOptions({\n tileOptions: this._tileOptions,\n timeline,\n })));\n this.emitChange(\"timelineViewModel\");\n } catch (err) {\n console.error(`room.openTimeline(): ${err.message}:\\n${err.stack}`);\n this._timelineError = err;\n this.emitChange(\"error\");\n }\n this._clearUnreadAfterDelay();\n }\n\n async _recreateComposerOnPowerLevelChange() {\n const powerLevelObservable = await this._room.observePowerLevels();\n const canSendMessage = () => powerLevelObservable.get().canSendType(\"m.room.message\");\n let oldCanSendMessage = canSendMessage();\n const recreateComposer = newCanSendMessage => {\n this._composerVM = this.disposeTracked(this._composerVM);\n if (newCanSendMessage) {\n this._composerVM = this.track(new ComposerViewModel(this));\n }\n else {\n this._composerVM = this.track(new LowerPowerLevelViewModel(this.childOptions()));\n }\n this.emitChange(\"powerLevelObservable\")\n };\n this.track(powerLevelObservable.subscribe(() => {\n const newCanSendMessage = canSendMessage();\n if (oldCanSendMessage !== newCanSendMessage) {\n recreateComposer(newCanSendMessage);\n oldCanSendMessage = newCanSendMessage;\n }\n }));\n recreateComposer(oldCanSendMessage);\n }\n\n async _clearUnreadAfterDelay() {\n if (this._room.isArchived || this._clearUnreadTimout) {\n return;\n }\n this._clearUnreadTimout = this.clock.createTimeout(2000);\n try {\n await this._clearUnreadTimout.elapsed();\n await this._room.clearUnread();\n this._clearUnreadTimout = null;\n } catch (err) {\n if (err.name !== \"AbortError\") {\n throw err;\n }\n }\n }\n\n focus() {\n this._clearUnreadAfterDelay();\n }\n\n dispose() {\n super.dispose();\n this._room.off(\"change\", this._onRoomChange);\n if (this._room.isArchived) {\n this._room.release();\n }\n if (this._clearUnreadTimout) {\n this._clearUnreadTimout.abort();\n this._clearUnreadTimout = null;\n }\n }\n\n // room doesn't tell us yet which fields changed,\n // so emit all fields originating from summary\n _onRoomChange() {\n // propagate the update to the child view models so it's bindings can update based on room changes\n this._composerVM.emitChange();\n this.emitChange();\n }\n\n get kind() { return \"room\"; }\n get closeUrl() { return this._closeUrl; }\n get name() { return this._room.name || this.i18n`Empty Room`; }\n get id() { return this._room.id; }\n get timelineViewModel() { return this._timelineVM; }\n get isEncrypted() { return this._room.isEncrypted; }\n\n get error() {\n if (this._timelineError) {\n return `Something went wrong loading the timeline: ${this._timelineError.message}`;\n }\n if (this._sendError) {\n return `Something went wrong sending your message: ${this._sendError.message}`;\n }\n return \"\";\n }\n\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._room.avatarColorId)\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._room.avatarUrl, size, this.platform, this._room.mediaRepository);\n }\n\n get avatarTitle() {\n return this.name;\n }\n\n get canLeave() {\n return this._room.isJoined;\n }\n\n leaveRoom() {\n this._room.leave();\n }\n\n get canForget() {\n return this._room.isArchived;\n }\n\n forgetRoom() {\n this._room.forget();\n }\n\n get canRejoin() {\n return this._room.isArchived;\n }\n\n rejoinRoom() {\n this._room.join();\n }\n\n _createTile(entry) {\n if (this._tileOptions) {\n const Tile = this._tileOptions.tileClassForEntry(entry);\n if (Tile) {\n return new Tile(entry, this._tileOptions);\n }\n }\n }\n \n async _processCommandJoin(roomName) {\n try {\n const roomId = await this._options.client.session.joinRoom(roomName);\n const roomStatusObserver = await this._options.client.session.observeRoomStatus(roomId);\n await roomStatusObserver.waitFor(status => status === RoomStatus.Joined);\n this.navigation.push(\"room\", roomId);\n } catch (err) {\n let exc;\n if ((err.statusCode ?? err.status) === 400) {\n exc = new Error(`/join : '${roomName}' was not legal room ID or room alias`);\n } else if ((err.statusCode ?? err.status) === 404 || (err.statusCode ?? err.status) === 502 || err.message == \"Internal Server Error\") {\n exc = new Error(`/join : room '${roomName}' not found`);\n } else if ((err.statusCode ?? err.status) === 403) {\n exc = new Error(`/join : you're not invited to join '${roomName}'`);\n } else {\n exc = err;\n }\n this._sendError = exc;\n this._timelineError = null;\n this.emitChange(\"error\");\n }\n } \n\n async _processCommand (message) {\n let msgtype;\n const [commandName, ...args] = message.substring(1).split(\" \");\n switch (commandName) {\n case \"me\":\n message = args.join(\" \");\n msgtype = \"m.emote\";\n break;\n case \"join\":\n if (args.length === 1) {\n const roomName = args[0];\n await this._processCommandJoin(roomName);\n } else {\n this._sendError = new Error(\"join syntax: /join \");\n this._timelineError = null;\n this.emitChange(\"error\");\n }\n break;\n case \"shrug\":\n message = \"¯\\\\_(ツ)_/¯ \" + args.join(\" \");\n msgtype = \"m.text\";\n break;\n case \"tableflip\":\n message = \"(╯°□°)╯︵ ┻━┻ \" + args.join(\" \");\n msgtype = \"m.text\";\n break;\n case \"unflip\":\n message = \"┬──┬ ノ( ゜-゜ノ) \" + args.join(\" \");\n msgtype = \"m.text\";\n break;\n case \"lenny\":\n message = \"( ͡° ͜ʖ ͡°) \" + args.join(\" \");\n msgtype = \"m.text\";\n break;\n default:\n this._sendError = new Error(`no command name \"${commandName}\". To send the message instead of executing, please type \"/${message}\"`);\n this._timelineError = null;\n this.emitChange(\"error\");\n message = undefined;\n }\n return {type: msgtype, message: message};\n }\n \n async _sendMessage(message, replyingTo) {\n if (!this._room.isArchived && message) {\n let messinfo = {type : \"m.text\", message : message};\n if (message.startsWith(\"//\")) {\n messinfo.message = message.substring(1).trim();\n } else if (message.startsWith(\"/\")) {\n messinfo = await this._processCommand(message);\n }\n try {\n const msgtype = messinfo.type;\n const message = messinfo.message;\n if (msgtype && message) {\n if (replyingTo) {\n await replyingTo.reply(msgtype, message);\n } else {\n await this._room.sendEvent(\"m.room.message\", {msgtype, body: message});\n }\n }\n } catch (err) {\n console.error(`room.sendMessage(): ${err.message}:\\n${err.stack}`);\n this._sendError = err;\n this._timelineError = null;\n this.emitChange(\"error\");\n return false;\n }\n return true;\n }\n return false;\n }\n\n async _pickAndSendFile() {\n try {\n const file = await this.platform.openFile();\n if (!file) {\n return;\n }\n return this._sendFile(file);\n } catch (err) {\n console.error(err);\n }\n }\n\n async _sendFile(file) {\n const content = {\n body: file.name,\n msgtype: \"m.file\"\n };\n await this._room.sendEvent(\"m.room.message\", content, {\n \"url\": this._room.createAttachment(file.blob, file.name)\n });\n }\n\n async _pickAndSendVideo() {\n try {\n if (!this.platform.hasReadPixelPermission()) {\n alert(\"Please allow canvas image data access, so we can scale your images down.\");\n return;\n }\n const file = await this.platform.openFile(\"video/*\");\n if (!file) {\n return;\n }\n if (!file.blob.mimeType.startsWith(\"video/\")) {\n return this._sendFile(file);\n }\n let video;\n try {\n video = await this.platform.loadVideo(file.blob);\n } catch (err) {\n // TODO: extract platform dependent code from view model\n if (err instanceof window.MediaError && err.code === 4) {\n throw new Error(`this browser does not support videos of type ${file?.blob.mimeType}.`);\n } else {\n throw err;\n }\n }\n const content = {\n body: file.name,\n msgtype: \"m.video\",\n info: videoToInfo(video)\n };\n const attachments = {\n \"url\": this._room.createAttachment(video.blob, file.name),\n };\n\n const limit = await this.platform.settingsStorage.getInt(\"sentImageSizeLimit\");\n const maxDimension = limit || Math.min(video.maxDimension, 800);\n const thumbnail = await video.scale(maxDimension);\n content.info.thumbnail_info = imageToInfo(thumbnail);\n attachments[\"info.thumbnail_url\"] = \n this._room.createAttachment(thumbnail.blob, file.name);\n await this._room.sendEvent(\"m.room.message\", content, attachments);\n } catch (err) {\n this._sendError = err;\n this.emitChange(\"error\");\n console.error(err.stack);\n }\n }\n\n async _pickAndSendPicture() {\n try {\n if (!this.platform.hasReadPixelPermission()) {\n alert(\"Please allow canvas image data access, so we can scale your images down.\");\n return;\n }\n const file = await this.platform.openFile(\"image/*\");\n if (!file) {\n return;\n }\n if (!file.blob.mimeType.startsWith(\"image/\")) {\n return this._sendFile(file);\n }\n let image = await this.platform.loadImage(file.blob);\n const limit = await this.platform.settingsStorage.getInt(\"sentImageSizeLimit\");\n if (limit && image.maxDimension > limit) {\n const scaledImage = await image.scale(limit);\n image.dispose();\n image = scaledImage;\n }\n const content = {\n body: file.name,\n msgtype: \"m.image\",\n info: imageToInfo(image)\n };\n const attachments = {\n \"url\": this._room.createAttachment(image.blob, file.name),\n };\n if (image.maxDimension > 600) {\n const thumbnail = await image.scale(400);\n content.info.thumbnail_info = imageToInfo(thumbnail);\n attachments[\"info.thumbnail_url\"] = \n this._room.createAttachment(thumbnail.blob, file.name);\n }\n await this._room.sendEvent(\"m.room.message\", content, attachments);\n } catch (err) {\n this._sendError = err;\n this.emitChange(\"error\");\n console.error(err.stack);\n }\n }\n\n get room() {\n return this._room;\n }\n\n get composerViewModel() {\n return this._composerVM;\n }\n\n openDetailsPanel() {\n let path = this.navigation.path.until(\"room\");\n path = path.with(this.navigation.segment(\"right-panel\", true));\n path = path.with(this.navigation.segment(\"details\", true));\n this.navigation.applyPath(path);\n }\n\n startReply(entry) {\n if (!this._room.isArchived) {\n this._composerVM.setReplyingTo(entry);\n }\n }\n \n dismissError() {\n this._sendError = null;\n this.emitChange(\"error\");\n }\n}\n\nfunction videoToInfo(video) {\n const info = imageToInfo(video);\n info.duration = video.duration;\n return info;\n}\n\nclass ArchivedViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._archivedRoom = options.archivedRoom;\n }\n\n get description() {\n if (this._archivedRoom.isKicked) {\n if (this._archivedRoom.kickReason) {\n return this.i18n`You were kicked from the room by ${this._archivedRoom.kickedBy.name} because: ${this._archivedRoom.kickReason}`;\n } else {\n return this.i18n`You were kicked from the room by ${this._archivedRoom.kickedBy.name}.`;\n }\n } else if (this._archivedRoom.isBanned) {\n if (this._archivedRoom.kickReason) {\n return this.i18n`You were banned from the room by ${this._archivedRoom.kickedBy.name} because: ${this._archivedRoom.kickReason}`;\n } else {\n return this.i18n`You were banned from the room by ${this._archivedRoom.kickedBy.name}.`;\n }\n } else {\n return this.i18n`You left this room`;\n }\n }\n\n get kind() {\n return \"disabled\";\n }\n}\n\nclass LowerPowerLevelViewModel extends ViewModel {\n get description() {\n return this.i18n`You do not have the powerlevel necessary to send messages`;\n }\n\n get kind() {\n return \"disabled\";\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\n\nexport class UnknownRoomViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {roomIdOrAlias, session} = options;\n this._session = session;\n this.roomIdOrAlias = roomIdOrAlias;\n this._error = null;\n this._busy = false;\n }\n\n get error() {\n return this._error?.message;\n }\n\n async join() {\n this._busy = true;\n this.emitChange(\"busy\");\n try {\n const roomId = await this._session.joinRoom(this.roomIdOrAlias);\n // navigate to roomId if we were at the alias\n // so we're subscribed to the right room status\n // and we'll switch to the room view model once\n // the join is synced\n this.navigation.push(\"room\", roomId);\n // keep busy on true while waiting for the join to sync\n } catch (err) {\n this._error = err;\n this._busy = false;\n this.emitChange(\"error\");\n }\n }\n\n get busy() {\n return this._busy;\n }\n\n get kind() {\n return \"unknown\";\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\nimport {ViewModel} from \"../../ViewModel\";\n\nexport class InviteViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {invite, mediaRepository} = options;\n this._invite = invite;\n this._mediaRepository = mediaRepository;\n this._onInviteChange = this._onInviteChange.bind(this);\n this._error = null;\n this._closeUrl = this.urlCreator.urlUntilSegment(\"session\");\n this._invite.on(\"change\", this._onInviteChange);\n this._inviter = null;\n if (this._invite.inviter) {\n this._inviter = new RoomMemberViewModel(this._invite.inviter, mediaRepository, this.platform);\n }\n this._roomDescription = this._createRoomDescription();\n }\n\n get kind() { return \"invite\"; }\n get closeUrl() { return this._closeUrl; }\n get name() { return this._invite.name; }\n get id() { return this._invite.id; }\n get isEncrypted() { return this._invite.isEncrypted; }\n get isDirectMessage() { return this._invite.isDirectMessage; }\n get inviter() { return this._inviter; }\n get busy() { return this._invite.accepting || this._invite.rejecting; }\n\n get error() {\n if (this._error) {\n return `Something went wrong: ${this._error.message}`;\n }\n return \"\";\n }\n\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._invite.avatarColorId)\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._invite.avatarUrl, size, this.platform, this._mediaRepository);\n }\n\n _createRoomDescription() {\n const parts = [];\n if (this._invite.isPublic) {\n parts.push(\"Public room\");\n } else {\n parts.push(\"Private room\");\n }\n\n if (this._invite.canonicalAlias) {\n parts.push(this._invite.canonicalAlias);\n }\n return parts.join(\" • \")\n }\n\n get roomDescription() {\n return this._roomDescription;\n }\n\n get avatarTitle() {\n return this.name;\n }\n\n focus() {}\n\n async accept() {\n try {\n await this._invite.accept();\n } catch (err) {\n this._error = err;\n this.emitChange(\"error\");\n }\n }\n\n async reject() {\n try {\n await this._invite.reject();\n } catch (err) {\n this._error = err;\n this.emitChange(\"error\");\n }\n }\n\n _onInviteChange() {\n this.emitChange();\n }\n\n dispose() {\n super.dispose();\n this._invite.off(\"change\", this._onInviteChange);\n }\n}\n\nclass RoomMemberViewModel {\n constructor(member, mediaRepository, platform) {\n this._member = member;\n this._mediaRepository = mediaRepository;\n this._platform = platform;\n }\n\n get id() {\n return this._member.userId;\n }\n\n get name() {\n return this._member.name;\n }\n\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._member.userId);\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._member.avatarUrl, size, this._platform, this._mediaRepository);\n }\n\n get avatarTitle() {\n return this.name;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020, 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\nimport {ViewModel} from \"../../ViewModel\";\n\nexport class RoomBeingCreatedViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {roomBeingCreated, mediaRepository} = options;\n this._roomBeingCreated = roomBeingCreated;\n this._mediaRepository = mediaRepository;\n this._onRoomChange = this._onRoomChange.bind(this);\n this._closeUrl = this.urlCreator.urlUntilSegment(\"session\");\n this._roomBeingCreated.on(\"change\", this._onRoomChange);\n }\n\n get kind() { return \"roomBeingCreated\"; }\n get closeUrl() { return this._closeUrl; }\n get name() { return this._roomBeingCreated.name; }\n get id() { return this._roomBeingCreated.id; }\n get isEncrypted() { return this._roomBeingCreated.isEncrypted; }\n get error() {\n const {error} = this._roomBeingCreated;\n if (error) {\n if (error.name === \"ConnectionError\") {\n return this.i18n`You seem to be offline`;\n } else {\n return error.message;\n }\n }\n return \"\";\n }\n get avatarLetter() { return avatarInitials(this.name); }\n get avatarColorNumber() { return getIdentifierColorNumber(this._roomBeingCreated.avatarColorId); }\n get avatarTitle() { return this.name; }\n\n avatarUrl(size) {\n // allow blob url which doesn't need mxc => http resolution\n return this._roomBeingCreated.avatarBlobUrl ??\n getAvatarHttpUrl(this._roomBeingCreated.avatarUrl, size, this.platform, this._mediaRepository);\n }\n\n focus() {}\n\n _onRoomChange() {\n this.emitChange();\n }\n\n cancel() {\n this._roomBeingCreated.cancel();\n // navigate away from the room\n this.navigation.applyPath(this.navigation.path.until(\"session\"));\n }\n\n dispose() {\n super.dispose();\n this._roomBeingCreated.off(\"change\", this._onRoomChange);\n }\n}\n\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\n\nexport class LightboxViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._eventId = options.eventId;\n this._unencryptedImageUrl = null;\n this._decryptedImage = null;\n this._closeUrl = this.urlCreator.urlUntilSegment(\"room\");\n this._eventEntry = null;\n this._date = null;\n this._subscribeToEvent(options.room, options.eventId);\n }\n\n _subscribeToEvent(room, eventId) {\n const eventObservable = room.observeEvent(eventId);\n this.track(eventObservable.subscribe(eventEntry => {\n this._loadEvent(room, eventEntry);\n }));\n this._loadEvent(room, eventObservable.get());\n }\n\n async _loadEvent(room, eventEntry) {\n if (!eventEntry) {\n return;\n }\n const {mediaRepository} = room;\n this._eventEntry = eventEntry;\n const {content} = this._eventEntry;\n this._date = this._eventEntry.timestamp ? new Date(this._eventEntry.timestamp) : null;\n if (content.url) {\n this._unencryptedImageUrl = mediaRepository.mxcUrl(content.url);\n this.emitChange(\"imageUrl\");\n } else if (content.file) {\n this._decryptedImage = this.track(await mediaRepository.downloadEncryptedFile(content.file));\n this.emitChange(\"imageUrl\");\n }\n }\n\n get imageWidth() {\n return this._eventEntry?.content?.info?.w;\n }\n\n get imageHeight() {\n return this._eventEntry?.content?.info?.h;\n }\n\n get name() {\n return this._eventEntry?.content?.body;\n }\n\n get sender() {\n return this._eventEntry?.displayName;\n }\n\n get imageUrl() {\n if (this._decryptedImage) {\n return this._decryptedImage.url;\n } else if (this._unencryptedImageUrl) {\n return this._unencryptedImageUrl;\n } else {\n return \"\";\n }\n }\n\n get date() {\n return this._date && this._date.toLocaleDateString({}, { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' });\n }\n\n get time() {\n return this._date && this._date.toLocaleTimeString({}, {hour: \"numeric\", minute: \"2-digit\"});\n }\n\n get closeUrl() {\n return this._closeUrl;\n }\n\n close() {\n this.platform.history.pushUrl(this.closeUrl);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../ViewModel\";\nimport {createEnum} from \"../../utils/enum\";\nimport {ConnectionStatus} from \"../../matrix/net/Reconnector\";\nimport {SyncStatus} from \"../../matrix/Sync.js\";\n\nconst SessionStatus = createEnum(\n \"Disconnected\",\n \"Connecting\",\n \"FirstSync\",\n \"Sending\",\n \"Syncing\",\n \"SyncError\"\n);\n\nexport class SessionStatusViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {sync, reconnector, session} = options;\n this._sync = sync;\n this._reconnector = reconnector;\n this._status = this._calculateState(reconnector.connectionStatus.get(), sync.status.get());\n this._session = session;\n this._setupKeyBackupUrl = this.urlCreator.urlForSegment(\"settings\");\n this._dismissSecretStorage = false;\n }\n\n start() {\n const update = () => this._updateStatus();\n this.track(this._sync.status.subscribe(update));\n this.track(this._reconnector.connectionStatus.subscribe(update));\n this.track(this._session.needsKeyBackup.subscribe(() => {\n this.emitChange();\n }));\n }\n\n get setupKeyBackupUrl () {\n return this._setupKeyBackupUrl;\n }\n\n get isShown() {\n return (this._session.needsKeyBackup.get() && !this._dismissSecretStorage) || this._status !== SessionStatus.Syncing;\n }\n\n get statusLabel() {\n switch (this._status) {\n case SessionStatus.Disconnected:{\n const retryIn = Math.round(this._reconnector.retryIn / 1000);\n return this.i18n`Disconnected, trying to reconnect in ${retryIn}s…`;\n }\n case SessionStatus.Connecting:\n return this.i18n`Trying to reconnect now…`;\n case SessionStatus.FirstSync:\n return this.i18n`Catching up with your conversations…`;\n case SessionStatus.SyncError:\n return this.i18n`Sync failed because of ${this._sync.error}`;\n }\n if (this._session.needsKeyBackup.get()) {\n return this.i18n`Set up session backup to decrypt older messages.`;\n }\n return \"\";\n }\n\n get isWaiting() {\n switch (this._status) {\n case SessionStatus.Connecting:\n case SessionStatus.FirstSync:\n return true;\n default:\n return false;\n }\n }\n\n _updateStatus() {\n const newStatus = this._calculateState(\n this._reconnector.connectionStatus.get(),\n this._sync.status.get()\n );\n if (newStatus !== this._status) {\n if (newStatus === SessionStatus.Disconnected) {\n this._retryTimer = this.track(this.clock.createInterval(() => {\n this.emitChange(\"statusLabel\");\n }, 1000));\n } else {\n this._retryTimer = this.disposeTracked(this._retryTimer);\n }\n this._status = newStatus;\n this.emitChange();\n }\n }\n\n _calculateState(connectionStatus, syncStatus) {\n if (connectionStatus !== ConnectionStatus.Online) {\n switch (connectionStatus) {\n case ConnectionStatus.Reconnecting:\n return SessionStatus.Connecting;\n case ConnectionStatus.Waiting:\n return SessionStatus.Disconnected;\n }\n } else if (syncStatus !== SyncStatus.Syncing) {\n switch (syncStatus) {\n // InitialSync should be awaited in the SessionLoadViewModel,\n // but include it here anyway\n case SyncStatus.InitialSync:\n case SyncStatus.CatchupSync:\n return SessionStatus.FirstSync;\n case SyncStatus.Stopped:\n return SessionStatus.SyncError;\n }\n } /* else if (session.pendingMessageCount) {\n return SessionStatus.Sending;\n } */ else {\n return SessionStatus.Syncing;\n }\n }\n\n get isConnectNowShown() {\n return this._status === SessionStatus.Disconnected;\n }\n\n get isSecretStorageShown() {\n // TODO: we need a model here where we can have multiple messages queued up and their buttons don't bleed into each other.\n return this._status === SessionStatus.Syncing && this._session.needsKeyBackup.get() && !this._dismissSecretStorage;\n }\n\n get canDismiss() {\n return this.isSecretStorageShown;\n }\n\n dismiss() {\n if (this.isSecretStorageShown) {\n this._dismissSecretStorage = true;\n this.emitChange();\n }\n }\n\n connectNow() {\n if (this.isConnectNowShown) {\n this._reconnector.tryNow();\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../ViewModel\";\nimport {addPanelIfNeeded} from \"../navigation/index\";\n\nfunction dedupeSparse(roomIds) {\n return roomIds.map((id, idx) => {\n if (roomIds.slice(0, idx).includes(id)) {\n return undefined;\n } else {\n return id;\n }\n });\n}\n\nexport class RoomGridViewModel extends ViewModel {\n constructor(options) {\n super(options);\n\n this._width = options.width;\n this._height = options.height;\n this._createRoomViewModelObservable = options.createRoomViewModelObservable;\n this._selectedIndex = 0;\n this._viewModelsObservables = [];\n this._setupNavigation();\n }\n\n _setupNavigation() {\n const focusTileIndex = this.navigation.observe(\"empty-grid-tile\");\n this.track(focusTileIndex.subscribe(index => {\n if (typeof index === \"number\") {\n this._setFocusIndex(index);\n }\n }));\n if (typeof focusTileIndex.get() === \"number\") {\n this._selectedIndex = focusTileIndex.get();\n }\n\n const focusedRoom = this.navigation.observe(\"room\");\n this.track(focusedRoom.subscribe(roomId => {\n if (roomId) {\n // as the room will be in the \"rooms\" observable\n // (monitored by the parent vmo) as well,\n // we only change the focus here and trust\n // setRoomIds to have created the vmo already\n this._setFocusRoom(roomId);\n }\n }));\n // initial focus for a room is set by initializeRoomIdsAndTransferVM\n }\n\n roomViewModelAt(i) {\n return this._viewModelsObservables[i]?.get();\n }\n\n get focusIndex() {\n return this._selectedIndex;\n }\n\n get width() {\n return this._width;\n }\n\n get height() {\n return this._height;\n }\n\n _switchToRoom(roomId) {\n let path = this.navigation.path.until(\"rooms\");\n path = path.with(this.navigation.segment(\"room\", roomId));\n path = addPanelIfNeeded(this.navigation, path);\n this.navigation.applyPath(path);\n }\n\n focusTile(index) {\n if (index === this._selectedIndex) {\n return;\n }\n const vmo = this._viewModelsObservables[index];\n if (vmo) {\n this._switchToRoom(vmo.id);\n } else {\n this.navigation.push(\"empty-grid-tile\", index);\n }\n }\n\n /** called from SessionViewModel */\n initializeRoomIdsAndTransferVM(roomIds, existingRoomVM) {\n roomIds = dedupeSparse(roomIds);\n let transfered = false;\n if (existingRoomVM) {\n const index = roomIds.indexOf(existingRoomVM.id);\n if (index !== -1) {\n this._viewModelsObservables[index] = this.track(existingRoomVM);\n existingRoomVM.subscribe(viewModel => this._refreshRoomViewModel(viewModel));\n transfered = true;\n }\n }\n this.setRoomIds(roomIds);\n // now all view models exist, set the focus to the selected room\n const focusedRoom = this.navigation.path.get(\"room\");\n if (focusedRoom) {\n const index = this._viewModelsObservables.findIndex(vmo => vmo && vmo.id === focusedRoom.value);\n if (index !== -1) {\n this._selectedIndex = index;\n }\n }\n return transfered;\n }\n\n /** called from SessionViewModel */\n setRoomIds(roomIds) {\n roomIds = dedupeSparse(roomIds);\n let changed = false;\n const len = this._height * this._width;\n for (let i = 0; i < len; i += 1) {\n const newId = roomIds[i];\n const vmo = this._viewModelsObservables[i];\n // did anything change?\n if ((!vmo && newId) || (vmo && vmo.id !== newId)) {\n if (vmo) {\n this._viewModelsObservables[i] = this.disposeTracked(vmo);\n }\n if (newId) {\n const vmo = this._createRoomViewModelObservable(newId);\n this._viewModelsObservables[i] = this.track(vmo);\n vmo.subscribe(viewModel => this._refreshRoomViewModel(viewModel));\n vmo.initialize();\n }\n changed = true;\n }\n }\n if (changed) {\n this.emitChange();\n }\n return changed;\n }\n\n _refreshRoomViewModel(viewModel) {\n this.emitChange();\n viewModel?.focus();\n }\n\n /** called from SessionViewModel */\n releaseRoomViewModel(roomId) {\n const index = this._viewModelsObservables.findIndex(vmo => vmo && vmo.id === roomId);\n if (index !== -1) {\n const vmo = this._viewModelsObservables[index];\n this.untrack(vmo);\n vmo.unsubscribeAll();\n this._viewModelsObservables[index] = null;\n return vmo;\n }\n }\n\n _setFocusIndex(idx) {\n if (idx === this._selectedIndex || idx >= (this._width * this._height)) {\n return;\n }\n this._selectedIndex = idx;\n const vmo = this._viewModelsObservables[this._selectedIndex];\n vmo?.get()?.focus();\n this.emitChange(\"focusIndex\");\n }\n\n _setFocusRoom(roomId) {\n const index = this._viewModelsObservables.findIndex(vmo => vmo?.id === roomId);\n if (index >= 0) {\n this._setFocusIndex(index);\n }\n }\n}\n\nimport {createNavigation} from \"../navigation/index\";\nimport {ObservableValue} from \"../../observable/ObservableValue\";\n\nexport function tests() { \n class RoomVMMock {\n constructor(id) {\n this.id = id;\n this.disposed = false;\n this.focused = false;\n }\n dispose() {\n this.disposed = true;\n }\n focus() {\n this.focused = true;\n }\n }\n\n class RoomViewModelObservableMock extends ObservableValue {\n async initialize() {}\n dispose() { this.get()?.dispose(); }\n get id() { return this.get()?.id; }\n }\n\n function createNavigationForRoom(rooms, room) {\n const navigation = createNavigation();\n navigation.applyPath(navigation.pathFrom([\n navigation.segment(\"session\", \"1\"),\n navigation.segment(\"rooms\", rooms),\n navigation.segment(\"room\", room),\n ]));\n return navigation;\n }\n\n function createNavigationForEmptyTile(rooms, idx) {\n const navigation = createNavigation();\n navigation.applyPath(navigation.pathFrom([\n navigation.segment(\"session\", \"1\"),\n navigation.segment(\"rooms\", rooms),\n navigation.segment(\"empty-grid-tile\", idx),\n ]));\n return navigation;\n }\n\n return {\n \"initialize with duplicate set of rooms\": assert => {\n const navigation = createNavigationForRoom([\"c\", \"a\", \"b\", undefined, \"a\"], \"a\");\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: id => new RoomViewModelObservableMock(new RoomVMMock(id)),\n navigation,\n width: 3,\n height: 2,\n });\n gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value);\n assert.equal(gridVM.focusIndex, 1);\n assert.equal(gridVM.roomViewModelAt(0).id, \"c\");\n assert.equal(gridVM.roomViewModelAt(1).id, \"a\");\n assert.equal(gridVM.roomViewModelAt(2).id, \"b\");\n assert.equal(gridVM.roomViewModelAt(3), undefined);\n assert.equal(gridVM.roomViewModelAt(4), undefined);\n assert.equal(gridVM.roomViewModelAt(5), undefined);\n },\n \"transfer room view model\": assert => {\n const navigation = createNavigationForRoom([\"a\"], \"a\");\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: () => assert.fail(\"no vms should be created\"),\n navigation,\n width: 3,\n height: 2,\n });\n const existingRoomVM = new RoomViewModelObservableMock(new RoomVMMock(\"a\"));\n const transfered = gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value, existingRoomVM);\n assert.equal(transfered, true);\n assert.equal(gridVM.focusIndex, 0);\n assert.equal(gridVM.roomViewModelAt(0).id, \"a\");\n },\n \"reject transfer for non-matching room view model\": assert => {\n const navigation = createNavigationForRoom([\"a\"], \"a\");\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: id => new RoomViewModelObservableMock(new RoomVMMock(id)),\n navigation,\n width: 3,\n height: 2,\n });\n const existingRoomVM = new RoomViewModelObservableMock(new RoomVMMock(\"f\"));\n const transfered = gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value, existingRoomVM);\n assert.equal(transfered, false);\n assert.equal(gridVM.focusIndex, 0);\n assert.equal(gridVM.roomViewModelAt(0).id, \"a\");\n },\n \"created & released room view model is not disposed\": assert => {\n const navigation = createNavigationForRoom([\"a\"], \"a\");\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: id => new RoomViewModelObservableMock(new RoomVMMock(id)),\n navigation,\n width: 3,\n height: 2,\n });\n const transfered = gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value);\n assert.equal(transfered, false);\n const releasedVM = gridVM.releaseRoomViewModel(\"a\");\n gridVM.dispose();\n assert.equal(releasedVM.get().disposed, false);\n },\n \"transfered & released room view model is not disposed\": assert => {\n const navigation = createNavigationForRoom([undefined, \"a\"], \"a\");\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: () => assert.fail(\"no vms should be created\"),\n navigation,\n width: 3,\n height: 2,\n });\n const existingRoomVM = new RoomViewModelObservableMock(new RoomVMMock(\"a\"));\n const transfered = gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value, existingRoomVM);\n assert.equal(transfered, true);\n const releasedVM = gridVM.releaseRoomViewModel(\"a\");\n gridVM.dispose();\n assert.equal(releasedVM.get().disposed, false);\n },\n \"try release non-existing room view model is\": assert => {\n const navigation = createNavigationForEmptyTile([undefined, \"b\"], 3);\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: id => new RoomViewModelObservableMock(new RoomVMMock(id)),\n navigation,\n width: 3,\n height: 2,\n });\n gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value);\n const releasedVM = gridVM.releaseRoomViewModel(\"c\");\n assert(!releasedVM);\n },\n \"initial focus is set to empty tile\": assert => {\n const navigation = createNavigationForEmptyTile([\"a\"], 1);\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: id => new RoomViewModelObservableMock(new RoomVMMock(id)),\n navigation,\n width: 3,\n height: 2,\n });\n gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value);\n assert.equal(gridVM.focusIndex, 1);\n assert.equal(gridVM.roomViewModelAt(0).id, \"a\");\n },\n \"change room ids after creation\": assert => {\n const navigation = createNavigationForRoom([\"a\", \"b\"], \"a\");\n const gridVM = new RoomGridViewModel({\n createRoomViewModelObservable: id => new RoomViewModelObservableMock(new RoomVMMock(id)),\n navigation,\n width: 3,\n height: 2,\n });\n navigation.observe(\"rooms\").subscribe(roomIds => {\n gridVM.setRoomIds(roomIds);\n });\n gridVM.initializeRoomIdsAndTransferVM(navigation.path.get(\"rooms\").value);\n const oldA = gridVM.roomViewModelAt(0);\n const oldB = gridVM.roomViewModelAt(1);\n assert.equal(oldA.id, \"a\");\n assert.equal(oldB.id, \"b\");\n navigation.applyPath(navigation.path\n .with(navigation.segment(\"rooms\", [\"b\", \"c\", \"b\"]))\n .with(navigation.segment(\"room\", \"c\"))\n );\n assert.equal(oldA.disposed, true);\n assert.equal(oldB.disposed, true);\n assert.equal(gridVM.focusIndex, 1);\n assert.equal(gridVM.roomViewModelAt(0).id, \"b\");\n assert.equal(gridVM.roomViewModelAt(0).disposed, false);\n assert.equal(gridVM.roomViewModelAt(1).id, \"c\");\n assert.equal(gridVM.roomViewModelAt(1).focused, true);\n assert.equal(gridVM.roomViewModelAt(2), undefined);\n }\n };\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {KeyType} from \"../../../matrix/ssss/index\";\nimport {createEnum} from \"../../../utils/enum\";\n\nexport const Status = createEnum(\"Enabled\", \"SetupKey\", \"SetupPhrase\", \"Pending\", \"NewVersionAvailable\"); \nexport const BackupWriteStatus = createEnum(\"Writing\", \"Stopped\", \"Done\", \"Pending\"); \n\nexport class KeyBackupViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._session = options.session;\n this._error = null;\n this._isBusy = false;\n this._dehydratedDeviceId = undefined;\n this._status = undefined;\n this._backupOperation = this._session.keyBackup.flatMap(keyBackup => keyBackup.operationInProgress);\n this._progress = this._backupOperation.flatMap(op => op.progress);\n this.track(this._backupOperation.subscribe(() => {\n // see if needsNewKey might be set\n this._reevaluateStatus();\n this.emitChange(\"isBackingUp\");\n }));\n this.track(this._progress.subscribe(() => this.emitChange(\"backupPercentage\")));\n this._reevaluateStatus();\n this.track(this._session.keyBackup.subscribe(() => {\n if (this._reevaluateStatus()) {\n this.emitChange(\"status\");\n }\n }));\n }\n\n _reevaluateStatus() {\n if (this._isBusy) {\n return false;\n }\n let status;\n const keyBackup = this._session.keyBackup.get();\n if (keyBackup) {\n status = keyBackup.needsNewKey ? Status.NewVersionAvailable : Status.Enabled;\n } else if (keyBackup === null) {\n status = this.showPhraseSetup() ? Status.SetupPhrase : Status.SetupKey;\n } else {\n status = Status.Pending;\n }\n const changed = status !== this._status;\n this._status = status;\n return changed;\n }\n\n get decryptAction() {\n return this.i18n`Set up`;\n }\n\n get purpose() {\n return this.i18n`set up key backup`;\n }\n\n offerDehydratedDeviceSetup() {\n return true;\n }\n\n get dehydratedDeviceId() {\n return this._dehydratedDeviceId;\n }\n \n get isBusy() {\n return this._isBusy;\n }\n\n get backupVersion() {\n return this._session.keyBackup.get()?.version;\n }\n\n get backupWriteStatus() {\n const keyBackup = this._session.keyBackup.get();\n if (!keyBackup) {\n return BackupWriteStatus.Pending;\n } else if (keyBackup.hasStopped) {\n return BackupWriteStatus.Stopped;\n }\n const operation = keyBackup.operationInProgress.get();\n if (operation) {\n return BackupWriteStatus.Writing;\n } else if (keyBackup.hasBackedUpAllKeys) {\n return BackupWriteStatus.Done;\n } else {\n return BackupWriteStatus.Pending;\n }\n }\n\n get backupError() {\n return this._session.keyBackup.get()?.error?.message;\n }\n\n get status() {\n return this._status;\n }\n\n get error() {\n return this._error?.message;\n }\n\n showPhraseSetup() {\n if (this._status === Status.SetupKey) {\n this._status = Status.SetupPhrase;\n this.emitChange(\"status\");\n }\n }\n\n showKeySetup() {\n if (this._status === Status.SetupPhrase) {\n this._status = Status.SetupKey;\n this.emitChange(\"status\");\n }\n }\n\n async _enterCredentials(keyType, credential, setupDehydratedDevice) {\n if (credential) {\n try {\n this._isBusy = true;\n this.emitChange(\"isBusy\");\n const key = await this._session.enableSecretStorage(keyType, credential);\n if (setupDehydratedDevice) {\n this._dehydratedDeviceId = await this._session.setupDehydratedDevice(key);\n }\n } catch (err) {\n console.error(err);\n this._error = err;\n this.emitChange(\"error\");\n } finally {\n this._isBusy = false;\n this._reevaluateStatus();\n this.emitChange(\"\");\n }\n }\n }\n\n enterSecurityPhrase(passphrase, setupDehydratedDevice) {\n this._enterCredentials(KeyType.Passphrase, passphrase, setupDehydratedDevice);\n }\n\n enterSecurityKey(securityKey, setupDehydratedDevice) {\n this._enterCredentials(KeyType.RecoveryKey, securityKey, setupDehydratedDevice);\n }\n\n async disable() {\n try {\n this._isBusy = true;\n this.emitChange(\"isBusy\");\n await this._session.disableSecretStorage();\n } catch (err) {\n console.error(err);\n this._error = err;\n this.emitChange(\"error\");\n } finally {\n this._isBusy = false;\n this._reevaluateStatus();\n this.emitChange(\"\");\n }\n }\n\n get isBackingUp() {\n return !!this._backupOperation.get();\n }\n\n get backupPercentage() {\n const progress = this._progress.get();\n if (progress) {\n return Math.round((progress.finished / progress.total) * 100);\n }\n return 0;\n }\n\n get backupInProgressLabel() {\n const progress = this._progress.get();\n if (progress) {\n return this.i18n`${progress.finished} of ${progress.total}`;\n }\n return this.i18n`…`;\n }\n\n cancelBackup() {\n this._backupOperation.get()?.abort();\n }\n\n startBackup() {\n this._session.keyBackup.get()?.flush();\n }\n}\n\n","/*\nCopyright 2022 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {BlobHandle} from \"../platform/web/dom/BlobHandle\";\nimport type {RequestFunction} from \"../platform/types/types\";\n\n// see https://github.com/matrix-org/rageshake#readme\ntype RageshakeData = {\n // A textual description of the problem. Included in the details.log.gz file.\n text: string | undefined;\n // Application user-agent. Included in the details.log.gz file.\n userAgent: string;\n // Identifier for the application (eg 'riot-web'). Should correspond to a mapping configured in the configuration file for github issue reporting to work.\n app: string;\n // Application version. Included in the details.log.gz file.\n version: string;\n // Label to attach to the github issue, and include in the details file.\n label: string | undefined;\n};\n\nexport async function submitLogsToRageshakeServer(data: RageshakeData, logsBlob: BlobHandle, submitUrl: string, request: RequestFunction): Promise {\n const formData = new Map();\n if (data.text) {\n formData.set(\"text\", data.text);\n }\n formData.set(\"user_agent\", data.userAgent);\n formData.set(\"app\", data.app);\n formData.set(\"version\", data.version);\n if (data.label) {\n formData.set(\"label\", data.label);\n }\n formData.set(\"file\", {name: \"logs.json\", blob: logsBlob});\n const headers: Map = new Map();\n headers.set(\"Accept\", \"application/json\");\n const result = request(submitUrl, {\n method: \"POST\",\n body: formData,\n headers\n });\n let response;\n try {\n response = await result.response();\n } catch (err) {\n throw new Error(`Could not submit logs to ${submitUrl}, got error ${err.message}`);\n }\n const {status, body} = response;\n if (status < 200 || status >= 300) {\n throw new Error(`Could not submit logs to ${submitUrl}, got status code ${status} with body ${body}`);\n }\n // we don't bother with reading report_url from the body as the rageshake server doesn't always return it\n // and would have to have CORS setup properly for us to be able to read it.\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {KeyBackupViewModel} from \"./KeyBackupViewModel.js\";\nimport {submitLogsToRageshakeServer} from \"../../../domain/rageshake\";\n\nclass PushNotificationStatus {\n constructor() {\n this.supported = null;\n this.enabled = false;\n this.updating = false;\n this.enabledOnServer = null;\n this.serverError = null;\n }\n}\n\nfunction formatKey(key) {\n const partLength = 4;\n const partCount = Math.ceil(key.length / partLength);\n let formattedKey = \"\";\n for (let i = 0; i < partCount; i += 1) {\n formattedKey += (formattedKey.length ? \" \" : \"\") + key.slice(i * partLength, (i + 1) * partLength);\n }\n return formattedKey;\n}\n\nexport class SettingsViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._updateService = options.updateService;\n const {client} = options;\n this._client = client;\n this._keyBackupViewModel = this.track(new KeyBackupViewModel(this.childOptions({session: this._session})));\n this._closeUrl = this.urlCreator.urlUntilSegment(\"session\");\n this._estimate = null;\n this.sentImageSizeLimit = null;\n this.minSentImageSizeLimit = 400;\n this.maxSentImageSizeLimit = 4000;\n this.pushNotifications = new PushNotificationStatus();\n this._activeTheme = undefined;\n this._logsFeedbackMessage = undefined;\n }\n\n get _session() {\n return this._client.session;\n }\n\n async logout() {\n this.navigation.push(\"logout\", this._client.sessionId);\n }\n\n setSentImageSizeLimit(size) {\n if (size > this.maxSentImageSizeLimit || size < this.minSentImageSizeLimit) {\n this.sentImageSizeLimit = null;\n this.platform.settingsStorage.remove(\"sentImageSizeLimit\");\n } else {\n this.sentImageSizeLimit = Math.round(size);\n this.platform.settingsStorage.setInt(\"sentImageSizeLimit\", size);\n }\n this.emitChange(\"sentImageSizeLimit\");\n }\n\n async load() {\n this._estimate = await this.platform.estimateStorageUsage();\n this.sentImageSizeLimit = await this.platform.settingsStorage.getInt(\"sentImageSizeLimit\");\n this.pushNotifications.supported = await this.platform.notificationService.supportsPush();\n this.pushNotifications.enabled = await this._session.arePushNotificationsEnabled();\n if (!import.meta.env.DEV) {\n this._activeTheme = await this.platform.themeLoader.getActiveTheme();\n }\n this.emitChange(\"\");\n }\n\n get closeUrl() {\n return this._closeUrl;\n }\n\n get fingerprintKey() {\n const key = this._session.fingerprintKey;\n if (!key) {\n return null;\n }\n return formatKey(key);\n }\n\n get deviceId() {\n return this._session.deviceId;\n }\n\n get userId() {\n return this._session.userId;\n }\n\n get version() {\n const {updateService} = this.platform; \n if (updateService) {\n return `${updateService.version} (${updateService.buildHash})`;\n }\n return this.i18n`development version`;\n }\n\n checkForUpdate() {\n this.platform.updateService?.checkForUpdate();\n }\n\n get showUpdateButton() {\n return !!this.platform.updateService;\n }\n\n get keyBackupViewModel() {\n return this._keyBackupViewModel;\n }\n\n get storageQuota() {\n return this._formatBytes(this._estimate?.quota);\n }\n\n get storageUsage() {\n return this._formatBytes(this._estimate?.usage);\n }\n\n get themeMapping() {\n return this.platform.themeLoader.themeMapping;\n }\n\n get activeTheme() {\n return this._activeTheme;\n }\n\n _formatBytes(n) {\n if (typeof n === \"number\") {\n return Math.round(n / (1024 * 1024)).toFixed(1) + \" MB\";\n } else {\n return this.i18n`unknown`;\n }\n }\n\n async exportLogs() {\n const logExport = await this.logger.export();\n this.platform.saveFileAs(logExport.asBlob(), `hydrogen-logs-${this.platform.clock.now()}.json`);\n }\n\n get canSendLogsToServer() {\n return !!this.platform.config.bugReportEndpointUrl;\n }\n\n get logsServer() {\n const {bugReportEndpointUrl} = this.platform.config;\n try {\n if (bugReportEndpointUrl) {\n return new URL(bugReportEndpointUrl).hostname;\n }\n } catch (e) {}\n return \"\";\n }\n\n async sendLogsToServer() {\n const {bugReportEndpointUrl} = this.platform.config;\n if (bugReportEndpointUrl) {\n this._logsFeedbackMessage = this.i18n`Sending logs…`;\n this.emitChange();\n try {\n const logExport = await this.logger.export();\n await submitLogsToRageshakeServer(\n {\n app: \"hydrogen\",\n userAgent: this.platform.description,\n version: DEFINE_VERSION,\n text: `Submit logs from settings for user ${this._session.userId} on device ${this._session.deviceId}`,\n },\n logExport.asBlob(),\n bugReportEndpointUrl,\n this.platform.request\n );\n this._logsFeedbackMessage = this.i18n`Logs sent succesfully!`;\n this.emitChange();\n } catch (err) {\n this._logsFeedbackMessage = err.message;\n this.emitChange();\n }\n }\n }\n\n get logsFeedbackMessage() {\n return this._logsFeedbackMessage;\n }\n\n async togglePushNotifications() {\n this.pushNotifications.updating = true;\n this.pushNotifications.enabledOnServer = null;\n this.pushNotifications.serverError = null;\n this.emitChange(\"pushNotifications.updating\");\n try {\n if (await this._session.enablePushNotifications(!this.pushNotifications.enabled)) {\n this.pushNotifications.enabled = !this.pushNotifications.enabled;\n if (this.pushNotifications.enabled) {\n this.platform.notificationService.showNotification(this.i18n`Push notifications are now enabled`);\n }\n }\n } finally {\n this.pushNotifications.updating = false;\n this.emitChange(\"pushNotifications.updating\");\n }\n }\n\n async checkPushEnabledOnServer() {\n this.pushNotifications.enabledOnServer = null;\n this.pushNotifications.serverError = null;\n try {\n this.pushNotifications.enabledOnServer = await this._session.checkPusherEnabledOnHomeserver();\n this.emitChange(\"pushNotifications.enabledOnServer\");\n } catch (err) {\n this.pushNotifications.serverError = err;\n this.emitChange(\"pushNotifications.serverError\");\n }\n }\n\n changeThemeOption(themeName, themeVariant) {\n this.platform.themeLoader.setTheme(themeName, themeVariant);\n // emit so that radio-buttons become displayed/hidden\n this.emitChange(\"themeOption\");\n }\n}\n\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../ViewModel\";\nimport {imageToInfo} from \"./common.js\";\nimport {RoomType} from \"../../matrix/room/common\";\n\nexport class CreateRoomViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {session} = options;\n this._session = session;\n this._name = undefined;\n this._topic = undefined;\n this._roomAlias = undefined;\n this._isPublic = false;\n this._isEncrypted = true;\n this._isAdvancedShown = false;\n this._isFederationDisabled = false;\n this._avatarScaledBlob = undefined;\n this._avatarFileName = undefined;\n this._avatarInfo = undefined;\n }\n\n get isPublic() { return this._isPublic; }\n get isEncrypted() { return this._isEncrypted; }\n get canCreate() { return !!this._name; }\n avatarUrl() { return this._avatarScaledBlob.url; }\n get avatarTitle() { return this._name; }\n get avatarLetter() { return \"\"; }\n get avatarColorNumber() { return 0; }\n get hasAvatar() { return !!this._avatarScaledBlob; }\n get isFederationDisabled() { return this._isFederationDisabled; }\n get isAdvancedShown() { return this._isAdvancedShown; }\n\n setName(name) {\n this._name = name;\n this.emitChange(\"canCreate\");\n }\n\n setRoomAlias(roomAlias) {\n this._roomAlias = roomAlias;\n }\n\n setTopic(topic) {\n this._topic = topic;\n }\n\n setPublic(isPublic) {\n this._isPublic = isPublic;\n this.emitChange(\"isPublic\");\n }\n\n setEncrypted(isEncrypted) {\n this._isEncrypted = isEncrypted;\n this.emitChange(\"isEncrypted\");\n }\n\n setFederationDisabled(disable) {\n this._isFederationDisabled = disable;\n this.emitChange(\"isFederationDisabled\");\n }\n\n toggleAdvancedShown() {\n this._isAdvancedShown = !this._isAdvancedShown;\n this.emitChange(\"isAdvancedShown\");\n }\n\n create() {\n let avatar;\n if (this._avatarScaledBlob) {\n avatar = {\n info: this._avatarInfo,\n name: this._avatarFileName,\n blob: this._avatarScaledBlob\n }\n }\n const roomBeingCreated = this._session.createRoom({\n type: this.isPublic ? RoomType.Public : RoomType.Private,\n name: this._name ?? undefined,\n topic: this._topic ?? undefined,\n isEncrypted: !this.isPublic && this._isEncrypted,\n isFederationDisabled: this._isFederationDisabled,\n alias: this.isPublic ? ensureAliasIsLocalPart(this._roomAlias) : undefined,\n avatar,\n });\n this.navigation.push(\"room\", roomBeingCreated.id);\n }\n\n async selectAvatar() {\n if (!this.platform.hasReadPixelPermission()) {\n alert(\"Please allow canvas image data access, so we can scale your images down.\");\n return;\n }\n if (this._avatarScaledBlob) {\n this._avatarScaledBlob.dispose();\n }\n this._avatarScaledBlob = undefined;\n this._avatarFileName = undefined;\n this._avatarInfo = undefined;\n\n const file = await this.platform.openFile(\"image/*\");\n if (!file || !file.blob.mimeType.startsWith(\"image/\")) {\n // allow to clear the avatar by not selecting an image\n this.emitChange(\"hasAvatar\");\n return;\n }\n let image = await this.platform.loadImage(file.blob);\n const limit = 800;\n if (image.maxDimension > limit) {\n const scaledImage = await image.scale(limit);\n image.dispose();\n image = scaledImage;\n }\n this._avatarScaledBlob = image.blob;\n this._avatarInfo = imageToInfo(image);\n this._avatarFileName = file.name;\n this.emitChange(\"hasAvatar\");\n }\n}\n\nfunction ensureAliasIsLocalPart(roomAliasLocalPart) {\n if (roomAliasLocalPart.startsWith(\"#\")) {\n roomAliasLocalPart = roomAliasLocalPart.substr(1);\n }\n const colonIdx = roomAliasLocalPart.indexOf(\":\");\n if (colonIdx !== -1) {\n roomAliasLocalPart = roomAliasLocalPart.substr(0, colonIdx);\n }\n return roomAliasLocalPart;\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ObservableValue} from \"../../observable/ObservableValue\";\nimport {RoomStatus} from \"../../matrix/room/common\";\n\n/**\nDepending on the status of a room (invited, joined, archived, or none),\nwe want to show a different view with a different view model\nwhen showing a room. Furthermore, this logic is needed both in the \nsingle room view and in the grid view. So this logic is extracted here,\nand this observable updates with the right view model as the status for\na room changes.\n\nTo not have to track the subscription manually in the SessionViewModel and\nthe RoomGridViewModel, all subscriptions are removed in the dispose method.\nOnly when transferring a RoomViewModelObservable between the SessionViewModel\nand RoomGridViewModel, unsubscribeAll should be called prior to doing\nthe transfer, so either parent view model don't keep getting updates for\nthe now transferred child view model.\n\nThis is also why there is an explicit initialize method, see comment there.\n*/\nexport class RoomViewModelObservable extends ObservableValue {\n constructor(sessionViewModel, roomIdOrLocalId) {\n super(null);\n this._statusSubscription = null;\n this._sessionViewModel = sessionViewModel;\n this.id = roomIdOrLocalId;\n }\n\n /**\n Separate initialize method rather than doing this onSubscribeFirst because \n we don't want to run this again when transferring this value between\n SessionViewModel and RoomGridViewModel, as onUnsubscribeLast and onSubscribeFirst\n are called in that case.\n */\n async initialize() {\n const {session} = this._sessionViewModel._client;\n const statusObservable = await session.observeRoomStatus(this.id);\n this.set(await this._statusToViewModel(statusObservable.get()));\n this._statusSubscription = statusObservable.subscribe(async status => {\n // first dispose existing VM, if any\n this.get()?.dispose();\n this.set(await this._statusToViewModel(status));\n });\n }\n\n async _statusToViewModel(status) {\n if (status & RoomStatus.Replaced) {\n if (status & RoomStatus.BeingCreated) {\n const {session} = this._sessionViewModel._client;\n const roomBeingCreated = session.roomsBeingCreated.get(this.id);\n this._sessionViewModel.notifyRoomReplaced(roomBeingCreated.id, roomBeingCreated.roomId);\n } else {\n throw new Error(\"Don't know how to replace a room with this status: \" + (status ^ RoomStatus.Replaced));\n }\n } else if (status & RoomStatus.BeingCreated) {\n return this._sessionViewModel._createRoomBeingCreatedViewModel(this.id);\n } else if (status & RoomStatus.Invited) {\n return this._sessionViewModel._createInviteViewModel(this.id);\n } else if (status & RoomStatus.Joined) {\n return this._sessionViewModel._createRoomViewModelInstance(this.id);\n } else if (status & RoomStatus.Archived) {\n return await this._sessionViewModel._createArchivedRoomViewModel(this.id);\n } else {\n return this._sessionViewModel._createUnknownRoomViewModel(this.id);\n }\n }\n\n dispose() {\n if (this._statusSubscription) {\n this._statusSubscription = this._statusSubscription();\n }\n this.unsubscribeAll();\n this.get()?.dispose();\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\n\nexport class RoomDetailsViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._room = options.room;\n this._onRoomChange = this._onRoomChange.bind(this);\n this._room.on(\"change\", this._onRoomChange);\n }\n\n get type() {\n return \"room-details\";\n }\n\n get shouldShowBackButton() {\n return false;\n }\n\n get previousSegmentName() {\n return false;\n }\n\n get roomId() {\n return this._room.id;\n }\n\n get canonicalAlias() {\n return this._room.canonicalAlias;\n }\n\n get name() {\n return this._room.name;\n }\n\n get isEncrypted() {\n return !!this._room.isEncrypted;\n }\n\n get memberCount() {\n return this._room.joinedMemberCount;\n }\n\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._room.avatarColorId)\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._room.avatarUrl, size, this.platform, this._room.mediaRepository);\n }\n\n get avatarTitle() {\n return this.name;\n }\n\n _onRoomChange() {\n this.emitChange();\n }\n\n dispose() {\n super.dispose();\n this._room.off(\"change\", this._onRoomChange);\n }\n\n openPanel(segment) {\n let path = this.navigation.path.until(\"room\");\n path = path.with(this.navigation.segment(\"right-panel\", true));\n path = path.with(this.navigation.segment(segment, true));\n this.navigation.applyPath(path);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\n\nexport class MemberTileViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._member = this._options.member;\n this._mediaRepository = options.mediaRepository\n this._previousName = null;\n this._nameChanged = true;\n }\n\n get name() {\n return `${this._member.name}${this._disambiguationPart}`;\n }\n\n get _disambiguationPart() {\n return this._disambiguate ? ` (${this.userId})` : \"\";\n }\n\n get userId() {\n return this._member.userId;\n }\n\n get previousName() {\n return this._previousName;\n }\n\n get nameChanged() {\n return this._nameChanged;\n }\n\n get detailsUrl() {\n const roomId = this.navigation.path.get(\"room\").value;\n return `${this.urlCreator.openRoomActionUrl(roomId)}/member/${this._member.userId}`;\n }\n\n _updatePreviousName(newName) {\n const currentName = this._member.name;\n if (currentName !== newName) {\n this._previousName = currentName;\n this._nameChanged = true;\n } else {\n this._nameChanged = false;\n }\n }\n\n setDisambiguation(status) {\n this._disambiguate = status;\n this.emitChange();\n }\n\n updateFrom(newMember) {\n this._updatePreviousName(newMember.name);\n this._member = newMember;\n }\n\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this.userId)\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._member.avatarUrl, size, this.platform, this._mediaRepository);\n }\n\n get avatarTitle() {\n return this.name;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {PowerLevels} from \"../../../../matrix/room/PowerLevels.js\";\n\nexport function createMemberComparator(powerLevels) {\n const collator = new Intl.Collator();\n const removeCharacter = string => string.charAt(0) === \"@\"? string.slice(1) : string;\n\n return function comparator(member, otherMember) {\n const p1 = powerLevels.getUserLevel(member.userId);\n const p2 = powerLevels.getUserLevel(otherMember.userId);\n if (p1 !== p2) { return p2 - p1; }\n const name = removeCharacter(member.name);\n const otherName = removeCharacter(otherMember.name);\n return collator.compare(name, otherName);\n };\n}\n\nexport function tests() {\n\n function createComparatorWithPowerLevel(map) {\n let users = {};\n for (const prop in map) {\n Object.assign(users, {[prop]: map[prop]});\n }\n const powerLevelEvent = {\n content: {users, users_default: 0}\n };\n return createMemberComparator(new PowerLevels({powerLevelEvent}));\n }\n\n return {\n \"power_level(member1) > power_level(member2) returns value <= 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@alice:hs.tld\": 50});\n const member1 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n const member2 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n assert.strictEqual(fn(member1, member2) <= 0, true);\n },\n\n \"power_level(member1) < power_level(member2) returns value > 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@alice:hs.tld\": 50});\n const member1 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n const member2 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n assert.strictEqual(fn(member1, member2) > 0, true);\n },\n\n \"alphabetic compare on name\": assert => {\n const fn = createComparatorWithPowerLevel();\n const member1 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n const member2 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n assert.strictEqual(fn(member1, member2) > 0, true);\n assert.strictEqual(fn(member2, member1) <= 0, true);\n },\n\n \"alphabetic compare with case (alice comes before Bob)\": assert => {\n const fn = createComparatorWithPowerLevel();\n const member1 = {userId: \"@bob:hs.tld\", name: \"Bob\"};\n const member2 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n assert.strictEqual(fn(member1, member2) > 0, true);\n assert.strictEqual(fn(member2, member1) <= 0, true);\n },\n\n \"equal powerlevel and same names returns 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@bobby:hs.tld\": 50, \"@bob:hs.tld\": 50});\n const member1 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n const member2 = {userId: \"@bobby:hs.tld\", name: \"bob\"};\n assert.strictEqual(fn(member1, member2), 0);\n assert.strictEqual(fn(member2, member1), 0);\n },\n\n \"(both_negative_powerlevel) power_level(member1) < power_level(member2) returns value > 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@alice:hs.tld\": -100, \"@bob:hs.tld\": -50});\n const member1 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n const member2 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n assert.strictEqual(fn(member1, member2) > 0, true);\n },\n\n \"(both_negative_powerlevel) power_level(member1) > power_level(member2) returns value <= 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@alice:hs.tld\": -50, \"@bob:hs.tld\": -100});\n const member1 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n const member2 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n assert.strictEqual(fn(member1, member2) <= 0, true);\n },\n\n \"(one_negative_powerlevel) power_level(member1) > power_level(member2) returns value <= 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@alice:hs.tld\": 50, \"@bob:hs.tld\": -100});\n const member1 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n const member2 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n assert.strictEqual(fn(member1, member2) <= 0, true);\n },\n\n \"(one_negative_powerlevel) power_level(member1) < power_level(member2) returns value > 0\": assert => {\n const fn = createComparatorWithPowerLevel({\"@alice:hs.tld\": -100, \"@bob:hs.tld\": 50});\n const member1 = {userId: \"@alice:hs.tld\", name: \"alice\"};\n const member2 = {userId: \"@bob:hs.tld\", name: \"bob\"};\n assert.strictEqual(fn(member1, member2) > 0, true);\n },\n };\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class Disambiguator {\n constructor() {\n this._map = new Map();\n }\n\n _unDisambiguate(vm, array) {\n const idx = array.indexOf(vm);\n if (idx !== -1) {\n const [removed] = array.splice(idx, 1);\n removed.setDisambiguation(false);\n }\n }\n\n _handlePreviousName(vm) {\n const previousName = vm.previousName;\n if (typeof previousName !== \"string\") { return; }\n const value = this._map.get(previousName);\n if (Array.isArray(value)) {\n this._unDisambiguate(vm, value);\n if (value.length === 1) {\n const vm = value[0];\n vm.setDisambiguation(false);\n this._map.set(previousName, vm);\n }\n } else {\n this._map.delete(previousName);\n }\n }\n\n _updateMap(vm) {\n const name = vm.name;\n const value = this._map.get(name);\n if (value) {\n if (Array.isArray(value)) {\n if (value.findIndex(member => member.userId === vm.userId) !== -1) { return; }\n value.push(vm);\n return value;\n } else if(vm.userId !== value.userId) {\n const array = [value, vm]\n this._map.set(name, array);\n return array;\n }\n } else {\n this._map.set(name, vm);\n }\n }\n\n disambiguate(vm) {\n if (!vm.nameChanged) { return; }\n this._handlePreviousName(vm);\n const value = this._updateMap(vm);\n value?.forEach((vm) => vm.setDisambiguation(true));\n }\n}\n\nexport function tests(){\n\n class MockViewModel {\n constructor(name, userId) {\n this.name = name;\n this.disambiguate = false;\n this.userId = userId;\n this.nameChanged = true;\n }\n \n updateName(newName) {\n if (this.name !== newName) {\n this.previousName = this.name;\n this.nameChanged = true;\n }\n else {\n this.nameChanged = false;\n }\n this.name = newName;\n }\n\n setDisambiguation(status) {\n this.disambiguate = status;\n }\n }\n\n function createVmAndDisambiguator(nameList) {\n const d = new Disambiguator();\n const array = nameList.map(([name, id]) => new MockViewModel(name, id));\n return [...array, d];\n }\n\n return {\n \"Unique names\": assert => {\n const [vm1, vm2, d] = createVmAndDisambiguator([[\"foo\", \"a\"], [\"bar\", \"b\"]]);\n d.disambiguate(vm1);\n d.disambiguate(vm2);\n assert.strictEqual(vm1.disambiguate, false);\n assert.strictEqual(vm2.disambiguate, false);\n },\n\n \"Same names are disambiguated\": assert => {\n const [vm1, vm2, vm3, d] = createVmAndDisambiguator([[\"foo\", \"a\"], [\"foo\", \"b\"], [\"foo\", \"c\"]]);\n d.disambiguate(vm1);\n d.disambiguate(vm2);\n d.disambiguate(vm3);\n assert.strictEqual(vm1.disambiguate, true);\n assert.strictEqual(vm2.disambiguate, true);\n assert.strictEqual(vm3.disambiguate, true);\n },\n\n \"Name updates disambiguate\": assert => {\n const [vm1, vm2, vm3, d] = createVmAndDisambiguator([[\"foo\", \"a\"], [\"bar\", \"b\"], [\"jar\", \"c\"]]);\n d.disambiguate(vm1);\n d.disambiguate(vm2);\n d.disambiguate(vm3);\n \n vm2.updateName(\"foo\");\n d.disambiguate(vm2);\n assert.strictEqual(vm1.disambiguate, true);\n assert.strictEqual(vm2.disambiguate, true);\n\n vm1.updateName(\"bar\");\n d.disambiguate(vm1);\n assert.strictEqual(vm1.disambiguate, false);\n assert.strictEqual(vm2.disambiguate, false);\n\n vm3.updateName(\"foo\");\n d.disambiguate(vm3);\n vm1.updateName(\"foo\");\n d.disambiguate(vm1);\n assert.strictEqual(vm1.disambiguate, true);\n assert.strictEqual(vm2.disambiguate, true);\n assert.strictEqual(vm3.disambiguate, true);\n\n vm2.updateName(\"bar\");\n d.disambiguate(vm2);\n assert.strictEqual(vm1.disambiguate, true);\n assert.strictEqual(vm2.disambiguate, false);\n assert.strictEqual(vm3.disambiguate, true);\n },\n\n \"Multiple disambiguate events\": assert => {\n const [vm1, d] = createVmAndDisambiguator([[\"foo\", \"a\"]]);\n d.disambiguate(vm1);\n vm1.updateName(vm1.name);\n d.disambiguate(vm1);\n assert.strictEqual(vm1.disambiguate, false);\n },\n\n \"Empty names must un-disambiguate\": assert => {\n const [vm1, vm2, d] = createVmAndDisambiguator([[\"\", \"a\"], [\"\", \"b\"]]);\n d.disambiguate(vm1);\n d.disambiguate(vm2);\n vm1.updateName(\"foo\");\n d.disambiguate(vm1);\n assert.strictEqual(vm1.disambiguate, false);\n assert.strictEqual(vm2.disambiguate, false);\n }\n };\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {MemberTileViewModel} from \"./MemberTileViewModel.js\";\nimport {createMemberComparator} from \"./members/comparator.js\";\nimport {Disambiguator} from \"./members/disambiguator.js\";\n\nexport class MemberListViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const list = options.members;\n\n const powerLevelsObservable = options.powerLevelsObservable;\n this.track(powerLevelsObservable.subscribe(() => { /*resort based on new power levels here*/ }));\n\n const powerLevels = powerLevelsObservable.get();\n this.memberTileViewModels = this._mapTileViewModels(list.members.filterValues(member => member.membership === \"join\"))\n .sortValues(createMemberComparator(powerLevels));\n this.nameDisambiguator = new Disambiguator();\n this.mediaRepository = options.mediaRepository;\n }\n\n get type() { return \"member-list\"; }\n\n get shouldShowBackButton() { return true; }\n\n get previousSegmentName() { return \"details\"; }\n\n _mapTileViewModels(members) {\n const mapper = (member, emitChange) => {\n const mediaRepository = this.mediaRepository;\n const vm = new MemberTileViewModel(this.childOptions({member, emitChange, mediaRepository}));\n this.nameDisambiguator.disambiguate(vm);\n return vm;\n }\n const updater = (vm, params, newMember) => {\n vm.updateFrom(newMember);\n this.nameDisambiguator.disambiguate(vm);\n };\n return members.mapValues(mapper, updater);\n }\n\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {RoomType} from \"../../../matrix/room/common\";\nimport {avatarInitials, getIdentifierColorNumber, getAvatarHttpUrl} from \"../../avatar\";\n\nexport class MemberDetailsViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._observableMember = options.observableMember;\n this._mediaRepository = options.mediaRepository;\n this._member = this._observableMember.get();\n this._isEncrypted = options.isEncrypted;\n this._powerLevelsObservable = options.powerLevelsObservable;\n this._session = options.session;\n this.track(this._powerLevelsObservable.subscribe(() => this._onPowerLevelsChange()));\n this.track(this._observableMember.subscribe( () => this._onMemberChange()));\n }\n\n get name() { return this._member.name; }\n get userId() { return this._member.userId; }\n\n get type() { return \"member-details\"; }\n get shouldShowBackButton() { return true; }\n get previousSegmentName() { return \"members\"; }\n \n get role() {\n if (this.powerLevel >= 100) { return this.i18n`Admin`; }\n else if (this.powerLevel >= 50) { return this.i18n`Moderator`; }\n else if (this.powerLevel === 0) { return this.i18n`Default`; }\n else { return this.i18n`Custom (${this.powerLevel})`; }\n }\n\n _onMemberChange() {\n this._member = this._observableMember.get();\n this.emitChange(\"member\");\n }\n\n _onPowerLevelsChange() {\n this.emitChange(\"role\");\n }\n\n get avatarLetter() {\n return avatarInitials(this.name);\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this.userId)\n }\n\n avatarUrl(size) {\n return getAvatarHttpUrl(this._member.avatarUrl, size, this.platform, this._mediaRepository);\n }\n\n get avatarTitle() {\n return this.name;\n }\n\n get isEncrypted() {\n return this._isEncrypted;\n }\n\n get powerLevel() {\n return this._powerLevelsObservable.get()?.getUserLevel(this._member.userId);\n }\n\n get linkToUser() {\n return `https://matrix.to/#/${encodeURIComponent(this._member.userId)}`;\n }\n\n async openDirectMessage() {\n const room = this._session.findDirectMessageForUserId(this.userId);\n let roomId = room?.id;\n if (!roomId) {\n const roomBeingCreated = await this._session.createRoom({\n type: RoomType.DirectMessage,\n invites: [this.userId]\n });\n roomId = roomBeingCreated.id;\n }\n this.navigation.push(\"room\", roomId);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../../ViewModel\";\nimport {RoomDetailsViewModel} from \"./RoomDetailsViewModel.js\";\nimport {MemberListViewModel} from \"./MemberListViewModel.js\";\nimport {MemberDetailsViewModel} from \"./MemberDetailsViewModel.js\";\n\nexport class RightPanelViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._room = options.room;\n this._session = options.session;\n this._members = null;\n this._setupNavigation();\n }\n\n get activeViewModel() { return this._activeViewModel; }\n\n async _getMemberListArguments() {\n if (!this._members) {\n this._members = await this._room.loadMemberList();\n this.track(() => this._members.release());\n }\n const room = this._room;\n const powerLevelsObservable = await this._room.observePowerLevels();\n return {members: this._members, powerLevelsObservable, mediaRepository: room.mediaRepository};\n }\n\n async _getMemberDetailsArguments() {\n const segment = this.navigation.path.get(\"member\"); \n const userId = segment.value;\n const observableMember = await this._room.observeMember(userId);\n if (!observableMember) {\n return false;\n }\n const isEncrypted = this._room.isEncrypted;\n const powerLevelsObservable = await this._room.observePowerLevels();\n return {\n observableMember,\n isEncrypted,\n powerLevelsObservable,\n mediaRepository: this._room.mediaRepository,\n session: this._session\n };\n }\n\n _setupNavigation() {\n this._hookUpdaterToSegment(\"details\", RoomDetailsViewModel, () => { return {room: this._room}; });\n this._hookUpdaterToSegment(\"members\", MemberListViewModel, () => this._getMemberListArguments());\n this._hookUpdaterToSegment(\"member\", MemberDetailsViewModel, () => this._getMemberDetailsArguments(),\n () => {\n // If we fail to create the member details panel, fallback to memberlist\n const url = `${this.urlCreator.urlUntilSegment(\"room\")}/members`;\n this.urlCreator.pushUrl(url);\n }\n );\n }\n\n _hookUpdaterToSegment(segment, viewmodel, argCreator, failCallback) {\n const observable = this.navigation.observe(segment);\n const updater = this._setupUpdater(segment, viewmodel, argCreator, failCallback);\n this.track(observable.subscribe(updater));\n }\n\n _setupUpdater(segment, viewmodel, argCreator, failCallback) {\n const updater = async (skipDispose = false) => {\n if (!skipDispose) {\n this._activeViewModel = this.disposeTracked(this._activeViewModel);\n }\n const enable = !!this.navigation.path.get(segment)?.value;\n if (enable) {\n const args = await argCreator();\n if (!args && failCallback) {\n failCallback();\n return;\n }\n this._activeViewModel = this.track(new viewmodel(this.childOptions(args)));\n }\n this.emitChange(\"activeViewModel\");\n };\n updater(true);\n return updater;\n }\n\n closePanel() {\n const path = this.navigation.path.until(\"room\");\n this.navigation.applyPath(path);\n }\n\n showPreviousPanel() {\n const segmentName = this.activeViewModel.previousSegmentName;\n if (segmentName) {\n let path = this.navigation.path.until(\"room\");\n path = path.with(this.navigation.segment(\"right-panel\", true));\n path = path.with(this.navigation.segment(segmentName, true));\n this.navigation.applyPath(path);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {LeftPanelViewModel} from \"./leftpanel/LeftPanelViewModel.js\";\nimport {RoomViewModel} from \"./room/RoomViewModel.js\";\nimport {UnknownRoomViewModel} from \"./room/UnknownRoomViewModel.js\";\nimport {InviteViewModel} from \"./room/InviteViewModel.js\";\nimport {RoomBeingCreatedViewModel} from \"./room/RoomBeingCreatedViewModel.js\";\nimport {LightboxViewModel} from \"./room/LightboxViewModel.js\";\nimport {SessionStatusViewModel} from \"./SessionStatusViewModel.js\";\nimport {RoomGridViewModel} from \"./RoomGridViewModel.js\";\nimport {SettingsViewModel} from \"./settings/SettingsViewModel.js\";\nimport {CreateRoomViewModel} from \"./CreateRoomViewModel.js\";\nimport {ViewModel} from \"../ViewModel\";\nimport {RoomViewModelObservable} from \"./RoomViewModelObservable.js\";\nimport {RightPanelViewModel} from \"./rightpanel/RightPanelViewModel.js\";\n\nexport class SessionViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {client} = options;\n this._client = this.track(client);\n this._sessionStatusViewModel = this.track(new SessionStatusViewModel(this.childOptions({\n sync: client.sync,\n reconnector: client.reconnector,\n session: client.session,\n })));\n this._leftPanelViewModel = this.track(new LeftPanelViewModel(this.childOptions({session: this._client.session})));\n this._settingsViewModel = null;\n this._roomViewModelObservable = null;\n this._gridViewModel = null;\n this._createRoomViewModel = null;\n this._setupNavigation();\n }\n\n _setupNavigation() {\n const gridRooms = this.navigation.observe(\"rooms\");\n // this gives us a set of room ids in the grid\n this.track(gridRooms.subscribe(roomIds => {\n this._updateGrid(roomIds);\n }));\n if (gridRooms.get()) {\n this._updateGrid(gridRooms.get());\n }\n\n const currentRoomId = this.navigation.observe(\"room\");\n // this gives us the active room\n this.track(currentRoomId.subscribe(roomId => {\n if (!this._gridViewModel) {\n this._updateRoom(roomId);\n }\n this._updateRightPanel();\n }));\n if (!this._gridViewModel) {\n this._updateRoom(currentRoomId.get());\n }\n\n const settings = this.navigation.observe(\"settings\");\n this.track(settings.subscribe(settingsOpen => {\n this._updateSettings(settingsOpen);\n }));\n this._updateSettings(settings.get());\n\n const createRoom = this.navigation.observe(\"create-room\");\n this.track(createRoom.subscribe(createRoomOpen => {\n this._updateCreateRoom(createRoomOpen);\n }));\n this._updateCreateRoom(createRoom.get());\n\n const lightbox = this.navigation.observe(\"lightbox\");\n this.track(lightbox.subscribe(eventId => {\n this._updateLightbox(eventId);\n }));\n this._updateLightbox(lightbox.get());\n\n\n const rightpanel = this.navigation.observe(\"right-panel\");\n this.track(rightpanel.subscribe(() => this._updateRightPanel()));\n this._updateRightPanel();\n }\n\n get id() {\n return this._client.sessionId;\n }\n\n start() {\n this._sessionStatusViewModel.start();\n }\n\n get activeMiddleViewModel() {\n return this._roomViewModelObservable?.get() || this._gridViewModel || this._settingsViewModel || this._createRoomViewModel;\n }\n\n get roomGridViewModel() {\n return this._gridViewModel;\n }\n\n get leftPanelViewModel() {\n return this._leftPanelViewModel;\n }\n\n get sessionStatusViewModel() {\n return this._sessionStatusViewModel;\n }\n\n get settingsViewModel() {\n return this._settingsViewModel;\n }\n\n get currentRoomViewModel() {\n return this._roomViewModelObservable?.get();\n }\n\n get rightPanelViewModel() {\n return this._rightPanelViewModel;\n }\n\n get createRoomViewModel() {\n return this._createRoomViewModel;\n }\n\n _updateGrid(roomIds) {\n const changed = !(this._gridViewModel && roomIds);\n const currentRoomId = this.navigation.path.get(\"room\");\n if (roomIds) {\n if (!this._gridViewModel) {\n this._gridViewModel = this.track(new RoomGridViewModel(this.childOptions({\n width: 3,\n height: 2,\n createRoomViewModelObservable: roomId => new RoomViewModelObservable(this, roomId),\n })));\n // try to transfer the current room view model, so we don't have to reload the timeline\n this._roomViewModelObservable?.unsubscribeAll();\n if (this._gridViewModel.initializeRoomIdsAndTransferVM(roomIds, this._roomViewModelObservable)) {\n this._roomViewModelObservable = this.untrack(this._roomViewModelObservable);\n } else if (this._roomViewModelObservable) {\n this._roomViewModelObservable = this.disposeTracked(this._roomViewModelObservable);\n }\n } else {\n this._gridViewModel.setRoomIds(roomIds);\n }\n } else if (this._gridViewModel && !roomIds) {\n // closing grid, try to show focused room in grid\n if (currentRoomId) {\n const vmo = this._gridViewModel.releaseRoomViewModel(currentRoomId.value);\n if (vmo) {\n this._roomViewModelObservable = this.track(vmo);\n this._roomViewModelObservable.subscribe(() => {\n this.emitChange(\"activeMiddleViewModel\");\n });\n }\n }\n this._gridViewModel = this.disposeTracked(this._gridViewModel);\n }\n if (changed) {\n this.emitChange(\"activeMiddleViewModel\");\n }\n }\n\n _createRoomViewModelInstance(roomId) {\n const room = this._client.session.rooms.get(roomId);\n if (room) {\n const roomVM = new RoomViewModel(this.childOptions({room}));\n roomVM.load();\n return roomVM;\n }\n return null;\n }\n\n _createUnknownRoomViewModel(roomIdOrAlias) {\n return new UnknownRoomViewModel(this.childOptions({\n roomIdOrAlias,\n session: this._client.session,\n }));\n }\n\n async _createArchivedRoomViewModel(roomId) {\n const room = await this._client.session.loadArchivedRoom(roomId);\n if (room) {\n const roomVM = new RoomViewModel(this.childOptions({room}));\n roomVM.load();\n return roomVM;\n }\n return null;\n }\n\n _createInviteViewModel(roomId) {\n const invite = this._client.session.invites.get(roomId);\n if (invite) {\n return new InviteViewModel(this.childOptions({\n invite,\n mediaRepository: this._client.session.mediaRepository,\n }));\n }\n return null;\n }\n\n _createRoomBeingCreatedViewModel(localId) {\n const roomBeingCreated = this._client.session.roomsBeingCreated.get(localId);\n if (roomBeingCreated) {\n return new RoomBeingCreatedViewModel(this.childOptions({\n roomBeingCreated,\n mediaRepository: this._client.session.mediaRepository,\n }));\n }\n return null;\n }\n\n _updateRoom(roomId) {\n // opening a room and already open?\n if (this._roomViewModelObservable?.id === roomId) {\n return;\n }\n // close if needed\n if (this._roomViewModelObservable) {\n this._roomViewModelObservable = this.disposeTracked(this._roomViewModelObservable);\n }\n if (!roomId) {\n // if clearing the activeMiddleViewModel rather than changing to a different one,\n // emit so the view picks it up and show the placeholder\n this.emitChange(\"activeMiddleViewModel\");\n return;\n }\n const vmo = new RoomViewModelObservable(this, roomId);\n this._roomViewModelObservable = this.track(vmo);\n // subscription is unsubscribed in RoomViewModelObservable.dispose, and thus handled by track\n this._roomViewModelObservable.subscribe(() => {\n this.emitChange(\"activeMiddleViewModel\");\n });\n vmo.initialize();\n }\n\n _updateSettings(settingsOpen) {\n if (this._settingsViewModel) {\n this._settingsViewModel = this.disposeTracked(this._settingsViewModel);\n }\n if (settingsOpen) {\n this._settingsViewModel = this.track(new SettingsViewModel(this.childOptions({\n client: this._client,\n })));\n this._settingsViewModel.load();\n }\n this.emitChange(\"activeMiddleViewModel\");\n }\n\n _updateCreateRoom(createRoomOpen) {\n if (this._createRoomViewModel) {\n this._createRoomViewModel = this.disposeTracked(this._createRoomViewModel);\n }\n if (createRoomOpen) {\n this._createRoomViewModel = this.track(new CreateRoomViewModel(this.childOptions({session: this._client.session})));\n }\n this.emitChange(\"activeMiddleViewModel\");\n }\n\n _updateLightbox(eventId) {\n if (this._lightboxViewModel) {\n this._lightboxViewModel = this.disposeTracked(this._lightboxViewModel);\n }\n if (eventId) {\n const room = this._roomFromNavigation();\n this._lightboxViewModel = this.track(new LightboxViewModel(this.childOptions({eventId, room})));\n }\n this.emitChange(\"lightboxViewModel\");\n }\n\n get lightboxViewModel() {\n return this._lightboxViewModel;\n }\n\n _roomFromNavigation() {\n const roomId = this.navigation.path.get(\"room\")?.value;\n const room = this._client.session.rooms.get(roomId);\n return room;\n }\n\n _updateRightPanel() {\n this._rightPanelViewModel = this.disposeTracked(this._rightPanelViewModel);\n const enable = !!this.navigation.path.get(\"right-panel\")?.value;\n if (enable) {\n const room = this._roomFromNavigation();\n this._rightPanelViewModel = this.track(new RightPanelViewModel(this.childOptions({room, session: this._client.session})));\n }\n this.emitChange(\"rightPanelViewModel\");\n }\n\n notifyRoomReplaced(oldId, newId) {\n this.navigation.push(\"room\", newId);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"./ViewModel\";\nimport {KeyType} from \"../matrix/ssss/index\";\nimport {Status} from \"./session/settings/KeyBackupViewModel.js\";\n\nexport class AccountSetupViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._accountSetup = options.accountSetup;\n this._dehydratedDevice = undefined;\n this._decryptDehydratedDeviceViewModel = undefined;\n if (this._accountSetup.encryptedDehydratedDevice) {\n this._decryptDehydratedDeviceViewModel = new DecryptDehydratedDeviceViewModel(this, dehydratedDevice => {\n this._dehydratedDevice = dehydratedDevice;\n this._decryptDehydratedDeviceViewModel = undefined;\n this.emitChange(\"deviceDecrypted\");\n });\n }\n }\n\n get decryptDehydratedDeviceViewModel() {\n return this._decryptDehydratedDeviceViewModel;\n }\n\n get deviceDecrypted() {\n return !!this._dehydratedDevice;\n }\n\n get dehydratedDeviceId() {\n return this._accountSetup.encryptedDehydratedDevice.deviceId;\n }\n\n finish() {\n this._accountSetup.finish(this._dehydratedDevice);\n }\n}\n\n// this vm adopts the same shape as KeyBackupViewModel so the same view can be reused.\nclass DecryptDehydratedDeviceViewModel extends ViewModel {\n constructor(accountSetupViewModel, decryptedCallback) {\n super(accountSetupViewModel.options);\n this._accountSetupViewModel = accountSetupViewModel;\n this._isBusy = false;\n this._status = Status.SetupKey;\n this._error = undefined;\n this._decryptedCallback = decryptedCallback;\n }\n\n get decryptAction() {\n return this.i18n`Restore`;\n }\n\n get purpose() {\n return this.i18n`claim your dehydrated device`;\n }\n\n get offerDehydratedDeviceSetup() {\n return false;\n }\n\n get dehydratedDeviceId() {\n return this._accountSetupViewModel._dehydratedDevice?.deviceId;\n }\n \n get isBusy() {\n return this._isBusy;\n }\n\n get backupVersion() { return 0; }\n\n get status() {\n return this._status;\n }\n\n get error() {\n return this._error?.message;\n }\n\n showPhraseSetup() {\n if (this._status === Status.SetupKey) {\n this._status = Status.SetupPhrase;\n this.emitChange(\"status\");\n }\n }\n\n showKeySetup() {\n if (this._status === Status.SetupPhrase) {\n this._status = Status.SetupKey;\n this.emitChange(\"status\");\n }\n }\n\n async _enterCredentials(keyType, credential) {\n if (credential) {\n try {\n this._isBusy = true;\n this.emitChange(\"isBusy\");\n const {encryptedDehydratedDevice} = this._accountSetupViewModel._accountSetup;\n const dehydratedDevice = await encryptedDehydratedDevice.decrypt(keyType, credential);\n this._decryptedCallback(dehydratedDevice);\n } catch (err) {\n console.error(err);\n this._error = err;\n this.emitChange(\"error\");\n } finally {\n this._isBusy = false;\n this.emitChange(\"\");\n }\n }\n }\n\n enterSecurityPhrase(passphrase) {\n this._enterCredentials(KeyType.Passphrase, passphrase);\n }\n\n enterSecurityKey(securityKey) {\n this._enterCredentials(KeyType.RecoveryKey, securityKey);\n }\n\n disable() {}\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AccountSetupViewModel} from \"./AccountSetupViewModel.js\";\nimport {LoadStatus} from \"../matrix/Client.js\";\nimport {SyncStatus} from \"../matrix/Sync.js\";\nimport {ViewModel} from \"./ViewModel\";\n\nexport class SessionLoadViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {client, ready, homeserver, deleteSessionOnCancel} = options;\n this._client = client;\n this._ready = ready;\n this._homeserver = homeserver;\n this._deleteSessionOnCancel = deleteSessionOnCancel;\n this._loading = false;\n this._error = null;\n this.backUrl = this.urlCreator.urlForSegment(\"session\", true);\n this._accountSetupViewModel = undefined;\n\n }\n\n async start() {\n if (this._loading) {\n return;\n }\n try {\n this._loading = true;\n this.emitChange(\"loading\");\n this._waitHandle = this._client.loadStatus.waitFor(s => {\n if (s === LoadStatus.AccountSetup) {\n this._accountSetupViewModel = new AccountSetupViewModel(this.childOptions({accountSetup: this._client.accountSetup}));\n } else {\n this._accountSetupViewModel = undefined;\n }\n this.emitChange(\"loadLabel\");\n // wait for initial sync, but not catchup sync\n const isCatchupSync = s === LoadStatus.FirstSync &&\n this._client.sync.status.get() === SyncStatus.CatchupSync;\n return isCatchupSync ||\n s === LoadStatus.LoginFailed ||\n s === LoadStatus.Error ||\n s === LoadStatus.Ready;\n });\n try {\n await this._waitHandle.promise;\n } catch (err) {\n return; // aborted by goBack\n }\n // TODO: should we deal with no connection during initial sync \n // and we're retrying as well here?\n // e.g. show in the label what is going on wrt connectionstatus\n // much like we will once you are in the app. Probably a good idea\n\n // did it finish or get stuck at LoginFailed or Error?\n const loadStatus = this._client.loadStatus.get();\n const loadError = this._client.loadError;\n if (loadStatus === LoadStatus.FirstSync || loadStatus === LoadStatus.Ready) {\n const client = this._client;\n // session container is ready,\n // don't dispose it anymore when \n // we get disposed\n this._client = null;\n this._ready(client);\n }\n if (loadError) {\n console.error(\"session load error\", loadError);\n }\n } catch (err) {\n this._error = err;\n console.error(\"error thrown during session load\", err.stack);\n } finally {\n this._loading = false;\n // loadLabel in case of client.loadError also gets updated through this\n this.emitChange(\"loading\");\n }\n }\n\n\n dispose() {\n if (this._client) {\n this._client.dispose();\n this._client = null;\n }\n if (this._waitHandle) {\n // rejects with AbortError\n this._waitHandle.dispose();\n this._waitHandle = null;\n }\n }\n\n // to show a spinner or not\n get loading() {\n const client = this._client;\n if (client && client.loadStatus.get() === LoadStatus.AccountSetup) {\n return false;\n }\n return this._loading;\n }\n\n get loadLabel() {\n const client = this._client;\n const error = this._getError();\n if (error || (client && client.loadStatus.get() === LoadStatus.Error)) {\n return `Something went wrong: ${error && error.message}.`;\n }\n\n // Statuses related to login are handled by respective login view models\n if (client) {\n switch (client.loadStatus.get()) {\n case LoadStatus.QueryAccount:\n return `Querying account encryption setup…`;\n case LoadStatus.AccountSetup:\n return \"\"; // we'll show a header ing AccountSetupView\n case LoadStatus.SessionSetup:\n return `Setting up your encryption keys…`;\n case LoadStatus.Loading:\n return `Loading your conversations…`;\n case LoadStatus.FirstSync:\n return `Getting your conversations from the server…`;\n default:\n return this._client.loadStatus.get();\n }\n }\n\n return `Preparing…`;\n }\n\n _getError() {\n return this._error || this._client?.loadError; \n }\n\n get hasError() {\n return !!this._getError();\n }\n\n async exportLogs() {\n const logExport = await this.logger.export();\n this.platform.saveFileAs(logExport.asBlob(), `hydrogen-logs-${this.platform.clock.now()}.json`);\n }\n\n async logout() {\n await this._client.logout();\n this.navigation.push(\"session\", true);\n }\n\n get accountSetupViewModel() {\n return this._accountSetupViewModel;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../ViewModel\";\nimport {LoginFailure} from \"../../matrix/Client.js\";\n\nexport class PasswordLoginViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {loginOptions, attemptLogin} = options;\n this._loginOptions = loginOptions;\n this._attemptLogin = attemptLogin;\n this._isBusy = false;\n this._errorMessage = \"\";\n }\n\n get isBusy() { return this._isBusy; }\n get errorMessage() { return this._errorMessage; }\n\n setBusy(status) {\n this._isBusy = status;\n this.emitChange(\"isBusy\");\n }\n\n _showError(message) {\n this._errorMessage = message;\n this.emitChange(\"errorMessage\");\n }\n\n async login(username, password) {\n this._errorMessage = \"\";\n this.emitChange(\"errorMessage\");\n const status = await this._attemptLogin(this._loginOptions.password(username, password));\n let error = \"\";\n switch (status) {\n case LoginFailure.Credentials:\n error = this.i18n`Your username and/or password don't seem to be correct.`;\n break;\n case LoginFailure.Connection:\n error = this.i18n`Can't connect to ${this._loginOptions.homeserver}.`;\n break;\n case LoginFailure.Unknown:\n error = this.i18n`Something went wrong while checking your login and password.`;\n break;\n }\n if (error) {\n this._showError(error);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../ViewModel\";\n\nexport class StartSSOLoginViewModel extends ViewModel{\n constructor(options) {\n super(options);\n this._sso = options.loginOptions.sso;\n this._isBusy = false;\n }\n \n get isBusy() { return this._isBusy; }\n \n setBusy(status) {\n this._isBusy = status;\n this.emitChange(\"isBusy\");\n }\n\n async startSSOLogin() {\n await this.platform.settingsStorage.setString(\"sso_ongoing_login_homeserver\", this._sso.homeserver);\n const link = this._sso.createSSORedirectURL(this.urlCreator.createSSOCallbackURL());\n this.platform.openUrl(link);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ViewModel} from \"../ViewModel\";\nimport {LoginFailure} from \"../../matrix/Client.js\";\n\nexport class CompleteSSOLoginViewModel extends ViewModel {\n constructor(options) {\n super(options);\n const {\n loginToken,\n client,\n attemptLogin,\n } = options;\n this._loginToken = loginToken;\n this._client = client;\n this._attemptLogin = attemptLogin;\n this._errorMessage = \"\";\n this.performSSOLoginCompletion();\n }\n\n get errorMessage() { return this._errorMessage; }\n\n _showError(message) {\n this._errorMessage = message;\n this.emitChange(\"errorMessage\");\n }\n\n async performSSOLoginCompletion() {\n if (!this._loginToken) {\n return;\n }\n const homeserver = await this.platform.settingsStorage.getString(\"sso_ongoing_login_homeserver\");\n let loginOptions;\n try {\n loginOptions = await this._client.queryLogin(homeserver).result;\n }\n catch (err) {\n this._showError(err.message);\n return;\n }\n if (!loginOptions.token) {\n this.navigation.push(\"session\");\n return;\n }\n const status = await this._attemptLogin(loginOptions.token(this._loginToken));\n let error = \"\";\n switch (status) {\n case LoginFailure.Credentials:\n error = this.i18n`Your login token is invalid.`;\n break;\n case LoginFailure.Connection:\n error = this.i18n`Can't connect to ${homeserver}.`;\n break;\n case LoginFailure.Unknown:\n error = this.i18n`Something went wrong while checking your login token.`;\n break;\n }\n if (error) {\n this._showError(error);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Client} from \"../../matrix/Client.js\";\nimport {Options as BaseOptions, ViewModel} from \"../ViewModel\";\nimport {PasswordLoginViewModel} from \"./PasswordLoginViewModel.js\";\nimport {StartSSOLoginViewModel} from \"./StartSSOLoginViewModel.js\";\nimport {CompleteSSOLoginViewModel} from \"./CompleteSSOLoginViewModel.js\";\nimport {LoadStatus} from \"../../matrix/Client.js\";\nimport {SessionLoadViewModel} from \"../SessionLoadViewModel.js\";\nimport {SegmentType} from \"../navigation/index\";\n\nimport type {PasswordLoginMethod, SSOLoginHelper, TokenLoginMethod, ILoginMethod} from \"../../matrix/login\";\n\ntype Options = {\n defaultHomeserver: string;\n ready: ReadyFn;\n loginToken?: string;\n} & BaseOptions;\n\nexport class LoginViewModel extends ViewModel {\n private _ready: ReadyFn;\n private _loginToken?: string;\n private _client: Client;\n private _loginOptions?: LoginOptions;\n private _passwordLoginViewModel?: PasswordLoginViewModel;\n private _startSSOLoginViewModel?: StartSSOLoginViewModel;\n private _completeSSOLoginViewModel?: CompleteSSOLoginViewModel;\n private _loadViewModel?: SessionLoadViewModel;\n private _loadViewModelSubscription?: () => void;\n private _homeserver: string;\n private _queriedHomeserver?: string;\n private _abortHomeserverQueryTimeout?: () => void;\n private _abortQueryOperation?: () => void;\n\n private _hideHomeserver: boolean = false;\n private _isBusy: boolean = false;\n private _errorMessage: string = \"\";\n\n constructor(options: Readonly) {\n super(options);\n const {ready, defaultHomeserver, loginToken} = options;\n this._ready = ready;\n this._loginToken = loginToken;\n this._client = new Client(this.platform);\n this._homeserver = defaultHomeserver;\n this._initViewModels();\n }\n\n get passwordLoginViewModel(): PasswordLoginViewModel {\n return this._passwordLoginViewModel;\n }\n\n get startSSOLoginViewModel(): StartSSOLoginViewModel {\n return this._startSSOLoginViewModel;\n }\n\n get completeSSOLoginViewModel(): CompleteSSOLoginViewModel {\n return this._completeSSOLoginViewModel;\n }\n\n get homeserver(): string {\n return this._homeserver;\n }\n\n get resolvedHomeserver(): string | undefined {\n return this._loginOptions?.homeserver;\n }\n\n get errorMessage(): string {\n return this._errorMessage;\n }\n\n get showHomeserver(): boolean {\n return !this._hideHomeserver;\n }\n\n get loadViewModel(): SessionLoadViewModel {\n return this._loadViewModel;\n }\n\n get isBusy(): boolean {\n return this._isBusy;\n }\n\n get isFetchingLoginOptions(): boolean {\n return !!this._abortQueryOperation;\n }\n\n goBack(): void {\n this.navigation.push(\"session\");\n }\n\n private _initViewModels(): void {\n if (this._loginToken) {\n this._hideHomeserver = true;\n this._completeSSOLoginViewModel = this.track(new CompleteSSOLoginViewModel(\n this.childOptions(\n {\n client: this._client,\n attemptLogin: (loginMethod: TokenLoginMethod) => this.attemptLogin(loginMethod),\n loginToken: this._loginToken\n })));\n this.emitChange(\"completeSSOLoginViewModel\");\n }\n else {\n void this.queryHomeserver();\n }\n }\n\n private _showPasswordLogin(): void {\n this._passwordLoginViewModel = this.track(new PasswordLoginViewModel(\n this.childOptions({\n loginOptions: this._loginOptions,\n attemptLogin: (loginMethod: PasswordLoginMethod) => this.attemptLogin(loginMethod)\n })));\n this.emitChange(\"passwordLoginViewModel\");\n }\n\n private _showSSOLogin(): void {\n this._startSSOLoginViewModel = this.track(\n new StartSSOLoginViewModel(this.childOptions({loginOptions: this._loginOptions}))\n );\n this.emitChange(\"startSSOLoginViewModel\");\n }\n\n private _showError(message: string): void {\n this._errorMessage = message;\n this.emitChange(\"errorMessage\");\n }\n\n private _setBusy(status: boolean): void {\n this._isBusy = status;\n this._passwordLoginViewModel?.setBusy(status);\n this._startSSOLoginViewModel?.setBusy(status);\n this.emitChange(\"isBusy\");\n }\n\n async attemptLogin(loginMethod: ILoginMethod): Promise {\n this._setBusy(true);\n void this._client.startWithLogin(loginMethod, {inspectAccountSetup: true});\n const loadStatus = this._client.loadStatus;\n const handle = loadStatus.waitFor((status: LoadStatus) => status !== LoadStatus.Login);\n await handle.promise;\n this._setBusy(false);\n const status = loadStatus.get();\n if (status === LoadStatus.LoginFailed) {\n return this._client.loginFailure;\n }\n this._hideHomeserver = true;\n this.emitChange(\"hideHomeserver\");\n this._disposeViewModels();\n void this._createLoadViewModel();\n return null;\n }\n\n private _createLoadViewModel(): void {\n this._loadViewModelSubscription = this.disposeTracked(this._loadViewModelSubscription);\n this._loadViewModel = this.disposeTracked(this._loadViewModel);\n this._loadViewModel = this.track(\n new SessionLoadViewModel(\n this.childOptions({\n ready: (client) => {\n // make sure we don't delete the session in dispose when navigating away\n this._client = null;\n this._ready(client);\n },\n client: this._client,\n homeserver: this._homeserver\n })\n )\n );\n void this._loadViewModel.start();\n this.emitChange(\"loadViewModel\");\n this._loadViewModelSubscription = this.track(\n this._loadViewModel.disposableOn(\"change\", () => {\n if (!this._loadViewModel.loading) {\n this._loadViewModelSubscription = this.disposeTracked(this._loadViewModelSubscription);\n }\n this._setBusy(false);\n })\n );\n }\n\n private _disposeViewModels(): void {\n this._startSSOLoginViewModel = this.disposeTracked(this._startSSOLoginViewModel);\n this._passwordLoginViewModel = this.disposeTracked(this._passwordLoginViewModel);\n this._completeSSOLoginViewModel = this.disposeTracked(this._completeSSOLoginViewModel);\n this.emitChange(\"disposeViewModels\");\n }\n\n async setHomeserver(newHomeserver: string): Promise {\n this._homeserver = newHomeserver;\n // clear everything set by queryHomeserver\n this._loginOptions = undefined;\n this._queriedHomeserver = undefined;\n this._showError(\"\");\n this._disposeViewModels();\n this._abortQueryOperation = this.disposeTracked(this._abortQueryOperation);\n this.emitChange(\"loginViewModels\"); // multiple fields changing\n // also clear the timeout if it is still running\n this.disposeTracked(this._abortHomeserverQueryTimeout);\n const timeout = this.clock.createTimeout(1000);\n this._abortHomeserverQueryTimeout = this.track(() => timeout.abort());\n try {\n await timeout.elapsed();\n } catch (err) {\n if (err.name === \"AbortError\") {\n return; // still typing, don't query\n } else {\n throw err;\n }\n }\n this._abortHomeserverQueryTimeout = this.disposeTracked(this._abortHomeserverQueryTimeout);\n void this.queryHomeserver();\n }\n\n async queryHomeserver(): Promise {\n // don't repeat a query we've just done\n if (this._homeserver === this._queriedHomeserver || this._homeserver === \"\") {\n return;\n }\n this._queriedHomeserver = this._homeserver;\n // given that setHomeserver already clears everything set here,\n // and that is the only way to change the homeserver,\n // we don't need to reset things again here.\n // However, clear things set by setHomeserver:\n // if query is called before the typing timeout hits (e.g. field lost focus),\n // cancel the timeout so we don't query again.\n this._abortHomeserverQueryTimeout = this.disposeTracked(this._abortHomeserverQueryTimeout);\n // cancel ongoing query operation, if any\n this._abortQueryOperation = this.disposeTracked(this._abortQueryOperation);\n try {\n const queryOperation = this._client.queryLogin(this._homeserver);\n this._abortQueryOperation = this.track(() => queryOperation.abort());\n this.emitChange(\"isFetchingLoginOptions\");\n this._loginOptions = await queryOperation.result;\n this.emitChange(\"resolvedHomeserver\");\n }\n catch (e) {\n if (e.name === \"AbortError\") {\n return; //aborted, bail out\n } else {\n this._loginOptions = undefined;\n }\n } finally {\n this._abortQueryOperation = this.disposeTracked(this._abortQueryOperation);\n this.emitChange(\"isFetchingLoginOptions\");\n }\n if (this._loginOptions) {\n if (this._loginOptions.sso) { this._showSSOLogin(); }\n if (this._loginOptions.password) { this._showPasswordLogin(); }\n if (!this._loginOptions.sso && !this._loginOptions.password) {\n this._showError(\"This homeserver supports neither SSO nor password based login flows\");\n }\n }\n else {\n this._showError(`Could not query login methods supported by ${this.homeserver}`);\n }\n }\n\n dispose(): void {\n super.dispose();\n if (this._client) {\n // if we move away before we're done with initial sync\n // delete the session\n void this._client.deleteSession();\n }\n }\n}\n\ntype ReadyFn = (client: Client) => void;\n\n// TODO: move to Client.js when its converted to typescript.\ntype LoginOptions = {\n homeserver: string;\n password?: (username: string, password: string) => PasswordLoginMethod;\n sso?: SSOLoginHelper;\n token?: (loginToken: string) => TokenLoginMethod;\n};\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Options as BaseOptions, ViewModel} from \"./ViewModel\";\nimport {Client} from \"../matrix/Client.js\";\nimport {SegmentType} from \"./navigation/index\";\n\ntype Options = { sessionId: string; } & BaseOptions;\n\nexport class LogoutViewModel extends ViewModel {\n private _sessionId: string;\n private _busy: boolean;\n private _showConfirm: boolean;\n private _error?: Error;\n\n constructor(options: Options) {\n super(options);\n this._sessionId = options.sessionId;\n this._busy = false;\n this._showConfirm = true;\n this._error = undefined;\n }\n\n get showConfirm(): boolean {\n return this._showConfirm;\n }\n\n get busy(): boolean {\n return this._busy;\n }\n\n get cancelUrl(): string | undefined {\n return this.urlCreator.urlForSegment(\"session\", true);\n }\n\n async logout(): Promise {\n this._busy = true;\n this._showConfirm = false;\n this.emitChange(\"busy\");\n try {\n const client = new Client(this.platform);\n await client.startLogout(this._sessionId);\n this.navigation.push(\"session\", true);\n } catch (err) {\n this._error = err;\n this._busy = false;\n this.emitChange(\"busy\");\n }\n }\n\n get status(): string {\n if (this._error) {\n return this.i18n`Could not log out of device: ${this._error.message}`;\n } else {\n return this.i18n`Logging out… Please don't close the app.`;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SortedArray} from \"../observable/index.js\";\nimport {ViewModel} from \"./ViewModel\";\nimport {avatarInitials, getIdentifierColorNumber} from \"./avatar\";\n\nclass SessionItemViewModel extends ViewModel {\n constructor(options, pickerVM) {\n super(options);\n this._pickerVM = pickerVM;\n this._sessionInfo = options.sessionInfo;\n this._isDeleting = false;\n this._isClearing = false;\n this._error = null;\n this._exportDataUrl = null;\n }\n\n get error() {\n return this._error && this._error.message;\n }\n\n get id() {\n return this._sessionInfo.id;\n }\n\n get openUrl() {\n return this.urlCreator.urlForSegment(\"session\", this.id);\n }\n\n get label() {\n const {userId, comment} = this._sessionInfo;\n if (comment) {\n return `${userId} (${comment})`;\n } else {\n return userId;\n }\n }\n\n get sessionInfo() {\n return this._sessionInfo;\n }\n\n get exportDataUrl() {\n return this._exportDataUrl;\n }\n\n get avatarColorNumber() {\n return getIdentifierColorNumber(this._sessionInfo.userId);\n }\n\n get avatarInitials() {\n return avatarInitials(this._sessionInfo.userId);\n }\n}\n\n\nexport class SessionPickerViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._sessions = new SortedArray((s1, s2) => s1.id.localeCompare(s2.id));\n this._loadViewModel = null;\n this._error = null;\n }\n\n // this loads all the sessions\n async load() {\n const sessions = await this.platform.sessionInfoStorage.getAll();\n this._sessions.setManyUnsorted(sessions.map(s => {\n return new SessionItemViewModel(this.childOptions({sessionInfo: s}), this);\n }));\n }\n\n // for the loading of 1 picked session\n get loadViewModel() {\n return this._loadViewModel;\n }\n\n get sessions() {\n return this._sessions;\n }\n\n get cancelUrl() {\n return this.urlCreator.urlForSegment(\"login\");\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Client} from \"../matrix/Client.js\";\nimport {SessionViewModel} from \"./session/SessionViewModel.js\";\nimport {SessionLoadViewModel} from \"./SessionLoadViewModel.js\";\nimport {LoginViewModel} from \"./login/LoginViewModel\";\nimport {LogoutViewModel} from \"./LogoutViewModel\";\nimport {SessionPickerViewModel} from \"./SessionPickerViewModel.js\";\nimport {ViewModel} from \"./ViewModel\";\n\nexport class RootViewModel extends ViewModel {\n constructor(options) {\n super(options);\n this._error = null;\n this._sessionPickerViewModel = null;\n this._sessionLoadViewModel = null;\n this._loginViewModel = null;\n this._logoutViewModel = null;\n this._sessionViewModel = null;\n this._pendingClient = null;\n }\n\n async load() {\n this.track(this.navigation.observe(\"login\").subscribe(() => this._applyNavigation()));\n this.track(this.navigation.observe(\"session\").subscribe(() => this._applyNavigation()));\n this.track(this.navigation.observe(\"sso\").subscribe(() => this._applyNavigation()));\n this._applyNavigation(true);\n }\n\n async _applyNavigation(shouldRestoreLastUrl) {\n const isLogin = this.navigation.path.get(\"login\");\n const logoutSessionId = this.navigation.path.get(\"logout\")?.value;\n const sessionId = this.navigation.path.get(\"session\")?.value;\n const loginToken = this.navigation.path.get(\"sso\")?.value;\n if (isLogin) {\n if (this.activeSection !== \"login\") {\n this._showLogin();\n }\n } else if (logoutSessionId) {\n if (this.activeSection !== \"logout\") {\n this._showLogout(logoutSessionId);\n }\n } else if (sessionId === true) {\n if (this.activeSection !== \"picker\") {\n this._showPicker();\n }\n } else if (sessionId) {\n if (!this._sessionViewModel || this._sessionViewModel.id !== sessionId) {\n // see _showLogin for where _pendingClient comes from\n if (this._pendingClient && this._pendingClient.sessionId === sessionId) {\n const client = this._pendingClient;\n this._pendingClient = null;\n this._showSession(client);\n } else {\n // this should never happen, but we want to be sure not to leak it\n if (this._pendingClient) {\n this._pendingClient.dispose();\n this._pendingClient = null;\n }\n this._showSessionLoader(sessionId);\n }\n }\n } else if (loginToken) {\n this.urlCreator.normalizeUrl();\n if (this.activeSection !== \"login\") {\n this._showLogin(loginToken);\n }\n }\n else {\n try {\n if (!(shouldRestoreLastUrl && this.urlCreator.tryRestoreLastUrl())) {\n const sessionInfos = await this.platform.sessionInfoStorage.getAll();\n if (sessionInfos.length === 0) {\n this.navigation.push(\"login\");\n } else if (sessionInfos.length === 1) {\n this.navigation.push(\"session\", sessionInfos[0].id);\n } else {\n this.navigation.push(\"session\");\n }\n }\n } catch (err) {\n this._setSection(() => this._error = err);\n }\n }\n }\n\n async _showPicker() {\n this._setSection(() => {\n this._sessionPickerViewModel = new SessionPickerViewModel(this.childOptions());\n });\n try {\n await this._sessionPickerViewModel.load();\n } catch (err) {\n this._setSection(() => this._error = err);\n }\n }\n\n _showLogin(loginToken) {\n this._setSection(() => {\n this._loginViewModel = new LoginViewModel(this.childOptions({\n defaultHomeserver: this.platform.config[\"defaultHomeServer\"],\n ready: client => {\n // we don't want to load the session container again,\n // but we also want the change of screen to go through the navigation\n // so we store the session container in a temporary variable that will be\n // consumed by _applyNavigation, triggered by the navigation change\n //\n // Also, we should not call _setSection before the navigation is in the correct state,\n // as url creation (e.g. in RoomTileViewModel)\n // won't be using the correct navigation base path.\n this._pendingClient = client;\n this.navigation.push(\"session\", client.sessionId);\n },\n loginToken\n }));\n });\n }\n\n _showLogout(sessionId) {\n this._setSection(() => {\n this._logoutViewModel = new LogoutViewModel(this.childOptions({sessionId}));\n });\n }\n\n _showSession(client) {\n this._setSection(() => {\n this._sessionViewModel = new SessionViewModel(this.childOptions({client}));\n this._sessionViewModel.start();\n });\n }\n\n _showSessionLoader(sessionId) {\n const client = new Client(this.platform);\n client.startWithExistingSession(sessionId);\n this._setSection(() => {\n this._sessionLoadViewModel = new SessionLoadViewModel(this.childOptions({\n client,\n ready: client => this._showSession(client)\n }));\n this._sessionLoadViewModel.start();\n });\n }\n\n get activeSection() {\n if (this._error) {\n return \"error\";\n } else if (this._sessionViewModel) {\n return \"session\";\n } else if (this._loginViewModel) {\n return \"login\";\n } else if (this._logoutViewModel) {\n return \"logout\";\n } else if (this._sessionPickerViewModel) {\n return \"picker\";\n } else if (this._sessionLoadViewModel) {\n return \"loading\";\n } else {\n return \"redirecting\";\n }\n }\n\n _setSection(setter) {\n // clear all members the activeSection depends on\n this._error = null;\n this._sessionPickerViewModel = this.disposeTracked(this._sessionPickerViewModel);\n this._sessionLoadViewModel = this.disposeTracked(this._sessionLoadViewModel);\n this._loginViewModel = this.disposeTracked(this._loginViewModel);\n this._logoutViewModel = this.disposeTracked(this._logoutViewModel);\n this._sessionViewModel = this.disposeTracked(this._sessionViewModel);\n // now set it again\n setter();\n this._sessionPickerViewModel && this.track(this._sessionPickerViewModel);\n this._sessionLoadViewModel && this.track(this._sessionLoadViewModel);\n this._loginViewModel && this.track(this._loginViewModel);\n this._logoutViewModel && this.track(this._logoutViewModel);\n this._sessionViewModel && this.track(this._sessionViewModel);\n this.emitChange(\"activeSection\");\n }\n\n get error() { return this._error; }\n get sessionViewModel() { return this._sessionViewModel; }\n get loginViewModel() { return this._loginViewModel; }\n get logoutViewModel() { return this._logoutViewModel; }\n get sessionPickerViewModel() { return this._sessionPickerViewModel; }\n get sessionLoadViewModel() { return this._sessionLoadViewModel; }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// import {RecordRequester, ReplayRequester} from \"./matrix/net/request/replay\";\nimport {RootViewModel} from \"../../domain/RootViewModel.js\";\nimport {createNavigation, createRouter} from \"../../domain/navigation/index\";\n// Don't use a default export here, as we use multiple entries during legacy build,\n// which does not support default exports,\n// see https://github.com/rollup/plugins/tree/master/packages/multi-entry\nexport async function main(platform) {\n try {\n // to replay:\n // const fetchLog = await (await fetch(\"/fetchlogs/constrainterror.json\")).json();\n // const replay = new ReplayRequester(fetchLog, {delay: false});\n // const request = replay.request;\n\n // to record:\n // const recorder = new RecordRequester(createFetchRequest(clock.createTimeout));\n // const request = recorder.request;\n // window.getBrawlFetchLog = () => recorder.log();\n await platform.init();\n const navigation = createNavigation();\n platform.setNavigation(navigation);\n const urlRouter = createRouter({navigation, history: platform.history});\n urlRouter.attach();\n const vm = new RootViewModel({\n platform,\n // the only public interface of the router is to create urls,\n // so we call it that in the view models\n urlCreator: urlRouter,\n navigation,\n });\n await vm.load();\n platform.createAndMountRootView(vm);\n } catch(err) {\n console.error(`${err.message}:\\n${err.stack}`);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ConnectionError} from \"../matrix/error.js\";\nimport type {Timeout} from \"../platform/web/dom/Clock.js\"\nimport type {IAbortable} from \"./AbortableOperation\";\n\ntype TimeoutCreator = (ms: number) => Timeout;\n\nexport function abortOnTimeout(createTimeout: TimeoutCreator, timeoutAmount: number, requestResult: IAbortable, responsePromise: Promise) {\n const timeout = createTimeout(timeoutAmount);\n // abort request if timeout finishes first\n let timedOut = false;\n timeout.elapsed().then(\n () => {\n timedOut = true;\n requestResult.abort();\n },\n () => {} // ignore AbortError when timeout is aborted\n );\n // abort timeout if request finishes first\n return responsePromise.then(\n response => {\n timeout.abort();\n return response;\n },\n err => {\n timeout.abort();\n // map error to TimeoutError\n if (err.name === \"AbortError\" && timedOut) {\n throw new ConnectionError(`Request timed out after ${timeoutAmount}ms`, true);\n } else {\n throw err;\n }\n }\n );\n}\n\n// because impunity only takes one entrypoint currently,\n// these tests aren't run by yarn test as that does not\n// include platform specific code,\n// and this file is only included by platform specific code,\n// see how to run in package.json and replace src/main.js with this file.\nimport {Clock as MockClock} from \"../mocks/Clock.js\";\nimport {Request as MockRequest} from \"../mocks/Request.js\";\nimport {AbortError} from \"../matrix/error.js\";\nexport function tests() {\n return {\n \"ConnectionError on timeout\": async assert => {\n const clock = new MockClock();\n const request = new MockRequest();\n const promise = abortOnTimeout(clock.createTimeout, 10000, request, request.response());\n clock.elapse(10000);\n await assert.rejects(promise, ConnectionError);\n assert(request.aborted);\n },\n \"Abort is canceled once response resolves\": async assert => {\n const clock = new MockClock();\n const request = new MockRequest();\n const promise = abortOnTimeout(clock.createTimeout, 10000, request, request.response());\n request.resolve(5);\n clock.elapse(10000);\n assert(!request.aborted);\n assert.equal(await promise, 5);\n },\n \"AbortError from request is not mapped to ConnectionError\": async assert => {\n const clock = new MockClock();\n const request = new MockRequest();\n const promise = abortOnTimeout(clock.createTimeout, 10000, request, request.response());\n request.reject(new AbortError());\n assert(!request.aborted);\n assert.rejects(promise, AbortError);\n }\n }\n\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function addCacheBuster(urlStr, random = Math.random) {\n // XHR doesn't have a good way to disable cache,\n // so add a random query param\n // see https://davidtranscend.com/blog/prevent-ie11-cache-ajax-requests/\n if (urlStr.includes(\"?\")) {\n urlStr = urlStr + \"&\";\n } else {\n urlStr = urlStr + \"?\";\n }\n return urlStr + `_cacheBuster=${Math.ceil(random() * Number.MAX_SAFE_INTEGER)}`;\n}\n\nexport function mapAsFormData(map) {\n const formData = new FormData();\n for (const [name, value] of map) {\n // Special case {name: string, blob: BlobHandle} to set a filename.\n // This is the format returned by platform.openFile\n if (value.blob?.nativeBlob && value.name) {\n formData.set(name, value.blob.nativeBlob, value.name);\n } else {\n formData.set(name, value);\n }\n }\n return formData;\n}\n\nexport function tests() {\n return {\n \"add cache buster\": assert => {\n const random = () => 0.5;\n assert.equal(addCacheBuster(\"http://foo\", random), \"http://foo?_cacheBuster=4503599627370496\");\n assert.equal(addCacheBuster(\"http://foo?bar=baz\", random), \"http://foo?bar=baz&_cacheBuster=4503599627370496\");\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n AbortError,\n ConnectionError\n} from \"../../../../matrix/error.js\";\nimport {addCacheBuster, mapAsFormData} from \"./common.js\";\n\nclass RequestResult {\n constructor(promise, xhr) {\n this._promise = promise;\n this._xhr = xhr;\n }\n\n abort() {\n this._xhr.abort();\n }\n\n response() {\n return this._promise;\n }\n}\n\nfunction createXhr(url, {method, headers, timeout, format, uploadProgress}) {\n const xhr = new XMLHttpRequest();\n\n if (uploadProgress) {\n xhr.upload.addEventListener(\"progress\", evt => uploadProgress(evt.loaded));\n }\n\n xhr.open(method, url);\n \n if (format === \"buffer\") {\n // important to call this after calling open\n xhr.responseType = \"arraybuffer\";\n }\n if (headers) {\n for(const [name, value] of headers.entries()) {\n try {\n xhr.setRequestHeader(name, value);\n } catch (err) {\n console.info(`Could not set ${name} header: ${err.message}`);\n }\n }\n }\n if (timeout) {\n xhr.timeout = timeout;\n }\n\n return xhr;\n}\n\nfunction xhrAsPromise(xhr, method, url) {\n return new Promise((resolve, reject) => {\n xhr.addEventListener(\"load\", () => resolve(xhr));\n xhr.addEventListener(\"abort\", () => reject(new AbortError()));\n xhr.addEventListener(\"error\", () => reject(new ConnectionError(`Error ${method} ${url}`)));\n xhr.addEventListener(\"timeout\", () => reject(new ConnectionError(`Timeout ${method} ${url}`, true)));\n });\n}\n\nexport function xhrRequest(url, options) {\n let {cache, format, body, method} = options;\n if (!cache) {\n url = addCacheBuster(url);\n }\n const xhr = createXhr(url, options);\n const promise = xhrAsPromise(xhr, method, url).then(xhr => {\n const {status} = xhr;\n let body = null;\n if (format === \"buffer\") {\n body = xhr.response;\n } else if (xhr.getResponseHeader(\"Content-Type\") === \"application/json\") {\n body = JSON.parse(xhr.responseText);\n }\n return {status, body};\n });\n\n // if a BlobHandle, take native blob\n if (body?.nativeBlob) {\n body = body.nativeBlob;\n }\n if (body instanceof Map) {\n body = mapAsFormData(body);\n }\n xhr.send(body || null);\n\n return new RequestResult(promise, xhr);\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n AbortError,\n ConnectionError\n} from \"../../../../matrix/error.js\";\nimport {abortOnTimeout} from \"../../../../utils/timeout\";\nimport {addCacheBuster, mapAsFormData} from \"./common.js\";\nimport {xhrRequest} from \"./xhr.js\";\n\nclass RequestResult {\n constructor(promise, controller) {\n if (!controller) {\n const abortPromise = new Promise((_, reject) => {\n this._controller = {\n abort() {\n const err = new Error(\"fetch request aborted\");\n err.name = \"AbortError\";\n reject(err);\n }\n };\n });\n this.promise = Promise.race([promise, abortPromise]);\n } else {\n this.promise = promise;\n this._controller = controller;\n }\n }\n\n abort() {\n this._controller.abort();\n }\n\n response() {\n return this.promise;\n }\n}\n\nexport function createFetchRequest(createTimeout, serviceWorkerHandler) {\n return function fetchRequest(url, requestOptions) {\n if (serviceWorkerHandler?.haltRequests) {\n // prevent any requests while waiting\n // for the new service worker to get activated.\n // Once this happens, the page will be reloaded\n // by the serviceWorkerHandler so this is fine.\n return new RequestResult(new Promise(() => {}), {});\n }\n // fetch doesn't do upload progress yet, delegate to xhr\n if (requestOptions?.uploadProgress) {\n return xhrRequest(url, requestOptions);\n }\n let {method, headers, body, timeout, format, cache = false} = requestOptions;\n const controller = typeof AbortController === \"function\" ? new AbortController() : null;\n // if a BlobHandle, take native blob\n if (body?.nativeBlob) {\n body = body.nativeBlob;\n }\n if (body instanceof Map) {\n body = mapAsFormData(body);\n }\n let options = {method, body};\n if (controller) {\n options = Object.assign(options, {\n signal: controller.signal\n });\n }\n if (!cache) {\n url = addCacheBuster(url);\n }\n options = Object.assign(options, {\n mode: \"cors\",\n credentials: \"omit\",\n referrer: \"no-referrer\",\n // ideally we'd turn off cache here, but Safari interprets\n // `Access-Control-Allow-Headers` strictly (only when fetch is\n // intercepted by a service worker strangely enough), in that\n // it gives a CORS error if Cache-Control is not present\n // in the list of allowed headers (which it isn't commonly, at least not on matrix.org).\n // With no-store or no-cache here, it does set `Cache-Control`\n // so we don't do that, and prevent caching with `addCacheBuster`.\n // We also hope the server responds with `Cache-Control: no-store` so\n // we don't fill the http cache with api responses.\n // \n // cache: \"no-store\",\n cache: \"default\",\n });\n if (headers) {\n const fetchHeaders = new Headers();\n for(const [name, value] of headers.entries()) {\n fetchHeaders.append(name, value);\n }\n options.headers = fetchHeaders;\n }\n const promise = fetch(url, options).then(async response => {\n const {status} = response;\n let body;\n try {\n if (format === \"json\") {\n body = await response.json();\n } else if (format === \"buffer\") {\n body = await response.arrayBuffer();\n }\n else if (format === \"text\") {\n body = await response.text();\n }\n } catch (err) {\n // some error pages return html instead of json, ignore error\n if (!(err.name === \"SyntaxError\" && status >= 400)) {\n throw err;\n }\n }\n return {status, body};\n }, err => {\n if (err.name === \"AbortError\") {\n // map DOMException with name AbortError to our own AbortError type\n // as we don't want DOMExceptions in the protocol layer.\n throw new AbortError();\n } else if (err instanceof TypeError) {\n // Network errors are reported as TypeErrors, see\n // https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch#Checking_that_the_fetch_was_successful\n // this can either mean user is offline, server is offline, or a CORS error (server misconfiguration).\n // \n // One could check navigator.onLine to rule out the first\n // but the 2 latter ones are indistinguishable from javascript.\n throw new ConnectionError(`${method} ${url}: ${err.message}`);\n }\n throw err;\n });\n const result = new RequestResult(promise, controller);\n\n if (timeout) {\n result.promise = abortOnTimeout(createTimeout, timeout, result, result.promise);\n }\n\n return result;\n } \n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\ninterface ISessionInfo {\n id: string;\n deviceId: string;\n userId: string;\n homeserver: string;\n homeServer: string; // deprecate this over time\n accessToken: string;\n lastUsed: number;\n}\n\n// todo: this should probably be in platform/types?\ninterface ISessionInfoStorage {\n getAll(): Promise;\n updateLastUsed(id: string, timestamp: number): Promise;\n get(id: string): Promise;\n add(sessionInfo: ISessionInfo): Promise;\n delete(sessionId: string): Promise;\n}\n\nexport class SessionInfoStorage implements ISessionInfoStorage {\n private readonly _name: string;\n\n constructor(name: string) {\n this._name = name;\n }\n\n getAll(): Promise {\n const sessionsJson = localStorage.getItem(this._name);\n if (sessionsJson) {\n const sessions = JSON.parse(sessionsJson);\n if (Array.isArray(sessions)) {\n return Promise.resolve(sessions);\n }\n }\n return Promise.resolve([]);\n }\n\n async updateLastUsed(id: string, timestamp: number): Promise {\n const sessions = await this.getAll();\n if (sessions) {\n const session = sessions.find(session => session.id === id);\n if (session) {\n session.lastUsed = timestamp;\n localStorage.setItem(this._name, JSON.stringify(sessions));\n }\n }\n }\n\n async get(id: string): Promise {\n const sessions = await this.getAll();\n if (sessions) {\n return sessions.find(session => session.id === id);\n }\n }\n\n async add(sessionInfo: ISessionInfo): Promise {\n const sessions = await this.getAll();\n sessions.push(sessionInfo);\n localStorage.setItem(this._name, JSON.stringify(sessions));\n }\n\n async delete(sessionId: string): Promise {\n let sessions = await this.getAll();\n sessions = sessions.filter(s => s.id !== sessionId);\n localStorage.setItem(this._name, JSON.stringify(sessions));\n }\n \n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class SettingsStorage {\n constructor(prefix) {\n this._prefix = prefix;\n }\n\n async setInt(key, value) {\n this._set(key, value);\n }\n\n async getInt(key, defaultValue = 0) {\n const value = window.localStorage.getItem(`${this._prefix}${key}`);\n if (typeof value === \"string\") {\n return parseInt(value, 10);\n }\n return defaultValue;\n }\n\n async setBool(key, value) {\n this._set(key, value);\n }\n\n async getBool(key, defaultValue = false) {\n const value = window.localStorage.getItem(`${this._prefix}${key}`);\n if (typeof value === \"string\") {\n return value === \"true\";\n }\n return defaultValue;\n }\n\n async setString(key, value) {\n this._set(key, value);\n }\n\n async getString(key) {\n return window.localStorage.getItem(`${this._prefix}${key}`);\n }\n\n async remove(key) {\n window.localStorage.removeItem(`${this._prefix}${key}`);\n }\n\n async _set(key, value) {\n window.localStorage.setItem(`${this._prefix}${key}`, value);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nexport class UTF8 {\n constructor() {\n this._encoder = null;\n this._decoder = null;\n }\n\n encode(str) {\n if (!this._encoder) {\n this._encoder = new TextEncoder();\n }\n return this._encoder.encode(str);\n }\n\n decode(buffer) {\n if (!this._decoder) {\n this._decoder = new TextDecoder();\n }\n return this._decoder.decode(buffer);\n }\n}\n","/*\n * base64-arraybuffer\n * https://github.com/niklasvh/base64-arraybuffer\n *\n * Copyright (c) 2012 Niklas von Hertzen\n * Licensed under the MIT license.\n */\n(function(){\n \"use strict\";\n\n var chars = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n // Use a lookup table to find the index.\n var lookup = new Uint8Array(256);\n for (var i = 0; i < chars.length; i++) {\n lookup[chars.charCodeAt(i)] = i;\n }\n\n exports.encode = function(arraybuffer) {\n var bytes = new Uint8Array(arraybuffer),\n i, len = bytes.length, base64 = \"\";\n\n for (i = 0; i < len; i+=3) {\n base64 += chars[bytes[i] >> 2];\n base64 += chars[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];\n base64 += chars[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];\n base64 += chars[bytes[i + 2] & 63];\n }\n\n if ((len % 3) === 2) {\n base64 = base64.substring(0, base64.length - 1) + \"=\";\n } else if (len % 3 === 1) {\n base64 = base64.substring(0, base64.length - 2) + \"==\";\n }\n\n return base64;\n };\n\n exports.decode = function(base64) {\n var bufferLength = base64.length * 0.75,\n len = base64.length, i, p = 0,\n encoded1, encoded2, encoded3, encoded4;\n\n if (base64[base64.length - 1] === \"=\") {\n bufferLength--;\n if (base64[base64.length - 2] === \"=\") {\n bufferLength--;\n }\n }\n\n var arraybuffer = new ArrayBuffer(bufferLength),\n bytes = new Uint8Array(arraybuffer);\n\n for (i = 0; i < len; i+=4) {\n encoded1 = lookup[base64.charCodeAt(i)];\n encoded2 = lookup[base64.charCodeAt(i+1)];\n encoded3 = lookup[base64.charCodeAt(i+2)];\n encoded4 = lookup[base64.charCodeAt(i+3)];\n\n bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);\n bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);\n bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);\n }\n\n return arraybuffer;\n };\n})();\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport base64 from \"base64-arraybuffer\";\n\nexport class Base64 {\n encodeUnpadded(buffer) {\n const str = base64.encode(buffer);\n const paddingIdx = str.indexOf(\"=\");\n if (paddingIdx !== -1) {\n return str.substr(0, paddingIdx);\n } else {\n return str;\n }\n }\n\n encode(buffer) {\n return base64.encode(buffer);\n }\n\n decode(str) {\n return base64.decode(str);\n }\n}\n","var Buffer = {\n isBuffer: function(array) {return array instanceof Uint8Array;},\n from: function(arrayBuffer) {return arrayBuffer;},\n allocUnsafe: function(size) {return Buffer.alloc(size);},\n alloc: function(size) {return new Uint8Array(size);}\n};\nexport default Buffer;\n","'use strict'\n// base-x encoding / decoding\n// Copyright (c) 2018 base-x contributors\n// Copyright (c) 2014-2018 The Bitcoin Core developers (base58.cpp)\n// Distributed under the MIT software license, see the accompanying\n// file LICENSE or http://www.opensource.org/licenses/mit-license.php.\n// @ts-ignore\nvar _Buffer = require('safe-buffer').Buffer\nfunction base (ALPHABET) {\n if (ALPHABET.length >= 255) { throw new TypeError('Alphabet too long') }\n var BASE_MAP = new Uint8Array(256)\n for (var j = 0; j < BASE_MAP.length; j++) {\n BASE_MAP[j] = 255\n }\n for (var i = 0; i < ALPHABET.length; i++) {\n var x = ALPHABET.charAt(i)\n var xc = x.charCodeAt(0)\n if (BASE_MAP[xc] !== 255) { throw new TypeError(x + ' is ambiguous') }\n BASE_MAP[xc] = i\n }\n var BASE = ALPHABET.length\n var LEADER = ALPHABET.charAt(0)\n var FACTOR = Math.log(BASE) / Math.log(256) // log(BASE) / log(256), rounded up\n var iFACTOR = Math.log(256) / Math.log(BASE) // log(256) / log(BASE), rounded up\n function encode (source) {\n if (Array.isArray(source) || source instanceof Uint8Array) { source = _Buffer.from(source) }\n if (!_Buffer.isBuffer(source)) { throw new TypeError('Expected Buffer') }\n if (source.length === 0) { return '' }\n // Skip & count leading zeroes.\n var zeroes = 0\n var length = 0\n var pbegin = 0\n var pend = source.length\n while (pbegin !== pend && source[pbegin] === 0) {\n pbegin++\n zeroes++\n }\n // Allocate enough space in big-endian base58 representation.\n var size = ((pend - pbegin) * iFACTOR + 1) >>> 0\n var b58 = new Uint8Array(size)\n // Process the bytes.\n while (pbegin !== pend) {\n var carry = source[pbegin]\n // Apply \"b58 = b58 * 256 + ch\".\n var i = 0\n for (var it1 = size - 1; (carry !== 0 || i < length) && (it1 !== -1); it1--, i++) {\n carry += (256 * b58[it1]) >>> 0\n b58[it1] = (carry % BASE) >>> 0\n carry = (carry / BASE) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n pbegin++\n }\n // Skip leading zeroes in base58 result.\n var it2 = size - length\n while (it2 !== size && b58[it2] === 0) {\n it2++\n }\n // Translate the result into a string.\n var str = LEADER.repeat(zeroes)\n for (; it2 < size; ++it2) { str += ALPHABET.charAt(b58[it2]) }\n return str\n }\n function decodeUnsafe (source) {\n if (typeof source !== 'string') { throw new TypeError('Expected String') }\n if (source.length === 0) { return _Buffer.alloc(0) }\n var psz = 0\n // Skip leading spaces.\n if (source[psz] === ' ') { return }\n // Skip and count leading '1's.\n var zeroes = 0\n var length = 0\n while (source[psz] === LEADER) {\n zeroes++\n psz++\n }\n // Allocate enough space in big-endian base256 representation.\n var size = (((source.length - psz) * FACTOR) + 1) >>> 0 // log(58) / log(256), rounded up.\n var b256 = new Uint8Array(size)\n // Process the characters.\n while (source[psz]) {\n // Decode character\n var carry = BASE_MAP[source.charCodeAt(psz)]\n // Invalid character\n if (carry === 255) { return }\n var i = 0\n for (var it3 = size - 1; (carry !== 0 || i < length) && (it3 !== -1); it3--, i++) {\n carry += (BASE * b256[it3]) >>> 0\n b256[it3] = (carry % 256) >>> 0\n carry = (carry / 256) >>> 0\n }\n if (carry !== 0) { throw new Error('Non-zero carry') }\n length = i\n psz++\n }\n // Skip trailing spaces.\n if (source[psz] === ' ') { return }\n // Skip leading zeroes in b256.\n var it4 = size - length\n while (it4 !== size && b256[it4] === 0) {\n it4++\n }\n var vch = _Buffer.allocUnsafe(zeroes + (size - it4))\n vch.fill(0x00, 0, zeroes)\n var j = zeroes\n while (it4 !== size) {\n vch[j++] = b256[it4++]\n }\n return vch\n }\n function decode (string) {\n var buffer = decodeUnsafe(string)\n if (buffer) { return buffer }\n throw new Error('Non-base' + BASE + ' character')\n }\n return {\n encode: encode,\n decodeUnsafe: decodeUnsafe,\n decode: decode\n }\n}\nmodule.exports = base\n","var basex = require('base-x')\nvar ALPHABET = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz'\n\nmodule.exports = basex(ALPHABET)\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport bs58 from \"bs58\";\n\nexport class Base58 {\n encode(buffer) {\n return bs58.encode(buffer);\n }\n\n decode(str) {\n return bs58.decode(str);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {UTF8} from \"../dom/UTF8.js\";\nimport {Base64} from \"./Base64.js\";\nimport {Base58} from \"./Base58.js\";\n\nexport class Encoding {\n constructor() {\n this.utf8 = new UTF8();\n this.base64 = new Base64();\n this.base58 = new Base58();\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class OlmWorker {\n constructor(workerPool) {\n this._workerPool = workerPool;\n }\n\n megolmDecrypt(session, ciphertext) {\n const sessionKey = session.export_session(session.first_known_index());\n return this._workerPool.send({type: \"megolm_decrypt\", ciphertext, sessionKey});\n }\n\n async createAccountAndOTKs(account, otkAmount) {\n // IE11 does not support getRandomValues in a worker, so we have to generate the values upfront.\n let randomValues;\n if (window.msCrypto) {\n randomValues = [\n window.msCrypto.getRandomValues(new Uint8Array(64)),\n window.msCrypto.getRandomValues(new Uint8Array(otkAmount * 32)),\n ];\n }\n const pickle = await this._workerPool.send({type: \"olm_create_account_otks\", randomValues, otkAmount}).response();\n account.unpickle(\"\", pickle);\n }\n\n async createOutboundOlmSession(account, newSession, theirIdentityKey, theirOneTimeKey) {\n const accountPickle = account.pickle(\"\");\n let randomValues;\n if (window.msCrypto) {\n randomValues = [\n window.msCrypto.getRandomValues(new Uint8Array(64)),\n ];\n }\n const sessionPickle = await this._workerPool.send({type: \"olm_create_outbound\", accountPickle, theirIdentityKey, theirOneTimeKey, randomValues}).response();\n newSession.unpickle(\"\", sessionPickle);\n }\n\n dispose() {\n this._workerPool.dispose();\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {\n openDatabase,\n txnAsPromise,\n reqAsPromise,\n iterateCursor,\n fetchResults,\n} from \"../matrix/storage/idb/utils\";\nimport {BaseLogger} from \"./BaseLogger\";\nimport type {Interval} from \"../platform/web/dom/Clock\";\nimport type {Platform} from \"../platform/web/Platform.js\";\nimport type {BlobHandle} from \"../platform/web/dom/BlobHandle.js\";\nimport type {ILogItem, ILogExport, ISerializedItem} from \"./types\";\nimport type {LogFilter} from \"./LogFilter\";\n\ntype QueuedItem = {\n json: string;\n id?: number;\n}\n\nexport class IDBLogger extends BaseLogger {\n private readonly _name: string;\n private readonly _limit: number;\n private readonly _flushInterval: Interval;\n private _queuedItems: QueuedItem[];\n\n constructor(options: {name: string, flushInterval?: number, limit?: number, platform: Platform, serializedTransformer?: (item: ISerializedItem) => ISerializedItem}) {\n super(options);\n const {name, flushInterval = 60 * 1000, limit = 3000} = options;\n this._name = name;\n this._limit = limit;\n this._queuedItems = this._loadQueuedItems();\n // TODO: also listen for unload just in case sync keeps on running after pagehide is fired?\n window.addEventListener(\"pagehide\", this, false);\n this._flushInterval = this._platform.clock.createInterval(() => this._tryFlush(), flushInterval);\n }\n\n // TODO: move dispose to ILogger, listen to pagehide elsewhere and call dispose from there, which calls _finishAllAndFlush\n dispose(): void {\n window.removeEventListener(\"pagehide\", this, false);\n this._flushInterval.dispose();\n }\n\n handleEvent(evt: Event): void {\n if (evt.type === \"pagehide\") {\n this._finishAllAndFlush();\n }\n }\n\n async _tryFlush(): Promise {\n const db = await this._openDB();\n try {\n const txn = db.transaction([\"logs\"], \"readwrite\");\n const logs = txn.objectStore(\"logs\");\n const amount = this._queuedItems.length;\n for(const i of this._queuedItems) {\n logs.add(i);\n }\n const itemCount = await reqAsPromise(logs.count());\n if (itemCount > this._limit) {\n // delete an extra 10% so we don't need to delete every time we flush\n let deleteAmount = (itemCount - this._limit) + Math.round(0.1 * this._limit);\n await iterateCursor(logs.openCursor(), (_, __, cursor) => {\n cursor.delete();\n deleteAmount -= 1;\n return {done: deleteAmount === 0};\n });\n }\n await txnAsPromise(txn);\n this._queuedItems.splice(0, amount);\n } catch (err) {\n console.error(\"Could not flush logs\", err);\n } finally {\n try {\n db.close();\n } catch (e) {}\n }\n }\n\n _finishAllAndFlush(): void {\n this._finishOpenItems();\n this.log({l: \"pagehide, closing logs\", t: \"navigation\"});\n this._persistQueuedItems(this._queuedItems);\n }\n\n _loadQueuedItems(): QueuedItem[] {\n const key = `${this._name}_queuedItems`;\n try {\n const json = window.localStorage.getItem(key);\n if (json) {\n window.localStorage.removeItem(key);\n return JSON.parse(json);\n }\n } catch (err) {\n console.error(\"Could not load queued log items\", err);\n }\n return [];\n }\n\n _openDB(): Promise {\n return openDatabase(this._name, db => db.createObjectStore(\"logs\", {keyPath: \"id\", autoIncrement: true}), 1);\n }\n \n _persistItem(logItem: ILogItem, filter: LogFilter, forced: boolean): void {\n const serializedItem = logItem.serialize(filter, undefined, forced);\n if (serializedItem) {\n const transformedSerializedItem = this._serializedTransformer(serializedItem);\n this._queuedItems.push({\n json: JSON.stringify(transformedSerializedItem)\n });\n }\n }\n\n _persistQueuedItems(items: QueuedItem[]): void {\n try {\n window.localStorage.setItem(`${this._name}_queuedItems`, JSON.stringify(items));\n } catch (e) {\n console.error(\"Could not persist queued log items in localStorage, they will likely be lost\", e);\n }\n }\n\n async export(): Promise {\n const db = await this._openDB();\n try {\n const txn = db.transaction([\"logs\"], \"readonly\");\n const logs = txn.objectStore(\"logs\");\n const storedItems: QueuedItem[] = await fetchResults(logs.openCursor(), () => false);\n const allItems = storedItems.concat(this._queuedItems);\n return new IDBLogExport(allItems, this, this._platform);\n } finally {\n try {\n db.close();\n } catch (e) {}\n }\n }\n\n async _removeItems(items: QueuedItem[]): Promise {\n const db = await this._openDB();\n try {\n const txn = db.transaction([\"logs\"], \"readwrite\");\n const logs = txn.objectStore(\"logs\");\n for (const item of items) {\n if (typeof item.id === \"number\") {\n logs.delete(item.id);\n } else {\n // assume the (non-persisted) object in each array will be the same\n const queuedIdx = this._queuedItems.indexOf(item);\n if (queuedIdx === -1) {\n this._queuedItems.splice(queuedIdx, 1);\n }\n }\n }\n await txnAsPromise(txn);\n } finally {\n try {\n db.close();\n } catch (e) {}\n }\n }\n}\n\nclass IDBLogExport implements ILogExport {\n private readonly _items: QueuedItem[];\n private readonly _logger: IDBLogger;\n private readonly _platform: Platform;\n\n constructor(items: QueuedItem[], logger: IDBLogger, platform: Platform) {\n this._items = items;\n this._logger = logger;\n this._platform = platform;\n }\n \n get count(): number {\n return this._items.length;\n }\n\n /**\n * @return {Promise}\n */\n removeFromStore(): Promise {\n return this._logger._removeItems(this._items);\n }\n\n asBlob(): BlobHandle {\n const log = {\n formatVersion: 1,\n appVersion: this._platform.updateService?.version,\n items: this._items.map(i => JSON.parse(i.json))\n };\n const json = JSON.stringify(log);\n const buffer: Uint8Array = this._platform.encoding.utf8.encode(json);\n const blob: BlobHandle = this._platform.createBlob(buffer, \"application/json\");\n return blob;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 Daniel Fedorin \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// DOM helper functions\n\nimport {ViewNode} from \"./types\";\n\nexport type ClassNames = { [className: string]: boolean | ((value: T) => boolean) }\nexport type BasicAttributes = { [attribute: string]: ClassNames | boolean | string }\nexport type Child = string | Text | ViewNode;\n\nexport function isChildren(children: object | Child | Child[]): children is Child | Child[] {\n // children should be an not-object (that's the attributes), or a domnode, or an array\n return typeof children !== \"object\" || \"nodeType\" in children || Array.isArray(children);\n}\n\nexport function classNames(obj: ClassNames, value: T): string {\n return Object.entries(obj).reduce((cn, [name, enabled]) => {\n if (typeof enabled === \"function\") {\n enabled = enabled(value);\n }\n if (enabled) {\n return cn + (cn.length ? \" \" : \"\") + name;\n } else {\n return cn;\n }\n }, \"\");\n}\n\nexport function setAttribute(el: Element, name: string, value: string | boolean): void {\n if (name === \"className\") {\n name = \"class\";\n }\n if (value === false) {\n el.removeAttribute(name);\n } else {\n if (value === true) {\n value = name;\n }\n el.setAttribute(name, value);\n }\n}\n\nexport function el(elementName: string, attributes?: BasicAttributes | Child | Child[], children?: Child | Child[]): Element {\n return elNS(HTML_NS, elementName, attributes, children);\n}\n\nexport function elNS(ns: string, elementName: string, attributes?: BasicAttributes | Child | Child[], children?: Child | Child[]): Element {\n if (attributes && isChildren(attributes)) {\n children = attributes;\n attributes = undefined;\n }\n\n const e = document.createElementNS(ns, elementName);\n\n if (attributes) {\n for (let [name, value] of Object.entries(attributes)) {\n if (typeof value === \"object\") {\n // Only className should ever be an object; be careful\n // here anyway and ignore object-valued non-className attributes.\n value = (value !== null && name === \"className\") ? classNames(value, undefined) : false;\n }\n setAttribute(e, name, value);\n }\n }\n\n if (children) {\n if (!Array.isArray(children)) {\n children = [children];\n }\n for (let c of children) {\n if (typeof c === \"string\") {\n c = text(c);\n }\n e.appendChild(c);\n }\n }\n return e;\n}\n\nexport function text(str: string): Text {\n return document.createTextNode(str);\n}\n\nexport const HTML_NS: string = \"http://www.w3.org/1999/xhtml\";\nexport const SVG_NS: string = \"http://www.w3.org/2000/svg\";\n\nexport const TAG_NAMES = {\n [HTML_NS]: [\n \"br\", \"a\", \"ol\", \"ul\", \"li\", \"div\", \"h1\", \"h2\", \"h3\", \"h4\", \"h5\", \"h6\",\n \"p\", \"strong\", \"em\", \"span\", \"img\", \"section\", \"main\", \"article\", \"aside\", \"del\", \"blockquote\",\n \"table\", \"thead\", \"tbody\", \"tr\", \"th\", \"td\", \"hr\",\n \"pre\", \"code\", \"button\", \"time\", \"input\", \"textarea\", \"select\", \"option\", \"label\", \"form\",\n \"progress\", \"output\", \"video\"],\n [SVG_NS]: [\"svg\", \"g\", \"path\", \"circle\", \"ellipse\", \"rect\", \"use\"]\n} as const;\n\nexport const tag: { [tagName in typeof TAG_NAMES[string][number]]: (attributes?: BasicAttributes | Child | Child[], children?: Child | Child[]) => Element } = {} as any;\n\nfor (const [ns, tags] of Object.entries(TAG_NAMES)) {\n for (const tagName of tags) {\n tag[tagName] = function(attributes, children) {\n return elNS(ns, tagName, attributes, children);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {IView, IMountArgs, ViewNode} from \"./types\";\nimport {tag} from \"./html\";\n\nexport function mountView(view: IView, mountArgs?: IMountArgs): ViewNode {\n let node;\n try {\n node = view.mount(mountArgs);\n } catch (err) {\n node = errorToDOM(err);\n }\n return node;\n}\n\nexport function errorToDOM(error: Error): Element {\n const stack = new Error().stack;\n let callee: string | null = null;\n if (stack) {\n callee = stack.split(\"\\n\")[1];\n }\n return tag.div([\n tag.h2(\"Something went wrong…\"),\n tag.h3(error.message),\n tag.p(`This occurred while running ${callee}.`),\n tag.pre(error.stack),\n ]);\n}\n\nexport function insertAt(parentNode: Element, idx: number, childNode: Node): void {\n const isLast = idx === parentNode.childElementCount;\n if (isLast) {\n parentNode.appendChild(childNode);\n } else {\n const nextDomNode = parentNode.children[idx];\n parentNode.insertBefore(childNode, nextDomNode);\n }\n}\n\nexport function removeChildren(parentNode: Element): void {\n parentNode.innerHTML = '';\n}\n\nexport function disableTargetCallback(callback: (evt: Event) => Promise): (evt: Event) => Promise {\n return async (evt: Event) => {\n (evt.target as HTMLElement)?.setAttribute(\"disabled\", \"disabled\");\n await callback(evt);\n (evt.target as HTMLElement)?.removeAttribute(\"disabled\");\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {el} from \"./html\";\nimport {mountView, insertAt} from \"./utils\";\nimport {SubscriptionHandle} from \"../../../../observable/BaseObservable\";\nimport {BaseObservableList as ObservableList, IListObserver} from \"../../../../observable/list/BaseObservableList\";\nimport {IView, IMountArgs} from \"./types\";\n\nexport interface IOptions {\n list: ObservableList,\n onItemClick?: (childView: V, evt: UIEvent) => void,\n className?: string,\n tagName?: string,\n parentProvidesUpdates?: boolean\n}\n\nexport class ListView implements IView, IListObserver {\n\n private _onItemClick?: (childView: V, evt: UIEvent) => void;\n private _className?: string;\n private _tagName: string;\n private _root?: Element;\n protected _subscription?: SubscriptionHandle;\n protected _childCreator: (value: T) => V;\n protected _mountArgs: IMountArgs;\n protected _list: ObservableList;\n protected _childInstances?: V[];\n\n constructor(\n {list, onItemClick, className, tagName = \"ul\", parentProvidesUpdates = true}: IOptions, \n childCreator: (value: T) => V\n ) {\n this._onItemClick = onItemClick;\n this._list = list;\n this._className = className;\n this._tagName = tagName;\n this._root = undefined;\n this._subscription = undefined;\n this._childCreator = childCreator;\n this._childInstances = undefined;\n this._mountArgs = {parentProvidesUpdates};\n }\n\n root(): Element | undefined {\n // won't be undefined when called between mount and unmount\n return this._root;\n }\n\n update(attributes: IOptions) {\n if (attributes.list) {\n if (this._subscription) {\n this._unloadList();\n while (this._root!.lastChild) {\n this._root!.lastChild.remove();\n }\n }\n this._list = attributes.list;\n this.loadList();\n }\n }\n\n mount(): Element {\n const attr: {[name: string]: any} = {};\n if (this._className) {\n attr.className = this._className;\n }\n const root = this._root = el(this._tagName, attr);\n this.loadList();\n if (this._onItemClick) {\n root.addEventListener(\"click\", this);\n }\n return root;\n }\n\n handleEvent(evt: Event) {\n if (evt.type === \"click\") {\n this._handleClick(evt as UIEvent);\n }\n }\n\n unmount(): void {\n if (this._list) {\n this._unloadList();\n }\n }\n\n private _handleClick(event: UIEvent) {\n if (event.target === this._root || !this._onItemClick) {\n return;\n }\n let childNode = event.target as Element;\n while (childNode.parentNode !== this._root) {\n childNode = childNode.parentNode as Element;\n }\n const index = Array.prototype.indexOf.call(this._root!.childNodes, childNode);\n const childView = this._childInstances![index];\n if (childView) {\n this._onItemClick(childView, event);\n }\n }\n\n private _unloadList() {\n this._subscription = this._subscription!();\n for (let child of this._childInstances!) {\n child.unmount();\n }\n this._childInstances = undefined;\n }\n\n protected loadList() {\n if (!this._list) {\n return;\n }\n this._subscription = this._list.subscribe(this);\n this._childInstances = [];\n const fragment = document.createDocumentFragment();\n for (let item of this._list) {\n const child = this._childCreator(item);\n this._childInstances!.push(child);\n fragment.appendChild(mountView(child, this._mountArgs));\n }\n this._root!.appendChild(fragment);\n }\n\n onReset() {\n for (const child of this._childInstances!) {\n child.root()!.remove();\n child.unmount();\n }\n this._childInstances!.length = 0;\n }\n\n onAdd(idx: number, value: T) {\n this.addChild(idx, value);\n }\n\n onRemove(idx: number, value: T) {\n this.removeChild(idx);\n }\n\n onMove(fromIdx: number, toIdx: number, value: T) {\n this.moveChild(fromIdx, toIdx);\n }\n\n onUpdate(i: number, value: T, params: any) {\n this.updateChild(i, value, params);\n }\n\n protected addChild(childIdx: number, value: T) {\n const child = this._childCreator(value);\n this._childInstances!.splice(childIdx, 0, child);\n insertAt(this._root!, childIdx, mountView(child, this._mountArgs));\n }\n\n protected removeChild(childIdx: number) {\n const [child] = this._childInstances!.splice(childIdx, 1);\n child.root()!.remove();\n child.unmount();\n }\n\n protected moveChild(fromChildIdx: number, toChildIdx: number) {\n const [child] = this._childInstances!.splice(fromChildIdx, 1);\n this._childInstances!.splice(toChildIdx, 0, child);\n child.root()!.remove();\n insertAt(this._root!, toChildIdx, child.root()! as Element);\n }\n\n protected updateChild(childIdx: number, value: T, params: any) {\n if (this._childInstances) {\n const instance = this._childInstances![childIdx];\n instance && instance.update(value, params);\n }\n }\n\n // TODO: is this the list or view index? \n protected recreateItem(index: number, value: T) {\n if (this._childInstances) {\n const child = this._childCreator(value);\n if (!child) {\n this.onRemove(index, value);\n } else {\n const [oldChild] = this._childInstances!.splice(index, 1, child);\n this._root!.replaceChild(child.mount(this._mountArgs), oldChild.root()!);\n oldChild.unmount();\n }\n }\n }\n\n public getChildInstanceByIndex(idx: number): V | undefined {\n return this._childInstances?.[idx];\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\nCopyright 2021 Daniel Fedorin \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {IMountArgs, ViewNode, IView} from \"./types\";\n\nexport interface IObservableValue {\n on?(event: \"change\", handler: (props?: string[]) => void): void;\n off?(event: \"change\", handler: (props?: string[]) => void): void;\n}\n\nexport abstract class BaseUpdateView implements IView {\n protected _value: T\n protected _boundUpdateFromValue: ((props?: string[]) => void) | null\n\n abstract mount(args?: IMountArgs): ViewNode;\n abstract root(): ViewNode | undefined;\n abstract update(...any);\n\n constructor(value :T) {\n this._value = value;\n // TODO: can avoid this if we adopt the handleEvent pattern in our EventListener\n this._boundUpdateFromValue = null;\n }\n\n subscribeOnMount(options?: IMountArgs): void {\n const parentProvidesUpdates = options && options.parentProvidesUpdates;\n if (!parentProvidesUpdates) {\n this._subscribe();\n }\n }\n\n unmount(): void {\n this._unsubscribe();\n }\n\n get value(): T {\n return this._value;\n }\n\n _updateFromValue(changedProps?: string[]) {\n this.update(this._value, changedProps);\n }\n\n _subscribe(): void {\n if (typeof this._value?.on === \"function\") {\n this._boundUpdateFromValue = this._updateFromValue.bind(this) as (props?: string[]) => void;\n this._value.on(\"change\", this._boundUpdateFromValue);\n }\n }\n\n _unsubscribe(): void {\n if (this._boundUpdateFromValue) {\n if (typeof this._value.off === \"function\") {\n this._value.off(\"change\", this._boundUpdateFromValue);\n }\n this._boundUpdateFromValue = null;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2021 Daniel Fedorin \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport { setAttribute, text, isChildren, classNames, TAG_NAMES, HTML_NS, ClassNames, Child as NonBoundChild} from \"./html\";\nimport {mountView} from \"./utils\";\nimport {BaseUpdateView, IObservableValue} from \"./BaseUpdateView\";\nimport {IMountArgs, ViewNode, IView} from \"./types\";\n\nfunction objHasFns(obj: ClassNames): obj is { [className: string]: boolean } {\n for(const value of Object.values(obj)) {\n if (typeof value === \"function\") {\n return true;\n }\n }\n return false;\n}\n\nexport type RenderFn = (t: Builder, vm: T) => ViewNode;\ntype TextBinding = (T) => string | number | boolean | undefined | null;\ntype Child = NonBoundChild | TextBinding;\ntype Children = Child | Child[];\ntype EventHandler = ((event: Event) => void);\ntype AttributeStaticValue = string | boolean;\ntype AttributeBinding = (value: T) => AttributeStaticValue;\nexport type AttrValue = AttributeStaticValue | AttributeBinding | EventHandler | ClassNames;\nexport type Attributes = { [attribute: string]: AttrValue };\ntype ElementFn = (attributes?: Attributes | Children, children?: Children) => Element;\nexport type Builder = TemplateBuilder & { [tagName in typeof TAG_NAMES[string][number]]: ElementFn };\n\n/**\n Bindable template. Renders once, and allows bindings for given nodes. If you need\n to change the structure on a condition, use a subtemplate (if)\n\n supports\n - event handlers (attribute fn value with name that starts with on)\n - one way binding of attributes (other attribute fn value)\n - one way binding of text values (child fn value)\n - refs to get dom nodes\n - className binding returning object with className => enabled map\n - add subviews inside the template\n*/\n// TODO: should we rename this to BoundView or something? As opposed to StaticView ...\nexport abstract class TemplateView extends BaseUpdateView {\n private _eventListeners?: { node: Element, name: string, fn: EventHandler, useCapture: boolean }[] = undefined;\n private _bindings?: (() => void)[] = undefined;\n private _root?: ViewNode = undefined;\n // public because used by TemplateBuilder\n _subViews?: IView[] = undefined;\n\n _attach(): void {\n if (this._eventListeners) {\n for (let {node, name, fn, useCapture} of this._eventListeners) {\n node.addEventListener(name, fn, useCapture);\n }\n }\n }\n\n _detach(): void {\n if (this._eventListeners) {\n for (let {node, name, fn, useCapture} of this._eventListeners) {\n node.removeEventListener(name, fn, useCapture);\n }\n }\n }\n\n abstract render(t: Builder, value: T): ViewNode;\n\n mount(options?: IMountArgs): ViewNode {\n const builder = new TemplateBuilder(this) as Builder;\n try {\n this._root = this.render(builder, this._value);\n } finally {\n builder.close();\n }\n // takes care of update being called when needed\n this.subscribeOnMount(options);\n this._attach();\n return this._root!;\n }\n\n unmount(): void {\n this._detach();\n super.unmount();\n if (this._subViews) {\n for (const v of this._subViews) {\n v.unmount();\n }\n }\n }\n\n root(): ViewNode | undefined {\n return this._root;\n }\n\n update(value: T, props?: string[]): void {\n this._value = value;\n if (this._bindings) {\n for (const binding of this._bindings) {\n binding();\n }\n }\n }\n\n _addEventListener(node: Element, name: string, fn: (event: Event) => void, useCapture: boolean = false): void {\n if (!this._eventListeners) {\n this._eventListeners = [];\n }\n this._eventListeners.push({node, name, fn, useCapture});\n }\n\n _addBinding(bindingFn: () => void): void {\n if (!this._bindings) {\n this._bindings = [];\n }\n this._bindings.push(bindingFn);\n }\n\n addSubView(view: IView): void {\n if (!this._subViews) {\n this._subViews = [];\n }\n this._subViews.push(view);\n }\n\n removeSubView(view: IView): void {\n if (!this._subViews) { return; }\n const idx = this._subViews.indexOf(view);\n if (idx !== -1) {\n this._subViews.splice(idx, 1);\n }\n }\n\n updateSubViews(value: IObservableValue, props: string[]) {\n if (this._subViews) {\n for (const v of this._subViews) {\n v.update(value, props);\n }\n }\n }\n}\n\n// what is passed to render\nexport class TemplateBuilder {\n private _templateView: TemplateView;\n private _closed: boolean = false;\n\n constructor(templateView: TemplateView) {\n this._templateView = templateView;\n }\n\n close(): void {\n this._closed = true;\n }\n\n _addBinding(fn: () => void): void {\n if (this._closed) {\n console.trace(\"Adding a binding after render will likely cause memory leaks\");\n }\n this._templateView._addBinding(fn);\n }\n\n get _value(): T {\n return this._templateView.value;\n }\n\n addEventListener(node: Element, name: string, fn: (event: Event) => void, useCapture: boolean = false): void {\n this._templateView._addEventListener(node, name, fn, useCapture);\n }\n\n _addAttributeBinding(node: Element, name: string, fn: (value: T) => boolean | string): void {\n let prevValue: string | boolean | undefined = undefined;\n const binding = () => {\n const newValue = fn(this._value);\n if (prevValue !== newValue) {\n prevValue = newValue;\n setAttribute(node, name, newValue);\n }\n };\n this._addBinding(binding);\n binding();\n }\n\n _addClassNamesBinding(node: Element, obj: ClassNames): void {\n this._addAttributeBinding(node, \"className\", value => classNames(obj, value));\n }\n\n _addTextBinding(fn: (value: T) => ReturnType>): Text {\n const initialValue = fn(this._value)+\"\";\n const node = text(initialValue);\n let prevValue = initialValue;\n const binding = () => {\n const newValue = fn(this._value)+\"\";\n if (prevValue !== newValue) {\n prevValue = newValue;\n node.textContent = newValue;\n }\n };\n\n this._addBinding(binding);\n return node;\n }\n\n _isEventHandler(key: string, value: AttrValue): value is (event: Event) => void {\n // This isn't actually safe, but it's incorrect to feed event handlers to\n // non-on* attributes.\n return key.startsWith(\"on\") && key.length > 2 && typeof value === \"function\";\n }\n\n _setNodeAttributes(node: Element, attributes: Attributes): void {\n for(let [key, value] of Object.entries(attributes)) {\n // binding for className as object of className => enabled\n if (typeof value === \"object\") {\n if (key !== \"className\" || value === null) {\n // Ignore non-className objects.\n continue;\n }\n if (objHasFns(value)) {\n this._addClassNamesBinding(node, value);\n } else {\n setAttribute(node, key, classNames(value, this._value));\n }\n } else if (this._isEventHandler(key, value)) {\n const eventName = key.substr(2, 1).toLowerCase() + key.substr(3);\n const handler = value;\n this._templateView._addEventListener(node, eventName, handler);\n } else if (typeof value === \"function\") {\n this._addAttributeBinding(node, key, value);\n } else {\n setAttribute(node, key, value);\n }\n }\n }\n\n _setNodeChildren(node: Element, children: Children): void{\n if (!Array.isArray(children)) {\n children = [children];\n }\n for (let child of children) {\n if (typeof child === \"function\") {\n child = this._addTextBinding(child);\n } else if (typeof child === \"string\") {\n // not a DOM node, turn into text\n child = text(child);\n }\n node.appendChild(child);\n }\n }\n \n _addReplaceNodeBinding(fn: (value: T) => R, renderNode: (old: ViewNode | null) => ViewNode): ViewNode {\n let prevValue = fn(this._value);\n let node = renderNode(null);\n\n const binding = () => {\n const newValue = fn(this._value);\n if (prevValue !== newValue) {\n prevValue = newValue;\n const newNode = renderNode(node);\n if (node.parentNode) {\n node.parentNode.replaceChild(newNode, node);\n }\n node = newNode;\n }\n };\n this._addBinding(binding);\n return node;\n }\n\n el(name: string, attributes?: Attributes | Children, children?: Children): ViewNode {\n return this.elNS(HTML_NS, name, attributes, children);\n }\n\n elNS(ns: string, name: string, attributesOrChildren?: Attributes | Children, children?: Children): ViewNode {\n let attributes: Attributes | undefined;\n if (attributesOrChildren) {\n if (isChildren(attributesOrChildren)) {\n children = attributesOrChildren as Children;\n } else {\n attributes = attributesOrChildren as Attributes;\n }\n }\n\n const node = document.createElementNS(ns, name);\n \n if (attributes) {\n this._setNodeAttributes(node, attributes);\n }\n if (children) {\n this._setNodeChildren(node, children);\n }\n\n return node;\n }\n\n // this inserts a view, and is not a view factory for `if`, so returns the root element to insert in the template\n // you should not call t.view() and not use the result (e.g. attach the result to the template DOM tree).\n view(view: IView, mountOptions?: IMountArgs): ViewNode {\n this._templateView.addSubView(view);\n return mountView(view, mountOptions);\n }\n\n // map a value to a view, every time the value changes\n mapView(mapFn: (value: T) => R, viewCreator: (mapped: R) => IView | null): ViewNode {\n return this._addReplaceNodeBinding(mapFn, (prevNode) => {\n if (prevNode && prevNode.nodeType !== Node.COMMENT_NODE) {\n const subViews = this._templateView._subViews;\n if (subViews) {\n const viewIdx = subViews.findIndex(v => v.root() === prevNode);\n if (viewIdx !== -1) {\n const [view] = subViews.splice(viewIdx, 1);\n view.unmount();\n }\n }\n }\n const view = viewCreator(mapFn(this._value));\n if (view) {\n return this.view(view);\n } else {\n return document.createComment(\"node binding placeholder\");\n }\n });\n }\n\n // Special case of mapView for a TemplateView.\n // Always creates a TemplateView, if this is optional depending\n // on mappedValue, use `if` or `mapView`\n map(mapFn: (value: T) => R, renderFn: (mapped: R, t: Builder, vm: T) => ViewNode): ViewNode {\n return this.mapView(mapFn, mappedValue => {\n return new InlineTemplateView(this._value, (t, vm) => {\n const rootNode = renderFn(mappedValue, t, vm);\n if (!rootNode) {\n // TODO: this will confuse mapView which assumes that\n // a comment node means there is no view to clean up\n return document.createComment(\"map placeholder\");\n }\n return rootNode;\n });\n });\n }\n\n ifView(predicate: (value: T) => boolean, viewCreator: (value: T) => IView): ViewNode {\n return this.mapView(\n value => !!predicate(value),\n enabled => enabled ? viewCreator(this._value) : null\n );\n }\n\n // creates a conditional subtemplate\n // use mapView if you need to map to a different view class\n if(predicate: (value: T) => boolean, renderFn: (t: Builder, vm: T) => ViewNode) {\n return this.ifView(predicate, vm => new InlineTemplateView(vm, renderFn));\n }\n\n /** You probably are looking for something else, like map or mapView.\n This is an escape hatch that allows you to do manual DOM manipulations\n as a reaction to a binding change.\n This should only be used if the side-effect won't add any bindings,\n event handlers, ...\n You should not call the TemplateBuilder (e.g. `t.xxx()`) at all from the side effect,\n instead use tags from html.ts to help you construct any DOM you need. */\n mapSideEffect(mapFn: (value: T) => R, sideEffect: (newV: R, oldV: R | undefined) => void) {\n let prevValue = mapFn(this._value);\n const binding = () => {\n const newValue = mapFn(this._value);\n if (prevValue !== newValue) {\n sideEffect(newValue, prevValue);\n prevValue = newValue;\n }\n };\n this._addBinding(binding);\n sideEffect(prevValue, undefined);\n }\n}\n\n\nfor (const [ns, tags] of Object.entries(TAG_NAMES)) {\n for (const tag of tags) {\n TemplateBuilder.prototype[tag] = function(attributes, children) {\n return this.elNS(ns, tag, attributes, children);\n };\n }\n}\n\nexport class InlineTemplateView extends TemplateView {\n private _render: RenderFn;\n\n constructor(value: T, render: RenderFn) {\n super(value);\n this._render = render;\n }\n\n override render(t: Builder, value: T): ViewNode {\n return this._render(t, value);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {tag, text, classNames, setAttribute} from \"./general/html\";\n/**\n * @param {Object} vm view model with {avatarUrl, avatarColorNumber, avatarTitle, avatarLetter}\n * @param {Number} size\n * @return {Element}\n */\nexport function renderStaticAvatar(vm, size, extraClasses = undefined) {\n const hasAvatar = !!vm.avatarUrl(size);\n let avatarClasses = classNames({\n avatar: true,\n [`size-${size}`]: true,\n [`usercolor${vm.avatarColorNumber}`]: !hasAvatar\n });\n if (extraClasses) {\n avatarClasses += ` ${extraClasses}`;\n }\n const avatarContent = hasAvatar ? renderImg(vm, size) : text(vm.avatarLetter);\n const avatar = tag.div({className: avatarClasses, \"data-testid\": \"avatar\"}, [avatarContent]);\n if (hasAvatar) {\n setAttribute(avatar, \"data-avatar-letter\", vm.avatarLetter);\n setAttribute(avatar, \"data-avatar-color\", vm.avatarColorNumber);\n }\n return avatar;\n}\n\nexport function renderImg(vm, size) {\n const sizeStr = size.toString();\n return tag.img({src: vm.avatarUrl(size), width: sizeStr, height: sizeStr, title: vm.avatarTitle});\n}\n\nfunction isAvatarEvent(e) {\n const element = e.target;\n const parent = element.parentElement;\n return element.tagName === \"IMG\" && parent.classList.contains(\"avatar\");\n}\n\nexport function handleAvatarError(e) {\n if (!isAvatarEvent(e)) { return; }\n const parent = e.target.parentElement;\n const avatarColorNumber = parent.getAttribute(\"data-avatar-color\");\n parent.classList.add(`usercolor${avatarColorNumber}`);\n const avatarLetter = parent.getAttribute(\"data-avatar-letter\");\n parent.textContent = avatarLetter;\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseUpdateView} from \"./general/BaseUpdateView\";\nimport {renderStaticAvatar, renderImg} from \"./avatar\";\n\n/*\noptimization to not use a sub view when changing between img and text\nbecause there can be many many instances of this view\n*/\n\nexport class AvatarView extends BaseUpdateView {\n /**\n * @param {ViewModel} value view model with {avatarUrl, avatarColorNumber, avatarTitle, avatarLetter}\n * @param {Number} size\n */\n constructor(value, size) {\n super(value);\n this._root = null;\n this._avatarUrl = null;\n this._avatarTitle = null;\n this._avatarLetter = null;\n this._size = size;\n }\n\n _avatarUrlChanged() {\n if (this.value.avatarUrl(this._size) !== this._avatarUrl) {\n this._avatarUrl = this.value.avatarUrl(this._size);\n return true;\n }\n return false;\n }\n\n _avatarTitleChanged() {\n if (this.value.avatarTitle !== this._avatarTitle) {\n this._avatarTitle = this.value.avatarTitle;\n return true;\n }\n return false;\n }\n\n _avatarLetterChanged() {\n if (this.value.avatarLetter !== this._avatarLetter) {\n this._avatarLetter = this.value.avatarLetter;\n return true;\n }\n return false;\n }\n\n mount(options) {\n this._avatarUrlChanged();\n this._avatarLetterChanged();\n this._avatarTitleChanged();\n this._root = renderStaticAvatar(this.value, this._size);\n // takes care of update being called when needed\n this.subscribeOnMount(options);\n return this._root;\n }\n\n root() {\n return this._root;\n }\n\n update(vm) {\n // important to always call _...changed for every prop \n if (this._avatarUrlChanged()) {\n // avatarColorNumber won't change, it's based on room/user id\n const bgColorClass = `usercolor${vm.avatarColorNumber}`;\n if (vm.avatarUrl(this._size)) {\n this._root.replaceChild(renderImg(vm, this._size), this._root.firstChild);\n this._root.classList.remove(bgColorClass);\n } else {\n this._root.textContent = vm.avatarLetter;\n this._root.classList.add(bgColorClass);\n }\n }\n const hasAvatar = !!vm.avatarUrl(this._size);\n if (this._avatarTitleChanged() && hasAvatar) {\n const element = this._root.firstChild;\n if (element.tagName === \"IMG\") {\n element.setAttribute(\"title\", vm.avatarTitle);\n }\n }\n if (this._avatarLetterChanged() && !hasAvatar) {\n this._root.textContent = vm.avatarLetter;\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nlet container;\n\nexport function spinner(t, extraClasses = undefined) {\n if (container === undefined) {\n container = document.querySelector(\".hydrogen\");\n }\n const classes = Object.assign({\"spinner\": true}, extraClasses);\n if (container?.classList.contains(\"legacy\")) {\n return t.div({className: classes}, [\n t.div(),\n t.div(),\n t.div(),\n t.div(),\n ]);\n } else {\n return t.svg({className: classes, viewBox:\"0 0 100 100\"}, \n t.circle({cx:\"50%\", cy:\"50%\", r:\"45%\", pathLength:\"100\"})\n );\n }\n}\n\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {AvatarView} from \"../../AvatarView.js\";\nimport {spinner} from \"../../common.js\";\n\nexport class RoomTileView extends TemplateView {\n render(t, vm) {\n const classes = {\n \"active\": vm => vm.isOpen,\n \"hidden\": vm => vm.hidden\n };\n return t.li({\"className\": classes}, [\n t.a({href: vm.url}, [\n t.view(new AvatarView(vm, 32), {parentProvidesUpdates: true}),\n t.div({className: \"description\"}, [\n t.div({className: {\"name\": true, unread: vm => vm.isUnread}}, vm => vm.name),\n t.map(vm => vm.busy, busy => {\n if (busy) {\n return spinner(t);\n } else {\n return t.div({\n className: {\n badge: true,\n highlighted: vm => vm.isHighlighted,\n hidden: vm => !vm.badgeCount\n }\n }, vm => vm.badgeCount);\n }\n })\n ])\n ])\n ]);\n }\n\n update(value, props) {\n super.update(value);\n // update the AvatarView as we told it to not subscribe itself with parentProvidesUpdates\n this.updateSubViews(value, props);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ListView} from \"../../general/ListView\";\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {RoomTileView} from \"./RoomTileView.js\";\n\nclass FilterField extends TemplateView {\n render(t, options) {\n const clear = () => {\n filterInput.value = \"\";\n filterInput.blur();\n clearButton.blur();\n options.clear();\n };\n const filterInput = t.input({\n type: \"text\",\n placeholder: options?.label,\n \"aria-label\": options?.label,\n autocomplete: options?.autocomplete,\n enterkeyhint: 'search',\n name: options?.name,\n onInput: event => options.set(event.target.value),\n onKeydown: event => {\n if (event.key === \"Escape\" || event.key === \"Esc\") {\n clear();\n }\n },\n onFocus: () => filterInput.select()\n });\n const clearButton = t.button({\n onClick: clear,\n title: options.i18n`Clear`,\n \"aria-label\": options.i18n`Clear`\n });\n return t.div({className: \"FilterField\"}, [filterInput, clearButton]);\n }\n}\n\nexport class LeftPanelView extends TemplateView {\n render(t, vm) {\n const gridButtonLabel = vm => {\n return vm.gridEnabled ?\n vm.i18n`Show single room` :\n vm.i18n`Enable grid layout`;\n };\n const roomList = t.view(new ListView(\n {\n className: \"RoomList\",\n list: vm.tileViewModels,\n },\n tileVM => new RoomTileView(tileVM)\n ));\n const utilitiesRow = t.div({className: \"utilities\"}, [\n t.a({className: \"button-utility close-session\", href: vm.closeUrl, \"aria-label\": vm.i18n`Back to account list`, title: vm.i18n`Back to account list`}),\n t.view(new FilterField({\n i18n: vm.i18n,\n label: vm.i18n`Filter rooms…`,\n name: \"room-filter\",\n autocomplete: true,\n set: query => {\n // scroll up if we just started filtering\n if (vm.setFilter(query)) {\n roomList.scrollTop = 0;\n }\n },\n clear: () => vm.clearFilter()\n })),\n t.button({\n onClick: () => vm.toggleGrid(),\n className: {\n \"button-utility\": true,\n grid: true,\n on: vm => vm.gridEnabled\n },\n title: gridButtonLabel,\n \"aria-label\": gridButtonLabel\n }),\n t.a({className: \"button-utility settings\", href: vm.settingsUrl, \"aria-label\": vm.i18n`Settings`, title: vm.i18n`Settings`}),\n t.a({className: \"button-utility create\", href: vm.createRoomUrl, \"aria-label\": vm.i18n`Create room`, title: vm.i18n`Create room`}),\n ]);\n\n return t.div({className: \"LeftPanel\"}, [\n utilitiesRow,\n roomList\n ]);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {tag} from \"./html\";\n\nexport class Popup {\n constructor(view, closeCallback = null) {\n this._view = view;\n this._target = null;\n this._arrangement = null;\n this._scroller = null;\n this._fakeRoot = null;\n this._trackingTemplateView = null;\n this._closeCallback = closeCallback;\n }\n\n _getPopupContainer() {\n const appContainer = this._target.closest(\".hydrogen\");\n let popupContainer = appContainer.querySelector(\".popupContainer\");\n if (!popupContainer) {\n popupContainer = tag.div({className: \"popupContainer\"});\n appContainer.appendChild(popupContainer);\n }\n return popupContainer;\n }\n\n trackInTemplateView(templateView) {\n this._trackingTemplateView = templateView;\n this._trackingTemplateView.addSubView(this);\n }\n\n showRelativeTo(target, verticalPadding = 0) {\n this._target = target;\n this._verticalPadding = verticalPadding;\n this._scroller = findScrollParent(this._target);\n this._view.mount();\n this._getPopupContainer().appendChild(this._popup);\n this._position();\n if (this._scroller) {\n document.body.addEventListener(\"scroll\", this, true);\n }\n setTimeout(() => {\n document.body.addEventListener(\"click\", this, false);\n }, 10);\n }\n\n get isOpen() {\n return !!this._view;\n }\n\n close() {\n if (this._view) {\n this._view.unmount();\n this._trackingTemplateView.removeSubView(this);\n if (this._scroller) {\n document.body.removeEventListener(\"scroll\", this, true);\n }\n document.body.removeEventListener(\"click\", this, false);\n this._popup.remove();\n this._view = null;\n if (this._closeCallback) {\n this._closeCallback();\n }\n }\n }\n\n get _popup() {\n return this._view.root();\n }\n\n handleEvent(evt) {\n if (evt.type === \"scroll\") {\n if(!this._position()) {\n this.close();\n }\n } else if (evt.type === \"click\") {\n this._onClick(evt);\n }\n }\n\n _onClick() {\n this.close();\n }\n\n _position() {\n const targetPosition = this._target.getBoundingClientRect();\n const popupWidth = this._popup.clientWidth;\n const popupHeight = this._popup.clientHeight;\n const viewport = (this._scroller ? this._scroller : document.documentElement).getBoundingClientRect();\n\n if (\n targetPosition.top > viewport.bottom ||\n targetPosition.left > viewport.right ||\n targetPosition.bottom < viewport.top ||\n targetPosition.right < viewport.left\n ) {\n return false;\n }\n if (viewport.bottom >= targetPosition.bottom + popupHeight) {\n // show below\n this._popup.style.top = `${targetPosition.bottom + this._verticalPadding}px`;\n } else if (viewport.top <= targetPosition.top - popupHeight) {\n // show top\n this._popup.style.top = `${targetPosition.top - popupHeight - this._verticalPadding}px`;\n } else {\n return false;\n }\n if (viewport.right >= targetPosition.right + popupWidth) {\n // show right\n this._popup.style.left = `${targetPosition.left}px`;\n } else if (viewport.left <= targetPosition.left - popupWidth) {\n // show left\n this._popup.style.left = `${targetPosition.right - popupWidth}px`;\n } else {\n return false;\n }\n return true;\n }\n\n /* fake IView api, so it can be tracked by a template view as a subview */\n root() {\n return this._fakeRoot;\n }\n\n mount() {\n this._fakeRoot = document.createComment(\"popup\");\n return this._fakeRoot;\n }\n\n unmount() {\n this.close();\n }\n\n update() {}\n}\n\nfunction findScrollParent(el) {\n let parent = el;\n do {\n parent = parent.parentElement;\n if (parent.scrollHeight > parent.clientHeight) {\n // double check that overflow would allow a scrollbar\n // because some elements, like a button with negative margin to increate the click target\n // can cause the scrollHeight to be larger than the clientHeight in the parent\n // see button.link class\n const style = window.getComputedStyle(parent);\n const overflowY = style.getPropertyValue(\"overflow-y\");\n if (overflowY === \"auto\" || overflowY === \"scroll\") {\n return parent;\n }\n }\n } while (parent !== document.body);\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"./TemplateView\";\n\nexport class Menu extends TemplateView {\n static option(label, callback) {\n return new MenuOption(label, callback);\n }\n\n constructor(options) {\n super();\n this._options = options;\n }\n\n render(t) {\n return t.ul({className: \"menu\", role: \"menu\"}, this._options.map(o => o.toDOM(t)));\n }\n}\n\nclass MenuOption {\n constructor(label, callback) {\n this.label = label;\n this.callback = callback;\n this.icon = null;\n this.destructive = false;\n }\n\n setIcon(className) {\n this.icon = className;\n return this;\n }\n\n setDestructive() {\n this.destructive = true;\n return this;\n }\n\n toDOM(t) {\n const className = {\n destructive: this.destructive,\n };\n if (this.icon) {\n className.icon = true;\n className[this.icon] = true;\n }\n return t.li({\n className,\n }, t.button({className:\"menu-item\", onClick: this.callback}, this.label));\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ListView} from \"../../general/ListView\";\nimport type {IView} from \"../../general/types\";\nimport {TemplateView, Builder} from \"../../general/TemplateView\";\nimport {IObservableValue} from \"../../general/BaseUpdateView\";\nimport {MissingAttachmentView} from \"./timeline/MissingAttachmentView.js\";\nimport {AnnouncementView} from \"./timeline/AnnouncementView.js\";\nimport {RedactedView} from \"./timeline/RedactedView.js\";\nimport {SimpleTile} from \"../../../../../domain/session/room/timeline/tiles/SimpleTile.js\";\nimport {BaseObservableList as ObservableList} from \"../../../../../observable/list/BaseObservableList\";\n\nexport interface TileView extends IView {\n readonly value: SimpleTile;\n onClick(event: UIEvent);\n} \nexport type TileViewConstructor = new (\n tile: SimpleTile,\n viewClassForTile: ViewClassForEntryFn,\n renderFlags?: { reply?: boolean, interactive?: boolean }\n) => TileView;\nexport type ViewClassForEntryFn = (tile: SimpleTile) => TileViewConstructor;\n\n//import {TimelineViewModel} from \"../../../../../domain/session/room/timeline/TimelineViewModel.js\";\nexport interface TimelineViewModel extends IObservableValue {\n showJumpDown: boolean;\n tiles: ObservableList;\n setVisibleTileRange(start?: SimpleTile, end?: SimpleTile);\n}\n\nfunction bottom(node: HTMLElement): number {\n return node.offsetTop + node.clientHeight;\n}\n\nfunction findFirstNodeIndexAtOrBelow(tiles: HTMLElement, top: number, startIndex: number = (tiles.children.length - 1)): number {\n for (var i = startIndex; i >= 0; i--) {\n const node = tiles.children[i] as HTMLElement;\n if (node.offsetTop < top) {\n return i;\n }\n }\n // return first item if nothing matched before\n return 0;\n}\n\nexport class TimelineView extends TemplateView {\n\n private anchoredNode?: HTMLElement;\n private anchoredBottom: number = 0;\n private stickToBottom: boolean = true;\n private tilesView?: TilesListView;\n private resizeObserver?: ResizeObserver;\n\n constructor(vm: TimelineViewModel, private readonly viewClassForTile: ViewClassForEntryFn) {\n super(vm);\n }\n\n render(t: Builder, vm: TimelineViewModel) {\n // assume this view will be mounted in the parent DOM straight away\n requestAnimationFrame(() => {\n // do initial scroll positioning\n this.restoreScrollPosition();\n });\n this.tilesView = new TilesListView(vm.tiles, () => this.restoreScrollPosition(), this.viewClassForTile);\n const root = t.div({className: \"Timeline\"}, [\n t.div({\n className: \"Timeline_scroller bottom-aligned-scroll\",\n onScroll: () => this.onScroll()\n }, t.view(this.tilesView)),\n t.button({\n className: {\n \"Timeline_jumpDown\": true,\n hidden: vm => !vm.showJumpDown\n },\n title: \"Jump down\",\n onClick: () => this.jumpDown()\n })\n ]);\n\n if (typeof ResizeObserver === \"function\") {\n this.resizeObserver = new ResizeObserver(() => {\n this.restoreScrollPosition();\n });\n this.resizeObserver.observe(root);\n }\n\n return root;\n }\n\n private get scrollNode(): HTMLElement {\n return (this.root()! as HTMLElement).firstElementChild! as HTMLElement;\n }\n\n private get tilesNode(): HTMLElement {\n return this.tilesView!.root()! as HTMLElement;\n }\n\n private jumpDown() {\n const {scrollNode} = this;\n this.stickToBottom = true;\n scrollNode.scrollTop = scrollNode.scrollHeight;\n }\n\n public unmount() {\n super.unmount();\n if (this.resizeObserver) {\n this.resizeObserver.unobserve(this.root()! as Element);\n this.resizeObserver = undefined;\n }\n }\n\n private restoreScrollPosition() {\n const {scrollNode, tilesNode} = this;\n\n const missingTilesHeight = scrollNode.clientHeight - tilesNode.clientHeight;\n if (missingTilesHeight > 0) {\n tilesNode.style.setProperty(\"margin-top\", `${missingTilesHeight}px`);\n // we don't have enough tiles to fill the viewport, so set all as visible\n const len = this.value.tiles.length;\n this.updateVisibleRange(0, len - 1);\n } else {\n tilesNode.style.removeProperty(\"margin-top\");\n if (this.stickToBottom) {\n scrollNode.scrollTop = scrollNode.scrollHeight;\n } else if (this.anchoredNode) {\n const newAnchoredBottom = bottom(this.anchoredNode!);\n if (newAnchoredBottom !== this.anchoredBottom) {\n const bottomDiff = newAnchoredBottom - this.anchoredBottom;\n // scrollBy tends to create less scroll jumps than reassigning scrollTop as it does\n // not depend on reading scrollTop, which might be out of date as some platforms\n // run scrolling off the main thread.\n if (typeof scrollNode.scrollBy === \"function\") {\n scrollNode.scrollBy(0, bottomDiff);\n } else {\n scrollNode.scrollTop = scrollNode.scrollTop + bottomDiff;\n }\n this.anchoredBottom = newAnchoredBottom;\n }\n }\n // TODO: should we be updating the visible range here as well as the range might have changed even though\n // we restored the bottom tile\n }\n }\n\n private onScroll(): void {\n const {scrollNode, tilesNode} = this;\n const {scrollHeight, scrollTop, clientHeight} = scrollNode;\n\n let bottomNodeIndex;\n this.stickToBottom = Math.abs(scrollHeight - (scrollTop + clientHeight)) < 1;\n if (this.stickToBottom) {\n const len = this.value.tiles.length;\n bottomNodeIndex = len - 1;\n } else {\n const viewportBottom = scrollTop + clientHeight;\n const anchoredNodeIndex = findFirstNodeIndexAtOrBelow(tilesNode, viewportBottom);\n this.anchoredNode = tilesNode.childNodes[anchoredNodeIndex] as HTMLElement;\n this.anchoredBottom = bottom(this.anchoredNode!);\n bottomNodeIndex = anchoredNodeIndex;\n }\n let topNodeIndex = findFirstNodeIndexAtOrBelow(tilesNode, scrollTop, bottomNodeIndex);\n this.updateVisibleRange(topNodeIndex, bottomNodeIndex);\n }\n\n private updateVisibleRange(startIndex: number, endIndex: number) {\n // can be undefined, meaning the tiles collection is still empty\n const firstVisibleChild = this.tilesView!.getChildInstanceByIndex(startIndex);\n const lastVisibleChild = this.tilesView!.getChildInstanceByIndex(endIndex);\n this.value.setVisibleTileRange(firstVisibleChild?.value, lastVisibleChild?.value);\n }\n}\n\nclass TilesListView extends ListView {\n\n private onChanged: () => void;\n\n constructor(tiles: ObservableList, onChanged: () => void, private readonly viewClassForTile: ViewClassForEntryFn) {\n super({\n list: tiles,\n onItemClick: (tileView, evt) => tileView.onClick(evt),\n }, tile => {\n const TileView = viewClassForTile(tile);\n return new TileView(tile, viewClassForTile);\n });\n this.onChanged = onChanged;\n }\n\n onReset() {\n super.onReset();\n this.onChanged();\n }\n\n onUpdate(index: number, value: SimpleTile, param: any) {\n if (param === \"shape\") {\n const ExpectedClass = this.viewClassForTile(value);\n const child = this.getChildInstanceByIndex(index);\n if (!ExpectedClass || !(child instanceof ExpectedClass)) {\n // shape was updated, so we need to recreate the tile view,\n // the shape parameter is set in EncryptedEventTile.updateEntry\n // (and perhaps elsewhere by the time you read this)\n super.recreateItem(index, value);\n return;\n }\n }\n super.onUpdate(index, value, param);\n this.onChanged();\n }\n\n onAdd(idx: number, value: SimpleTile) {\n super.onAdd(idx, value);\n this.onChanged();\n }\n\n onRemove(idx: number, value: SimpleTile) {\n super.onRemove(idx, value);\n this.onChanged();\n }\n\n onMove(fromIdx: number, toIdx: number, value: SimpleTile) {\n super.onMove(fromIdx, toIdx, value);\n this.onChanged();\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {spinner} from \"../../common.js\";\n\nexport class TimelineLoadingView extends TemplateView {\n render(t, vm) {\n return t.div({className: \"TimelineLoadingView\"}, [\n spinner(t),\n t.div(vm.isEncrypted ? vm.i18n`Loading encrypted messages…` : vm.i18n`Loading messages…`)\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {Popup} from \"../../general/Popup.js\";\nimport {Menu} from \"../../general/Menu.js\";\n\nexport class MessageComposer extends TemplateView {\n constructor(viewModel, viewClassForTile) {\n super(viewModel);\n this._viewClassForTile = viewClassForTile;\n this._input = null;\n this._attachmentPopup = null;\n this._focusInput = null;\n this._rafResizeHandle = undefined;\n }\n\n render(t, vm) {\n this._input = t.textarea({\n onKeydown: e => this._onKeyDown(e),\n onInput: () => {\n vm.setInput(this._input.value);\n if (this._input.value) {\n this._adjustHeight();\n } else {\n this._clearHeight();\n }\n },\n placeholder: vm => vm.isEncrypted ? \"Send an encrypted message…\" : \"Send a message…\",\n rows: \"1\"\n });\n this._focusInput = () => this._input.focus();\n this.value.on(\"focus\", this._focusInput);\n const replyPreview = t.map(vm => vm.replyViewModel, (rvm, t) => {\n const TileView = rvm && this._viewClassForTile(rvm);\n if (!TileView) { return null; }\n return t.div({\n className: \"MessageComposer_replyPreview\"\n }, [\n t.span({ className: \"replying\" }, \"Replying\"),\n t.button({\n className: \"cancel\",\n onClick: () => this._clearReplyingTo()\n }, \"Close\"),\n t.view(new TileView(rvm, this._viewClassForTile, { interactive: false }, \"div\"))\n ]);\n });\n const input = t.div({className: \"MessageComposer_input\"}, [\n this._input,\n t.button({\n className: \"sendFile\",\n title: vm.i18n`Pick attachment`,\n onClick: evt => this._toggleAttachmentMenu(evt),\n }, vm.i18n`Send file`),\n t.button({\n className: \"send\",\n title: vm.i18n`Send`,\n onClick: () => this._trySend(),\n }, vm.i18n`Send`),\n ]);\n return t.div({ className: {\n MessageComposer: true,\n MessageComposer_canSend: vm => vm.canSend\n } }, [replyPreview, input]);\n }\n\n unmount() {\n if (this._focusInput) {\n this.value.off(\"focus\", this._focusInput);\n }\n super.unmount();\n }\n\n _clearReplyingTo() {\n this.value.clearReplyingTo();\n }\n\n async _trySend() {\n this._input.focus();\n // we clear the composer while enqueuing\n // and restore it when that didn't work somehow\n // to prevent the user from sending the message\n // every time they hit enter while it's still enqueuing.\n const {value} = this._input;\n const restoreValue = () => {\n this._input.value = value;\n this._adjustHeight();\n };\n this._input.value = \"\";\n this._clearHeight();\n try {\n if (!await this.value.sendMessage(value)) {\n restoreValue();\n }\n } catch (err) {\n restoreValue();\n console.error(err);\n }\n }\n\n _onKeyDown(event) {\n if (event.key === \"Enter\" && !event.shiftKey) {\n // don't insert newline into composer\n event.preventDefault();\n this._trySend();\n }\n }\n\n _toggleAttachmentMenu(evt) {\n if (this._attachmentPopup && this._attachmentPopup.isOpen) {\n this._attachmentPopup.close();\n } else {\n const vm = this.value;\n this._attachmentPopup = new Popup(new Menu([\n Menu.option(vm.i18n`Send video`, () => vm.sendVideo()).setIcon(\"video\"),\n Menu.option(vm.i18n`Send picture`, () => vm.sendPicture()).setIcon(\"picture\"),\n Menu.option(vm.i18n`Send file`, () => vm.sendFile()).setIcon(\"file\"),\n ]));\n this._attachmentPopup.trackInTemplateView(this);\n this._attachmentPopup.showRelativeTo(evt.target, 12);\n }\n }\n\n _adjustHeight() {\n if (this._rafResizeHandle) {\n return;\n }\n this._rafResizeHandle = window.requestAnimationFrame(() => {\n const scrollHeight = this._input.scrollHeight;\n this._input.style.height = `${scrollHeight}px`;\n this._rafResizeHandle = undefined;\n });\n }\n\n _clearHeight() {\n this._input.style.removeProperty(\"height\");\n }\n\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\n\nexport class DisabledComposerView extends TemplateView {\n render(t) {\n return t.div({className: \"DisabledComposerView\"}, t.h3(vm => vm.description));\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {Popup} from \"../../general/Popup.js\";\nimport {Menu} from \"../../general/Menu.js\";\nimport {TimelineView} from \"./TimelineView\";\nimport {TimelineLoadingView} from \"./TimelineLoadingView.js\";\nimport {MessageComposer} from \"./MessageComposer.js\";\nimport {DisabledComposerView} from \"./DisabledComposerView.js\";\nimport {AvatarView} from \"../../AvatarView.js\";\n\nexport class RoomView extends TemplateView {\n constructor(vm, viewClassForTile) {\n super(vm);\n this._viewClassForTile = viewClassForTile;\n this._optionsPopup = null;\n }\n\n render(t, vm) {\n return t.main({className: \"RoomView middle\"}, [\n t.div({className: \"RoomHeader middle-header\"}, [\n t.a({className: \"button-utility close-middle\", href: vm.closeUrl, title: vm.i18n`Close room`}),\n t.view(new AvatarView(vm, 32)),\n t.div({className: \"room-description\"}, [\n t.h2(vm => vm.name),\n ]),\n t.button({\n className: \"button-utility room-options\",\n \"aria-label\":vm.i18n`Room options`,\n onClick: evt => this._toggleOptionsMenu(evt)\n })\n ]),\n t.div({className: \"RoomView_body\"}, [\n t.div({className: \"RoomView_error\"}, [\n t.if(vm => vm.error, t => t.div( \n [\n t.p({}, vm => vm.error),\n t.button({ className: \"RoomView_error_closerButton\", onClick: evt => vm.dismissError(evt) })\n ])\n )]),\n t.mapView(vm => vm.timelineViewModel, timelineViewModel => {\n return timelineViewModel ?\n new TimelineView(timelineViewModel, this._viewClassForTile) :\n new TimelineLoadingView(vm); // vm is just needed for i18n\n }),\n t.mapView(vm => vm.composerViewModel,\n composerViewModel => {\n switch (composerViewModel?.kind) {\n case \"composer\":\n return new MessageComposer(vm.composerViewModel, this._viewClassForTile);\n case \"disabled\":\n return new DisabledComposerView(vm.composerViewModel);\n }\n }),\n ])\n ]);\n }\n \n _toggleOptionsMenu(evt) {\n if (this._optionsPopup && this._optionsPopup.isOpen) {\n this._optionsPopup.close();\n } else {\n const vm = this.value;\n const options = [];\n options.push(Menu.option(vm.i18n`Room details`, () => vm.openDetailsPanel()))\n if (vm.canLeave) {\n options.push(Menu.option(vm.i18n`Leave room`, () => this._confirmToLeaveRoom()).setDestructive());\n }\n if (vm.canForget) {\n options.push(Menu.option(vm.i18n`Forget room`, () => vm.forgetRoom()).setDestructive());\n }\n if (vm.canRejoin) {\n options.push(Menu.option(vm.i18n`Rejoin room`, () => vm.rejoinRoom()));\n }\n if (!options.length) {\n return;\n }\n this._optionsPopup = new Popup(new Menu(options));\n this._optionsPopup.trackInTemplateView(this);\n this._optionsPopup.showRelativeTo(evt.target, 10);\n }\n }\n\n _confirmToLeaveRoom() {\n if (confirm(this.value.i18n`Are you sure you want to leave \"${this.value.name}\"?`)) {\n this.value.leaveRoom();\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\n\nexport class UnknownRoomView extends TemplateView {\n render(t, vm) {\n return t.main({className: \"UnknownRoomView middle\"}, t.div([\n t.h2([\n vm.i18n`You are currently not in ${vm.roomIdOrAlias}.`,\n t.br(),\n vm.i18n`Want to join it?`\n ]),\n t.button({\n className: \"button-action primary\",\n onClick: () => vm.join(),\n disabled: vm => vm.busy,\n }, vm.i18n`Join room`),\n t.if(vm => vm.error, t => t.p({className: \"error\"}, vm.error))\n ]));\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {tag} from \"../general/html\";\n\nexport class StaticView {\n constructor(value, render = undefined) {\n if (typeof value === \"function\" && !render) {\n render = value;\n value = null;\n }\n this._root = render ? render(tag, value) : this.render(tag, value);\n }\n\n mount() {\n return this._root;\n }\n\n root() {\n return this._root;\n }\n\n unmount() {}\n update() {}\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {StaticView} from \"./StaticView\";\nimport {spinner} from \"../common.js\";\n\nexport class LoadingView extends StaticView {\n constructor(label = \"Loading\") {\n super(label, (t, label) => {\n return t.div({ className: \"LoadingView\" }, [spinner(t), label]);\n });\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {LoadingView} from \"../../general/LoadingView\";\nimport {AvatarView} from \"../../AvatarView\";\n\nexport class RoomBeingCreatedView extends TemplateView {\n render(t, vm) {\n return t.main({className: \"RoomView middle\"}, [\n t.div({className: \"RoomHeader middle-header\"}, [\n t.a({className: \"button-utility close-middle\", href: vm.closeUrl, title: vm.i18n`Close room`}),\n t.view(new AvatarView(vm, 32)),\n t.div({className: \"room-description\"}, [\n t.h2(vm => vm.name),\n ])\n ]),\n t.div({className: \"RoomView_body\"}, [\n t.mapView(vm => vm.error, error => {\n if (error) {\n return new ErrorView(vm);\n } else {\n return new LoadingView(vm.i18n`Setting up the room…`);\n }\n })\n ])\n ]);\n }\n}\n\nclass ErrorView extends TemplateView {\n render(t,vm) {\n return t.div({className: \"RoomBeingCreated_error centered-column\"}, [\n t.h3(vm.i18n`Could not create the room, something went wrong:`),\n t.div({className: \"RoomView_error form-group\"}, vm.error),\n t.div({className: \"button-row\"},\n t.button({\n className: \"button-action primary destructive\",\n onClick: () => vm.cancel()\n }, vm.i18n`Cancel`))\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {renderStaticAvatar} from \"../../avatar\";\n\nexport class InviteView extends TemplateView {\n render(t, vm) {\n let inviteNodes = [];\n if (vm.isDirectMessage) {\n inviteNodes.push(renderStaticAvatar(vm, 128, \"InviteView_dmAvatar\"));\n }\n let inviterNodes;\n if (vm.isDirectMessage) {\n inviterNodes = [t.strong(vm.name), ` (${vm.inviter?.id}) wants to chat with you.`];\n } else if (vm.inviter) {\n inviterNodes = [renderStaticAvatar(vm.inviter, 24), t.strong(vm.inviter.name), ` (${vm.inviter.id}) invited you.`];\n } else {\n inviterNodes = `You were invited to join.`;\n }\n inviteNodes.push(t.p({className: \"InviteView_inviter\"}, inviterNodes));\n if (!vm.isDirectMessage) {\n inviteNodes.push(t.div({className: \"InviteView_roomProfile\"}, [\n renderStaticAvatar(vm, 64, \"InviteView_roomAvatar\"),\n t.h3(vm.name),\n t.p({className: \"InviteView_roomDescription\"}, vm.roomDescription)\n ]));\n }\n\n return t.main({className: \"InviteView middle\"}, [\n t.div({className: \"RoomHeader middle-header\"}, [\n t.a({className: \"button-utility close-middle\", href: vm.closeUrl, title: vm.i18n`Close invite`}),\n renderStaticAvatar(vm, 32),\n t.div({className: \"room-description\"}, [\n t.h2(vm => vm.name),\n ]),\n ]),\n t.if(vm => vm.error, t => t.div({className: \"RoomView_error\"}, vm => vm.error)),\n t.div({className: \"InviteView_body\"}, [\n t.div({className: \"InviteView_invite\"}, [\n ...inviteNodes,\n t.div({className: \"InviteView_buttonRow\"},\n t.button({\n className: \"button-action primary\",\n disabled: vm => vm.busy,\n onClick: () => vm.accept()\n }, vm.i18n`Accept`)\n ),\n t.div({className: \"InviteView_buttonRow\"},\n t.button({\n className: \"button-action primary destructive\",\n disabled: vm => vm.busy,\n onClick: () => vm.reject()\n }, vm.i18n`Reject`)\n ),\n ])\n ])\n ]);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {spinner} from \"../../common.js\";\n\nexport class LightboxView extends TemplateView {\n render(t, vm) {\n const close = t.a({href: vm.closeUrl, title: vm.i18n`Close`, className: \"close\"});\n const image = t.div({\n role: \"img\",\n \"aria-label\": vm => vm.name,\n title: vm => vm.name,\n className: {\n picture: true,\n hidden: vm => !vm.imageUrl,\n },\n style: vm => `background-image: url('${vm.imageUrl}'); max-width: ${vm.imageWidth}px; max-height: ${vm.imageHeight}px;`\n });\n const loading = t.div({\n className: {\n loading: true,\n hidden: vm => !!vm.imageUrl\n }\n }, [\n spinner(t),\n t.div(vm.i18n`Loading image…`)\n ]);\n const details = t.div({\n className: \"details\"\n }, [t.strong(vm => vm.name), t.br(), \"uploaded by \", t.strong(vm => vm.sender), vm => ` at ${vm.time} on ${vm.date}.`]);\n const dialog = t.div({\n role: \"dialog\",\n className: \"lightbox\",\n onClick: evt => this.clickToClose(evt),\n onKeydown: evt => this.closeOnEscKey(evt)\n }, [image, loading, details, close]);\n trapFocus(t, dialog);\n return dialog;\n }\n\n clickToClose(evt) {\n if (evt.target === this.root()) {\n this.value.close();\n }\n }\n\n closeOnEscKey(evt) {\n if (evt.key === \"Escape\" || evt.key === \"Esc\") {\n this.value.close();\n }\n }\n}\n\nfunction trapFocus(t, element) {\n const elements = focusables(element);\n const first = elements[0];\n const last = elements[elements.length - 1];\n\n t.addEventListener(element, \"keydown\", evt => {\n if (evt.key === \"Tab\") {\n if (evt.shiftKey) {\n if (document.activeElement === first) {\n last.focus();\n evt.preventDefault();\n }\n } else {\n if (document.activeElement === last) {\n first.focus();\n evt.preventDefault();\n }\n }\n }\n }, true);\n Promise.resolve().then(() => {\n first.focus();\n });\n}\n\nfunction focusables(element) {\n return element.querySelectorAll('a[href], button, textarea, input, select');\n}\n\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {spinner} from \"../common.js\";\n\nexport class SessionStatusView extends TemplateView {\n render(t, vm) {\n return t.div({className: {\n \"SessionStatusView\": true,\n \"hidden\": vm => !vm.isShown,\n }}, [\n spinner(t, {hidden: vm => !vm.isWaiting}),\n t.p(vm => vm.statusLabel),\n t.if(vm => vm.isConnectNowShown, t => t.button({className: \"link\", onClick: () => vm.connectNow()}, \"Retry now\")),\n t.if(vm => vm.isSecretStorageShown, t => t.a({href: vm.setupKeyBackupUrl}, \"Go to settings\")),\n t.if(vm => vm.canDismiss, t => t.div({className: \"end\"}, t.button({className: \"dismiss\", onClick: () => vm.dismiss()}))),\n ]);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {RoomView} from \"./room/RoomView.js\";\nimport {RoomBeingCreatedView} from \"./room/RoomBeingCreatedView.js\";\nimport {InviteView} from \"./room/InviteView.js\";\nimport {TemplateView} from \"../general/TemplateView\";\nimport {StaticView} from \"../general/StaticView.js\";\n\nexport class RoomGridView extends TemplateView {\n constructor(vm, viewClassForTile) {\n super(vm);\n this._viewClassForTile = viewClassForTile;\n }\n\n render(t, vm) {\n const children = [];\n for (let i = 0; i < (vm.height * vm.width); i+=1) {\n children.push(t.div({\n onClick: () => vm.focusTile(i),\n onFocusin: () => vm.focusTile(i),\n className: {\n \"container\": true,\n [`tile${i}`]: true,\n \"focused\": vm => vm.focusIndex === i\n },\n }, t.mapView(vm => vm.roomViewModelAt(i), roomVM => {\n if (roomVM) {\n if (roomVM.kind === \"roomBeingCreated\") {\n return new RoomBeingCreatedView(roomVM);\n } else if (roomVM.kind === \"invite\") {\n return new InviteView(roomVM);\n } else {\n return new RoomView(roomVM, this._viewClassForTile);\n }\n } else {\n return new StaticView(t => t.div({className: \"room-placeholder\"}, [\n t.h2({className: \"focused\"}, vm.i18n`Select a room on the left`),\n t.h2({className: \"unfocused\"}, vm.i18n`Click to select this tile`),\n ]));\n }\n })));\n }\n children.push(t.div({className: vm => `focus-ring tile${vm.focusIndex}`}));\n return t.div({className: \"RoomGridView middle layout3x2\"}, children);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\n\nexport class KeyBackupSettingsView extends TemplateView {\n render(t) {\n return t.div([\n t.map(vm => vm.status, (status, t, vm) => {\n switch (status) {\n case \"Enabled\": return renderEnabled(t, vm);\n case \"NewVersionAvailable\": return renderNewVersionAvailable(t, vm);\n case \"SetupKey\": return renderEnableFromKey(t, vm);\n case \"SetupPhrase\": return renderEnableFromPhrase(t, vm);\n case \"Pending\": return t.p(vm.i18n`Waiting to go online…`);\n }\n }),\n t.map(vm => vm.backupWriteStatus, (status, t, vm) => {\n switch (status) {\n case \"Writing\": {\n const progress = t.progress({\n min: 0,\n max: 100,\n value: vm => vm.backupPercentage,\n });\n return t.div([`Backup in progress `, progress, \" \", vm => vm.backupInProgressLabel]);\n }\n case \"Stopped\": {\n let label;\n const error = vm.backupError;\n if (error) {\n label = `Backup has stopped because of an error: ${vm.backupError}`;\n } else {\n label = `Backup has stopped`;\n }\n return t.p(label, \" \", t.button({onClick: () => vm.startBackup()}, `Backup now`));\n }\n case \"Done\":\n return t.p(`All keys are backed up.`);\n default:\n return null;\n }\n })\n ]);\n }\n}\n\nfunction renderEnabled(t, vm) {\n const items = [\n t.p([vm.i18n`Key backup is enabled, using backup version ${vm.backupVersion}. `, t.button({onClick: () => vm.disable()}, vm.i18n`Disable`)])\n ];\n if (vm.dehydratedDeviceId) {\n items.push(t.p(vm.i18n`A dehydrated device id was set up with id ${vm.dehydratedDeviceId} which you can use during your next login with your secret storage key.`));\n }\n return t.div(items);\n}\n\nfunction renderNewVersionAvailable(t, vm) {\n const items = [\n t.p([vm.i18n`A new backup version has been created from another device. Disable key backup and enable it again with the new key.`, t.button({onClick: () => vm.disable()}, vm.i18n`Disable`)])\n ];\n return t.div(items);\n}\n\nfunction renderEnableFromKey(t, vm) {\n const useASecurityPhrase = t.button({className: \"link\", onClick: () => vm.showPhraseSetup()}, vm.i18n`use a security phrase`);\n return t.div([\n t.p(vm.i18n`Enter your secret storage security key below to ${vm.purpose}, which will enable you to decrypt messages received before you logged into this session. The security key is a code of 12 groups of 4 characters separated by a space that Element created for you when setting up security.`),\n renderError(t),\n renderEnableFieldRow(t, vm, vm.i18n`Security key`, (key, setupDehydratedDevice) => vm.enterSecurityKey(key, setupDehydratedDevice)),\n t.p([vm.i18n`Alternatively, you can `, useASecurityPhrase, vm.i18n` if you have one.`]),\n ]);\n}\n\nfunction renderEnableFromPhrase(t, vm) {\n const useASecurityKey = t.button({className: \"link\", onClick: () => vm.showKeySetup()}, vm.i18n`use your security key`);\n return t.div([\n t.p(vm.i18n`Enter your secret storage security phrase below to ${vm.purpose}, which will enable you to decrypt messages received before you logged into this session. The security phrase is a freeform secret phrase you optionally chose when setting up security in Element. It is different from your password to login, unless you chose to set them to the same value.`),\n renderError(t),\n renderEnableFieldRow(t, vm, vm.i18n`Security phrase`, (phrase, setupDehydratedDevice) => vm.enterSecurityPhrase(phrase, setupDehydratedDevice)),\n t.p([vm.i18n`You can also `, useASecurityKey, vm.i18n`.`]),\n ]);\n}\n\nfunction renderEnableFieldRow(t, vm, label, callback) {\n let setupDehydrationCheck;\n const eventHandler = () => callback(input.value, setupDehydrationCheck?.checked || false);\n const input = t.input({type: \"password\", disabled: vm => vm.isBusy, placeholder: label});\n const children = [\n t.p([\n input,\n t.button({disabled: vm => vm.isBusy, onClick: eventHandler}, vm.decryptAction),\n ]),\n ];\n if (vm.offerDehydratedDeviceSetup) {\n setupDehydrationCheck = t.input({type: \"checkbox\", id:\"enable-dehydrated-device\"});\n const moreInfo = t.a({href: \"https://github.com/uhoreg/matrix-doc/blob/dehydration/proposals/2697-device-dehydration.md\", target: \"_blank\", rel: \"noopener\"}, \"more info\");\n children.push(t.p([\n setupDehydrationCheck,\n t.label({for: setupDehydrationCheck.id}, [vm.i18n`Back up my device as well (`, moreInfo, \")\"])\n ]));\n }\n return t.div({className: `row`}, [\n t.div({className: \"label\"}, label),\n t.div({className: \"content\"}, children),\n ]);\n}\n\nfunction renderError(t) {\n return t.if(vm => vm.error, (t, vm) => {\n return t.div([\n t.p({className: \"error\"}, vm => vm.i18n`Could not enable key backup: ${vm.error}.`),\n t.p(vm.i18n`Try double checking that you did not mix up your security key, security phrase and login password as explained above.`)\n ])\n });\n}\n\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {disableTargetCallback} from \"../../general/utils\";\nimport {KeyBackupSettingsView} from \"./KeyBackupSettingsView.js\"\n\nexport class SettingsView extends TemplateView {\n render(t, vm) {\n let version = vm.version;\n if (vm.showUpdateButton) {\n version = t.span([\n vm.version,\n t.button({onClick: () => vm.checkForUpdate()}, vm.i18n`Check for updates`)\n ]);\n }\n\n const row = (t, label, content, extraClass = \"\") => {\n return t.div({className: `row ${extraClass}`}, [\n t.div({className: \"label\"}, label),\n t.div({className: \"content\"}, content),\n ]);\n };\n\n const settingNodes = [];\n\n settingNodes.push(\n t.h3(\"Session\"),\n row(t, vm.i18n`User ID`, vm.userId),\n row(t, vm.i18n`Session ID`, vm.deviceId, \"code\"),\n row(t, vm.i18n`Session key`, vm.fingerprintKey, \"code\"),\n row(t, \"\", t.button({\n onClick: () => vm.logout(),\n disabled: vm => vm.isLoggingOut\n }, vm.i18n`Log out`)),\n );\n settingNodes.push(\n t.h3(\"Key backup\"),\n t.view(new KeyBackupSettingsView(vm.keyBackupViewModel))\n );\n\n settingNodes.push(\n t.h3(\"Notifications\"),\n t.map(vm => vm.pushNotifications.supported, (supported, t) => {\n if (supported === null) {\n return t.p(vm.i18n`Loading…`);\n } else if (supported) {\n const label = vm => vm.pushNotifications.enabled ?\n vm.i18n`Push notifications are enabled`:\n vm.i18n`Push notifications are disabled`;\n const buttonLabel = vm => vm.pushNotifications.enabled ?\n vm.i18n`Disable`:\n vm.i18n`Enable`;\n return row(t, label, t.button({\n onClick: () => vm.togglePushNotifications(),\n disabled: vm => vm.pushNotifications.updating\n }, buttonLabel));\n } else {\n return t.p(vm.i18n`Push notifications are not supported on this browser`);\n }\n }),\n t.if(vm => vm.pushNotifications.supported && vm.pushNotifications.enabled, t => {\n return t.div([\n t.p([\n \"If you think push notifications are not being delivered, \",\n t.button({className: \"link\", onClick: () => vm.checkPushEnabledOnServer()}, \"check\"),\n \" if they got disabled on the server\"\n ]),\n t.map(vm => vm.pushNotifications.enabledOnServer, (enabled, t) => {\n if (enabled === true) {\n return t.p(\"Push notifications are still enabled on the server, so everything should be working. Sometimes notifications can get dropped if they can't be delivered within a given time.\");\n } else if (enabled === false) {\n return t.p(\"Push notifications have been disabled on the server, likely due to a bug. Please re-enable them by clicking Disable and then Enable again above.\");\n }\n }),\n t.map(vm => vm.pushNotifications.serverError, (err, t) => {\n if (err) {\n return t.p(\"Couldn't not check on server: \" + err.message);\n }\n })\n ]);\n })\n );\n \n settingNodes.push(\n t.h3(\"Preferences\"),\n row(t, vm.i18n`Scale down images when sending`, this._imageCompressionRange(t, vm)),\n t.if(vm => !import.meta.env.DEV && vm.activeTheme, (t, vm) => {\n return row(t, vm.i18n`Use the following theme`, this._themeOptions(t, vm));\n }),\n );\n const logButtons = [];\n if (vm.canSendLogsToServer) {\n logButtons.push(t.button({onClick: disableTargetCallback(() => vm.sendLogsToServer())}, `Submit logs to ${vm.logsServer}`));\n }\n logButtons.push(t.button({onClick: () => vm.exportLogs()}, \"Download logs\"));\n settingNodes.push(\n t.h3(\"Application\"),\n row(t, vm.i18n`Version`, version),\n row(t, vm.i18n`Storage usage`, vm => `${vm.storageUsage} / ${vm.storageQuota}`),\n row(t, vm.i18n`Debug logs`, logButtons),\n t.p({className: {hidden: vm => !vm.logsFeedbackMessage}}, vm => vm.logsFeedbackMessage),\n t.p([\"Debug logs contain application usage data including your username, the IDs or aliases of the rooms or groups you have visited, the usernames of other users and the names of files you send. They do not contain messages. For more information, review our \",\n t.a({href: \"https://element.io/privacy\", target: \"_blank\", rel: \"noopener\"}, \"privacy policy\"), \".\"]),\n );\n\n return t.main({className: \"Settings middle\"}, [\n t.div({className: \"middle-header\"}, [\n t.a({className: \"button-utility close-middle\", href: vm.closeUrl, title: vm.i18n`Close settings`}),\n t.h2(\"Settings\")\n ]),\n t.div({className: \"SettingsBody\"}, settingNodes)\n ]);\n }\n\n _imageCompressionRange(t, vm) {\n const step = 32;\n const min = Math.ceil(vm.minSentImageSizeLimit / step) * step;\n const max = (Math.floor(vm.maxSentImageSizeLimit / step) + 1) * step;\n const updateSetting = evt => vm.setSentImageSizeLimit(parseInt(evt.target.value, 10));\n return [t.input({\n type: \"range\",\n step,\n min,\n max,\n value: vm => vm.sentImageSizeLimit || max,\n onInput: updateSetting,\n onChange: updateSetting,\n }), \" \", t.output(vm => {\n return vm.sentImageSizeLimit ? \n vm.i18n`resize to ${vm.sentImageSizeLimit}px` :\n vm.i18n`no resizing`;\n })];\n }\n\n _themeOptions(t, vm) {\n const { themeName: activeThemeName, themeVariant: activeThemeVariant } = vm.activeTheme;\n const optionTags = [];\n // 1. render the dropdown containing the themes\n for (const name of Object.keys(vm.themeMapping)) {\n optionTags.push( t.option({ value: name, selected: name === activeThemeName} , name));\n }\n const select = t.select({\n onChange: (e) => {\n const themeName = e.target.value;\n if(!(\"id\" in vm.themeMapping[themeName])) {\n const colorScheme = darkRadioButton.checked ? \"dark\" : lightRadioButton.checked ? \"light\" : \"default\";\n // execute the radio-button callback so that the theme actually changes!\n // otherwise the theme would only change when another radio-button is selected.\n radioButtonCallback(colorScheme);\n return;\n }\n vm.changeThemeOption(themeName);\n }\n }, optionTags);\n // 2. render the radio-buttons used to choose variant\n const radioButtonCallback = (colorScheme) => {\n const selectedThemeName = select.options[select.selectedIndex].value;\n vm.changeThemeOption(selectedThemeName, colorScheme);\n };\n const isDarkSelected = activeThemeVariant === \"dark\";\n const isLightSelected = activeThemeVariant === \"light\";\n const darkRadioButton = t.input({ type: \"radio\", name: \"radio-chooser\", value: \"dark\", id: \"dark\", checked: isDarkSelected });\n const defaultRadioButton = t.input({ type: \"radio\", name: \"radio-chooser\", value: \"default\", id: \"default\", checked: !(isDarkSelected || isLightSelected) });\n const lightRadioButton = t.input({ type: \"radio\", name: \"radio-chooser\", value: \"light\", id: \"light\", checked: isLightSelected });\n const radioButtons = t.form({\n className: {\n hidden: () => {\n const themeName = select.options[select.selectedIndex].value;\n return \"id\" in vm.themeMapping[themeName];\n }\n },\n onChange: (e) => radioButtonCallback(e.target.value)\n },\n [\n defaultRadioButton,\n t.label({for: \"default\"}, \"Match system theme\"),\n darkRadioButton,\n t.label({for: \"dark\"}, \"dark\"),\n lightRadioButton,\n t.label({for: \"light\"}, \"light\"),\n ]);\n return t.div({ className: \"theme-chooser\" }, [select, radioButtons]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {AvatarView} from \"../AvatarView\";\nimport {StaticView} from \"../general/StaticView\";\n\nexport class CreateRoomView extends TemplateView {\n render(t, vm) {\n return t.main({className: \"middle\"}, \n t.div({className: \"CreateRoomView centered-column\"}, [\n t.h2(\"Create room\"),\n //t.div({className: \"RoomView_error\"}, vm => vm.error),\n t.form({className: \"CreateRoomView_detailsForm form\", onChange: evt => this.onFormChange(evt), onSubmit: evt => this.onSubmit(evt)}, [\n t.div({className: \"vertical-layout\"}, [\n t.button({type: \"button\", className: \"CreateRoomView_selectAvatar\", onClick: () => vm.selectAvatar()},\n t.mapView(vm => vm.hasAvatar, hasAvatar => {\n if (hasAvatar) {\n return new AvatarView(vm, 64);\n } else {\n return new StaticView(undefined, t => {\n return t.div({className: \"CreateRoomView_selectAvatarPlaceholder\"})\n });\n }\n })\n ),\n t.div({className: \"stretch form-row text\"}, [\n t.label({for: \"name\"}, vm.i18n`Room name`),\n t.input({\n onInput: evt => vm.setName(evt.target.value),\n type: \"text\", name: \"name\", id: \"name\",\n placeholder: vm.i18n`Enter a room name`\n }),\n ]),\n ]),\n t.div({className: \"form-row text\"}, [\n t.label({for: \"topic\"}, vm.i18n`Topic (optional)`),\n t.textarea({\n onInput: evt => vm.setTopic(evt.target.value),\n name: \"topic\", id: \"topic\",\n placeholder: vm.i18n`Topic`\n }),\n ]),\n t.div({className: \"form-group\"}, [\n t.div({className: \"form-row check\"}, [\n t.input({type: \"radio\", name: \"isPublic\", id: \"isPrivate\", value: \"false\", checked: !vm.isPublic}),\n t.label({for: \"isPrivate\"}, vm.i18n`Private room, only upon invitation.`)\n ]),\n t.div({className: \"form-row check\"}, [\n t.input({type: \"radio\", name: \"isPublic\", id: \"isPublic\", value: \"true\", checked: vm.isPublic}),\n t.label({for: \"isPublic\"}, vm.i18n`Public room, anyone can join`)\n ]),\n ]),\n t.div({className: {\"form-row check\": true, hidden: vm => vm.isPublic}}, [\n t.input({type: \"checkbox\", name: \"isEncrypted\", id: \"isEncrypted\", checked: vm.isEncrypted}),\n t.label({for: \"isEncrypted\"}, vm.i18n`Enable end-to-end encryption`)\n ]),\n t.div({className: {\"form-row text\": true, hidden: vm => !vm.isPublic}}, [\n t.label({for: \"roomAlias\"}, vm.i18n`Room alias`),\n t.input({\n onInput: evt => vm.setRoomAlias(evt.target.value),\n type: \"text\", name: \"roomAlias\", id: \"roomAlias\",\n placeholder: vm.i18n`Room alias (, or # or #:hs.tld`}),\n ]),\n t.div({className: \"form-group\"}, [\n t.div(t.button({className: \"link\", type: \"button\", onClick: () => vm.toggleAdvancedShown()},\n vm => vm.isAdvancedShown ? vm.i18n`Hide advanced settings` : vm.i18n`Show advanced settings`)),\n t.div({className: {\"form-row check\": true, hidden: vm => !vm.isAdvancedShown}}, [\n t.input({type: \"checkbox\", name: \"isFederationDisabled\", id: \"isFederationDisabled\", checked: vm.isFederationDisabled}),\n t.label({for: \"isFederationDisabled\"}, [\n vm.i18n`Disable federation`,\n t.p({className: \"form-row-description\"}, vm.i18n`Can't be changed later. This will prevent people on other homeservers from joining the room. This is typically used when only people from your own organisation (if applicable) should be allowed in the room, and is otherwise not needed.`)\n ]),\n ]),\n ]),\n t.div({className: \"button-row\"}, [\n t.button({\n className: \"button-action primary\",\n type: \"submit\",\n disabled: vm => !vm.canCreate\n }, vm.i18n`Create room`),\n ]),\n ])\n ])\n );\n }\n\n onFormChange(evt) {\n switch (evt.target.name) {\n case \"isEncrypted\":\n this.value.setEncrypted(evt.target.checked);\n break;\n case \"isPublic\":\n this.value.setPublic(evt.currentTarget.isPublic.value === \"true\");\n break;\n case \"isFederationDisabled\":\n this.value.setFederationDisabled(evt.target.checked);\n break;\n }\n }\n\n onSubmit(evt) {\n evt.preventDefault();\n this.value.create();\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {classNames, tag} from \"../../general/html\";\nimport {AvatarView} from \"../../AvatarView.js\";\n\nexport class RoomDetailsView extends TemplateView {\n render(t, vm) {\n const encryptionString = () => vm.isEncrypted ? vm.i18n`On` : vm.i18n`Off`;\n return t.div({className: \"RoomDetailsView\"}, [\n t.div({className: \"RoomDetailsView_avatar\"},\n [\n t.view(new AvatarView(vm, 52)),\n t.mapView(vm => vm.isEncrypted, isEncrypted => new EncryptionIconView(isEncrypted))\n ]),\n t.div({className: \"RoomDetailsView_name\"}, [t.h2(vm => vm.name)]),\n this._createRoomAliasDisplay(vm),\n t.div({className: \"RoomDetailsView_rows\"},\n [\n this._createRightPanelButtonRow(t, vm.i18n`People`, { MemberCount: true }, vm => vm.memberCount,\n () => vm.openPanel(\"members\")),\n this._createRightPanelRow(t, vm.i18n`Encryption`, {EncryptionStatus: true}, encryptionString)\n ])\n ]);\n }\n\n _createRoomAliasDisplay(vm) {\n return vm.canonicalAlias ? tag.div({className: \"RoomDetailsView_id\"}, [vm.canonicalAlias]) :\n \"\";\n }\n\n _createRightPanelRow(t, label, labelClass, value) {\n const labelClassString = classNames({RoomDetailsView_label: true, ...labelClass});\n return t.div({className: \"RoomDetailsView_row\"}, [\n t.div({className: labelClassString}, [label]),\n t.div({className: \"RoomDetailsView_value\"}, value)\n ]);\n }\n\n _createRightPanelButtonRow(t, label, labelClass, value, onClick) {\n const labelClassString = classNames({RoomDetailsView_label: true, ...labelClass});\n return t.button({className: \"RoomDetailsView_row\", onClick}, [\n t.div({className: labelClassString}, [label]),\n t.div({className: \"RoomDetailsView_value\"}, value)\n ]);\n }\n\n}\n\nclass EncryptionIconView extends TemplateView {\n render(t, isEncrypted) {\n return t.div({className: \"EncryptionIconView\"},\n [t.div({className: isEncrypted ? \"EncryptionIconView_encrypted\" : \"EncryptionIconView_unencrypted\"})]);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// start is included in the range,\n// end is excluded,\n// so [2, 2[ means an empty range\nexport class Range {\n constructor(\n public readonly start: number,\n public readonly end: number\n ) {}\n\n get length() {\n return this.end - this.start;\n }\n\n contains(range: Range): boolean {\n return range.start >= this.start && range.end <= this.end;\n }\n\n containsIndex(idx: number): boolean {\n return idx >= this.start && idx < this.end;\n }\n\n toLocalIndex(idx: number) {\n return idx - this.start;\n }\n\n intersects(range: Range): boolean {\n return range.start < this.end && this.start < range.end;\n }\n\n forEachInIterator(it: Iterator, callback: ((T, i: number) => void)) {\n let i = 0;\n for (i = 0; i < this.start; i += 1) {\n it.next();\n }\n for (i = 0; i < this.length; i += 1) {\n const result = it.next();\n if (result.done) {\n break;\n } else {\n callback(result.value, this.start + i);\n }\n }\n }\n\n [Symbol.iterator](): Iterator {\n return new RangeIterator(this);\n }\n\n reverseIterable(): Iterable {\n return new ReverseRangeIterator(this);\n }\n\n clampIndex(idx: number, end = this.end - 1) {\n return Math.min(Math.max(this.start, idx), end);\n }\n\n getIndexZone(idx): RangeZone {\n if (idx < this.start) {\n return RangeZone.Before;\n } else if (idx < this.end) {\n return RangeZone.Inside;\n } else {\n return RangeZone.After;\n }\n }\n}\n\nexport enum RangeZone {\n Before = 1,\n Inside,\n After\n}\n\nclass RangeIterator implements Iterator {\n private idx: number;\n constructor(private readonly range: Range) {\n this.idx = range.start - 1;\n }\n\n next(): IteratorResult {\n if (this.idx < (this.range.end - 1)) {\n this.idx += 1;\n return {value: this.idx, done: false};\n } else {\n return {value: undefined, done: true};\n }\n }\n}\n\nclass ReverseRangeIterator implements Iterable, Iterator {\n private idx: number;\n constructor(private readonly range: Range) {\n this.idx = range.end;\n }\n\n [Symbol.iterator]() {\n return this;\n }\n\n next(): IteratorResult {\n if (this.idx > this.range.start) {\n this.idx -= 1;\n return {value: this.idx, done: false};\n } else {\n return {value: undefined, done: true};\n }\n }\n}\n\nexport function tests() {\n return {\n \"length\": assert => {\n const a = new Range(2, 5);\n assert.equal(a.length, 3);\n },\n \"iterator\": assert => {\n assert.deepEqual(Array.from(new Range(2, 5)), [2, 3, 4]);\n },\n \"reverseIterable\": assert => {\n assert.deepEqual(Array.from(new Range(2, 5).reverseIterable()), [4, 3, 2]);\n },\n \"containsIndex\": assert => {\n const a = new Range(2, 5);\n assert.equal(a.containsIndex(0), false);\n assert.equal(a.containsIndex(1), false);\n assert.equal(a.containsIndex(2), true);\n assert.equal(a.containsIndex(3), true);\n assert.equal(a.containsIndex(4), true);\n assert.equal(a.containsIndex(5), false);\n assert.equal(a.containsIndex(6), false);\n },\n \"intersects returns false for touching ranges\": assert => {\n const a = new Range(2, 5);\n const b = new Range(5, 10);\n assert.equal(a.intersects(b), false);\n assert.equal(b.intersects(a), false);\n },\n \"intersects returns false\": assert => {\n const a = new Range(2, 5);\n const b = new Range(50, 100);\n assert.equal(a.intersects(b), false);\n assert.equal(b.intersects(a), false);\n },\n \"intersects returns true for 1 overlapping item\": assert => {\n const a = new Range(2, 5);\n const b = new Range(4, 10);\n assert.equal(a.intersects(b), true);\n assert.equal(b.intersects(a), true);\n },\n \"contains beyond left edge\": assert => {\n const a = new Range(2, 5);\n const b = new Range(1, 3);\n assert.equal(a.contains(b), false);\n },\n \"contains at left edge\": assert => {\n const a = new Range(2, 5);\n const b = new Range(2, 3);\n assert.equal(a.contains(b), true);\n },\n \"contains between edges\": assert => {\n const a = new Range(2, 5);\n const b = new Range(3, 4);\n assert.equal(a.contains(b), true);\n },\n \"contains at right edge\": assert => {\n const a = new Range(2, 5);\n const b = new Range(3, 5);\n assert.equal(a.contains(b), true);\n },\n \"contains beyond right edge\": assert => {\n const a = new Range(2, 5);\n const b = new Range(4, 6);\n assert.equal(a.contains(b), false);\n },\n \"contains for non-intersecting ranges\": assert => {\n const a = new Range(2, 5);\n const b = new Range(5, 6);\n assert.equal(a.contains(b), false);\n },\n \"forEachInIterator with more values available\": assert => {\n const callbackValues: {v: string, i: number}[] = [];\n const values = [\"a\", \"b\", \"c\", \"d\", \"e\", \"f\"];\n const it = values[Symbol.iterator]();\n new Range(2, 5).forEachInIterator(it, (v, i) => callbackValues.push({v, i}));\n assert.deepEqual(callbackValues, [\n {v: \"c\", i: 2},\n {v: \"d\", i: 3},\n {v: \"e\", i: 4},\n ]);\n },\n \"forEachInIterator with fewer values available\": assert => {\n const callbackValues: {v: string, i: number}[] = [];\n const values = [\"a\", \"b\", \"c\"];\n const it = values[Symbol.iterator]();\n new Range(2, 5).forEachInIterator(it, (v, i) => callbackValues.push({v, i}));\n assert.deepEqual(callbackValues, [\n {v: \"c\", i: 2},\n ]);\n },\n \"clampIndex\": assert => {\n assert.equal(new Range(2, 5).clampIndex(0), 2);\n assert.equal(new Range(2, 5).clampIndex(2), 2);\n assert.equal(new Range(2, 5).clampIndex(3), 3);\n assert.equal(new Range(2, 5).clampIndex(4), 4);\n assert.equal(new Range(2, 5).clampIndex(5), 4);\n assert.equal(new Range(2, 5).clampIndex(10), 4);\n }\n };\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {Range, RangeZone} from \"./Range\";\nimport {defaultObserverWith} from \"../../../../observable/list/BaseObservableList\";\n\nfunction skipOnIterator(it: Iterator, pos: number): boolean {\n let i = 0;\n while (i < pos) {\n i += 1;\n if(it.next().done) {\n return false;\n }\n }\n return true;\n}\n\nfunction getIteratorValueAtIdx(it: Iterator, idx: number): undefined | T {\n if (skipOnIterator(it, idx)) {\n const result = it.next();\n if (!result.done) {\n return result.value;\n }\n }\n return undefined;\n}\n\nexport enum ResultType {\n Move,\n Add,\n Remove,\n RemoveAndAdd,\n UpdateRange\n}\n\nexport interface MoveResult {\n type: ResultType.Move;\n fromIdx: number;\n toIdx: number\n}\n\ninterface AddResult {\n type: ResultType.Add;\n newRange?: ListRange;\n /** the list index of an item to add */\n addIdx: number;\n /** the value to add at addIdx */\n value: T\n}\n\ninterface RemoveResult {\n type: ResultType.Remove;\n newRange?: ListRange;\n /** the list index of an item to remove, before the add or remove event has been taken into account */\n removeIdx: number;\n}\n\n// need to repeat the fields from RemoveResult and AddResult here\n// to make the discriminated union work\ninterface RemoveAndAddResult {\n type: ResultType.RemoveAndAdd;\n newRange?: ListRange;\n /** the list index of an item to remove, before the add or remove event has been taken into account */\n removeIdx: number;\n /** the list index of an item to add */\n addIdx: number;\n /** the value to add at addIdx */\n value: T;\n}\n\ninterface UpdateRangeResult {\n type: ResultType.UpdateRange;\n newRange?: ListRange;\n}\n\nexport type AddRemoveResult = AddResult | RemoveResult | RemoveAndAddResult | UpdateRangeResult;\n\nexport class ListRange extends Range {\n constructor(\n start: number,\n end: number,\n private _totalLength: number,\n private _viewportItemCount: number = end - start\n ) {\n super(start, end);\n }\n\n expand(amount: number): ListRange {\n // don't expand ranges that won't render anything\n if (this.length === 0) {\n return this;\n }\n const newStart = Math.max(0, this.start - amount);\n const newEnd = Math.min(this.totalLength, this.end + amount);\n return new ListRange(\n newStart,\n newEnd,\n this.totalLength,\n this._viewportItemCount\n );\n }\n\n get totalLength(): number {\n return this._totalLength;\n }\n\n get viewportItemCount(): number {\n return this._viewportItemCount;\n }\n\n static fromViewport(listLength: number, itemHeight: number, listHeight: number, scrollTop: number) {\n const topCount = Math.min(Math.max(0, Math.floor(scrollTop / itemHeight)), listLength);\n const itemsAfterTop = listLength - topCount;\n const viewportItemCount = listHeight !== 0 ? Math.ceil(listHeight / itemHeight) : 0;\n const renderCount = Math.min(viewportItemCount, itemsAfterTop);\n return new ListRange(topCount, topCount + renderCount, listLength, viewportItemCount);\n }\n\n queryAdd(idx: number, value: T, list: Iterable): AddRemoveResult {\n const maxAddIdx = this.viewportItemCount > this.length ? this.end : this.end - 1;\n if (idx <= maxAddIdx) {\n // use maxAddIdx to allow to grow the range by one at a time\n // if the viewport isn't filled yet\n const addIdx = this.clampIndex(idx, maxAddIdx);\n const addValue = addIdx === idx ? value : getIteratorValueAtIdx(list[Symbol.iterator](), addIdx)!;\n return this.createAddResult(addIdx, addValue);\n } else {\n // if the add happened after the range, we only update the range with the new length\n return {type: ResultType.UpdateRange, newRange: this.deriveRange(1, 0)};\n }\n }\n\n queryRemove(idx: number, list: Iterable): AddRemoveResult {\n if (idx < this.end) {\n const removeIdx = this.clampIndex(idx);\n return this.createRemoveResult(removeIdx, list);\n } else {\n return {type: ResultType.UpdateRange, newRange: this.deriveRange(-1, 0)};\n }\n }\n\n queryMove(fromIdx: number, toIdx: number, value: T, list: Iterable): MoveResult | AddRemoveResult | undefined {\n const fromZone = this.getIndexZone(fromIdx);\n const toZone = this.getIndexZone(toIdx);\n if (fromZone === toZone) {\n if (fromZone === RangeZone.Before || fromZone === RangeZone.After) {\n return;\n } else if (fromZone === RangeZone.Inside) {\n return {type: ResultType.Move, fromIdx, toIdx};\n }\n } else {\n const addIdx = this.clampIndex(toIdx);\n const removeIdx = this.clampIndex(fromIdx);\n const addValue = addIdx === toIdx ? value : getIteratorValueAtIdx(list[Symbol.iterator](), addIdx)!;\n return {type: ResultType.RemoveAndAdd, removeIdx, addIdx, value: addValue};\n }\n }\n\n private createAddResult(addIdx: number, value: T): AddRemoveResult {\n // if the view port isn't filled yet, we don't remove\n if (this.viewportItemCount > this.length) {\n return {type: ResultType.Add, addIdx, value, newRange: this.deriveRange(1, 1)};\n } else {\n const removeIdx = this.clampIndex(Number.MAX_SAFE_INTEGER);\n return {type: ResultType.RemoveAndAdd, removeIdx, addIdx, value, newRange: this.deriveRange(1, 0)};\n }\n }\n\n private createRemoveResult(removeIdx: number, list: Iterable): AddRemoveResult {\n if (this.end < this.totalLength) {\n // we have items below the range, we can add one from there to fill the viewport\n const addIdx = this.clampIndex(Number.MAX_SAFE_INTEGER);\n // we assume the value has already been removed from the list,\n // so we can just look up the next value which is already at the same idx\n const value = getIteratorValueAtIdx(list[Symbol.iterator](), addIdx)!;\n return {type: ResultType.RemoveAndAdd, removeIdx, value, addIdx, newRange: this.deriveRange(-1, 0)};\n } else if (this.start !== 0) {\n // move the range 1 item up so we still display a viewport full of items\n const newRange = this.deriveRange(-1, 0, 1);\n const addIdx = newRange.start;\n // we assume the value has already been removed from the list,\n // so we can just look up the next value which is already at the same idx\n const value = getIteratorValueAtIdx(list[Symbol.iterator](), addIdx)!;\n return {type: ResultType.RemoveAndAdd, removeIdx, value, addIdx, newRange};\n } else {\n // we can't add at the bottom nor top, already constrained\n return {type: ResultType.Remove, removeIdx, newRange: this.deriveRange(-1, 0)};\n }\n }\n\n private deriveRange(totalLengthInc: number, viewportItemCountDecr: number, startDecr: number = 0): ListRange {\n const start = this.start - startDecr;\n const totalLength = this.totalLength + totalLengthInc;\n // prevent end being larger than totalLength\n const end = Math.min(Math.max(start, this.end - startDecr + viewportItemCountDecr), totalLength);\n return new ListRange(\n start,\n end,\n totalLength,\n this.viewportItemCount\n );\n }\n}\n\nimport {ObservableArray} from \"../../../../observable/list/ObservableArray\";\n\nexport function tests() {\n return {\n \"fromViewport\": assert => {\n const range = ListRange.fromViewport(10, 20, 90, 30);\n assert.equal(range.start, 1);\n assert.equal(range.end, 6);\n assert.equal(range.totalLength, 10);\n },\n \"fromViewport at end\": assert => {\n const itemHeight = 20;\n const range = ListRange.fromViewport(10, itemHeight, 3 * itemHeight, 7 * itemHeight);\n assert.equal(range.start, 7);\n assert.equal(range.end, 10);\n assert.equal(range.totalLength, 10);\n },\n \"fromViewport with not enough items to fill viewport\": assert => {\n const itemHeight = 20;\n const range = ListRange.fromViewport(5, itemHeight, 8 * itemHeight, 0);\n assert.equal(range.start, 0);\n assert.equal(range.end, 5);\n assert.equal(range.totalLength, 5);\n assert.equal(range.length, 5);\n assert.equal(range.viewportItemCount, 8);\n },\n \"expand at start of list\": assert => {\n const range = new ListRange(1, 5, 10);\n const expanded = range.expand(2);\n assert.equal(expanded.start, 0);\n assert.equal(expanded.end, 7);\n assert.equal(expanded.totalLength, 10);\n assert.equal(expanded.length, 7);\n },\n \"expand at end of list\": assert => {\n const range = new ListRange(7, 9, 10);\n const expanded = range.expand(2);\n assert.equal(expanded.start, 5);\n assert.equal(expanded.end, 10);\n assert.equal(expanded.totalLength, 10);\n assert.equal(expanded.length, 5);\n },\n \"expand in middle of list\": assert => {\n const range = new ListRange(4, 6, 10);\n const expanded = range.expand(2);\n assert.equal(expanded.start, 2);\n assert.equal(expanded.end, 8);\n assert.equal(expanded.totalLength, 10);\n assert.equal(expanded.length, 6);\n },\n \"queryAdd with addition before range\": assert => {\n const list = new ObservableArray([\"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(1, 3, list.length);\n let added = false;\n list.subscribe(defaultObserverWith({\n onAdd(idx, value) {\n added = true;\n const result = range.queryAdd(idx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 2,\n addIdx: 1,\n value: \"b\",\n newRange: new ListRange(1, 3, 5)\n });\n }\n }));\n list.insert(0, \"a\");\n assert(added);\n },\n \"queryAdd with addition within range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"d\", \"e\"]);\n const range = new ListRange(1, 3, list.length);\n let added = false;\n list.subscribe(defaultObserverWith({\n onAdd(idx, value) {\n added = true;\n const result = range.queryAdd(idx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 2,\n addIdx: 2,\n value: \"c\",\n newRange: new ListRange(1, 3, 5)\n });\n }\n }));\n list.insert(2, \"c\");\n assert(added);\n },\n \"queryAdd with addition after range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\"]);\n const range = new ListRange(1, 3, list.length);\n let added = false;\n list.subscribe(defaultObserverWith({\n onAdd(idx, value) {\n added = true;\n const result = range.queryAdd(idx, value, list);\n assert.deepEqual(result, {\n type: ResultType.UpdateRange,\n newRange: new ListRange(1, 3, 5)\n });\n }\n }));\n list.insert(4, \"e\");\n assert(added);\n },\n \"queryAdd with too few items to fill viewport grows the range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"d\"]);\n const viewportItemCount = 4;\n const range = new ListRange(0, 3, list.length, viewportItemCount);\n let added = false;\n list.subscribe(defaultObserverWith({\n onAdd(idx, value) {\n added = true;\n const result = range.queryAdd(idx, value, list);\n assert.deepEqual(result, {\n type: ResultType.Add,\n newRange: new ListRange(0, 4, 4),\n addIdx: 2,\n value: \"c\"\n });\n }\n }));\n list.insert(2, \"c\");\n assert(added);\n },\n \"queryRemove with removal before range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(1, 3, list.length);\n let removed = false;\n list.subscribe(defaultObserverWith({\n onRemove(idx) {\n removed = true;\n const result = range.queryRemove(idx, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 1,\n addIdx: 2,\n value: \"d\",\n newRange: new ListRange(1, 3, 4)\n });\n }\n }));\n list.remove(0);\n assert(removed);\n },\n \"queryRemove with removal within range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(1, 3, list.length);\n let removed = false;\n list.subscribe(defaultObserverWith({\n onRemove(idx) {\n removed = true;\n const result = range.queryRemove(idx, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 2,\n addIdx: 2,\n value: \"d\",\n newRange: new ListRange(1, 3, 4)\n });\n assert.equal(list.length, 4);\n }\n }));\n list.remove(2);\n assert(removed);\n },\n \"queryRemove with removal after range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(1, 3, list.length);\n let removed = false;\n list.subscribe(defaultObserverWith({\n onRemove(idx) {\n removed = true;\n const result = range.queryRemove(idx, list);\n assert.deepEqual(result, {\n type: ResultType.UpdateRange,\n newRange: new ListRange(1, 3, 4)\n });\n }\n }));\n list.remove(3);\n assert(removed);\n },\n \"queryRemove at bottom of range moves range one up\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\"]);\n const range = new ListRange(1, 3, list.length);\n let removed = false;\n list.subscribe(defaultObserverWith({\n onRemove(idx) {\n removed = true;\n const result = range.queryRemove(idx, list);\n assert.deepEqual(result, {\n newRange: new ListRange(0, 2, 2),\n type: ResultType.RemoveAndAdd,\n removeIdx: 2,\n addIdx: 0,\n value: \"a\"\n });\n }\n }));\n list.remove(2);\n assert(removed);\n },\n \"queryRemove with range on full length shrinks range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\"]);\n const range = new ListRange(0, 3, list.length);\n let removed = false;\n list.subscribe(defaultObserverWith({\n onRemove(idx) {\n removed = true;\n const result = range.queryRemove(idx, list);\n assert.deepEqual(result, {\n newRange: new ListRange(0, 2, 2, 3),\n type: ResultType.Remove,\n removeIdx: 2,\n });\n }\n }));\n list.remove(2);\n assert(removed);\n },\n \"queryMove with move inside range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(1, 4, list.length);\n let moved = false;\n list.subscribe(defaultObserverWith({\n onMove(fromIdx, toIdx, value) {\n moved = true;\n const result = range.queryMove(fromIdx, toIdx, value, list);\n assert.deepEqual(result, {\n type: ResultType.Move,\n fromIdx: 2,\n toIdx: 3\n });\n }\n }));\n list.move(2, 3);\n assert(moved);\n },\n \"queryMove with move from before to inside range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(2, 5, list.length);\n let moved = false;\n list.subscribe(defaultObserverWith({\n onMove(fromIdx, toIdx, value) {\n moved = true;\n const result = range.queryMove(fromIdx, toIdx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 2,\n addIdx: 3,\n value: \"a\"\n });\n }\n }));\n list.move(0, 3); // move \"a\" to after \"d\"\n assert(moved);\n },\n \"queryMove with move from after to inside range\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(0, 3, list.length);\n let moved = false;\n list.subscribe(defaultObserverWith({\n onMove(fromIdx, toIdx, value) {\n moved = true;\n const result = range.queryMove(fromIdx, toIdx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 2,\n addIdx: 1,\n value: \"e\"\n });\n }\n }));\n list.move(4, 1); // move \"e\" to before \"b\"\n assert(moved);\n },\n \"queryMove with move inside range to after\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(0, 3, list.length);\n let moved = false;\n list.subscribe(defaultObserverWith({\n onMove(fromIdx, toIdx, value) {\n moved = true;\n const result = range.queryMove(fromIdx, toIdx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 1,\n addIdx: 2,\n value: \"d\"\n });\n }\n }));\n list.move(1, 3); // move \"b\" to after \"d\"\n assert(moved);\n },\n \"queryMove with move inside range to before\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(2, 5, list.length);\n let moved = false;\n list.subscribe(defaultObserverWith({\n onMove(fromIdx, toIdx, value) {\n moved = true;\n const result = range.queryMove(fromIdx, toIdx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 3,\n addIdx: 2,\n value: \"b\"\n });\n }\n }));\n list.move(3, 0); // move \"d\" to before \"a\"\n assert(moved);\n },\n \"queryMove with move from before range to after\": assert => {\n const list = new ObservableArray([\"a\", \"b\", \"c\", \"d\", \"e\"]);\n const range = new ListRange(1, 4, list.length);\n let moved = false;\n list.subscribe(defaultObserverWith({\n onMove(fromIdx, toIdx, value) {\n moved = true;\n const result = range.queryMove(fromIdx, toIdx, value, list);\n assert.deepEqual(result, {\n type: ResultType.RemoveAndAdd,\n removeIdx: 1,\n addIdx: 3,\n value: \"e\"\n });\n }\n }));\n list.move(0, 4); // move \"a\" to after \"e\"\n assert(moved);\n },\n // would be good to test here what multiple mutations look like with executing the result of queryXXX\n // on an array, much like we do in the view.\n };\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {tag} from \"./html\";\nimport {removeChildren, mountView} from \"./utils\";\nimport {ListRange, ResultType, AddRemoveResult} from \"./ListRange\";\nimport {ListView, IOptions as IParentOptions} from \"./ListView\";\nimport {IView} from \"./types\";\n\nexport interface IOptions extends IParentOptions {\n itemHeight: number;\n overflowItems?: number;\n}\n\nexport class LazyListView extends ListView {\n private renderRange?: ListRange;\n private height?: number;\n private itemHeight: number;\n private overflowItems: number;\n private scrollContainer?: HTMLElement;\n\n constructor(\n {itemHeight, overflowItems = 20, ...options}: IOptions, \n childCreator: (value: T) => V\n ) {\n super(options, childCreator);\n this.itemHeight = itemHeight;\n this.overflowItems = overflowItems;\n }\n\n handleEvent(e: Event) {\n if (e.type === \"scroll\") {\n this.handleScroll();\n } else {\n super.handleEvent(e);\n }\n }\n\n handleScroll() {\n const visibleRange = this._getVisibleRange();\n // don't contain empty ranges\n // as it will prevent clearing the list\n // once it is scrolled far enough out of view\n if (visibleRange.length !== 0 && !this.renderRange!.contains(visibleRange)) {\n const prevRenderRange = this.renderRange!;\n this.renderRange = visibleRange.expand(this.overflowItems);\n this.renderUpdate(prevRenderRange, this.renderRange);\n }\n }\n \n // override\n async loadList() {\n /*\n Wait two frames for the return from mount() to be inserted into DOM.\n This should be enough, but if this gives us trouble we can always use\n MutationObserver.\n */\n await new Promise(r => requestAnimationFrame(r));\n await new Promise(r => requestAnimationFrame(r));\n\n if (!this._list) {\n return;\n }\n this._subscription = this._list.subscribe(this);\n const visibleRange = this._getVisibleRange();\n this.renderRange = visibleRange.expand(this.overflowItems);\n this._childInstances = [];\n this.reRenderFullRange(this.renderRange);\n }\n\n private _getVisibleRange() {\n const {clientHeight, scrollTop} = this.root()!;\n if (clientHeight === 0) {\n throw new Error(\"LazyListView height is 0\");\n }\n return ListRange.fromViewport(this._list.length, this.itemHeight, clientHeight, scrollTop);\n }\n\n private reRenderFullRange(range: ListRange) {\n removeChildren(this._listElement!);\n const fragment = document.createDocumentFragment();\n const it = this._list[Symbol.iterator]();\n this._childInstances!.length = 0;\n range.forEachInIterator(it, item => {\n const child = this._childCreator(item);\n this._childInstances!.push(child);\n fragment.appendChild(mountView(child, this._mountArgs));\n });\n this._listElement!.appendChild(fragment);\n this.adjustPadding(range);\n }\n\n private renderUpdate(prevRange: ListRange, newRange: ListRange) {\n if (newRange.intersects(prevRange)) {\n // remove children in reverse order so child index isn't affected by previous removals\n for (const idxInList of prevRange.reverseIterable()) {\n if (!newRange.containsIndex(idxInList)) {\n const localIdx = idxInList - prevRange.start;\n this.removeChild(localIdx);\n }\n }\n // use forEachInIterator instead of for loop as we need to advance\n // the list iterator to the start of the range first\n newRange.forEachInIterator(this._list[Symbol.iterator](), (item, idxInList) => {\n if (!prevRange.containsIndex(idxInList)) {\n const localIdx = idxInList - newRange.start;\n this.addChild(localIdx, item);\n }\n });\n this.adjustPadding(newRange);\n } else {\n this.reRenderFullRange(newRange);\n }\n }\n\n private adjustPadding(range: ListRange) {\n const paddingTop = range.start * this.itemHeight;\n const paddingBottom = (range.totalLength - range.end) * this.itemHeight;\n const style = this._listElement!.style;\n style.paddingTop = `${paddingTop}px`;\n style.paddingBottom = `${paddingBottom}px`;\n }\n\n mount() {\n const listElement = super.mount();\n this.scrollContainer = tag.div({className: \"LazyListParent\"}, listElement) as HTMLElement;\n this.scrollContainer.addEventListener(\"scroll\", this);\n return this.scrollContainer;\n }\n\n unmount() {\n this.root()!.removeEventListener(\"scroll\", this);\n this.scrollContainer = undefined;\n super.unmount();\n }\n\n root(): Element | undefined {\n return this.scrollContainer;\n }\n\n private get _listElement(): HTMLElement | undefined {\n return super.root() as HTMLElement | undefined;\n }\n\n onAdd(idx: number, value: T) {\n const result = this.renderRange!.queryAdd(idx, value, this._list);\n this.applyRemoveAddResult(result);\n }\n\n onRemove(idx: number, value: T) {\n const result = this.renderRange!.queryRemove(idx, this._list);\n this.applyRemoveAddResult(result);\n }\n\n onMove(fromIdx: number, toIdx: number, value: T) {\n const result = this.renderRange!.queryMove(fromIdx, toIdx, value, this._list);\n if (result) {\n if (result.type === ResultType.Move) {\n this.moveChild(\n this.renderRange!.toLocalIndex(result.fromIdx),\n this.renderRange!.toLocalIndex(result.toIdx)\n );\n } else {\n this.applyRemoveAddResult(result);\n }\n }\n }\n\n onUpdate(i: number, value: T, params: any) {\n if (this.renderRange!.containsIndex(i)) {\n this.updateChild(this.renderRange!.toLocalIndex(i), value, params);\n }\n }\n\n private applyRemoveAddResult(result: AddRemoveResult) {\n // order is important here, the new range can have a different start\n if (result.type === ResultType.Remove || result.type === ResultType.RemoveAndAdd) {\n this.removeChild(this.renderRange!.toLocalIndex(result.removeIdx));\n }\n if (result.newRange) {\n this.renderRange = result.newRange;\n this.adjustPadding(this.renderRange)\n }\n if (result.type === ResultType.Add || result.type === ResultType.RemoveAndAdd) {\n this.addChild(this.renderRange!.toLocalIndex(result.addIdx), result.value);\n }\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {AvatarView} from \"../../AvatarView.js\";\n\nexport class MemberTileView extends TemplateView {\n render(t, vm) {\n return t.li({ className: \"MemberTileView\" },\n t.a({ href: vm.detailsUrl },\n [\n t.view(new AvatarView(vm, 32)),\n t.div({ className: \"MemberTileView_name\" }, (vm) => vm.name),\n ])\n );\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {LazyListView} from \"../../general/LazyListView\";\nimport {MemberTileView} from \"./MemberTileView.js\";\n\nexport class MemberListView extends LazyListView {\n constructor(vm) {\n super({\n list: vm.memberTileViewModels,\n className: \"MemberListView\",\n itemHeight: 40\n }, tileViewModel => new MemberTileView(tileViewModel));\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AvatarView} from \"../../AvatarView.js\";\nimport {TemplateView} from \"../../general/TemplateView\";\n\nexport class MemberDetailsView extends TemplateView {\n render(t, vm) {\n return t.div({className: \"MemberDetailsView\"},\n [ t.view(new AvatarView(vm, 128)),\n t.div({className: \"MemberDetailsView_name\"}, t.h2(vm => vm.name)),\n t.div({className: \"MemberDetailsView_id\"}, vm.userId),\n this._createSection(t, vm.i18n`Role`, vm => vm.role),\n this._createSection(t, vm.i18n`Security`, vm.isEncrypted ?\n vm.i18n`Messages in this room are end-to-end encrypted.` :\n vm.i18n`Messages in this room are not end-to-end encrypted.`\n ),\n this._createOptions(t, vm)\n ]);\n }\n\n _createSection(t, label, value) {\n return t.div({ className: \"MemberDetailsView_section\" },\n [\n t.div({className: \"MemberDetailsView_label\"}, label),\n t.div({className: \"MemberDetailsView_value\"}, value)\n ]);\n }\n\n _createOptions(t, vm) {\n return t.div({ className: \"MemberDetailsView_section\" },\n [\n t.div({className: \"MemberDetailsView_label\"}, vm.i18n`Options`),\n t.div({className: \"MemberDetailsView_options\"},\n [\n t.a({href: vm.linkToUser, target: \"_blank\", rel: \"noopener\"}, vm.i18n`Open Link to User`),\n t.button({className: \"text\", onClick: () => vm.openDirectMessage()}, vm.i18n`Open direct message`)\n ])\n ]);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../general/TemplateView\";\nimport {RoomDetailsView} from \"./RoomDetailsView.js\";\nimport {MemberListView} from \"./MemberListView.js\";\nimport {LoadingView} from \"../../general/LoadingView.js\";\nimport {MemberDetailsView} from \"./MemberDetailsView.js\";\n\nexport class RightPanelView extends TemplateView {\n render(t) {\n return t.div({ className: \"RightPanelView\" },\n [\n t.ifView(vm => vm.activeViewModel, vm => new ButtonsView(vm)),\n t.mapView(vm => vm.activeViewModel, vm => this._viewFromType(vm))\n ]\n );\n }\n\n _viewFromType(vm) {\n const type = vm?.type;\n switch (type) {\n case \"room-details\":\n return new RoomDetailsView(vm);\n case \"member-list\":\n return new MemberListView(vm);\n case \"member-details\":\n return new MemberDetailsView(vm);\n default:\n return new LoadingView();\n }\n }\n}\n\nclass ButtonsView extends TemplateView {\n render(t, vm) {\n return t.div({ className: \"RightPanelView_buttons\" },\n [\n t.button({\n className: {\n \"back\": true,\n \"button-utility\": true,\n \"hide\": !vm.activeViewModel.shouldShowBackButton\n }, onClick: () => vm.showPreviousPanel()}),\n t.button({className: \"close button-utility\", onClick: () => vm.closePanel()})\n ]);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ListView} from \"../../../general/ListView\";\nimport {TemplateView} from \"../../../general/TemplateView\";\n\nexport class ReactionsView extends ListView {\n constructor(reactionsViewModel) {\n const options = {\n className: \"Timeline_messageReactions\",\n tagName: \"div\",\n list: reactionsViewModel.reactions,\n onItemClick: reactionView => reactionView.onClick(),\n }\n super(options, reactionVM => new ReactionView(reactionVM));\n }\n}\n\nclass ReactionView extends TemplateView {\n render(t, vm) {\n return t.button({\n className: {\n active: vm => vm.isActive,\n pending: vm => vm.isPending\n },\n }, [vm.key, \" \", vm => `${vm.count}`]);\n }\n\n onClick() {\n this.value.toggle();\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {renderStaticAvatar} from \"../../../avatar\";\nimport {tag} from \"../../../general/html\";\nimport {mountView} from \"../../../general/utils\";\nimport {TemplateView} from \"../../../general/TemplateView\";\nimport {Popup} from \"../../../general/Popup.js\";\nimport {Menu} from \"../../../general/Menu.js\";\nimport {ReactionsView} from \"./ReactionsView.js\";\n\nexport class BaseMessageView extends TemplateView {\n constructor(value, viewClassForTile, renderFlags, tagName = \"li\") {\n super(value);\n this._menuPopup = null;\n this._tagName = tagName;\n this._viewClassForTile = viewClassForTile;\n // TODO An enum could be nice to make code easier to read at call sites.\n this._renderFlags = renderFlags;\n }\n\n get _interactive() { return this._renderFlags?.interactive ?? true; }\n get _isReplyPreview() { return this._renderFlags?.reply; }\n\n render(t, vm) {\n const children = [this.renderMessageBody(t, vm)];\n if (this._interactive) {\n children.push(t.button({className: \"Timeline_messageOptions\"}, \"⋯\"));\n }\n const li = t.el(this._tagName, {\n className: {\n \"Timeline_message\": true,\n own: vm.isOwn,\n unsent: vm.isUnsent,\n unverified: vm.isUnverified,\n disabled: !this._interactive,\n continuation: vm => vm.isContinuation,\n },\n 'data-event-id': vm.eventId\n }, children);\n // given that there can be many tiles, we don't add\n // unneeded DOM nodes in case of a continuation, and we add it\n // with a side-effect binding to not have to create sub views,\n // as the avatar or sender doesn't need any bindings or event handlers.\n // don't use `t` from within the side-effect callback\n t.mapSideEffect(vm => vm.isContinuation, (isContinuation, wasContinuation) => {\n if (isContinuation && wasContinuation === false) {\n li.removeChild(li.querySelector(\".Timeline_messageAvatar\"));\n li.removeChild(li.querySelector(\".Timeline_messageSender\"));\n } else if (!isContinuation && !this._isReplyPreview) {\n const avatar = tag.a({href: vm.memberPanelLink, className: \"Timeline_messageAvatar\"}, [renderStaticAvatar(vm, 30)]);\n const sender = tag.div({className: `Timeline_messageSender usercolor${vm.avatarColorNumber}`}, vm.displayName);\n li.insertBefore(avatar, li.firstChild);\n li.insertBefore(sender, li.firstChild);\n }\n });\n // similarly, we could do this with a simple ifView,\n // but that adds a comment node to all messages without reactions\n let reactionsView = null;\n t.mapSideEffect(vm => vm.reactions, reactions => {\n if (reactions && this._interactive && !reactionsView) {\n reactionsView = new ReactionsView(reactions);\n this.addSubView(reactionsView);\n li.appendChild(mountView(reactionsView));\n } else if (!reactions && reactionsView) {\n li.removeChild(reactionsView.root());\n reactionsView.unmount();\n this.removeSubView(reactionsView);\n reactionsView = null;\n }\n });\n return li;\n }\n\n /* This is called by the parent ListView, which just has 1 listener for the whole list */\n onClick(evt) {\n if (evt.target.className === \"Timeline_messageOptions\") {\n this._toggleMenu(evt.target);\n }\n }\n\n _toggleMenu(button) {\n if (this._menuPopup && this._menuPopup.isOpen) {\n this._menuPopup.close();\n } else {\n const options = this.createMenuOptions(this.value);\n if (!options.length) {\n return;\n }\n this.root().classList.add(\"menuOpen\");\n const onClose = () => this.root().classList.remove(\"menuOpen\");\n this._menuPopup = new Popup(new Menu(options), onClose);\n this._menuPopup.trackInTemplateView(this);\n this._menuPopup.showRelativeTo(button, 2);\n }\n }\n\n createMenuOptions(vm) {\n const options = [];\n if (vm.canReact && vm.shape !== \"redacted\" && !vm.isPending) {\n options.push(new QuickReactionsMenuOption(vm));\n options.push(Menu.option(vm.i18n`Reply`, () => vm.startReply()));\n }\n if (vm.canAbortSending) {\n options.push(Menu.option(vm.i18n`Cancel`, () => vm.abortSending()));\n } else if (vm.canRedact) {\n options.push(Menu.option(vm.i18n`Delete`, () => vm.redact()).setDestructive());\n }\n return options;\n }\n\n renderMessageBody() {}\n}\n\nclass QuickReactionsMenuOption {\n constructor(vm) {\n this._vm = vm;\n }\n toDOM(t) {\n const emojiButtons = [\"👍\", \"👎\", \"😄\", \"🎉\", \"😕\", \"❤️\", \"🚀\", \"👀\"].map(emoji => {\n return t.button({onClick: () => this._vm.react(emoji)}, emoji);\n });\n const customButton = t.button({onClick: () => {\n const key = prompt(\"Enter your reaction (emoji)\");\n if (key) {\n this._vm.react(key);\n }\n }}, \"…\");\n return t.li({className: \"quick-reactions\"}, [...emojiButtons, customButton]);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {renderStaticAvatar} from \"../../../avatar\";\nimport {TemplateView} from \"../../../general/TemplateView\";\n\nexport class ReplyPreviewView extends TemplateView {\n constructor(vm, viewClassForTile) {\n super(vm);\n this._viewClassForTile = viewClassForTile;\n }\n render(t, vm) {\n const TileView = this._viewClassForTile(vm);\n if (!TileView) {\n throw new Error(`Shape ${vm.shape} is unrecognized.`)\n }\n const view = new TileView(vm, this._viewClassForTile, { reply: true, interactive: false });\n return t.div(\n { className: \"ReplyPreviewView\" },\n t.blockquote([\n t.a({ className: \"link\", href: vm.permaLink }, \"In reply to\"),\n t.a({ className: \"pill\", href: vm.senderProfileLink }, [\n renderStaticAvatar(vm, 12, undefined, true),\n vm.displayName,\n ]),\n t.br(),\n t.view(view),\n ])\n );\n }\n}\n\nexport class ReplyPreviewError extends TemplateView {\n render(t) {\n return t.blockquote({ className: \"ReplyPreviewView\" }, [\n t.div({ className: \"Timeline_messageBody statusMessage\" }, \"This reply could not be found.\")\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {tag, text} from \"../../../general/html\";\nimport {BaseMessageView} from \"./BaseMessageView.js\";\nimport {ReplyPreviewError, ReplyPreviewView} from \"./ReplyPreviewView.js\";\n\nexport class TextMessageView extends BaseMessageView {\n renderMessageBody(t, vm) {\n const time = t.time({className: {hidden: !vm.date}}, vm.date + \" \" + vm.time);\n const container = t.div({\n className: {\n \"Timeline_messageBody\": true,\n statusMessage: vm => vm.shape === \"message-status\",\n }\n }, t.mapView(vm => vm.replyTile, replyTile => {\n if (this._isReplyPreview) {\n // if this._isReplyPreview = true, this is already a reply preview, don't nest replies for now.\n return null;\n }\n else if (vm.isReply && !replyTile) {\n return new ReplyPreviewError();\n }\n else if (replyTile) {\n return new ReplyPreviewView(replyTile, this._viewClassForTile);\n }\n else {\n return null;\n }\n }));\n\n // exclude comment nodes as they are used by t.map and friends for placeholders\n const shouldRemove = (element) => element?.nodeType !== Node.COMMENT_NODE && element.className !== \"ReplyPreviewView\";\n\n t.mapSideEffect(vm => vm.body, body => {\n while (shouldRemove(container.lastChild)) {\n container.removeChild(container.lastChild);\n }\n for (const part of body.parts) {\n container.appendChild(renderPart(part));\n }\n container.appendChild(time);\n });\n\n return container;\n }\n}\n\nfunction renderList(listBlock) {\n const items = listBlock.items.map(item => tag.li(renderParts(item)));\n const start = listBlock.startOffset;\n if (start) {\n return tag.ol({ start }, items);\n } else {\n return tag.ul(items);\n }\n}\n\nfunction renderImage(imagePart) {\n const attributes = { src: imagePart.src };\n if (imagePart.width) { attributes.width = imagePart.width }\n if (imagePart.height) { attributes.height = imagePart.height }\n if (imagePart.alt) { attributes.alt = imagePart.alt }\n if (imagePart.title) { attributes.title = imagePart.title }\n return tag.img(attributes);\n}\n\nfunction renderPill(pillPart) {\n // The classes and structure are borrowed from avatar.js;\n // We don't call renderStaticAvatar because that would require\n // an intermediate object that has getAvatarUrl etc.\n const classes = `avatar size-12 usercolor${pillPart.avatarColorNumber}`;\n const avatar = tag.div({class: classes}, text(pillPart.avatarInitials));\n const children = renderParts(pillPart.children);\n children.unshift(avatar);\n return tag.a({class: \"pill\", href: pillPart.href, rel: \"noopener\", target: \"_blank\"}, children);\n}\n\nfunction renderTable(tablePart) {\n const children = [];\n if (tablePart.head) {\n const headers = tablePart.head\n .map(cell => tag.th(renderParts(cell)));\n children.push(tag.thead(tag.tr(headers)))\n }\n const rows = [];\n for (const row of tablePart.body) {\n const data = row.map(cell => tag.td(renderParts(cell)));\n rows.push(tag.tr(data));\n }\n children.push(tag.tbody(rows));\n return tag.table(children);\n}\n\n/**\n * Map from part to function that outputs DOM for the part\n */\nconst formatFunction = {\n header: headerBlock => tag[\"h\" + Math.min(6,headerBlock.level)](renderParts(headerBlock.inlines)),\n codeblock: codeBlock => tag.pre(tag.code(text(codeBlock.text))),\n table: tableBlock => renderTable(tableBlock),\n code: codePart => tag.code(text(codePart.text)),\n text: textPart => text(textPart.text),\n link: linkPart => tag.a({href: linkPart.url, className: \"link\", target: \"_blank\", rel: \"noopener\" }, renderParts(linkPart.inlines)),\n pill: renderPill,\n format: formatPart => tag[formatPart.format](renderParts(formatPart.children)),\n rule: () => tag.hr(),\n list: renderList,\n image: renderImage,\n newline: () => tag.br()\n};\n\nfunction renderPart(part) {\n const f = formatFunction[part.type];\n if (!f) {\n return text(`[unknown part type ${part.type}]`);\n }\n return f(part);\n}\n\nfunction renderParts(parts) {\n return Array.from(parts, renderPart);\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageView} from \"./BaseMessageView.js\";\nimport {Menu} from \"../../../general/Menu.js\";\n\nexport class BaseMediaView extends BaseMessageView {\n renderMessageBody(t, vm) {\n const heightRatioPercent = (vm.height / vm.width) * 100; \n let spacerStyle = `padding-top: ${heightRatioPercent}%;`;\n if (vm.platform.isIE11) {\n // preserving aspect-ratio in a grid with padding percentages\n // does not work in IE11, so we assume people won't use it\n // with viewports narrower than 400px where thumbnails will get\n // scaled. If they do, the thumbnail will still scale, but\n // there will be whitespace underneath the picture\n // An alternative would be to use position: absolute but that\n // can slow down rendering, and was bleeding through the lightbox.\n spacerStyle = `height: ${vm.height}px`;\n }\n const children = [\n t.div({className: \"spacer\", style: spacerStyle}),\n this.renderMedia(t, vm),\n t.time(vm.date + \" \" + vm.time),\n ];\n const status = t.div({\n className: {\n status: true,\n hidden: vm => !vm.status\n },\n }, vm => vm.status);\n children.push(status);\n if (vm.isPending) {\n const progress = t.progress({\n min: 0,\n max: 100,\n value: vm => vm.uploadPercentage,\n className: {hidden: vm => !vm.isUploading}\n });\n children.push(progress);\n }\n return t.div({className: \"Timeline_messageBody\"}, [\n t.div({className: \"media\", style: `max-width: ${vm.width}px`, \"data-testid\": \"media\"}, children),\n t.if(vm => vm.error, t => t.p({className: \"error\"}, vm.error))\n ]);\n }\n\n createMenuOptions(vm) {\n const options = super.createMenuOptions(vm);\n if (!vm.isPending) {\n let label;\n switch (vm.shape) {\n case \"image\": label = vm.i18n`Download image`; break;\n case \"video\": label = vm.i18n`Download video`; break;\n default: label = vm.i18n`Download media`; break;\n }\n options.push(Menu.option(label, () => vm.downloadMedia()));\n }\n return options;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMediaView} from \"./BaseMediaView.js\";\n\nexport class ImageView extends BaseMediaView {\n renderMedia(t, vm) {\n const img = t.img({\n src: vm => vm.thumbnailUrl,\n alt: vm => vm.label,\n title: vm => vm.label,\n style: `max-width: ${vm.width}px; max-height: ${vm.height}px;`\n });\n return vm.isPending || !vm.lightboxUrl ? img : t.a({href: vm.lightboxUrl}, img);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function domEventAsPromise(element, successEvent) {\n return new Promise((resolve, reject) => {\n let detach;\n const handleError = evt => {\n detach();\n reject(evt.target.error);\n };\n const handleSuccess = () => {\n detach();\n resolve();\n };\n detach = () => {\n element.removeEventListener(successEvent, handleSuccess);\n element.removeEventListener(\"error\", handleError);\n };\n element.addEventListener(successEvent, handleSuccess);\n element.addEventListener(\"error\", handleError);\n });\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMediaView} from \"./BaseMediaView.js\";\nimport {domEventAsPromise} from \"../../../../dom/utils.js\";\n\nexport class VideoView extends BaseMediaView {\n renderMedia(t) {\n const video = t.video({\n // provide empty data url if video is not decrypted yet.\n // Chrome/Electron need this to enable the play button.\n src: vm => vm.videoUrl || `data:${vm.mimeType},`,\n title: vm => vm.label,\n controls: true,\n preload: \"none\",\n poster: vm => vm.thumbnailUrl,\n onPlay: this._onPlay.bind(this),\n style: vm => `max-width: ${vm.width}px; max-height: ${vm.height}px;${vm.isPending ? \"z-index: -1\": \"\"}`\n });\n\n video.addEventListener(\"error\", this._onError.bind(this));\n\n return video;\n }\n\n async _onPlay(evt) {\n const vm = this.value;\n // download and decrypt the video if needed,\n if (!vm.videoUrl) {\n try {\n const video = evt.target;\n // this will trigger the src to update\n await vm.loadVideo();\n // important to only listen for this after src has changed,\n // or we get the error for the placeholder data url\n const loadPromise = domEventAsPromise(video, \"loadeddata\");\n // now, reload the video and play\n video.load();\n await loadPromise;\n video.play();\n } catch (err) {/* errors are already caught in error event handler */}\n } \n }\n\n _onError(evt) {\n const vm = this.value;\n const video = evt.target;\n const err = video.error;\n if (err instanceof window.MediaError && err.code === 4) {\n if (!video.src.startsWith(\"data:\")) {\n vm.setViewError(new Error(`this browser does not support videos of type ${vm.mimeType}.`));\n } else {\n // ignore placeholder url failing to load\n return;\n }\n } else {\n vm.setViewError(err);\n }\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageView} from \"./BaseMessageView.js\";\n\nexport class FileView extends BaseMessageView {\n renderMessageBody(t, vm) {\n const children = [];\n if (vm.isPending) {\n children.push(vm => vm.label);\n } else {\n children.push(\n t.button({className: \"link\", onClick: () => vm.download()}, vm => vm.label),\n t.time(vm.date + \" \" + vm.time)\n );\n }\n return t.p({className: \"Timeline_messageBody statusMessage\"}, children);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageView} from \"./BaseMessageView.js\";\n\nexport class LocationView extends BaseMessageView {\n renderMessageBody(t, vm) {\n return t.p({className: \"Timeline_messageBody statusMessage\"}, [\n t.span(vm.label),\n t.a({className: \"Timeline_locationLink\", href: vm.mapsLink, target: \"_blank\", rel: \"noopener\"}, vm.i18n`Open in maps`),\n t.time(vm.date + \" \" + vm.time)\n ]);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageView} from \"./BaseMessageView.js\";\n\nexport class MissingAttachmentView extends BaseMessageView {\n renderMessageBody(t, vm) {\n return t.p({className: \"Timeline_messageBody statusMessage\"}, vm.label);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../../general/TemplateView\";\n\nexport class AnnouncementView extends TemplateView {\n // ignore other arguments\n constructor(vm) {\n super(vm);\n }\n\n render(t) {\n return t.li({className: \"AnnouncementView\"}, t.div(vm => vm.announcement));\n }\n \n /* This is called by the parent ListView, which just has 1 listener for the whole list */\n onClick() {}\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseMessageView} from \"./BaseMessageView.js\";\nimport {Menu} from \"../../../general/Menu.js\";\n\nexport class RedactedView extends BaseMessageView {\n renderMessageBody(t) {\n return t.p({className: \"Timeline_messageBody statusMessage\"}, vm => vm.description);\n }\n\n createMenuOptions(vm) {\n const options = super.createMenuOptions(vm);\n if (vm.isRedacting) {\n options.push(Menu.option(vm.i18n`Cancel`, () => vm.abortPendingRedaction()));\n }\n return options;\n }\n}","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../../../general/TemplateView\";\nimport {spinner} from \"../../../common.js\";\n\nexport class GapView extends TemplateView {\n // ignore other argument\n constructor(vm) {\n super(vm);\n }\n\n render(t) {\n const className = {\n GapView: true,\n isLoading: vm => vm.isLoading,\n isAtTop: vm => vm.isAtTop,\n };\n return t.li({className}, [\n spinner(t),\n t.div(vm => vm.isLoading ? vm.i18n`Loading more messages …` : vm.i18n`Not loading!`),\n t.if(vm => vm.error, t => t.strong(vm => vm.error))\n ]);\n }\n\n /* This is called by the parent ListView, which just has 1 listener for the whole list */\n onClick() {}\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TextMessageView} from \"./timeline/TextMessageView.js\";\nimport {ImageView} from \"./timeline/ImageView.js\";\nimport {VideoView} from \"./timeline/VideoView.js\";\nimport {FileView} from \"./timeline/FileView.js\";\nimport {LocationView} from \"./timeline/LocationView.js\";\nimport {MissingAttachmentView} from \"./timeline/MissingAttachmentView.js\";\nimport {AnnouncementView} from \"./timeline/AnnouncementView.js\";\nimport {RedactedView} from \"./timeline/RedactedView.js\";\nimport {SimpleTile} from \"../../../../../domain/session/room/timeline/tiles/SimpleTile.js\";\nimport {GapView} from \"./timeline/GapView.js\";\nimport type {TileViewConstructor, ViewClassForEntryFn} from \"./TimelineView\";\n\nexport function viewClassForTile(vm: SimpleTile): TileViewConstructor {\n switch (vm.shape) {\n case \"gap\":\n return GapView;\n case \"announcement\":\n return AnnouncementView;\n case \"message\":\n case \"message-status\":\n return TextMessageView;\n case \"image\":\n return ImageView;\n case \"video\":\n return VideoView;\n case \"file\":\n return FileView;\n case \"location\":\n return LocationView;\n case \"missing-attachment\":\n return MissingAttachmentView;\n case \"redacted\":\n return RedactedView;\n default:\n throw new Error(`Tiles of shape \"${vm.shape}\" are not supported, check the tileClassForEntry function in the view model`);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {LeftPanelView} from \"./leftpanel/LeftPanelView.js\";\nimport {RoomView} from \"./room/RoomView.js\";\nimport {UnknownRoomView} from \"./room/UnknownRoomView.js\";\nimport {RoomBeingCreatedView} from \"./room/RoomBeingCreatedView.js\";\nimport {InviteView} from \"./room/InviteView.js\";\nimport {LightboxView} from \"./room/LightboxView.js\";\nimport {TemplateView} from \"../general/TemplateView\";\nimport {StaticView} from \"../general/StaticView.js\";\nimport {SessionStatusView} from \"./SessionStatusView.js\";\nimport {RoomGridView} from \"./RoomGridView.js\";\nimport {SettingsView} from \"./settings/SettingsView.js\";\nimport {CreateRoomView} from \"./CreateRoomView.js\";\nimport {RightPanelView} from \"./rightpanel/RightPanelView.js\";\nimport {viewClassForTile} from \"./room/common\";\n\nexport class SessionView extends TemplateView {\n render(t, vm) {\n return t.div({\n className: {\n \"SessionView\": true,\n \"middle-shown\": vm => !!vm.activeMiddleViewModel,\n \"right-shown\": vm => !!vm.rightPanelViewModel\n },\n }, [\n t.view(new SessionStatusView(vm.sessionStatusViewModel)),\n t.view(new LeftPanelView(vm.leftPanelViewModel)),\n t.mapView(vm => vm.activeMiddleViewModel, () => {\n if (vm.roomGridViewModel) {\n return new RoomGridView(vm.roomGridViewModel, viewClassForTile);\n } else if (vm.settingsViewModel) {\n return new SettingsView(vm.settingsViewModel);\n } else if (vm.createRoomViewModel) {\n return new CreateRoomView(vm.createRoomViewModel);\n } else if (vm.currentRoomViewModel) {\n if (vm.currentRoomViewModel.kind === \"invite\") {\n return new InviteView(vm.currentRoomViewModel);\n } else if (vm.currentRoomViewModel.kind === \"room\") {\n return new RoomView(vm.currentRoomViewModel, viewClassForTile);\n } else if (vm.currentRoomViewModel.kind === \"roomBeingCreated\") {\n return new RoomBeingCreatedView(vm.currentRoomViewModel);\n } else {\n return new UnknownRoomView(vm.currentRoomViewModel);\n }\n } else {\n return new StaticView(t => t.div({className: \"room-placeholder\"}, t.h2(vm.i18n`Choose a room on the left side.`)));\n }\n }),\n t.mapView(vm => vm.lightboxViewModel, lightboxViewModel => lightboxViewModel ? new LightboxView(lightboxViewModel) : null),\n t.mapView(vm => vm.rightPanelViewModel, rightPanelViewModel => rightPanelViewModel ? new RightPanelView(rightPanelViewModel) : null)\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function hydrogenGithubLink(t) {\n if (DEFINE_VERSION && DEFINE_GLOBAL_HASH) {\n return t.a({target: \"_blank\",\n href: `https://github.com/vector-im/hydrogen-web/releases/tag/v${DEFINE_VERSION}`},\n `Hydrogen v${DEFINE_VERSION} (${DEFINE_GLOBAL_HASH}) on Github`);\n } else {\n return t.a({target: \"_blank\", href: \"https://github.com/vector-im/hydrogen-web\"},\n \"Hydrogen on Github\");\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\n\nexport class PasswordLoginView extends TemplateView {\n render(t, vm) {\n const disabled = vm => !!vm.isBusy;\n const username = t.input({\n id: \"username\",\n type: \"text\",\n placeholder: vm.i18n`Username`,\n disabled\n });\n const password = t.input({\n id: \"password\",\n type: \"password\",\n placeholder: vm.i18n`Password`,\n disabled\n });\n \n return t.div({className: \"PasswordLoginView form\"}, [\n t.if(vm => vm.error, t => t.div({ className: \"error\" }, vm => vm.error)),\n t.form({\n onSubmit: evnt => {\n evnt.preventDefault();\n vm.login(username.value, password.value);\n }\n }, [\n t.if(vm => vm.errorMessage, (t, vm) => t.p({className: \"error\"}, vm.i18n(vm.errorMessage))),\n t.div({ className: \"form-row text\" }, [t.label({ for: \"username\" }, vm.i18n`Username`), username]),\n t.div({ className: \"form-row text\" }, [t.label({ for: \"password\" }, vm.i18n`Password`), password]),\n t.div({ className: \"button-row\" }, [\n t.button({\n className: \"button-action primary\",\n type: \"submit\",\n disabled\n }, vm.i18n`Log In`),\n ]),\n ])\n ]);\n }\n}\n\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {KeyBackupSettingsView} from \"../session/settings/KeyBackupSettingsView.js\";\n\nexport class AccountSetupView extends TemplateView {\n render(t, vm) {\n return t.div({className: \"Settings\" /* hack for now to get the layout right*/}, [\n t.h3(vm.i18n`Restore your encrypted history?`),\n t.ifView(vm => vm.decryptDehydratedDeviceViewModel, vm => new KeyBackupSettingsView(vm.decryptDehydratedDeviceViewModel)),\n t.map(vm => vm.deviceDecrypted, (decrypted, t) => {\n if (decrypted) {\n return t.p(vm.i18n`That worked out, you're good to go!`);\n } else {\n return t.p(vm.i18n`This will claim the dehydrated device ${vm.dehydratedDeviceId}, and will set up a new one.`);\n }\n }),\n t.div({ className: \"button-row\" }, [\n t.button({\n className: \"button-action primary\",\n onClick: () => { vm.finish(); },\n type: \"button\",\n }, vm => vm.deviceDecrypted ? vm.i18n`Continue` : vm.i18n`Continue without restoring`),\n ]),\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {spinner} from \"../common.js\";\nimport {AccountSetupView} from \"./AccountSetupView.js\";\n\n/** a view used both in the login view and the loading screen\nto show the current state of loading the session.\nJust a spinner and a label, meant to be used as a paragraph */\nexport class SessionLoadStatusView extends TemplateView {\n render(t) {\n const exportLogsButtonIfFailed = t.if(vm => vm.hasError, (t, vm) => {\n return t.button({\n onClick: () => vm.exportLogs()\n }, vm.i18n`Export logs`);\n });\n const logoutButtonIfFailed = t.if(vm => vm.hasError, (t, vm) => {\n return t.button({\n onClick: () => vm.logout()\n }, vm.i18n`Log out`);\n });\n return t.div({className: \"SessionLoadStatusView\"}, [\n t.p({className: \"status\"}, [\n spinner(t, {hidden: vm => !vm.loading}),\n t.p(vm => vm.loadLabel),\n exportLogsButtonIfFailed,\n logoutButtonIfFailed\n ]),\n t.ifView(vm => vm.accountSetupViewModel, vm => new AccountSetupView(vm.accountSetupViewModel)),\n ]);\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {SessionLoadStatusView} from \"./SessionLoadStatusView.js\";\n\nexport class CompleteSSOView extends TemplateView {\n render(t) {\n return t.div({ className: \"CompleteSSOView\" },\n [\n t.p({ className: \"CompleteSSOView_title\" }, \"Finishing up your SSO Login\"),\n t.if(vm => vm.errorMessage, (t, vm) => t.p({className: \"error\"}, vm.i18n(vm.errorMessage))),\n t.mapView(vm => vm.loadViewModel, loadViewModel => loadViewModel ? new SessionLoadStatusView(loadViewModel) : null),\n ]\n );\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {hydrogenGithubLink} from \"./common.js\";\nimport {PasswordLoginView} from \"./PasswordLoginView.js\";\nimport {CompleteSSOView} from \"./CompleteSSOView.js\";\nimport {SessionLoadStatusView} from \"./SessionLoadStatusView.js\";\nimport {spinner} from \"../common.js\";\n\nexport class LoginView extends TemplateView {\n render(t, vm) {\n const disabled = vm => vm.isBusy;\n\n return t.div({className: \"PreSessionScreen\"}, [\n t.button({\n className: \"button-utility LoginView_back\",\n onClick: () => vm.goBack(),\n disabled\n }),\n t.div({className: \"logo\"}),\n t.h1([vm.i18n`Sign In`]),\n t.mapView(vm => vm.completeSSOLoginViewModel, vm => vm ? new CompleteSSOView(vm) : null),\n t.if(vm => vm.showHomeserver, (t, vm) => t.div({ className: \"LoginView_sso form-row text\" },\n [\n t.label({for: \"homeserver\"}, vm.i18n`Homeserver`),\n t.input({\n id: \"homeserver\",\n type: \"text\",\n placeholder: vm.i18n`Your matrix homeserver`,\n value: vm.homeserver,\n disabled,\n onInput: event => vm.setHomeserver(event.target.value),\n onChange: () => vm.queryHomeserver(),\n }),\n t.p({className: {\n LoginView_forwardInfo: true,\n hidden: vm => !vm.resolvedHomeserver\n }}, vm => vm.i18n`You will connect to ${vm.resolvedHomeserver}.`),\n t.if(vm => vm.errorMessage, (t, vm) => t.p({className: \"error\"}, vm.i18n(vm.errorMessage))),\n ]\n )),\n t.if(vm => vm.isFetchingLoginOptions, t => t.div({className: \"LoginView_query-spinner\"}, [spinner(t), t.p(\"Fetching available login options...\")])),\n t.mapView(vm => vm.passwordLoginViewModel, vm => vm ? new PasswordLoginView(vm): null),\n t.if(vm => vm.passwordLoginViewModel && vm.startSSOLoginViewModel, t => t.p({className: \"LoginView_separator\"}, vm.i18n`or`)),\n t.mapView(vm => vm.startSSOLoginViewModel, vm => vm ? new StartSSOLoginView(vm) : null),\n t.mapView(vm => vm.loadViewModel, loadViewModel => loadViewModel ? new SessionLoadStatusView(loadViewModel) : null),\n // use t.mapView rather than t.if to create a new view when the view model changes too\n t.p(hydrogenGithubLink(t))\n ]);\n }\n}\n\nclass StartSSOLoginView extends TemplateView {\n render(t, vm) {\n return t.div({ className: \"StartSSOLoginView\" },\n t.button({\n className: \"StartSSOLoginView_button button-action secondary\",\n type: \"button\",\n onClick: () => vm.startSSOLogin(),\n disabled: vm => vm.isBusy\n }, vm.i18n`Log in with SSO`)\n );\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView, InlineTemplateView} from \"./general/TemplateView\";\nimport {spinner} from \"./common.js\";\n\nexport class LogoutView extends TemplateView {\n render(t, vm) {\n const confirmView = new InlineTemplateView(vm, t => {\n return t.div([\n t.p(\"Are you sure you want to log out?\"),\n t.div({ className: \"button-row\" }, [\n t.a({\n className: \"button-action\",\n type: \"submit\",\n href: vm.cancelUrl,\n }, [\"Cancel\"]),\n t.button({\n className: \"button-action primary destructive\",\n type: \"submit\",\n onClick: () => vm.logout(),\n }, vm.i18n`Log out`)\n ]),\n ]);\n });\n const progressView = new InlineTemplateView(vm, t => {\n return t.p({className: \"status\", hidden: vm => !vm.showStatus}, [\n spinner(t, {hidden: vm => !vm.busy}), t.span(vm => vm.status)\n ]);\n });\n\n return t.div({className: \"LogoutScreen\"}, [\n t.div({className: \"content\"}, [\n t.mapView(vm => vm.showConfirm, showConfirm => {\n return showConfirm ? confirmView : progressView;\n })\n ]),\n ]);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {TemplateView} from \"../general/TemplateView\";\nimport {SessionLoadStatusView} from \"./SessionLoadStatusView.js\";\n\nexport class SessionLoadView extends TemplateView {\n render(t, vm) {\n return t.div({className: \"PreSessionScreen\"}, [\n t.div({className: \"logo\"}),\n t.div({className: \"SessionLoadView\"}, [\n t.view(new SessionLoadStatusView(vm))\n ]),\n t.div({className: {\"button-row\": true, hidden: vm => vm.loading}},\n t.a({className: \"button-action primary\", href: vm.backUrl}, vm.i18n`Go back`))\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {ListView} from \"../general/ListView\";\nimport {TemplateView} from \"../general/TemplateView\";\nimport {hydrogenGithubLink} from \"./common.js\";\nimport {SessionLoadStatusView} from \"./SessionLoadStatusView.js\";\n\nclass SessionPickerItemView extends TemplateView {\n _onDeleteClick() {\n if (confirm(\"Are you sure?\")) {\n this.value.delete();\n }\n }\n\n _onClearClick() {\n if (confirm(\"Are you sure?\")) {\n this.value.clear();\n }\n }\n\n render(t, vm) {\n return t.li([\n t.a({className: \"session-info\", href: vm.openUrl}, [\n t.div({className: `avatar usercolor${vm.avatarColorNumber}`}, vm => vm.avatarInitials),\n t.div({className: \"user-id\"}, vm => vm.label),\n ])\n ]);\n }\n}\n\nexport class SessionPickerView extends TemplateView {\n render(t, vm) {\n const sessionList = new ListView({\n list: vm.sessions,\n parentProvidesUpdates: false,\n }, sessionInfo => {\n return new SessionPickerItemView(sessionInfo);\n });\n\n return t.div({className: \"PreSessionScreen\"}, [\n t.div({className: \"logo\"}),\n t.div({className: \"SessionPickerView\"}, [\n t.h1([\"Continue as …\"]),\n t.view(sessionList),\n t.div({className: \"button-row\"}, [\n t.a({\n className: \"button-action primary\",\n href: vm.cancelUrl\n }, vm.i18n`Sign In`)\n ]),\n t.ifView(vm => vm.loadViewModel, () => new SessionLoadStatusView(vm.loadViewModel)),\n t.p(hydrogenGithubLink(t))\n ])\n ]);\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {SessionView} from \"./session/SessionView.js\";\nimport {LoginView} from \"./login/LoginView\";\nimport {LogoutView} from \"./LogoutView.js\";\nimport {SessionLoadView} from \"./login/SessionLoadView.js\";\nimport {SessionPickerView} from \"./login/SessionPickerView.js\";\nimport {TemplateView} from \"./general/TemplateView\";\nimport {StaticView} from \"./general/StaticView.js\";\n\nexport class RootView extends TemplateView {\n render(t, vm) {\n return t.mapView(vm => vm.activeSection, activeSection => {\n switch (activeSection) {\n case \"error\":\n return new StaticView(t => {\n return t.div({className: \"StatusView\"}, [\n t.h1(\"Something went wrong\"),\n t.p(vm.errorText),\n ])\n });\n case \"session\":\n return new SessionView(vm.sessionViewModel);\n case \"login\":\n return new LoginView(vm.loginViewModel);\n case \"logout\":\n return new LogoutView(vm.logoutViewModel);\n case \"picker\":\n return new SessionPickerView(vm.sessionPickerViewModel);\n case \"redirecting\":\n return new StaticView(t => t.p(\"Redirecting...\"));\n case \"loading\":\n return new SessionLoadView(vm.sessionLoadViewModel);\n default:\n throw new Error(`Unknown section: ${vm.activeSection}`);\n }\n });\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AbortError} from \"../../../utils/error\";\n\nclass Timeout {\n constructor(ms) {\n this._reject = null;\n this._handle = null;\n this._promise = new Promise((resolve, reject) => {\n this._reject = reject;\n this._handle = setTimeout(() => {\n this._reject = null;\n resolve();\n }, ms);\n });\n }\n\n elapsed() {\n return this._promise;\n }\n\n abort() {\n if (this._reject) {\n this._reject(new AbortError());\n clearTimeout(this._handle);\n this._handle = null;\n this._reject = null;\n }\n }\n\n dispose() {\n this.abort();\n }\n}\n\nclass Interval {\n constructor(ms, callback) {\n this._handle = setInterval(callback, ms);\n }\n\n dispose() {\n if (this._handle) {\n clearInterval(this._handle);\n this._handle = null;\n }\n }\n}\n\nclass TimeMeasure {\n constructor() {\n this._start = window.performance.now();\n }\n\n measure() {\n return window.performance.now() - this._start;\n }\n}\n\nexport class Clock {\n createMeasure() {\n return new TimeMeasure();\n }\n\n createTimeout(ms) {\n return new Timeout(ms);\n }\n\n createInterval(callback, ms) {\n return new Interval(ms, callback);\n }\n\n now() {\n return Date.now();\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\n// 3 (imaginary) interfaces are implemented here:\n// - OfflineAvailability (done by registering the sw)\n// - UpdateService (see checkForUpdate method, and should also emit events rather than showing confirm dialog here)\n// - ConcurrentAccessBlocker (see preventConcurrentSessionAccess method)\nexport class ServiceWorkerHandler {\n constructor() {\n this._waitingForReply = new Map();\n this._messageIdCounter = 0;\n this._navigation = null;\n this._registration = null;\n this._registrationPromise = null;\n this._currentController = null;\n this.haltRequests = false;\n }\n\n setNavigation(navigation) {\n this._navigation = navigation;\n }\n\n registerAndStart(path) {\n this._registrationPromise = (async () => {\n navigator.serviceWorker.addEventListener(\"message\", this);\n navigator.serviceWorker.addEventListener(\"controllerchange\", this);\n this._registration = await navigator.serviceWorker.register(path);\n await navigator.serviceWorker.ready;\n this._currentController = navigator.serviceWorker.controller;\n this._registration.addEventListener(\"updatefound\", this);\n this._registrationPromise = null;\n // do we have a new service worker waiting to activate?\n if (this._registration.waiting && this._registration.active) {\n this._proposeUpdate();\n }\n console.log(\"Service Worker registered\");\n })();\n }\n\n _onMessage(event) {\n const {data} = event;\n const replyTo = data.replyTo;\n if (replyTo) {\n const resolve = this._waitingForReply.get(replyTo);\n if (resolve) {\n this._waitingForReply.delete(replyTo);\n resolve(data.payload);\n }\n }\n if (data.type === \"hasSessionOpen\") {\n const hasOpen = this._navigation.observe(\"session\").get() === data.payload.sessionId;\n event.source.postMessage({replyTo: data.id, payload: hasOpen});\n } else if (data.type === \"hasRoomOpen\") {\n const hasSessionOpen = this._navigation.observe(\"session\").get() === data.payload.sessionId;\n const hasRoomOpen = this._navigation.observe(\"room\").get() === data.payload.roomId;\n event.source.postMessage({replyTo: data.id, payload: hasSessionOpen && hasRoomOpen});\n } else if (data.type === \"closeSession\") {\n const {sessionId} = data.payload;\n this._closeSessionIfNeeded(sessionId).finally(() => {\n event.source.postMessage({replyTo: data.id});\n });\n } else if (data.type === \"haltRequests\") {\n // this flag is read in fetch.js\n this.haltRequests = true;\n event.source.postMessage({replyTo: data.id});\n } else if (data.type === \"openRoom\") {\n this._navigation.push(\"room\", data.payload.roomId);\n }\n }\n\n _closeSessionIfNeeded(sessionId) {\n const currentSession = this._navigation?.path.get(\"session\");\n if (sessionId && currentSession?.value === sessionId) {\n return new Promise(resolve => {\n const unsubscribe = this._navigation.pathObservable.subscribe(path => {\n const session = path.get(\"session\");\n if (!session || session.value !== sessionId) {\n unsubscribe();\n resolve();\n }\n });\n this._navigation.push(\"session\");\n });\n } else {\n return Promise.resolve();\n }\n }\n\n async _proposeUpdate() {\n if (document.hidden) {\n return;\n }\n const version = await this._sendAndWaitForReply(\"version\", null, this._registration.waiting);\n if (confirm(`Version ${version.version} (${version.buildHash}) is available. Reload to apply?`)) {\n // prevent any fetch requests from going to the service worker\n // from any client, so that it is not kept active\n // when calling skipWaiting on the new one\n await this._sendAndWaitForReply(\"haltRequests\");\n // only once all requests are blocked, ask the new\n // service worker to skipWaiting\n this._send(\"skipWaiting\", null, this._registration.waiting);\n }\n }\n\n handleEvent(event) {\n switch (event.type) {\n case \"message\":\n this._onMessage(event);\n break;\n case \"updatefound\":\n this._registration.installing.addEventListener(\"statechange\", this);\n break;\n case \"statechange\": {\n if (event.target.state === \"installed\") {\n this._proposeUpdate();\n event.target.removeEventListener(\"statechange\", this);\n }\n break;\n }\n case \"controllerchange\":\n if (!this._currentController) {\n // Clients.claim() in the SW can trigger a controllerchange event\n // if we had no SW before. This is fine,\n // and now our requests will be served from the SW.\n this._currentController = navigator.serviceWorker.controller;\n } else {\n // active service worker changed,\n // refresh, so we can get all assets \n // (and not only some if we would not refresh)\n // up to date from it\n document.location.reload();\n }\n break;\n }\n }\n\n async _send(type, payload, worker = undefined) {\n if (this._registrationPromise) {\n await this._registrationPromise;\n }\n if (!worker) {\n worker = this._registration.active;\n }\n worker.postMessage({type, payload});\n }\n\n async _sendAndWaitForReply(type, payload, worker = undefined) {\n if (this._registrationPromise) {\n await this._registrationPromise;\n }\n if (!worker) {\n worker = this._registration.active;\n }\n this._messageIdCounter += 1;\n const id = this._messageIdCounter;\n const promise = new Promise(resolve => {\n this._waitingForReply.set(id, resolve);\n });\n worker.postMessage({type, id, payload});\n return await promise;\n }\n\n async checkForUpdate() {\n if (this._registrationPromise) {\n await this._registrationPromise;\n }\n this._registration.update();\n }\n\n get version() {\n return DEFINE_VERSION;\n }\n\n get buildHash() {\n return DEFINE_GLOBAL_HASH;\n }\n\n async preventConcurrentSessionAccess(sessionId) {\n return this._sendAndWaitForReply(\"closeSession\", {sessionId});\n }\n\n async getRegistration() {\n if (this._registrationPromise) {\n await this._registrationPromise;\n }\n return this._registration;\n }\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport class NotificationService {\n constructor(serviceWorkerHandler, pushConfig) {\n this._serviceWorkerHandler = serviceWorkerHandler;\n this._pushConfig = pushConfig;\n }\n\n async enablePush(pusherFactory, defaultPayload) {\n const registration = await this._serviceWorkerHandler?.getRegistration();\n if (registration?.pushManager) {\n const subscription = await registration.pushManager.subscribe({\n userVisibleOnly: true,\n applicationServerKey: this._pushConfig.applicationServerKey,\n });\n const subscriptionData = subscription.toJSON();\n const pushkey = subscriptionData.keys.p256dh;\n const data = {\n endpoint: subscriptionData.endpoint,\n auth: subscriptionData.keys.auth,\n // don't deliver unread count push messages\n // as we don't want to show a notification in this case\n events_only: true,\n default_payload: defaultPayload\n };\n return pusherFactory.httpPusher(\n this._pushConfig.gatewayUrl,\n this._pushConfig.appId,\n pushkey,\n data\n );\n }\n }\n\n async disablePush() {\n const registration = await this._serviceWorkerHandler?.getRegistration();\n if (registration?.pushManager) {\n const subscription = await registration.pushManager.getSubscription();\n if (subscription) {\n await subscription.unsubscribe();\n }\n }\n }\n\n async isPushEnabled() {\n const registration = await this._serviceWorkerHandler?.getRegistration();\n if (registration?.pushManager) {\n const subscription = await registration.pushManager.getSubscription();\n return !!subscription;\n }\n return false;\n }\n\n async supportsPush() {\n if (!this._pushConfig) {\n return false;\n }\n const registration = await this._serviceWorkerHandler?.getRegistration();\n return registration && \"pushManager\" in registration;\n }\n\n async enableNotifications() {\n if (\"Notification\" in window) {\n return (await Notification.requestPermission()) === \"granted\";\n }\n return false;\n }\n\n async supportsNotifications() {\n return \"Notification\" in window;\n }\n\n async areNotificationsEnabled() {\n if (\"Notification\" in window) {\n return Notification.permission === \"granted\";\n } else {\n return false;\n }\n }\n\n async showNotification(title, body = undefined) {\n if (\"Notification\" in window) {\n new Notification(title, {body});\n return;\n }\n // Chrome on Android does not support the Notification constructor\n const registration = await this._serviceWorkerHandler?.getRegistration();\n registration?.showNotification(title, {body});\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableValue} from \"../../../observable/ObservableValue\";\n\nexport class History extends BaseObservableValue {\n \n constructor() {\n super();\n this._lastSessionHash = undefined;\n }\n \n handleEvent(event) {\n if (event.type === \"hashchange\") {\n this.emit(this.get());\n this._storeHash(this.get());\n }\n }\n\n get() {\n /*\n All URLS in Hydrogen will use /#/segment/value/...\n But for SSO, we need to handle /?loginToken=\n Handle that as a special case for now.\n */\n if (document.location.search.includes(\"loginToken\")) {\n return document.location.search;\n }\n return document.location.hash;\n }\n\n /** does not emit */\n replaceUrlSilently(url) {\n window.history.replaceState(null, null, url);\n this._storeHash(url);\n }\n\n /** does not emit */\n pushUrlSilently(url) {\n window.history.pushState(null, null, url);\n this._storeHash(url);\n }\n\n pushUrl(url) {\n document.location.hash = url;\n }\n\n urlAsPath(url) {\n if (url.startsWith(\"#\")) {\n return url.substr(1);\n } else {\n return url;\n }\n }\n\n pathAsUrl(path) {\n return `#${path}`;\n }\n\n onSubscribeFirst() {\n this._lastSessionHash = window.localStorage?.getItem(\"hydrogen_last_url_hash\");\n window.addEventListener('hashchange', this);\n }\n\n onUnsubscribeLast() {\n window.removeEventListener('hashchange', this);\n }\n\n _storeHash(hash) {\n window.localStorage?.setItem(\"hydrogen_last_url_hash\", hash);\n }\n\n getLastSessionUrl() {\n return this._lastSessionHash;\n }\n}\n","/*\nCopyright 2020 Bruno Windels \n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BaseObservableValue} from \"../../../observable/ObservableValue\";\n\nexport class OnlineStatus extends BaseObservableValue {\n constructor() {\n super();\n this._onOffline = this._onOffline.bind(this);\n this._onOnline = this._onOnline.bind(this);\n }\n\n _onOffline() {\n this.emit(false);\n }\n\n _onOnline() {\n this.emit(true);\n }\n\n get() {\n return navigator.onLine;\n }\n\n onSubscribeFirst() {\n window.addEventListener('offline', this._onOffline);\n window.addEventListener('online', this._onOnline);\n }\n\n onUnsubscribeLast() {\n window.removeEventListener('offline', this._onOffline);\n window.removeEventListener('online', this._onOnline);\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport base64 from \"base64-arraybuffer\";\n\n// turn IE11 result into promise\nfunction subtleCryptoResult(promiseOrOp, method) {\n if (promiseOrOp instanceof Promise) {\n return promiseOrOp;\n } else {\n return new Promise((resolve, reject) => {\n promiseOrOp.oncomplete = e => resolve(e.target.result);\n promiseOrOp.onerror = () => reject(new Error(\"Crypto error on \" + method));\n });\n }\n}\n\nclass HMACCrypto {\n constructor(subtleCrypto) {\n this._subtleCrypto = subtleCrypto;\n }\n /**\n * [hmac description]\n * @param {BufferSource} key\n * @param {BufferSource} mac\n * @param {BufferSource} data\n * @param {HashName} hash\n * @return {boolean}\n */\n async verify(key, mac, data, hash) {\n const opts = {\n name: 'HMAC',\n hash: {name: hashName(hash)},\n };\n const hmacKey = await subtleCryptoResult(this._subtleCrypto.importKey(\n 'raw',\n key,\n opts,\n false,\n ['verify'],\n ), \"importKey\");\n const isVerified = await subtleCryptoResult(this._subtleCrypto.verify(\n opts,\n hmacKey,\n mac,\n data,\n ), \"verify\");\n return isVerified;\n }\n\n async compute(key, data, hash) {\n const opts = {\n name: 'HMAC',\n hash: {name: hashName(hash)},\n };\n const hmacKey = await subtleCryptoResult(this._subtleCrypto.importKey(\n 'raw',\n key,\n opts,\n false,\n ['sign'],\n ), \"importKey\");\n const buffer = await subtleCryptoResult(this._subtleCrypto.sign(\n opts,\n hmacKey,\n data,\n ), \"sign\");\n return new Uint8Array(buffer);\n }\n}\n\nclass DeriveCrypto {\n constructor(subtleCrypto, crypto, cryptoExtras) {\n this._subtleCrypto = subtleCrypto;\n this._crypto = crypto;\n this._cryptoExtras = cryptoExtras;\n }\n /**\n * [pbkdf2 description]\n * @param {BufferSource} password\n * @param {Number} iterations\n * @param {BufferSource} salt\n * @param {HashName} hash\n * @param {Number} length the desired length of the generated key, in bits (not bytes!)\n * @return {BufferSource}\n */\n async pbkdf2(password, iterations, salt, hash, length) {\n if (!this._subtleCrypto.deriveBits) {\n throw new Error(\"PBKDF2 is not supported\");\n }\n const key = await subtleCryptoResult(this._subtleCrypto.importKey(\n 'raw',\n password,\n {name: 'PBKDF2'},\n false,\n ['deriveBits'],\n ), \"importKey\");\n const keybits = await subtleCryptoResult(this._subtleCrypto.deriveBits(\n {\n name: 'PBKDF2',\n salt,\n iterations,\n hash: hashName(hash),\n },\n key,\n length,\n ), \"deriveBits\");\n return new Uint8Array(keybits);\n }\n\n /**\n * [hkdf description]\n * @param {BufferSource} key [description]\n * @param {BufferSource} salt [description]\n * @param {BufferSource} info [description]\n * @param {HashName} hash the hash to use\n * @param {Number} length desired length of the generated key in bits (not bytes!)\n * @return {[type]} [description]\n */\n async hkdf(key, salt, info, hash, length) {\n if (!this._subtleCrypto.deriveBits) {\n return this._cryptoExtras.hkdf(this._crypto, key, salt, info, hash, length);\n }\n const hkdfkey = await subtleCryptoResult(this._subtleCrypto.importKey(\n 'raw',\n key,\n {name: \"HKDF\"},\n false,\n [\"deriveBits\"],\n ), \"importKey\");\n const keybits = await subtleCryptoResult(this._subtleCrypto.deriveBits({\n name: \"HKDF\",\n salt,\n info,\n hash: hashName(hash),\n },\n hkdfkey,\n length,\n ), \"deriveBits\");\n return new Uint8Array(keybits);\n }\n}\n\nclass AESCrypto {\n constructor(subtleCrypto, crypto) {\n this._subtleCrypto = subtleCrypto;\n this._crypto = crypto;\n }\n /**\n * [decrypt description]\n * @param {BufferSource} key [description]\n * @param {Object} jwkKey [description]\n * @param {BufferSource} iv [description]\n * @param {BufferSource} data [description]\n * @param {Number} counterLength the size of the counter, in bits\n * @return {BufferSource} [description]\n */\n async decryptCTR({key, jwkKey, iv, data, counterLength = 64}) {\n const opts = {\n name: \"AES-CTR\",\n counter: iv,\n length: counterLength,\n };\n let aesKey;\n try {\n const selectedKey = key || jwkKey;\n const format = jwkKey ? \"jwk\" : \"raw\";\n aesKey = await subtleCryptoResult(this._subtleCrypto.importKey(\n format,\n selectedKey,\n opts,\n false,\n ['decrypt'],\n ), \"importKey\");\n } catch (err) {\n throw new Error(`Could not import key for AES-CTR decryption: ${err.message}`);\n }\n try {\n const plaintext = await subtleCryptoResult(this._subtleCrypto.decrypt(\n // see https://developer.mozilla.org/en-US/docs/Web/API/AesCtrParams\n opts,\n aesKey,\n data,\n ), \"decrypt\");\n return new Uint8Array(plaintext);\n } catch (err) {\n throw new Error(`Could not decrypt with AES-CTR: ${err.message}`);\n }\n }\n\n async encryptCTR({key, jwkKey, iv, data}) {\n const opts = {\n name: \"AES-CTR\",\n counter: iv,\n length: 64,\n };\n let aesKey;\n const selectedKey = key || jwkKey;\n const format = jwkKey ? \"jwk\" : \"raw\";\n try {\n aesKey = await subtleCryptoResult(this._subtleCrypto.importKey(\n format,\n selectedKey,\n opts,\n false,\n ['encrypt'],\n ), \"importKey\");\n } catch (err) {\n throw new Error(`Could not import key for AES-CTR encryption: ${err.message}`);\n }\n try {\n const ciphertext = await subtleCryptoResult(this._subtleCrypto.encrypt(\n // see https://developer.mozilla.org/en-US/docs/Web/API/AesCtrParams\n opts,\n aesKey,\n data,\n ), \"encrypt\");\n return new Uint8Array(ciphertext);\n } catch (err) {\n throw new Error(`Could not encrypt with AES-CTR: ${err.message}`);\n }\n }\n\n /**\n * Generate a CTR key\n * @param {String} format \"raw\" or \"jwk\"\n * @param {Number} length 128 or 256\n * @return {Promise} an object for jwk, or a BufferSource for raw\n */\n async generateKey(format, length = 256) {\n const cryptoKey = await subtleCryptoResult(this._subtleCrypto.generateKey(\n {\"name\": \"AES-CTR\", length}, true, [\"encrypt\", \"decrypt\"]));\n return subtleCryptoResult(this._subtleCrypto.exportKey(format, cryptoKey));\n }\n\n async generateIV() {\n return generateIV(this._crypto);\n }\n}\n\nfunction generateIV(crypto) {\n const randomBytes = crypto.getRandomValues(new Uint8Array(8));\n const ivArray = new Uint8Array(16);\n for (let i = 0; i < randomBytes.length; i += 1) {\n ivArray[i] = randomBytes[i];\n }\n return ivArray;\n}\n\nfunction jwkKeyToRaw(jwkKey) {\n if (jwkKey.alg !== \"A256CTR\") {\n throw new Error(`Unknown algorithm: ${jwkKey.alg}`);\n }\n if (!jwkKey.key_ops.includes(\"decrypt\")) {\n throw new Error(`decrypt missing from key_ops`);\n }\n if (jwkKey.kty !== \"oct\") {\n throw new Error(`Invalid key type, \"oct\" expected: ${jwkKey.kty}`);\n }\n // convert base64-url to normal base64\n const base64UrlKey = jwkKey.k;\n const base64Key = base64UrlKey.replace(/-/g, \"+\").replace(/_/g, \"/\");\n return base64.decode(base64Key);\n}\n\nfunction encodeUnpaddedBase64(buffer) {\n const str = base64.encode(buffer);\n const paddingIdx = str.indexOf(\"=\");\n if (paddingIdx !== -1) {\n return str.substr(0, paddingIdx);\n } else {\n return str;\n }\n}\n\nfunction encodeUrlBase64(buffer) {\n const unpadded = encodeUnpaddedBase64(buffer);\n return unpadded.replace(/\\+/g, \"-\").replace(/\\//g, \"_\");\n}\n\nfunction rawKeyToJwk(key) {\n return {\n \"alg\": \"A256CTR\",\n \"ext\": true,\n \"k\": encodeUrlBase64(key),\n \"key_ops\": [\n \"encrypt\",\n \"decrypt\"\n ],\n \"kty\": \"oct\"\n };\n}\n\n\nclass AESLegacyCrypto {\n constructor(aesjs, crypto) {\n this._aesjs = aesjs;\n this._crypto = crypto;\n }\n /**\n * [decrypt description]\n * @param {BufferSource} key [description]\n * @param {BufferSource} iv [description]\n * @param {BufferSource} ciphertext [description]\n * @param {Number} counterLength the size of the counter, in bits\n * @return {BufferSource} [description]\n */\n async decryptCTR({key, jwkKey, iv, data, counterLength = 64}) {\n if (counterLength !== 64) {\n throw new Error(`Unsupported counter length: ${counterLength}`);\n }\n if (jwkKey) {\n key = jwkKeyToRaw(jwkKey);\n }\n const aesjs = this._aesjs;\n var aesCtr = new aesjs.ModeOfOperation.ctr(new Uint8Array(key), new aesjs.Counter(new Uint8Array(iv)));\n return aesCtr.decrypt(new Uint8Array(data));\n }\n\n async encryptCTR({key, jwkKey, iv, data}) {\n if (jwkKey) {\n key = jwkKeyToRaw(jwkKey);\n }\n const aesjs = this._aesjs;\n var aesCtr = new aesjs.ModeOfOperation.ctr(new Uint8Array(key), new aesjs.Counter(new Uint8Array(iv)));\n return aesCtr.encrypt(new Uint8Array(data));\n }\n\n /**\n * Generate a CTR key\n * @param {String} format \"raw\" or \"jwk\"\n * @param {Number} length 128 or 256\n * @return {Promise} an object for jwk, or a BufferSource for raw\n */\n async generateKey(format, length = 256) {\n let key = crypto.getRandomValues(new Uint8Array(length / 8));\n if (format === \"jwk\") {\n key = rawKeyToJwk(key);\n }\n return key;\n }\n\n async generateIV() {\n return generateIV(this._crypto);\n }\n}\n\nfunction hashName(name) {\n if (name !== \"SHA-256\" && name !== \"SHA-512\") {\n throw new Error(`Invalid hash name: ${name}`);\n }\n return name;\n}\n\nexport class Crypto {\n constructor(cryptoExtras) {\n const crypto = window.crypto || window.msCrypto;\n const subtleCrypto = crypto.subtle || crypto.webkitSubtle;\n this._subtleCrypto = subtleCrypto;\n // not exactly guaranteeing AES-CTR support\n // but in practice IE11 doesn't have this\n if (!subtleCrypto.deriveBits && cryptoExtras?.aesjs) {\n this.aes = new AESLegacyCrypto(cryptoExtras.aesjs, crypto);\n } else {\n this.aes = new AESCrypto(subtleCrypto, crypto);\n }\n this.hmac = new HMACCrypto(subtleCrypto);\n this.derive = new DeriveCrypto(subtleCrypto, this, cryptoExtras);\n }\n\n /**\n * [digest description]\n * @param {HashName} hash\n * @param {BufferSource} data\n * @return {BufferSource}\n */\n async digest(hash, data) {\n return await subtleCryptoResult(this._subtleCrypto.digest(hashName(hash), data));\n }\n\n digestSize(hash) {\n switch (hashName(hash)) {\n case \"SHA-512\": return 64;\n case \"SHA-256\": return 32;\n default: throw new Error(`Not implemented for ${hashName(hash)}`);\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport async function estimateStorageUsage() {\n if (navigator?.storage?.estimate) {\n const {quota, usage} = await navigator.storage.estimate();\n return {quota, usage};\n } else {\n return {quota: null, usage: null};\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {AbortError} from \"../../../utils/error\";\n\nclass WorkerState {\n constructor(worker) {\n this.worker = worker;\n this.busy = false;\n }\n\n attach(pool) {\n this.worker.addEventListener(\"message\", pool);\n this.worker.addEventListener(\"error\", pool);\n }\n\n detach(pool) {\n this.worker.removeEventListener(\"message\", pool);\n this.worker.removeEventListener(\"error\", pool);\n }\n}\n\nclass Request {\n constructor(message, pool) {\n this._promise = new Promise((_resolve, _reject) => {\n this._resolve = _resolve;\n this._reject = _reject;\n });\n this._message = message;\n this._pool = pool;\n this._worker = null;\n }\n\n abort() {\n if (this._isNotDisposed) {\n this._pool._abortRequest(this);\n this._dispose();\n }\n }\n\n response() {\n return this._promise;\n }\n\n _dispose() {\n this._reject = null;\n this._resolve = null;\n }\n\n get _isNotDisposed() {\n return this._resolve && this._reject;\n }\n}\n\nexport class WorkerPool {\n // TODO: extract DOM specific bits and write unit tests\n constructor(path, amount) {\n this._workers = [];\n for (let i = 0; i < amount ; ++i) {\n const worker = new WorkerState(new Worker(path));\n worker.attach(this);\n this._workers[i] = worker;\n }\n this._requests = new Map();\n this._counter = 0;\n this._pendingFlag = false;\n this._init = null;\n\n }\n\n init() {\n const promise = new Promise((resolve, reject) => {\n this._init = {resolve, reject};\n });\n this.sendAll({type: \"ping\"})\n .then(this._init.resolve, this._init.reject)\n .finally(() => {\n this._init = null;\n });\n return promise;\n }\n\n handleEvent(e) {\n if (e.type === \"message\") {\n const message = e.data;\n const request = this._requests.get(message.replyToId);\n if (request) {\n request._worker.busy = false;\n if (request._isNotDisposed) {\n if (message.type === \"success\") {\n request._resolve(message.payload);\n } else if (message.type === \"error\") {\n const err = new Error(message.message);\n err.stack = message.stack;\n request._reject(err);\n }\n request._dispose();\n }\n this._requests.delete(message.replyToId);\n }\n this._sendPending();\n } else if (e.type === \"error\") {\n if (this._init) {\n this._init.reject(new Error(\"worker error during init\"));\n }\n console.error(\"worker error\", e);\n }\n }\n\n _getPendingRequest() {\n for (const r of this._requests.values()) {\n if (!r._worker) {\n return r;\n }\n }\n }\n\n _getFreeWorker() {\n for (const w of this._workers) {\n if (!w.busy) {\n return w;\n }\n }\n }\n\n _sendPending() {\n this._pendingFlag = false;\n let success;\n do {\n success = false;\n const request = this._getPendingRequest();\n if (request) {\n const worker = this._getFreeWorker();\n if (worker) {\n this._sendWith(request, worker);\n success = true;\n }\n }\n } while (success);\n }\n\n _sendWith(request, worker) {\n request._worker = worker;\n worker.busy = true;\n worker.worker.postMessage(request._message);\n }\n\n _enqueueRequest(message) {\n this._counter += 1;\n message.id = this._counter;\n const request = new Request(message, this);\n this._requests.set(message.id, request);\n return request;\n }\n\n send(message) {\n const request = this._enqueueRequest(message);\n const worker = this._getFreeWorker();\n if (worker) {\n this._sendWith(request, worker);\n }\n return request;\n }\n\n // assumes all workers are free atm\n sendAll(message) {\n const promises = this._workers.map(worker => {\n const request = this._enqueueRequest(Object.assign({}, message));\n this._sendWith(request, worker);\n return request.response();\n });\n return Promise.all(promises);\n }\n\n dispose() {\n for (const w of this._workers) {\n w.detach(this);\n w.worker.terminate();\n }\n }\n\n _trySendPendingInNextTick() {\n if (!this._pendingFlag) {\n this._pendingFlag = true;\n Promise.resolve().then(() => {\n this._sendPending();\n });\n }\n }\n\n _abortRequest(request) {\n request._reject(new AbortError());\n if (request._worker) {\n request._worker.busy = false;\n }\n this._requests.delete(request._message.id);\n // allow more requests to be aborted before trying to send other pending\n this._trySendPendingInNextTick();\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {BlobHandle} from \"./BlobHandle.js\";\nimport {domEventAsPromise} from \"./utils.js\";\n\nexport class ImageHandle {\n static async fromBlob(blob) {\n const img = await loadImgFromBlob(blob);\n const {width, height} = img;\n return new ImageHandle(blob, width, height, img);\n }\n\n constructor(blob, width, height, imgElement) {\n this.blob = blob;\n this.width = width;\n this.height = height;\n this._domElement = imgElement;\n }\n\n get maxDimension() {\n return Math.max(this.width, this.height);\n }\n\n async _getDomElement() {\n if (!this._domElement) {\n this._domElement = await loadImgFromBlob(this.blob);\n }\n return this._domElement;\n }\n\n async scale(maxDimension) {\n const aspectRatio = this.width / this.height;\n const scaleFactor = Math.min(1, maxDimension / (aspectRatio >= 1 ? this.width : this.height));\n const scaledWidth = Math.round(this.width * scaleFactor);\n const scaledHeight = Math.round(this.height * scaleFactor);\n const canvas = document.createElement(\"canvas\");\n canvas.width = scaledWidth;\n canvas.height = scaledHeight;\n const ctx = canvas.getContext(\"2d\");\n const drawableElement = await this._getDomElement();\n ctx.drawImage(drawableElement, 0, 0, scaledWidth, scaledHeight);\n let mimeType = this.blob.mimeType === \"image/jpeg\" ? \"image/jpeg\" : \"image/png\";\n let nativeBlob;\n if (canvas.toBlob) {\n nativeBlob = await new Promise(resolve => canvas.toBlob(resolve, mimeType));\n } else if (canvas.msToBlob) {\n // TODO: provide a mimetype override in blob handle for this case\n mimeType = \"image/png\";\n nativeBlob = canvas.msToBlob();\n } else {\n throw new Error(\"canvas can't be turned into blob\");\n }\n const blob = BlobHandle.fromBlob(nativeBlob);\n return new ImageHandle(blob, scaledWidth, scaledHeight, null);\n }\n\n dispose() {\n this.blob.dispose();\n }\n}\n\nexport class VideoHandle extends ImageHandle {\n get duration() {\n if (typeof this._domElement.duration === \"number\") {\n return Math.round(this._domElement.duration * 1000);\n }\n return undefined;\n }\n\n static async fromBlob(blob) {\n const video = await loadVideoFromBlob(blob);\n const {videoWidth, videoHeight} = video;\n return new VideoHandle(blob, videoWidth, videoHeight, video);\n }\n}\n\nexport function hasReadPixelPermission() {\n const canvas = document.createElement(\"canvas\");\n canvas.width = 1;\n canvas.height = 1;\n const ctx = canvas.getContext(\"2d\");\n const rgb = [\n Math.round(Math.random() * 255),\n Math.round(Math.random() * 255),\n Math.round(Math.random() * 255),\n ]\n ctx.fillStyle = `rgb(${rgb[0]}, ${rgb[1]}, ${rgb[2]})`;\n ctx.fillRect(0, 0, 1, 1);\n const data = ctx.getImageData(0, 0, 1, 1).data;\n return data[0] === rgb[0] && data[1] === rgb[1] && data[2] === rgb[2];\n}\n\nasync function loadImgFromBlob(blob) {\n const img = document.createElement(\"img\");\n const loadPromise = domEventAsPromise(img, \"load\");\n img.src = blob.url;\n await loadPromise;\n return img;\n}\n\nasync function loadVideoFromBlob(blob) {\n const video = document.createElement(\"video\");\n video.muted = true;\n const loadPromise = domEventAsPromise(video, \"loadedmetadata\");\n video.src = blob.url;\n video.load();\n await loadPromise;\n // seek to the first 1/10s to make sure that drawing the video\n // on a canvas won't give a blank image\n const seekPromise = domEventAsPromise(video, \"seeked\");\n // needed for safari to reliably fire the seeked event,\n // somewhat hacky but using raf for example didn't do the trick\n await new Promise(r => setTimeout(r, 200));\n video.currentTime = 0.1;\n await seekPromise;\n return video;\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport async function downloadInIframe(container, iframeSrc, blobHandle, filename, isIOS) {\n let iframe = container.querySelector(\"iframe.downloadSandbox\");\n if (!iframe) {\n iframe = document.createElement(\"iframe\");\n iframe.setAttribute(\"sandbox\", \"allow-scripts allow-downloads allow-downloads-without-user-activation\");\n iframe.setAttribute(\"src\", iframeSrc);\n iframe.className = \"hidden downloadSandbox\";\n container.appendChild(iframe);\n let detach;\n await new Promise((resolve, reject) => {\n detach = () => {\n iframe.removeEventListener(\"load\", resolve);\n iframe.removeEventListener(\"error\", reject); \n }\n iframe.addEventListener(\"load\", resolve);\n iframe.addEventListener(\"error\", reject);\n });\n detach();\n }\n if (isIOS) {\n // iOS can't read a blob in a sandboxed iframe,\n // see https://github.com/vector-im/hydrogen-web/issues/244\n const buffer = await blobHandle.readAsBuffer();\n iframe.contentWindow.postMessage({\n type: \"downloadBuffer\",\n buffer,\n mimeType: blobHandle.mimeType,\n filename: filename\n }, \"*\");\n } else {\n iframe.contentWindow.postMessage({\n type: \"downloadBlob\",\n blob: blobHandle.nativeBlob,\n filename: filename\n }, \"*\");\n }\n}\n","/*! @license DOMPurify 2.3.0 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/2.3.0/LICENSE */\n\nfunction _toConsumableArray(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar hasOwnProperty = Object.hasOwnProperty,\n setPrototypeOf = Object.setPrototypeOf,\n isFrozen = Object.isFrozen,\n getPrototypeOf = Object.getPrototypeOf,\n getOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;\nvar freeze = Object.freeze,\n seal = Object.seal,\n create = Object.create; // eslint-disable-line import/no-mutable-exports\n\nvar _ref = typeof Reflect !== 'undefined' && Reflect,\n apply = _ref.apply,\n construct = _ref.construct;\n\nif (!apply) {\n apply = function apply(fun, thisValue, args) {\n return fun.apply(thisValue, args);\n };\n}\n\nif (!freeze) {\n freeze = function freeze(x) {\n return x;\n };\n}\n\nif (!seal) {\n seal = function seal(x) {\n return x;\n };\n}\n\nif (!construct) {\n construct = function construct(Func, args) {\n return new (Function.prototype.bind.apply(Func, [null].concat(_toConsumableArray(args))))();\n };\n}\n\nvar arrayForEach = unapply(Array.prototype.forEach);\nvar arrayPop = unapply(Array.prototype.pop);\nvar arrayPush = unapply(Array.prototype.push);\n\nvar stringToLowerCase = unapply(String.prototype.toLowerCase);\nvar stringMatch = unapply(String.prototype.match);\nvar stringReplace = unapply(String.prototype.replace);\nvar stringIndexOf = unapply(String.prototype.indexOf);\nvar stringTrim = unapply(String.prototype.trim);\n\nvar regExpTest = unapply(RegExp.prototype.test);\n\nvar typeErrorCreate = unconstruct(TypeError);\n\nfunction unapply(func) {\n return function (thisArg) {\n for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {\n args[_key - 1] = arguments[_key];\n }\n\n return apply(func, thisArg, args);\n };\n}\n\nfunction unconstruct(func) {\n return function () {\n for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {\n args[_key2] = arguments[_key2];\n }\n\n return construct(func, args);\n };\n}\n\n/* Add properties to a lookup table */\nfunction addToSet(set, array) {\n if (setPrototypeOf) {\n // Make 'in' and truthy checks like Boolean(set.constructor)\n // independent of any properties defined on Object.prototype.\n // Prevent prototype setters from intercepting set as a this value.\n setPrototypeOf(set, null);\n }\n\n var l = array.length;\n while (l--) {\n var element = array[l];\n if (typeof element === 'string') {\n var lcElement = stringToLowerCase(element);\n if (lcElement !== element) {\n // Config presets (e.g. tags.js, attrs.js) are immutable.\n if (!isFrozen(array)) {\n array[l] = lcElement;\n }\n\n element = lcElement;\n }\n }\n\n set[element] = true;\n }\n\n return set;\n}\n\n/* Shallow clone an object */\nfunction clone(object) {\n var newObject = create(null);\n\n var property = void 0;\n for (property in object) {\n if (apply(hasOwnProperty, object, [property])) {\n newObject[property] = object[property];\n }\n }\n\n return newObject;\n}\n\n/* IE10 doesn't support __lookupGetter__ so lets'\n * simulate it. It also automatically checks\n * if the prop is function or getter and behaves\n * accordingly. */\nfunction lookupGetter(object, prop) {\n while (object !== null) {\n var desc = getOwnPropertyDescriptor(object, prop);\n if (desc) {\n if (desc.get) {\n return unapply(desc.get);\n }\n\n if (typeof desc.value === 'function') {\n return unapply(desc.value);\n }\n }\n\n object = getPrototypeOf(object);\n }\n\n function fallbackValue(element) {\n console.warn('fallback value for', element);\n return null;\n }\n\n return fallbackValue;\n}\n\nvar html = freeze(['a', 'abbr', 'acronym', 'address', 'area', 'article', 'aside', 'audio', 'b', 'bdi', 'bdo', 'big', 'blink', 'blockquote', 'body', 'br', 'button', 'canvas', 'caption', 'center', 'cite', 'code', 'col', 'colgroup', 'content', 'data', 'datalist', 'dd', 'decorator', 'del', 'details', 'dfn', 'dialog', 'dir', 'div', 'dl', 'dt', 'element', 'em', 'fieldset', 'figcaption', 'figure', 'font', 'footer', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'head', 'header', 'hgroup', 'hr', 'html', 'i', 'img', 'input', 'ins', 'kbd', 'label', 'legend', 'li', 'main', 'map', 'mark', 'marquee', 'menu', 'menuitem', 'meter', 'nav', 'nobr', 'ol', 'optgroup', 'option', 'output', 'p', 'picture', 'pre', 'progress', 'q', 'rp', 'rt', 'ruby', 's', 'samp', 'section', 'select', 'shadow', 'small', 'source', 'spacer', 'span', 'strike', 'strong', 'style', 'sub', 'summary', 'sup', 'table', 'tbody', 'td', 'template', 'textarea', 'tfoot', 'th', 'thead', 'time', 'tr', 'track', 'tt', 'u', 'ul', 'var', 'video', 'wbr']);\n\n// SVG\nvar svg = freeze(['svg', 'a', 'altglyph', 'altglyphdef', 'altglyphitem', 'animatecolor', 'animatemotion', 'animatetransform', 'circle', 'clippath', 'defs', 'desc', 'ellipse', 'filter', 'font', 'g', 'glyph', 'glyphref', 'hkern', 'image', 'line', 'lineargradient', 'marker', 'mask', 'metadata', 'mpath', 'path', 'pattern', 'polygon', 'polyline', 'radialgradient', 'rect', 'stop', 'style', 'switch', 'symbol', 'text', 'textpath', 'title', 'tref', 'tspan', 'view', 'vkern']);\n\nvar svgFilters = freeze(['feBlend', 'feColorMatrix', 'feComponentTransfer', 'feComposite', 'feConvolveMatrix', 'feDiffuseLighting', 'feDisplacementMap', 'feDistantLight', 'feFlood', 'feFuncA', 'feFuncB', 'feFuncG', 'feFuncR', 'feGaussianBlur', 'feMerge', 'feMergeNode', 'feMorphology', 'feOffset', 'fePointLight', 'feSpecularLighting', 'feSpotLight', 'feTile', 'feTurbulence']);\n\n// List of SVG elements that are disallowed by default.\n// We still need to know them so that we can do namespace\n// checks properly in case one wants to add them to\n// allow-list.\nvar svgDisallowed = freeze(['animate', 'color-profile', 'cursor', 'discard', 'fedropshadow', 'feimage', 'font-face', 'font-face-format', 'font-face-name', 'font-face-src', 'font-face-uri', 'foreignobject', 'hatch', 'hatchpath', 'mesh', 'meshgradient', 'meshpatch', 'meshrow', 'missing-glyph', 'script', 'set', 'solidcolor', 'unknown', 'use']);\n\nvar mathMl = freeze(['math', 'menclose', 'merror', 'mfenced', 'mfrac', 'mglyph', 'mi', 'mlabeledtr', 'mmultiscripts', 'mn', 'mo', 'mover', 'mpadded', 'mphantom', 'mroot', 'mrow', 'ms', 'mspace', 'msqrt', 'mstyle', 'msub', 'msup', 'msubsup', 'mtable', 'mtd', 'mtext', 'mtr', 'munder', 'munderover']);\n\n// Similarly to SVG, we want to know all MathML elements,\n// even those that we disallow by default.\nvar mathMlDisallowed = freeze(['maction', 'maligngroup', 'malignmark', 'mlongdiv', 'mscarries', 'mscarry', 'msgroup', 'mstack', 'msline', 'msrow', 'semantics', 'annotation', 'annotation-xml', 'mprescripts', 'none']);\n\nvar text = freeze(['#text']);\n\nvar html$1 = freeze(['accept', 'action', 'align', 'alt', 'autocapitalize', 'autocomplete', 'autopictureinpicture', 'autoplay', 'background', 'bgcolor', 'border', 'capture', 'cellpadding', 'cellspacing', 'checked', 'cite', 'class', 'clear', 'color', 'cols', 'colspan', 'controls', 'controlslist', 'coords', 'crossorigin', 'datetime', 'decoding', 'default', 'dir', 'disabled', 'disablepictureinpicture', 'disableremoteplayback', 'download', 'draggable', 'enctype', 'enterkeyhint', 'face', 'for', 'headers', 'height', 'hidden', 'high', 'href', 'hreflang', 'id', 'inputmode', 'integrity', 'ismap', 'kind', 'label', 'lang', 'list', 'loading', 'loop', 'low', 'max', 'maxlength', 'media', 'method', 'min', 'minlength', 'multiple', 'muted', 'name', 'noshade', 'novalidate', 'nowrap', 'open', 'optimum', 'pattern', 'placeholder', 'playsinline', 'poster', 'preload', 'pubdate', 'radiogroup', 'readonly', 'rel', 'required', 'rev', 'reversed', 'role', 'rows', 'rowspan', 'spellcheck', 'scope', 'selected', 'shape', 'size', 'sizes', 'span', 'srclang', 'start', 'src', 'srcset', 'step', 'style', 'summary', 'tabindex', 'title', 'translate', 'type', 'usemap', 'valign', 'value', 'width', 'xmlns', 'slot']);\n\nvar svg$1 = freeze(['accent-height', 'accumulate', 'additive', 'alignment-baseline', 'ascent', 'attributename', 'attributetype', 'azimuth', 'basefrequency', 'baseline-shift', 'begin', 'bias', 'by', 'class', 'clip', 'clippathunits', 'clip-path', 'clip-rule', 'color', 'color-interpolation', 'color-interpolation-filters', 'color-profile', 'color-rendering', 'cx', 'cy', 'd', 'dx', 'dy', 'diffuseconstant', 'direction', 'display', 'divisor', 'dur', 'edgemode', 'elevation', 'end', 'fill', 'fill-opacity', 'fill-rule', 'filter', 'filterunits', 'flood-color', 'flood-opacity', 'font-family', 'font-size', 'font-size-adjust', 'font-stretch', 'font-style', 'font-variant', 'font-weight', 'fx', 'fy', 'g1', 'g2', 'glyph-name', 'glyphref', 'gradientunits', 'gradienttransform', 'height', 'href', 'id', 'image-rendering', 'in', 'in2', 'k', 'k1', 'k2', 'k3', 'k4', 'kerning', 'keypoints', 'keysplines', 'keytimes', 'lang', 'lengthadjust', 'letter-spacing', 'kernelmatrix', 'kernelunitlength', 'lighting-color', 'local', 'marker-end', 'marker-mid', 'marker-start', 'markerheight', 'markerunits', 'markerwidth', 'maskcontentunits', 'maskunits', 'max', 'mask', 'media', 'method', 'mode', 'min', 'name', 'numoctaves', 'offset', 'operator', 'opacity', 'order', 'orient', 'orientation', 'origin', 'overflow', 'paint-order', 'path', 'pathlength', 'patterncontentunits', 'patterntransform', 'patternunits', 'points', 'preservealpha', 'preserveaspectratio', 'primitiveunits', 'r', 'rx', 'ry', 'radius', 'refx', 'refy', 'repeatcount', 'repeatdur', 'restart', 'result', 'rotate', 'scale', 'seed', 'shape-rendering', 'specularconstant', 'specularexponent', 'spreadmethod', 'startoffset', 'stddeviation', 'stitchtiles', 'stop-color', 'stop-opacity', 'stroke-dasharray', 'stroke-dashoffset', 'stroke-linecap', 'stroke-linejoin', 'stroke-miterlimit', 'stroke-opacity', 'stroke', 'stroke-width', 'style', 'surfacescale', 'systemlanguage', 'tabindex', 'targetx', 'targety', 'transform', 'text-anchor', 'text-decoration', 'text-rendering', 'textlength', 'type', 'u1', 'u2', 'unicode', 'values', 'viewbox', 'visibility', 'version', 'vert-adv-y', 'vert-origin-x', 'vert-origin-y', 'width', 'word-spacing', 'wrap', 'writing-mode', 'xchannelselector', 'ychannelselector', 'x', 'x1', 'x2', 'xmlns', 'y', 'y1', 'y2', 'z', 'zoomandpan']);\n\nvar mathMl$1 = freeze(['accent', 'accentunder', 'align', 'bevelled', 'close', 'columnsalign', 'columnlines', 'columnspan', 'denomalign', 'depth', 'dir', 'display', 'displaystyle', 'encoding', 'fence', 'frame', 'height', 'href', 'id', 'largeop', 'length', 'linethickness', 'lspace', 'lquote', 'mathbackground', 'mathcolor', 'mathsize', 'mathvariant', 'maxsize', 'minsize', 'movablelimits', 'notation', 'numalign', 'open', 'rowalign', 'rowlines', 'rowspacing', 'rowspan', 'rspace', 'rquote', 'scriptlevel', 'scriptminsize', 'scriptsizemultiplier', 'selection', 'separator', 'separators', 'stretchy', 'subscriptshift', 'supscriptshift', 'symmetric', 'voffset', 'width', 'xmlns']);\n\nvar xml = freeze(['xlink:href', 'xml:id', 'xlink:title', 'xml:space', 'xmlns:xlink']);\n\n// eslint-disable-next-line unicorn/better-regex\nvar MUSTACHE_EXPR = seal(/\\{\\{[\\s\\S]*|[\\s\\S]*\\}\\}/gm); // Specify template detection regex for SAFE_FOR_TEMPLATES mode\nvar ERB_EXPR = seal(/<%[\\s\\S]*|[\\s\\S]*%>/gm);\nvar DATA_ATTR = seal(/^data-[\\-\\w.\\u00B7-\\uFFFF]/); // eslint-disable-line no-useless-escape\nvar ARIA_ATTR = seal(/^aria-[\\-\\w]+$/); // eslint-disable-line no-useless-escape\nvar IS_ALLOWED_URI = seal(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp):|[^a-z]|[a-z+.\\-]+(?:[^a-z+.\\-:]|$))/i // eslint-disable-line no-useless-escape\n);\nvar IS_SCRIPT_OR_DATA = seal(/^(?:\\w+script|data):/i);\nvar ATTR_WHITESPACE = seal(/[\\u0000-\\u0020\\u00A0\\u1680\\u180E\\u2000-\\u2029\\u205F\\u3000]/g // eslint-disable-line no-control-regex\n);\n\nvar _typeof = typeof Symbol === \"function\" && typeof Symbol.iterator === \"symbol\" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === \"function\" && obj.constructor === Symbol && obj !== Symbol.prototype ? \"symbol\" : typeof obj; };\n\nfunction _toConsumableArray$1(arr) { if (Array.isArray(arr)) { for (var i = 0, arr2 = Array(arr.length); i < arr.length; i++) { arr2[i] = arr[i]; } return arr2; } else { return Array.from(arr); } }\n\nvar getGlobal = function getGlobal() {\n return typeof window === 'undefined' ? null : window;\n};\n\n/**\n * Creates a no-op policy for internal use only.\n * Don't export this function outside this module!\n * @param {?TrustedTypePolicyFactory} trustedTypes The policy factory.\n * @param {Document} document The document object (to determine policy name suffix)\n * @return {?TrustedTypePolicy} The policy created (or null, if Trusted Types\n * are not supported).\n */\nvar _createTrustedTypesPolicy = function _createTrustedTypesPolicy(trustedTypes, document) {\n if ((typeof trustedTypes === 'undefined' ? 'undefined' : _typeof(trustedTypes)) !== 'object' || typeof trustedTypes.createPolicy !== 'function') {\n return null;\n }\n\n // Allow the callers to control the unique policy name\n // by adding a data-tt-policy-suffix to the script element with the DOMPurify.\n // Policy creation with duplicate names throws in Trusted Types.\n var suffix = null;\n var ATTR_NAME = 'data-tt-policy-suffix';\n if (document.currentScript && document.currentScript.hasAttribute(ATTR_NAME)) {\n suffix = document.currentScript.getAttribute(ATTR_NAME);\n }\n\n var policyName = 'dompurify' + (suffix ? '#' + suffix : '');\n\n try {\n return trustedTypes.createPolicy(policyName, {\n createHTML: function createHTML(html$$1) {\n return html$$1;\n }\n });\n } catch (_) {\n // Policy creation failed (most likely another DOMPurify script has\n // already run). Skip creating the policy, as this will only cause errors\n // if TT are enforced.\n console.warn('TrustedTypes policy ' + policyName + ' could not be created.');\n return null;\n }\n};\n\nfunction createDOMPurify() {\n var window = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : getGlobal();\n\n var DOMPurify = function DOMPurify(root) {\n return createDOMPurify(root);\n };\n\n /**\n * Version label, exposed for easier checks\n * if DOMPurify is up to date or not\n */\n DOMPurify.version = '2.3.0';\n\n /**\n * Array of elements that DOMPurify removed during sanitation.\n * Empty if nothing was removed.\n */\n DOMPurify.removed = [];\n\n if (!window || !window.document || window.document.nodeType !== 9) {\n // Not running in a browser, provide a factory function\n // so that you can pass your own Window\n DOMPurify.isSupported = false;\n\n return DOMPurify;\n }\n\n var originalDocument = window.document;\n\n var document = window.document;\n var DocumentFragment = window.DocumentFragment,\n HTMLTemplateElement = window.HTMLTemplateElement,\n Node = window.Node,\n Element = window.Element,\n NodeFilter = window.NodeFilter,\n _window$NamedNodeMap = window.NamedNodeMap,\n NamedNodeMap = _window$NamedNodeMap === undefined ? window.NamedNodeMap || window.MozNamedAttrMap : _window$NamedNodeMap,\n Text = window.Text,\n Comment = window.Comment,\n DOMParser = window.DOMParser,\n trustedTypes = window.trustedTypes;\n\n\n var ElementPrototype = Element.prototype;\n\n var cloneNode = lookupGetter(ElementPrototype, 'cloneNode');\n var getNextSibling = lookupGetter(ElementPrototype, 'nextSibling');\n var getChildNodes = lookupGetter(ElementPrototype, 'childNodes');\n var getParentNode = lookupGetter(ElementPrototype, 'parentNode');\n\n // As per issue #47, the web-components registry is inherited by a\n // new document created via createHTMLDocument. As per the spec\n // (http://w3c.github.io/webcomponents/spec/custom/#creating-and-passing-registries)\n // a new empty registry is used when creating a template contents owner\n // document, so we use that as our parent document to ensure nothing\n // is inherited.\n if (typeof HTMLTemplateElement === 'function') {\n var template = document.createElement('template');\n if (template.content && template.content.ownerDocument) {\n document = template.content.ownerDocument;\n }\n }\n\n var trustedTypesPolicy = _createTrustedTypesPolicy(trustedTypes, originalDocument);\n var emptyHTML = trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML('') : '';\n\n var _document = document,\n implementation = _document.implementation,\n createNodeIterator = _document.createNodeIterator,\n createDocumentFragment = _document.createDocumentFragment,\n getElementsByTagName = _document.getElementsByTagName;\n var importNode = originalDocument.importNode;\n\n\n var documentMode = {};\n try {\n documentMode = clone(document).documentMode ? document.documentMode : {};\n } catch (_) {}\n\n var hooks = {};\n\n /**\n * Expose whether this browser supports running the full DOMPurify.\n */\n DOMPurify.isSupported = typeof getParentNode === 'function' && implementation && typeof implementation.createHTMLDocument !== 'undefined' && documentMode !== 9;\n\n var MUSTACHE_EXPR$$1 = MUSTACHE_EXPR,\n ERB_EXPR$$1 = ERB_EXPR,\n DATA_ATTR$$1 = DATA_ATTR,\n ARIA_ATTR$$1 = ARIA_ATTR,\n IS_SCRIPT_OR_DATA$$1 = IS_SCRIPT_OR_DATA,\n ATTR_WHITESPACE$$1 = ATTR_WHITESPACE;\n var IS_ALLOWED_URI$$1 = IS_ALLOWED_URI;\n\n /**\n * We consider the elements and attributes below to be safe. Ideally\n * don't add any new ones but feel free to remove unwanted ones.\n */\n\n /* allowed element names */\n\n var ALLOWED_TAGS = null;\n var DEFAULT_ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(html), _toConsumableArray$1(svg), _toConsumableArray$1(svgFilters), _toConsumableArray$1(mathMl), _toConsumableArray$1(text)));\n\n /* Allowed attribute names */\n var ALLOWED_ATTR = null;\n var DEFAULT_ALLOWED_ATTR = addToSet({}, [].concat(_toConsumableArray$1(html$1), _toConsumableArray$1(svg$1), _toConsumableArray$1(mathMl$1), _toConsumableArray$1(xml)));\n\n /* Explicitly forbidden tags (overrides ALLOWED_TAGS/ADD_TAGS) */\n var FORBID_TAGS = null;\n\n /* Explicitly forbidden attributes (overrides ALLOWED_ATTR/ADD_ATTR) */\n var FORBID_ATTR = null;\n\n /* Decide if ARIA attributes are okay */\n var ALLOW_ARIA_ATTR = true;\n\n /* Decide if custom data attributes are okay */\n var ALLOW_DATA_ATTR = true;\n\n /* Decide if unknown protocols are okay */\n var ALLOW_UNKNOWN_PROTOCOLS = false;\n\n /* Output should be safe for common template engines.\n * This means, DOMPurify removes data attributes, mustaches and ERB\n */\n var SAFE_FOR_TEMPLATES = false;\n\n /* Decide if document with ... should be returned */\n var WHOLE_DOCUMENT = false;\n\n /* Track whether config is already set on this instance of DOMPurify. */\n var SET_CONFIG = false;\n\n /* Decide if all elements (e.g. style, script) must be children of\n * document.body. By default, browsers might move them to document.head */\n var FORCE_BODY = false;\n\n /* Decide if a DOM `HTMLBodyElement` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported).\n * If `WHOLE_DOCUMENT` is enabled a `HTMLHtmlElement` will be returned instead\n */\n var RETURN_DOM = false;\n\n /* Decide if a DOM `DocumentFragment` should be returned, instead of a html\n * string (or a TrustedHTML object if Trusted Types are supported) */\n var RETURN_DOM_FRAGMENT = false;\n\n /* If `RETURN_DOM` or `RETURN_DOM_FRAGMENT` is enabled, decide if the returned DOM\n * `Node` is imported into the current `Document`. If this flag is not enabled the\n * `Node` will belong (its ownerDocument) to a fresh `HTMLDocument`, created by\n * DOMPurify.\n *\n * This defaults to `true` starting DOMPurify 2.2.0. Note that setting it to `false`\n * might cause XSS from attacks hidden in closed shadowroots in case the browser\n * supports Declarative Shadow: DOM https://web.dev/declarative-shadow-dom/\n */\n var RETURN_DOM_IMPORT = true;\n\n /* Try to return a Trusted Type object instead of a string, return a string in\n * case Trusted Types are not supported */\n var RETURN_TRUSTED_TYPE = false;\n\n /* Output should be free from DOM clobbering attacks? */\n var SANITIZE_DOM = true;\n\n /* Keep element content when removing element? */\n var KEEP_CONTENT = true;\n\n /* If a `Node` is passed to sanitize(), then performs sanitization in-place instead\n * of importing it into a new Document and returning a sanitized copy */\n var IN_PLACE = false;\n\n /* Allow usage of profiles like html, svg and mathMl */\n var USE_PROFILES = {};\n\n /* Tags to ignore content of when KEEP_CONTENT is true */\n var FORBID_CONTENTS = addToSet({}, ['annotation-xml', 'audio', 'colgroup', 'desc', 'foreignobject', 'head', 'iframe', 'math', 'mi', 'mn', 'mo', 'ms', 'mtext', 'noembed', 'noframes', 'noscript', 'plaintext', 'script', 'style', 'svg', 'template', 'thead', 'title', 'video', 'xmp']);\n\n /* Tags that are safe for data: URIs */\n var DATA_URI_TAGS = null;\n var DEFAULT_DATA_URI_TAGS = addToSet({}, ['audio', 'video', 'img', 'source', 'image', 'track']);\n\n /* Attributes safe for values like \"javascript:\" */\n var URI_SAFE_ATTRIBUTES = null;\n var DEFAULT_URI_SAFE_ATTRIBUTES = addToSet({}, ['alt', 'class', 'for', 'id', 'label', 'name', 'pattern', 'placeholder', 'summary', 'title', 'value', 'style', 'xmlns']);\n\n var MATHML_NAMESPACE = 'http://www.w3.org/1998/Math/MathML';\n var SVG_NAMESPACE = 'http://www.w3.org/2000/svg';\n var HTML_NAMESPACE = 'http://www.w3.org/1999/xhtml';\n /* Document namespace */\n var NAMESPACE = HTML_NAMESPACE;\n var IS_EMPTY_INPUT = false;\n\n /* Keep a reference to config to pass to hooks */\n var CONFIG = null;\n\n /* Ideally, do not touch anything below this line */\n /* ______________________________________________ */\n\n var formElement = document.createElement('form');\n\n /**\n * _parseConfig\n *\n * @param {Object} cfg optional config literal\n */\n // eslint-disable-next-line complexity\n var _parseConfig = function _parseConfig(cfg) {\n if (CONFIG && CONFIG === cfg) {\n return;\n }\n\n /* Shield configuration object from tampering */\n if (!cfg || (typeof cfg === 'undefined' ? 'undefined' : _typeof(cfg)) !== 'object') {\n cfg = {};\n }\n\n /* Shield configuration object from prototype pollution */\n cfg = clone(cfg);\n\n /* Set configuration parameters */\n ALLOWED_TAGS = 'ALLOWED_TAGS' in cfg ? addToSet({}, cfg.ALLOWED_TAGS) : DEFAULT_ALLOWED_TAGS;\n ALLOWED_ATTR = 'ALLOWED_ATTR' in cfg ? addToSet({}, cfg.ALLOWED_ATTR) : DEFAULT_ALLOWED_ATTR;\n URI_SAFE_ATTRIBUTES = 'ADD_URI_SAFE_ATTR' in cfg ? addToSet(clone(DEFAULT_URI_SAFE_ATTRIBUTES), cfg.ADD_URI_SAFE_ATTR) : DEFAULT_URI_SAFE_ATTRIBUTES;\n DATA_URI_TAGS = 'ADD_DATA_URI_TAGS' in cfg ? addToSet(clone(DEFAULT_DATA_URI_TAGS), cfg.ADD_DATA_URI_TAGS) : DEFAULT_DATA_URI_TAGS;\n FORBID_TAGS = 'FORBID_TAGS' in cfg ? addToSet({}, cfg.FORBID_TAGS) : {};\n FORBID_ATTR = 'FORBID_ATTR' in cfg ? addToSet({}, cfg.FORBID_ATTR) : {};\n USE_PROFILES = 'USE_PROFILES' in cfg ? cfg.USE_PROFILES : false;\n ALLOW_ARIA_ATTR = cfg.ALLOW_ARIA_ATTR !== false; // Default true\n ALLOW_DATA_ATTR = cfg.ALLOW_DATA_ATTR !== false; // Default true\n ALLOW_UNKNOWN_PROTOCOLS = cfg.ALLOW_UNKNOWN_PROTOCOLS || false; // Default false\n SAFE_FOR_TEMPLATES = cfg.SAFE_FOR_TEMPLATES || false; // Default false\n WHOLE_DOCUMENT = cfg.WHOLE_DOCUMENT || false; // Default false\n RETURN_DOM = cfg.RETURN_DOM || false; // Default false\n RETURN_DOM_FRAGMENT = cfg.RETURN_DOM_FRAGMENT || false; // Default false\n RETURN_DOM_IMPORT = cfg.RETURN_DOM_IMPORT !== false; // Default true\n RETURN_TRUSTED_TYPE = cfg.RETURN_TRUSTED_TYPE || false; // Default false\n FORCE_BODY = cfg.FORCE_BODY || false; // Default false\n SANITIZE_DOM = cfg.SANITIZE_DOM !== false; // Default true\n KEEP_CONTENT = cfg.KEEP_CONTENT !== false; // Default true\n IN_PLACE = cfg.IN_PLACE || false; // Default false\n IS_ALLOWED_URI$$1 = cfg.ALLOWED_URI_REGEXP || IS_ALLOWED_URI$$1;\n NAMESPACE = cfg.NAMESPACE || HTML_NAMESPACE;\n if (SAFE_FOR_TEMPLATES) {\n ALLOW_DATA_ATTR = false;\n }\n\n if (RETURN_DOM_FRAGMENT) {\n RETURN_DOM = true;\n }\n\n /* Parse profile info */\n if (USE_PROFILES) {\n ALLOWED_TAGS = addToSet({}, [].concat(_toConsumableArray$1(text)));\n ALLOWED_ATTR = [];\n if (USE_PROFILES.html === true) {\n addToSet(ALLOWED_TAGS, html);\n addToSet(ALLOWED_ATTR, html$1);\n }\n\n if (USE_PROFILES.svg === true) {\n addToSet(ALLOWED_TAGS, svg);\n addToSet(ALLOWED_ATTR, svg$1);\n addToSet(ALLOWED_ATTR, xml);\n }\n\n if (USE_PROFILES.svgFilters === true) {\n addToSet(ALLOWED_TAGS, svgFilters);\n addToSet(ALLOWED_ATTR, svg$1);\n addToSet(ALLOWED_ATTR, xml);\n }\n\n if (USE_PROFILES.mathMl === true) {\n addToSet(ALLOWED_TAGS, mathMl);\n addToSet(ALLOWED_ATTR, mathMl$1);\n addToSet(ALLOWED_ATTR, xml);\n }\n }\n\n /* Merge configuration parameters */\n if (cfg.ADD_TAGS) {\n if (ALLOWED_TAGS === DEFAULT_ALLOWED_TAGS) {\n ALLOWED_TAGS = clone(ALLOWED_TAGS);\n }\n\n addToSet(ALLOWED_TAGS, cfg.ADD_TAGS);\n }\n\n if (cfg.ADD_ATTR) {\n if (ALLOWED_ATTR === DEFAULT_ALLOWED_ATTR) {\n ALLOWED_ATTR = clone(ALLOWED_ATTR);\n }\n\n addToSet(ALLOWED_ATTR, cfg.ADD_ATTR);\n }\n\n if (cfg.ADD_URI_SAFE_ATTR) {\n addToSet(URI_SAFE_ATTRIBUTES, cfg.ADD_URI_SAFE_ATTR);\n }\n\n /* Add #text in case KEEP_CONTENT is set to true */\n if (KEEP_CONTENT) {\n ALLOWED_TAGS['#text'] = true;\n }\n\n /* Add html, head and body to ALLOWED_TAGS in case WHOLE_DOCUMENT is true */\n if (WHOLE_DOCUMENT) {\n addToSet(ALLOWED_TAGS, ['html', 'head', 'body']);\n }\n\n /* Add tbody to ALLOWED_TAGS in case tables are permitted, see #286, #365 */\n if (ALLOWED_TAGS.table) {\n addToSet(ALLOWED_TAGS, ['tbody']);\n delete FORBID_TAGS.tbody;\n }\n\n // Prevent further manipulation of configuration.\n // Not available in IE8, Safari 5, etc.\n if (freeze) {\n freeze(cfg);\n }\n\n CONFIG = cfg;\n };\n\n var MATHML_TEXT_INTEGRATION_POINTS = addToSet({}, ['mi', 'mo', 'mn', 'ms', 'mtext']);\n\n var HTML_INTEGRATION_POINTS = addToSet({}, ['foreignobject', 'desc', 'title', 'annotation-xml']);\n\n /* Keep track of all possible SVG and MathML tags\n * so that we can perform the namespace checks\n * correctly. */\n var ALL_SVG_TAGS = addToSet({}, svg);\n addToSet(ALL_SVG_TAGS, svgFilters);\n addToSet(ALL_SVG_TAGS, svgDisallowed);\n\n var ALL_MATHML_TAGS = addToSet({}, mathMl);\n addToSet(ALL_MATHML_TAGS, mathMlDisallowed);\n\n /**\n *\n *\n * @param {Element} element a DOM element whose namespace is being checked\n * @returns {boolean} Return false if the element has a\n * namespace that a spec-compliant parser would never\n * return. Return true otherwise.\n */\n var _checkValidNamespace = function _checkValidNamespace(element) {\n var parent = getParentNode(element);\n\n // In JSDOM, if we're inside shadow DOM, then parentNode\n // can be null. We just simulate parent in this case.\n if (!parent || !parent.tagName) {\n parent = {\n namespaceURI: HTML_NAMESPACE,\n tagName: 'template'\n };\n }\n\n var tagName = stringToLowerCase(element.tagName);\n var parentTagName = stringToLowerCase(parent.tagName);\n\n if (element.namespaceURI === SVG_NAMESPACE) {\n // The only way to switch from HTML namespace to SVG\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'svg';\n }\n\n // The only way to switch from MathML to SVG is via\n // svg if parent is either or MathML\n // text integration points.\n if (parent.namespaceURI === MATHML_NAMESPACE) {\n return tagName === 'svg' && (parentTagName === 'annotation-xml' || MATHML_TEXT_INTEGRATION_POINTS[parentTagName]);\n }\n\n // We only allow elements that are defined in SVG\n // spec. All others are disallowed in SVG namespace.\n return Boolean(ALL_SVG_TAGS[tagName]);\n }\n\n if (element.namespaceURI === MATHML_NAMESPACE) {\n // The only way to switch from HTML namespace to MathML\n // is via . If it happens via any other tag, then\n // it should be killed.\n if (parent.namespaceURI === HTML_NAMESPACE) {\n return tagName === 'math';\n }\n\n // The only way to switch from SVG to MathML is via\n // and HTML integration points\n if (parent.namespaceURI === SVG_NAMESPACE) {\n return tagName === 'math' && HTML_INTEGRATION_POINTS[parentTagName];\n }\n\n // We only allow elements that are defined in MathML\n // spec. All others are disallowed in MathML namespace.\n return Boolean(ALL_MATHML_TAGS[tagName]);\n }\n\n if (element.namespaceURI === HTML_NAMESPACE) {\n // The only way to switch from SVG to HTML is via\n // HTML integration points, and from MathML to HTML\n // is via MathML text integration points\n if (parent.namespaceURI === SVG_NAMESPACE && !HTML_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n\n if (parent.namespaceURI === MATHML_NAMESPACE && !MATHML_TEXT_INTEGRATION_POINTS[parentTagName]) {\n return false;\n }\n\n // Certain elements are allowed in both SVG and HTML\n // namespace. We need to specify them explicitly\n // so that they don't get erronously deleted from\n // HTML namespace.\n var commonSvgAndHTMLElements = addToSet({}, ['title', 'style', 'font', 'a', 'script']);\n\n // We disallow tags that are specific for MathML\n // or SVG and should never appear in HTML namespace\n return !ALL_MATHML_TAGS[tagName] && (commonSvgAndHTMLElements[tagName] || !ALL_SVG_TAGS[tagName]);\n }\n\n // The code should never reach this place (this means\n // that the element somehow got namespace that is not\n // HTML, SVG or MathML). Return false just in case.\n return false;\n };\n\n /**\n * _forceRemove\n *\n * @param {Node} node a DOM node\n */\n var _forceRemove = function _forceRemove(node) {\n arrayPush(DOMPurify.removed, { element: node });\n try {\n // eslint-disable-next-line unicorn/prefer-dom-node-remove\n node.parentNode.removeChild(node);\n } catch (_) {\n try {\n node.outerHTML = emptyHTML;\n } catch (_) {\n node.remove();\n }\n }\n };\n\n /**\n * _removeAttribute\n *\n * @param {String} name an Attribute name\n * @param {Node} node a DOM node\n */\n var _removeAttribute = function _removeAttribute(name, node) {\n try {\n arrayPush(DOMPurify.removed, {\n attribute: node.getAttributeNode(name),\n from: node\n });\n } catch (_) {\n arrayPush(DOMPurify.removed, {\n attribute: null,\n from: node\n });\n }\n\n node.removeAttribute(name);\n\n // We void attribute values for unremovable \"is\"\" attributes\n if (name === 'is' && !ALLOWED_ATTR[name]) {\n if (RETURN_DOM || RETURN_DOM_FRAGMENT) {\n try {\n _forceRemove(node);\n } catch (_) {}\n } else {\n try {\n node.setAttribute(name, '');\n } catch (_) {}\n }\n }\n };\n\n /**\n * _initDocument\n *\n * @param {String} dirty a string of dirty markup\n * @return {Document} a DOM, filled with the dirty markup\n */\n var _initDocument = function _initDocument(dirty) {\n /* Create a HTML document */\n var doc = void 0;\n var leadingWhitespace = void 0;\n\n if (FORCE_BODY) {\n dirty = '' + dirty;\n } else {\n /* If FORCE_BODY isn't used, leading whitespace needs to be preserved manually */\n var matches = stringMatch(dirty, /^[\\r\\n\\t ]+/);\n leadingWhitespace = matches && matches[0];\n }\n\n var dirtyPayload = trustedTypesPolicy ? trustedTypesPolicy.createHTML(dirty) : dirty;\n /*\n * Use the DOMParser API by default, fallback later if needs be\n * DOMParser not work for svg when has multiple root element.\n */\n if (NAMESPACE === HTML_NAMESPACE) {\n try {\n doc = new DOMParser().parseFromString(dirtyPayload, 'text/html');\n } catch (_) {}\n }\n\n /* Use createHTMLDocument in case DOMParser is not available */\n if (!doc || !doc.documentElement) {\n doc = implementation.createDocument(NAMESPACE, 'template', null);\n try {\n doc.documentElement.innerHTML = IS_EMPTY_INPUT ? '' : dirtyPayload;\n } catch (_) {\n // Syntax error if dirtyPayload is invalid xml\n }\n }\n\n var body = doc.body || doc.documentElement;\n\n if (dirty && leadingWhitespace) {\n body.insertBefore(document.createTextNode(leadingWhitespace), body.childNodes[0] || null);\n }\n\n /* Work on whole document or just its body */\n if (NAMESPACE === HTML_NAMESPACE) {\n return getElementsByTagName.call(doc, WHOLE_DOCUMENT ? 'html' : 'body')[0];\n }\n\n return WHOLE_DOCUMENT ? doc.documentElement : body;\n };\n\n /**\n * _createIterator\n *\n * @param {Document} root document/fragment to create iterator for\n * @return {Iterator} iterator instance\n */\n var _createIterator = function _createIterator(root) {\n return createNodeIterator.call(root.ownerDocument || root, root, NodeFilter.SHOW_ELEMENT | NodeFilter.SHOW_COMMENT | NodeFilter.SHOW_TEXT, null, false);\n };\n\n /**\n * _isClobbered\n *\n * @param {Node} elm element to check for clobbering attacks\n * @return {Boolean} true if clobbered, false if safe\n */\n var _isClobbered = function _isClobbered(elm) {\n if (elm instanceof Text || elm instanceof Comment) {\n return false;\n }\n\n if (typeof elm.nodeName !== 'string' || typeof elm.textContent !== 'string' || typeof elm.removeChild !== 'function' || !(elm.attributes instanceof NamedNodeMap) || typeof elm.removeAttribute !== 'function' || typeof elm.setAttribute !== 'function' || typeof elm.namespaceURI !== 'string' || typeof elm.insertBefore !== 'function') {\n return true;\n }\n\n return false;\n };\n\n /**\n * _isNode\n *\n * @param {Node} obj object to check whether it's a DOM node\n * @return {Boolean} true is object is a DOM node\n */\n var _isNode = function _isNode(object) {\n return (typeof Node === 'undefined' ? 'undefined' : _typeof(Node)) === 'object' ? object instanceof Node : object && (typeof object === 'undefined' ? 'undefined' : _typeof(object)) === 'object' && typeof object.nodeType === 'number' && typeof object.nodeName === 'string';\n };\n\n /**\n * _executeHook\n * Execute user configurable hooks\n *\n * @param {String} entryPoint Name of the hook's entry point\n * @param {Node} currentNode node to work on with the hook\n * @param {Object} data additional hook parameters\n */\n var _executeHook = function _executeHook(entryPoint, currentNode, data) {\n if (!hooks[entryPoint]) {\n return;\n }\n\n arrayForEach(hooks[entryPoint], function (hook) {\n hook.call(DOMPurify, currentNode, data, CONFIG);\n });\n };\n\n /**\n * _sanitizeElements\n *\n * @protect nodeName\n * @protect textContent\n * @protect removeChild\n *\n * @param {Node} currentNode to check for permission to exist\n * @return {Boolean} true if node was killed, false if left alive\n */\n var _sanitizeElements = function _sanitizeElements(currentNode) {\n var content = void 0;\n\n /* Execute a hook if present */\n _executeHook('beforeSanitizeElements', currentNode, null);\n\n /* Check if element is clobbered or can clobber */\n if (_isClobbered(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Check if tagname contains Unicode */\n if (stringMatch(currentNode.nodeName, /[\\u0080-\\uFFFF]/)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Now let's check the element's type and name */\n var tagName = stringToLowerCase(currentNode.nodeName);\n\n /* Execute a hook if present */\n _executeHook('uponSanitizeElement', currentNode, {\n tagName: tagName,\n allowedTags: ALLOWED_TAGS\n });\n\n /* Detect mXSS attempts abusing namespace confusion */\n if (!_isNode(currentNode.firstElementChild) && (!_isNode(currentNode.content) || !_isNode(currentNode.content.firstElementChild)) && regExpTest(/<[/\\w]/g, currentNode.innerHTML) && regExpTest(/<[/\\w]/g, currentNode.textContent)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Remove element if anything forbids its presence */\n if (!ALLOWED_TAGS[tagName] || FORBID_TAGS[tagName]) {\n /* Keep content except for bad-listed elements */\n if (KEEP_CONTENT && !FORBID_CONTENTS[tagName]) {\n var parentNode = getParentNode(currentNode) || currentNode.parentNode;\n var childNodes = getChildNodes(currentNode) || currentNode.childNodes;\n\n if (childNodes && parentNode) {\n var childCount = childNodes.length;\n\n for (var i = childCount - 1; i >= 0; --i) {\n parentNode.insertBefore(cloneNode(childNodes[i], true), getNextSibling(currentNode));\n }\n }\n }\n\n _forceRemove(currentNode);\n return true;\n }\n\n /* Check whether element has a valid namespace */\n if (currentNode instanceof Element && !_checkValidNamespace(currentNode)) {\n _forceRemove(currentNode);\n return true;\n }\n\n if ((tagName === 'noscript' || tagName === 'noembed') && regExpTest(/<\\/no(script|embed)/i, currentNode.innerHTML)) {\n _forceRemove(currentNode);\n return true;\n }\n\n /* Sanitize element content to be template-safe */\n if (SAFE_FOR_TEMPLATES && currentNode.nodeType === 3) {\n /* Get the element's text content */\n content = currentNode.textContent;\n content = stringReplace(content, MUSTACHE_EXPR$$1, ' ');\n content = stringReplace(content, ERB_EXPR$$1, ' ');\n if (currentNode.textContent !== content) {\n arrayPush(DOMPurify.removed, { element: currentNode.cloneNode() });\n currentNode.textContent = content;\n }\n }\n\n /* Execute a hook if present */\n _executeHook('afterSanitizeElements', currentNode, null);\n\n return false;\n };\n\n /**\n * _isValidAttribute\n *\n * @param {string} lcTag Lowercase tag name of containing element.\n * @param {string} lcName Lowercase attribute name.\n * @param {string} value Attribute value.\n * @return {Boolean} Returns true if `value` is valid, otherwise false.\n */\n // eslint-disable-next-line complexity\n var _isValidAttribute = function _isValidAttribute(lcTag, lcName, value) {\n /* Make sure attribute cannot clobber */\n if (SANITIZE_DOM && (lcName === 'id' || lcName === 'name') && (value in document || value in formElement)) {\n return false;\n }\n\n /* Allow valid data-* attributes: At least one character after \"-\"\n (https://html.spec.whatwg.org/multipage/dom.html#embedding-custom-non-visible-data-with-the-data-*-attributes)\n XML-compatible (https://html.spec.whatwg.org/multipage/infrastructure.html#xml-compatible and http://www.w3.org/TR/xml/#d0e804)\n We don't need to check the value; it's always URI safe. */\n if (ALLOW_DATA_ATTR && !FORBID_ATTR[lcName] && regExpTest(DATA_ATTR$$1, lcName)) ; else if (ALLOW_ARIA_ATTR && regExpTest(ARIA_ATTR$$1, lcName)) ; else if (!ALLOWED_ATTR[lcName] || FORBID_ATTR[lcName]) {\n return false;\n\n /* Check value is safe. First, is attr inert? If so, is safe */\n } else if (URI_SAFE_ATTRIBUTES[lcName]) ; else if (regExpTest(IS_ALLOWED_URI$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if ((lcName === 'src' || lcName === 'xlink:href' || lcName === 'href') && lcTag !== 'script' && stringIndexOf(value, 'data:') === 0 && DATA_URI_TAGS[lcTag]) ; else if (ALLOW_UNKNOWN_PROTOCOLS && !regExpTest(IS_SCRIPT_OR_DATA$$1, stringReplace(value, ATTR_WHITESPACE$$1, ''))) ; else if (!value) ; else {\n return false;\n }\n\n return true;\n };\n\n /**\n * _sanitizeAttributes\n *\n * @protect attributes\n * @protect nodeName\n * @protect removeAttribute\n * @protect setAttribute\n *\n * @param {Node} currentNode to sanitize\n */\n var _sanitizeAttributes = function _sanitizeAttributes(currentNode) {\n var attr = void 0;\n var value = void 0;\n var lcName = void 0;\n var l = void 0;\n /* Execute a hook if present */\n _executeHook('beforeSanitizeAttributes', currentNode, null);\n\n var attributes = currentNode.attributes;\n\n /* Check if we have attributes; if not we might have a text node */\n\n if (!attributes) {\n return;\n }\n\n var hookEvent = {\n attrName: '',\n attrValue: '',\n keepAttr: true,\n allowedAttributes: ALLOWED_ATTR\n };\n l = attributes.length;\n\n /* Go backwards over all attributes; safely remove bad ones */\n while (l--) {\n attr = attributes[l];\n var _attr = attr,\n name = _attr.name,\n namespaceURI = _attr.namespaceURI;\n\n value = stringTrim(attr.value);\n lcName = stringToLowerCase(name);\n\n /* Execute a hook if present */\n hookEvent.attrName = lcName;\n hookEvent.attrValue = value;\n hookEvent.keepAttr = true;\n hookEvent.forceKeepAttr = undefined; // Allows developers to see this is a property they can set\n _executeHook('uponSanitizeAttribute', currentNode, hookEvent);\n value = hookEvent.attrValue;\n /* Did the hooks approve of the attribute? */\n if (hookEvent.forceKeepAttr) {\n continue;\n }\n\n /* Remove attribute */\n _removeAttribute(name, currentNode);\n\n /* Did the hooks approve of the attribute? */\n if (!hookEvent.keepAttr) {\n continue;\n }\n\n /* Work around a security issue in jQuery 3.0 */\n if (regExpTest(/\\/>/i, value)) {\n _removeAttribute(name, currentNode);\n continue;\n }\n\n /* Sanitize attribute content to be template-safe */\n if (SAFE_FOR_TEMPLATES) {\n value = stringReplace(value, MUSTACHE_EXPR$$1, ' ');\n value = stringReplace(value, ERB_EXPR$$1, ' ');\n }\n\n /* Is `value` valid for this attribute? */\n var lcTag = currentNode.nodeName.toLowerCase();\n if (!_isValidAttribute(lcTag, lcName, value)) {\n continue;\n }\n\n /* Handle invalid data-* attribute set by try-catching it */\n try {\n if (namespaceURI) {\n currentNode.setAttributeNS(namespaceURI, name, value);\n } else {\n /* Fallback to setAttribute() for browser-unrecognized namespaces e.g. \"x-schema\". */\n currentNode.setAttribute(name, value);\n }\n\n arrayPop(DOMPurify.removed);\n } catch (_) {}\n }\n\n /* Execute a hook if present */\n _executeHook('afterSanitizeAttributes', currentNode, null);\n };\n\n /**\n * _sanitizeShadowDOM\n *\n * @param {DocumentFragment} fragment to iterate over recursively\n */\n var _sanitizeShadowDOM = function _sanitizeShadowDOM(fragment) {\n var shadowNode = void 0;\n var shadowIterator = _createIterator(fragment);\n\n /* Execute a hook if present */\n _executeHook('beforeSanitizeShadowDOM', fragment, null);\n\n while (shadowNode = shadowIterator.nextNode()) {\n /* Execute a hook if present */\n _executeHook('uponSanitizeShadowNode', shadowNode, null);\n\n /* Sanitize tags and elements */\n if (_sanitizeElements(shadowNode)) {\n continue;\n }\n\n /* Deep shadow DOM detected */\n if (shadowNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(shadowNode.content);\n }\n\n /* Check attributes, sanitize if necessary */\n _sanitizeAttributes(shadowNode);\n }\n\n /* Execute a hook if present */\n _executeHook('afterSanitizeShadowDOM', fragment, null);\n };\n\n /**\n * Sanitize\n * Public method providing core sanitation functionality\n *\n * @param {String|Node} dirty string or DOM node\n * @param {Object} configuration object\n */\n // eslint-disable-next-line complexity\n DOMPurify.sanitize = function (dirty, cfg) {\n var body = void 0;\n var importedNode = void 0;\n var currentNode = void 0;\n var oldNode = void 0;\n var returnNode = void 0;\n /* Make sure we have a string to sanitize.\n DO NOT return early, as this will return the wrong type if\n the user has requested a DOM object rather than a string */\n IS_EMPTY_INPUT = !dirty;\n if (IS_EMPTY_INPUT) {\n dirty = '';\n }\n\n /* Stringify, in case dirty is an object */\n if (typeof dirty !== 'string' && !_isNode(dirty)) {\n // eslint-disable-next-line no-negated-condition\n if (typeof dirty.toString !== 'function') {\n throw typeErrorCreate('toString is not a function');\n } else {\n dirty = dirty.toString();\n if (typeof dirty !== 'string') {\n throw typeErrorCreate('dirty is not a string, aborting');\n }\n }\n }\n\n /* Check we can run. Otherwise fall back or ignore */\n if (!DOMPurify.isSupported) {\n if (_typeof(window.toStaticHTML) === 'object' || typeof window.toStaticHTML === 'function') {\n if (typeof dirty === 'string') {\n return window.toStaticHTML(dirty);\n }\n\n if (_isNode(dirty)) {\n return window.toStaticHTML(dirty.outerHTML);\n }\n }\n\n return dirty;\n }\n\n /* Assign config vars */\n if (!SET_CONFIG) {\n _parseConfig(cfg);\n }\n\n /* Clean up removed elements */\n DOMPurify.removed = [];\n\n /* Check if dirty is correctly typed for IN_PLACE */\n if (typeof dirty === 'string') {\n IN_PLACE = false;\n }\n\n if (IN_PLACE) ; else if (dirty instanceof Node) {\n /* If dirty is a DOM element, append to an empty document to avoid\n elements being stripped by the parser */\n body = _initDocument('');\n importedNode = body.ownerDocument.importNode(dirty, true);\n if (importedNode.nodeType === 1 && importedNode.nodeName === 'BODY') {\n /* Node is already a body, use as is */\n body = importedNode;\n } else if (importedNode.nodeName === 'HTML') {\n body = importedNode;\n } else {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n body.appendChild(importedNode);\n }\n } else {\n /* Exit directly if we have nothing to do */\n if (!RETURN_DOM && !SAFE_FOR_TEMPLATES && !WHOLE_DOCUMENT &&\n // eslint-disable-next-line unicorn/prefer-includes\n dirty.indexOf('<') === -1) {\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(dirty) : dirty;\n }\n\n /* Initialize the document to work on */\n body = _initDocument(dirty);\n\n /* Check we have a DOM node from the data */\n if (!body) {\n return RETURN_DOM ? null : emptyHTML;\n }\n }\n\n /* Remove first element node (ours) if FORCE_BODY is set */\n if (body && FORCE_BODY) {\n _forceRemove(body.firstChild);\n }\n\n /* Get node iterator */\n var nodeIterator = _createIterator(IN_PLACE ? dirty : body);\n\n /* Now start iterating over the created document */\n while (currentNode = nodeIterator.nextNode()) {\n /* Fix IE's strange behavior with manipulated textNodes #89 */\n if (currentNode.nodeType === 3 && currentNode === oldNode) {\n continue;\n }\n\n /* Sanitize tags and elements */\n if (_sanitizeElements(currentNode)) {\n continue;\n }\n\n /* Shadow DOM detected, sanitize it */\n if (currentNode.content instanceof DocumentFragment) {\n _sanitizeShadowDOM(currentNode.content);\n }\n\n /* Check attributes, sanitize if necessary */\n _sanitizeAttributes(currentNode);\n\n oldNode = currentNode;\n }\n\n oldNode = null;\n\n /* If we sanitized `dirty` in-place, return it. */\n if (IN_PLACE) {\n return dirty;\n }\n\n /* Return sanitized string or DOM */\n if (RETURN_DOM) {\n if (RETURN_DOM_FRAGMENT) {\n returnNode = createDocumentFragment.call(body.ownerDocument);\n\n while (body.firstChild) {\n // eslint-disable-next-line unicorn/prefer-dom-node-append\n returnNode.appendChild(body.firstChild);\n }\n } else {\n returnNode = body;\n }\n\n if (RETURN_DOM_IMPORT) {\n /*\n AdoptNode() is not used because internal state is not reset\n (e.g. the past names map of a HTMLFormElement), this is safe\n in theory but we would rather not risk another attack vector.\n The state that is cloned by importNode() is explicitly defined\n by the specs.\n */\n returnNode = importNode.call(originalDocument, returnNode, true);\n }\n\n return returnNode;\n }\n\n var serializedHTML = WHOLE_DOCUMENT ? body.outerHTML : body.innerHTML;\n\n /* Sanitize final string template-safe */\n if (SAFE_FOR_TEMPLATES) {\n serializedHTML = stringReplace(serializedHTML, MUSTACHE_EXPR$$1, ' ');\n serializedHTML = stringReplace(serializedHTML, ERB_EXPR$$1, ' ');\n }\n\n return trustedTypesPolicy && RETURN_TRUSTED_TYPE ? trustedTypesPolicy.createHTML(serializedHTML) : serializedHTML;\n };\n\n /**\n * Public method to set the configuration once\n * setConfig\n *\n * @param {Object} cfg configuration object\n */\n DOMPurify.setConfig = function (cfg) {\n _parseConfig(cfg);\n SET_CONFIG = true;\n };\n\n /**\n * Public method to remove the configuration\n * clearConfig\n *\n */\n DOMPurify.clearConfig = function () {\n CONFIG = null;\n SET_CONFIG = false;\n };\n\n /**\n * Public method to check if an attribute value is valid.\n * Uses last set config, if any. Otherwise, uses config defaults.\n * isValidAttribute\n *\n * @param {string} tag Tag name of containing element.\n * @param {string} attr Attribute name.\n * @param {string} value Attribute value.\n * @return {Boolean} Returns true if `value` is valid. Otherwise, returns false.\n */\n DOMPurify.isValidAttribute = function (tag, attr, value) {\n /* Initialize shared config vars if necessary. */\n if (!CONFIG) {\n _parseConfig({});\n }\n\n var lcTag = stringToLowerCase(tag);\n var lcName = stringToLowerCase(attr);\n return _isValidAttribute(lcTag, lcName, value);\n };\n\n /**\n * AddHook\n * Public method to add DOMPurify hooks\n *\n * @param {String} entryPoint entry point for the hook to add\n * @param {Function} hookFunction function to execute\n */\n DOMPurify.addHook = function (entryPoint, hookFunction) {\n if (typeof hookFunction !== 'function') {\n return;\n }\n\n hooks[entryPoint] = hooks[entryPoint] || [];\n arrayPush(hooks[entryPoint], hookFunction);\n };\n\n /**\n * RemoveHook\n * Public method to remove a DOMPurify hook at a given entryPoint\n * (pops it from the stack of hooks if more are present)\n *\n * @param {String} entryPoint entry point for the hook to remove\n */\n DOMPurify.removeHook = function (entryPoint) {\n if (hooks[entryPoint]) {\n arrayPop(hooks[entryPoint]);\n }\n };\n\n /**\n * RemoveHooks\n * Public method to remove all DOMPurify hooks at a given entryPoint\n *\n * @param {String} entryPoint entry point for the hooks to remove\n */\n DOMPurify.removeHooks = function (entryPoint) {\n if (hooks[entryPoint]) {\n hooks[entryPoint] = [];\n }\n };\n\n /**\n * RemoveAllHooks\n * Public method to remove all DOMPurify hooks\n *\n */\n DOMPurify.removeAllHooks = function () {\n hooks = {};\n };\n\n return DOMPurify;\n}\n\nvar purify = createDOMPurify();\n\nexport default purify;\n//# sourceMappingURL=purify.es.js.map\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport DOMPurify from \"dompurify\"\n\nclass HTMLParseResult {\n constructor(bodyNode) {\n this._bodyNode = bodyNode;\n }\n\n get rootNodes() {\n return Array.from(this._bodyNode.childNodes);\n }\n \n getChildNodes(node) {\n return Array.from(node.childNodes);\n }\n\n getAttributeNames(node) {\n return Array.from(node.getAttributeNames());\n }\n\n getAttributeValue(node, attr) {\n return node.getAttribute(attr);\n }\n\n isTextNode(node) { \n return node.nodeType === Node.TEXT_NODE;\n }\n\n getNodeText(node) {\n return node.textContent;\n }\n\n isElementNode(node) {\n return node.nodeType === Node.ELEMENT_NODE;\n }\n\n getNodeElementName(node) {\n return node.tagName;\n }\n}\n\nconst sanitizeConfig = {\n ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|xxx|mxc):|[^a-z]|[a-z+.-]+(?:[^a-z+.-:]|$))/i,\n FORBID_TAGS: ['mx-reply'],\n KEEP_CONTENT: false,\n}\n\nexport function parseHTML(html) {\n // If DOMPurify uses DOMParser, can't we just get the built tree from it\n // instead of re-parsing?\n const sanitized = DOMPurify.sanitize(html, sanitizeConfig);\n const bodyNode = new DOMParser().parseFromString(`${sanitized}`, \"text/html\").body;\n return new HTMLParseResult(bodyNode);\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport type NormalVariant = {\n id: string;\n cssLocation: string;\n variables?: any;\n};\n\nexport type Variant = NormalVariant & {\n variantName: string;\n};\n\nexport type DefaultVariant = {\n dark: Variant;\n light: Variant;\n default: Variant;\n}\n\nexport type ThemeInformation = NormalVariant | DefaultVariant; \n\nexport enum ColorSchemePreference {\n Dark,\n Light\n};\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nexport function getColoredSvgString(svgString, primaryColor, secondaryColor) {\n let coloredSVGCode = svgString.replaceAll(\"#ff00ff\", primaryColor);\n coloredSVGCode = coloredSVGCode.replaceAll(\"#00ffff\", secondaryColor);\n if (svgString === coloredSVGCode) {\n throw new Error(\"svg-colorizer made no color replacements! The input svg should only contain colors #ff00ff (primary, case-sensitive) and #00ffff (secondary, case-sensitive).\");\n }\n return coloredSVGCode;\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport type {Platform} from \"../Platform.js\";\nimport {getColoredSvgString} from \"./shared/svg-colorizer.mjs\";\n\ntype ParsedStructure = {\n [variableName: string]: {\n svg: Promise<{ status: number; body: string }>;\n primary: string | null;\n secondary: string | null;\n };\n};\n\nexport class IconColorizer {\n private _iconVariables: Record;\n private _resolvedVariables: Record;\n private _manifestLocation: string;\n private _platform: Platform;\n\n constructor(platform: Platform, iconVariables: Record, resolvedVariables: Record, manifestLocation: string) {\n this._platform = platform;\n this._iconVariables = iconVariables;\n this._resolvedVariables = resolvedVariables;\n this._manifestLocation = manifestLocation;\n }\n\n async toVariables(): Promise> {\n const { parsedStructure, promises } = await this._fetchAndParseIcons();\n await Promise.all(promises);\n return this._produceColoredIconVariables(parsedStructure);\n }\n\n private async _fetchAndParseIcons(): Promise<{ parsedStructure: ParsedStructure, promises: any[] }> {\n const promises: any[] = [];\n const parsedStructure: ParsedStructure = {};\n for (const [variable, url] of Object.entries(this._iconVariables)) {\n const urlObject = new URL(`https://${url}`);\n const pathWithoutQueryParams = urlObject.hostname;\n const relativePath = new URL(pathWithoutQueryParams, new URL(this._manifestLocation, window.location.origin));\n const responsePromise = this._platform.request(relativePath, { method: \"GET\", format: \"text\", cache: true, }).response()\n promises.push(responsePromise);\n const searchParams = urlObject.searchParams;\n parsedStructure[variable] = {\n svg: responsePromise,\n primary: searchParams.get(\"primary\"),\n secondary: searchParams.get(\"secondary\")\n };\n }\n return { parsedStructure, promises };\n }\n\n private async _produceColoredIconVariables(parsedStructure: ParsedStructure): Promise> {\n let coloredVariables: Record = {};\n for (const [variable, { svg, primary, secondary }] of Object.entries(parsedStructure)) {\n const { body: svgCode } = await svg;\n if (!primary) {\n throw new Error(`Primary color variable ${primary} not in list of variables!`);\n }\n const primaryColor = this._resolvedVariables[primary], secondaryColor = this._resolvedVariables[secondary!];\n const coloredSvgCode = getColoredSvgString(svgCode, primaryColor, secondaryColor);\n const dataURI = `url('data:image/svg+xml;utf8,${encodeURIComponent(coloredSvgCode)}')`;\n coloredVariables[variable] = dataURI;\n }\n return coloredVariables;\n }\n}\n","module.exports=function(n){var t={};function r(e){if(t[e])return t[e].exports;var o=t[e]={i:e,l:!1,exports:{}};return n[e].call(o.exports,o,o.exports,r),o.l=!0,o.exports}return r.m=n,r.c=t,r.d=function(n,t,e){r.o(n,t)||Object.defineProperty(n,t,{enumerable:!0,get:e})},r.r=function(n){\"undefined\"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(n,Symbol.toStringTag,{value:\"Module\"}),Object.defineProperty(n,\"__esModule\",{value:!0})},r.t=function(n,t){if(1&t&&(n=r(n)),8&t)return n;if(4&t&&\"object\"==typeof n&&n&&n.__esModule)return n;var e=Object.create(null);if(r.r(e),Object.defineProperty(e,\"default\",{enumerable:!0,value:n}),2&t&&\"string\"!=typeof n)for(var o in n)r.d(e,o,function(t){return n[t]}.bind(null,o));return e},r.n=function(n){var t=n&&n.__esModule?function(){return n.default}:function(){return n};return r.d(t,\"a\",t),t},r.o=function(n,t){return Object.prototype.hasOwnProperty.call(n,t)},r.p=\"\",r(r.s=0)}([function(n,t,r){\"use strict\";function e(n){let t,r;const e={light:function(){return!a()},dark:a,lighten:d,darken:l,saturate:p,desaturate:function(n=0){return p(n*=-1)},increaseContrast:function(n=0){return b(n*=-1)},decreaseContrast:b,active:function(){return b(.123)},highlight:function(){return b(.1)},selected:function(){return b(.066)},text:function(){return r=s()?o(\"#333333\"):o(\"#FFFFFF\"),e},shadow:function(){return r=s()?o(\"#000000\"):o(\"#FFFFFF\"),e},hex:function(){const n=r;return r=t,\"#\"+n.map(n=>parseInt(n+\"\",10).toString(16).padStart(2,\"0\")).join(\"\")},rgb:function(){const n=r;return r=t,`rgb(${n.join()})`},rgba:function(n=1){const e=r;return r=t,`rgba(${e.join()}, ${n})`},setHex:c,setRgb:function(n=[0,0,0]){let[o,u,c]=n;return o=f(o,0,255),u=f(u,0,255),c=f(c,0,255),t=[o,u,c],r=[o,u,c],e}};function c(n=\"#000000\"){return t=o(n),r=t,e}function a(){const[n,e,o]=r;return r=t,(299*n+587*e+114*o)/1e3<128}function s(){const[n,t,e]=r;return(299*n+587*t+114*e)/1e3>=128}function l(n=0){return d(n*=-1)}function d(n=0){let[t,o,c]=i(r);return c=f(c+n,0,1),r=u([t,o,c]),e}function p(n=0){let[t,o,c]=i(r);return o=f(o+n,0,1),r=u([t,o,c]),e}function b(n=0){return s()?l(n):d(n)}return c(n),e}function o(n){if(\"string\"!=typeof n)throw new TypeError(\"Expected a string\");3===(n=n.replace(/^#/,\"\")).length&&(n=n[0]+n[0]+n[1]+n[1]+n[2]+n[2]);var t=parseInt(n,16);return[t>>16,t>>8&255,255&t]}function u(n){const[t,r,e]=n;let o,u,c;if(0===r)o=u=c=e;else{const n=function(n,t,r){return r<0&&(r+=1),r>1&&(r-=1),r<1/6?n+6*(t-n)*r:r<.5?t:r<2/3?n+(t-n)*(2/3-r)*6:n},i=e<.5?e*(1+r):e+r-e*r,a=2*e-i;o=f(n(a,i,t+1/3),0,1),u=f(n(a,i,t),0,1),c=f(n(a,i,t-1/3),0,1)}return[Math.round(255*o),Math.round(255*u),Math.round(255*c)]}r.r(t),r.d(t,\"offColor\",(function(){return e})),r.d(t,\"hexRgb\",(function(){return o})),r.d(t,\"hslToRgb\",(function(){return u})),r.d(t,\"color\",(function(){return c})),r.d(t,\"rgbToHsl\",(function(){return i}));const c=e;function i(n){const t=n[0]/255,r=n[1]/255,e=n[2]/255,o=Math.max(t,r,e),u=Math.min(t,r,e);let c=(o+u)/2,i=(o+u)/2;const f=(o+u)/2;if(o===u)c=i=0;else{const n=o-u;switch(i=f>.5?n/(2-o-u):n/(o+u),o){case t:c=(r-e)/n+(r=t?n:t}}]);","'use strict';\n\nif (process.env.NODE_ENV === 'production') {\n module.exports = require('./cjs/index.min.js');\n} else {\n module.exports = require('./cjs/index.js');\n}\n","/*\nCopyright 2021 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport * as pkg from 'off-color';\nconst offColor = pkg.offColor ?? pkg.default.offColor;\n\nexport function derive(value, operation, argument, isDark) {\n const argumentAsNumber = parseInt(argument);\n if (isDark) {\n // For dark themes, invert the operation\n if (operation === 'darker') {\n operation = \"lighter\";\n }\n else if (operation === 'lighter') {\n operation = \"darker\";\n }\n }\n switch (operation) {\n case \"darker\": {\n const newColorString = offColor(value).darken(argumentAsNumber / 100).hex();\n return newColorString;\n }\n case \"lighter\": {\n const newColorString = offColor(value).lighten(argumentAsNumber / 100).hex();\n return newColorString;\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n \nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport {derive} from \"./shared/color.mjs\";\n\nexport class DerivedVariables {\n private _baseVariables: Record;\n private _variablesToDerive: string[]\n private _isDark: boolean\n private _aliases: Record = {};\n private _derivedAliases: string[] = [];\n\n constructor(baseVariables: Record, variablesToDerive: string[], isDark: boolean) {\n this._baseVariables = baseVariables;\n this._variablesToDerive = variablesToDerive;\n this._isDark = isDark;\n }\n\n toVariables(): Record {\n const resolvedVariables: any = {};\n this._detectAliases();\n for (const variable of this._variablesToDerive) {\n const resolvedValue = this._derive(variable);\n if (resolvedValue) {\n resolvedVariables[variable] = resolvedValue;\n }\n }\n for (const [alias, variable] of Object.entries(this._aliases) as any) {\n resolvedVariables[alias] = this._baseVariables[variable] ?? resolvedVariables[variable];\n }\n for (const variable of this._derivedAliases) {\n const resolvedValue = this._deriveAlias(variable, resolvedVariables);\n if (resolvedValue) {\n resolvedVariables[variable] = resolvedValue;\n }\n }\n return resolvedVariables;\n }\n\n private _detectAliases(): void {\n const newVariablesToDerive: string[] = [];\n for (const variable of this._variablesToDerive) {\n const [alias, value] = variable.split(\"=\");\n if (value) {\n this._aliases[alias] = value;\n }\n else {\n newVariablesToDerive.push(variable);\n }\n }\n this._variablesToDerive = newVariablesToDerive;\n }\n\n private _derive(variable: string): string | undefined {\n const RE_VARIABLE_VALUE = /(.+)--(.+)-(.+)/;\n const matches = variable.match(RE_VARIABLE_VALUE);\n if (matches) {\n const [, baseVariable, operation, argument] = matches;\n const value = this._baseVariables[baseVariable];\n if (!value ) {\n if (this._aliases[baseVariable]) {\n this._derivedAliases.push(variable);\n return;\n }\n else {\n throw new Error(`Cannot find value for base variable \"${baseVariable}\"!`);\n }\n }\n const resolvedValue = derive(value, operation, argument, this._isDark);\n return resolvedValue;\n }\n }\n\n private _deriveAlias(variable: string, resolvedVariables: Record): string | undefined {\n const RE_VARIABLE_VALUE = /(.+)--(.+)-(.+)/;\n const matches = variable.match(RE_VARIABLE_VALUE);\n if (matches) {\n const [, baseVariable, operation, argument] = matches;\n const value = resolvedVariables[baseVariable];\n if (!value ) {\n throw new Error(`Cannot find value for alias \"${baseVariable}\" when trying to derive ${variable}!`);\n }\n const resolvedValue = derive(value, operation, argument, this._isDark);\n return resolvedValue;\n }\n }\n}\n\nimport * as pkg from \"off-color\";\n// @ts-ignore \nconst offColor = pkg.offColor ?? pkg.default.offColor;\n\nexport function tests() {\n return {\n \"Simple variable derivation\": assert => {\n const deriver = new DerivedVariables({ \"background-color\": \"#ff00ff\" }, [\"background-color--darker-5\"], false);\n const result = deriver.toVariables();\n const resultColor = offColor(\"#ff00ff\").darken(5/100).hex();\n assert.deepEqual(result, {\"background-color--darker-5\": resultColor});\n },\n\n \"For dark themes, lighten and darken are inverted\": assert => {\n const deriver = new DerivedVariables({ \"background-color\": \"#ff00ff\" }, [\"background-color--darker-5\"], true);\n const result = deriver.toVariables();\n const resultColor = offColor(\"#ff00ff\").lighten(5/100).hex();\n assert.deepEqual(result, {\"background-color--darker-5\": resultColor});\n },\n\n \"Aliases can be derived\": assert => {\n const deriver = new DerivedVariables({ \"background-color\": \"#ff00ff\" }, [\"my-awesome-alias=background-color\",\"my-awesome-alias--darker-5\"], false);\n const result = deriver.toVariables();\n const resultColor = offColor(\"#ff00ff\").darken(5/100).hex();\n assert.deepEqual(result, {\n \"my-awesome-alias\": \"#ff00ff\",\n \"my-awesome-alias--darker-5\": resultColor,\n });\n },\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\nimport type {ThemeInformation} from \"./types\";\nimport type {Platform} from \"../../Platform.js\";\nimport type {ThemeManifest} from \"../../../types/theme\";\nimport {ColorSchemePreference} from \"./types\";\nimport {IconColorizer} from \"../IconColorizer\";\nimport {DerivedVariables} from \"../DerivedVariables\";\nimport {ILogItem} from \"../../../../logging/types\";\n\nexport class RuntimeThemeParser {\n private _themeMapping: Record = {};\n private _preferredColorScheme?: ColorSchemePreference;\n private _platform: Platform;\n\n constructor(platform: Platform, preferredColorScheme?: ColorSchemePreference) {\n this._preferredColorScheme = preferredColorScheme;\n this._platform = platform;\n }\n\n async parse(manifest: ThemeManifest, baseManifest: ThemeManifest, baseManifestLocation: string, log: ILogItem): Promise {\n await log.wrap(\"RuntimeThemeParser.parse\", async () => {\n const {cssLocation, derivedVariables, icons} = this._getSourceData(baseManifest, baseManifestLocation, log);\n const themeName = manifest.name;\n if (!themeName) {\n throw new Error(`Theme name not found in manifest!`);\n }\n let defaultDarkVariant: any = {}, defaultLightVariant: any = {};\n for (const [variant, variantDetails] of Object.entries(manifest.values?.variants!) as [string, any][]) {\n try {\n const themeId = `${manifest.id}-${variant}`;\n const { name: variantName, default: isDefault, dark, variables } = variantDetails;\n const resolvedVariables = new DerivedVariables(variables, derivedVariables, dark).toVariables();\n Object.assign(variables, resolvedVariables);\n const iconVariables = await new IconColorizer(this._platform, icons, variables, baseManifestLocation).toVariables();\n Object.assign(variables, resolvedVariables, iconVariables);\n const themeDisplayName = `${themeName} ${variantName}`;\n if (isDefault) {\n const defaultVariant = dark ? defaultDarkVariant : defaultLightVariant;\n Object.assign(defaultVariant, { variantName, id: themeId, cssLocation, variables });\n continue;\n }\n this._themeMapping[themeDisplayName] = { cssLocation, id: themeId, variables: variables, };\n }\n catch (e) {\n console.error(e);\n continue;\n }\n }\n if (defaultDarkVariant.id && defaultLightVariant.id) {\n const defaultVariant = this._preferredColorScheme === ColorSchemePreference.Dark ? defaultDarkVariant : defaultLightVariant;\n this._themeMapping[themeName] = { dark: defaultDarkVariant, light: defaultLightVariant, default: defaultVariant };\n }\n else {\n const variant = defaultDarkVariant.id ? defaultDarkVariant : defaultLightVariant;\n this._themeMapping[`${themeName} ${variant.variantName}`] = { id: variant.id, cssLocation: variant.cssLocation };\n }\n });\n }\n\n private _getSourceData(manifest: ThemeManifest, location: string, log: ILogItem)\n : { cssLocation: string, derivedVariables: string[], icons: Record} {\n return log.wrap(\"getSourceData\", () => {\n const runtimeCSSLocation = manifest.source?.[\"runtime-asset\"];\n if (!runtimeCSSLocation) {\n throw new Error(`Run-time asset not found in source section for theme at ${location}`);\n }\n const cssLocation = new URL(runtimeCSSLocation, new URL(location, window.location.origin)).href;\n const derivedVariables = manifest.source?.[\"derived-variables\"];\n if (!derivedVariables) {\n throw new Error(`Derived variables not found in source section for theme at ${location}`);\n }\n const icons = manifest.source?.[\"icon\"];\n if (!icons) {\n throw new Error(`Icon mapping not found in source section for theme at ${location}`);\n }\n return { cssLocation, derivedVariables, icons };\n });\n }\n\n get themeMapping(): Record {\n return this._themeMapping;\n }\n\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {ThemeInformation} from \"./types\";\nimport type {ThemeManifest} from \"../../../types/theme\";\nimport type {ILogItem} from \"../../../../logging/types\";\nimport {ColorSchemePreference} from \"./types\";\n\nexport class BuiltThemeParser {\n private _themeMapping: Record = {};\n private _preferredColorScheme?: ColorSchemePreference;\n\n constructor(preferredColorScheme?: ColorSchemePreference) {\n this._preferredColorScheme = preferredColorScheme;\n }\n\n parse(manifest: ThemeManifest, manifestLocation: string, log: ILogItem) {\n log.wrap(\"BuiltThemeParser.parse\", () => {\n /*\n After build has finished, the source section of each theme manifest\n contains `built-assets` which is a mapping from the theme-id to\n cssLocation of theme\n */\n const builtAssets: Record = manifest.source?.[\"built-assets\"];\n const themeName = manifest.name;\n if (!themeName) {\n throw new Error(`Theme name not found in manifest at ${manifestLocation}`);\n }\n let defaultDarkVariant: any = {}, defaultLightVariant: any = {};\n for (let [themeId, cssLocation] of Object.entries(builtAssets)) {\n try {\n /**\n * This cssLocation is relative to the location of the manifest file.\n * So we first need to resolve it relative to the root of this hydrogen instance.\n */\n cssLocation = new URL(cssLocation, new URL(manifestLocation, window.location.origin)).href;\n }\n catch {\n continue;\n }\n const variant = themeId.match(/.+-(.+)/)?.[1];\n const variantDetails = manifest.values?.variants[variant!];\n if (!variantDetails) {\n throw new Error(`Variant ${variant} is missing in manifest at ${manifestLocation}`);\n }\n const { name: variantName, default: isDefault, dark } = variantDetails;\n const themeDisplayName = `${themeName} ${variantName}`;\n if (isDefault) {\n /**\n * This is a default variant!\n * We'll add these to the themeMapping (separately) keyed with just the\n * theme-name (i.e \"Element\" instead of \"Element Dark\").\n * We need to be able to distinguish them from other variants!\n * \n * This allows us to render radio-buttons with \"dark\" and\n * \"light\" options.\n */\n const defaultVariant = dark ? defaultDarkVariant : defaultLightVariant;\n defaultVariant.variantName = variantName;\n defaultVariant.id = themeId\n defaultVariant.cssLocation = cssLocation;\n continue;\n }\n // Non-default variants are keyed in themeMapping with \"theme_name variant_name\"\n // eg: \"Element Dark\"\n this._themeMapping[themeDisplayName] = {\n cssLocation,\n id: themeId\n };\n }\n if (defaultDarkVariant.id && defaultLightVariant.id) {\n /**\n * As mentioned above, if there's both a default dark and a default light variant,\n * add them to themeMapping separately.\n */\n const defaultVariant = this._preferredColorScheme === ColorSchemePreference.Dark ? defaultDarkVariant : defaultLightVariant;\n this._themeMapping[themeName] = { dark: defaultDarkVariant, light: defaultLightVariant, default: defaultVariant };\n }\n else {\n /**\n * If only one default variant is found (i.e only dark default or light default but not both),\n * treat it like any other variant.\n */\n const variant = defaultDarkVariant.id ? defaultDarkVariant : defaultLightVariant;\n this._themeMapping[`${themeName} ${variant.variantName}`] = { id: variant.id, cssLocation: variant.cssLocation };\n }\n });\n }\n\n get themeMapping(): Record {\n return this._themeMapping;\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport type {ILogItem} from \"../../../logging/types\";\nimport type {Platform} from \"../Platform.js\";\nimport {RuntimeThemeParser} from \"./parsers/RuntimeThemeParser\";\nimport type {Variant, ThemeInformation} from \"./parsers/types\";\nimport {ColorSchemePreference} from \"./parsers/types\";\nimport {BuiltThemeParser} from \"./parsers/BuiltThemeParser\";\n\nexport class ThemeLoader {\n private _platform: Platform;\n private _themeMapping: Record;\n private _injectedVariables?: Record;\n\n constructor(platform: Platform) {\n this._platform = platform;\n }\n\n async init(manifestLocations: string[], log?: ILogItem): Promise {\n await this._platform.logger.wrapOrRun(log, \"ThemeLoader.init\", async (log) => {\n const results = await Promise.all(\n manifestLocations.map(location => this._platform.request(location, { method: \"GET\", format: \"json\", cache: true, }).response())\n );\n const runtimeThemeParser = new RuntimeThemeParser(this._platform, this.preferredColorScheme);\n const builtThemeParser = new BuiltThemeParser(this.preferredColorScheme);\n const runtimeThemePromises: Promise[] = [];\n for (let i = 0; i < results.length; ++i) {\n const { body } = results[i];\n try {\n if (body.extends) {\n const indexOfBaseManifest = results.findIndex(manifest => manifest.body.id === body.extends);\n if (indexOfBaseManifest === -1) {\n throw new Error(`Base manifest for derived theme at ${manifestLocations[i]} not found!`);\n }\n const {body: baseManifest} = results[indexOfBaseManifest];\n const baseManifestLocation = manifestLocations[indexOfBaseManifest];\n const promise = runtimeThemeParser.parse(body, baseManifest, baseManifestLocation, log);\n runtimeThemePromises.push(promise);\n }\n else {\n builtThemeParser.parse(body, manifestLocations[i], log);\n }\n }\n catch(e) {\n console.error(e);\n }\n }\n await Promise.all(runtimeThemePromises);\n this._themeMapping = { ...builtThemeParser.themeMapping, ...runtimeThemeParser.themeMapping };\n Object.assign(this._themeMapping, builtThemeParser.themeMapping, runtimeThemeParser.themeMapping);\n this._addDefaultThemeToMapping(log);\n log.log({ l: \"Preferred colorscheme\", scheme: this.preferredColorScheme === ColorSchemePreference.Dark ? \"dark\" : \"light\" });\n log.log({ l: \"Result\", themeMapping: this._themeMapping });\n });\n }\n\n setTheme(themeName: string, themeVariant?: \"light\" | \"dark\" | \"default\", log?: ILogItem) {\n this._platform.logger.wrapOrRun(log, { l: \"change theme\", name: themeName, variant: themeVariant }, () => {\n let cssLocation: string, variables: Record;\n let themeDetails = this._themeMapping[themeName];\n if (\"id\" in themeDetails) {\n cssLocation = themeDetails.cssLocation;\n variables = themeDetails.variables;\n }\n else {\n if (!themeVariant) {\n throw new Error(\"themeVariant is undefined!\");\n }\n cssLocation = themeDetails[themeVariant].cssLocation;\n variables = themeDetails[themeVariant].variables;\n }\n this._platform.replaceStylesheet(cssLocation);\n if (variables) {\n log?.log({l: \"Derived Theme\", variables});\n this._injectCSSVariables(variables);\n }\n else {\n this._removePreviousCSSVariables();\n }\n this._platform.settingsStorage.setString(\"theme-name\", themeName);\n if (themeVariant) {\n this._platform.settingsStorage.setString(\"theme-variant\", themeVariant);\n }\n else {\n this._platform.settingsStorage.remove(\"theme-variant\");\n }\n });\n }\n\n private _injectCSSVariables(variables: Record): void {\n const root = document.documentElement;\n for (const [variable, value] of Object.entries(variables)) {\n root.style.setProperty(`--${variable}`, value);\n }\n this._injectedVariables = variables;\n }\n\n private _removePreviousCSSVariables(): void {\n if (!this._injectedVariables) {\n return;\n }\n const root = document.documentElement;\n for (const variable of Object.keys(this._injectedVariables)) {\n root.style.removeProperty(`--${variable}`);\n }\n this._injectedVariables = undefined;\n }\n\n /** Maps theme display name to theme information */\n get themeMapping(): Record {\n return this._themeMapping;\n }\n\n async getActiveTheme(): Promise<{themeName: string, themeVariant?: string}> {\n let themeName = await this._platform.settingsStorage.getString(\"theme-name\");\n let themeVariant = await this._platform.settingsStorage.getString(\"theme-variant\");\n if (!themeName || !this._themeMapping[themeName]) {\n themeName = \"Default\" in this._themeMapping ? \"Default\" : Object.keys(this._themeMapping)[0];\n if (!this._themeMapping[themeName][themeVariant]) {\n themeVariant = \"default\" in this._themeMapping[themeName] ? \"default\" : undefined;\n }\n }\n return { themeName, themeVariant };\n }\n\n getDefaultTheme(): string | undefined {\n switch (this.preferredColorScheme) {\n case ColorSchemePreference.Dark:\n return this._platform.config[\"defaultTheme\"]?.dark;\n case ColorSchemePreference.Light:\n return this._platform.config[\"defaultTheme\"]?.light;\n }\n }\n\n private _findThemeDetailsFromId(themeId: string): {themeName: string, themeData: Partial} | undefined {\n for (const [themeName, themeData] of Object.entries(this._themeMapping)) {\n if (\"id\" in themeData && themeData.id === themeId) {\n return { themeName, themeData };\n }\n else if (\"light\" in themeData && themeData.light?.id === themeId) {\n return { themeName, themeData: themeData.light };\n }\n else if (\"dark\" in themeData && themeData.dark?.id === themeId) {\n return { themeName, themeData: themeData.dark };\n }\n }\n }\n\n private _addDefaultThemeToMapping(log: ILogItem) {\n log.wrap(\"addDefaultThemeToMapping\", l => { \n const defaultThemeId = this.getDefaultTheme();\n if (defaultThemeId) {\n const themeDetails = this._findThemeDetailsFromId(defaultThemeId);\n if (themeDetails) {\n this._themeMapping[\"Default\"] = { id: \"default\", cssLocation: themeDetails.themeData.cssLocation! };\n const variables = themeDetails.themeData.variables;\n if (variables) {\n this._themeMapping[\"Default\"].variables = variables;\n }\n }\n }\n l.log({ l: \"Default Theme\", theme: defaultThemeId});\n });\n }\n\n get preferredColorScheme(): ColorSchemePreference | undefined {\n if (window.matchMedia(\"(prefers-color-scheme: dark)\").matches) {\n return ColorSchemePreference.Dark;\n }\n else if (window.matchMedia(\"(prefers-color-scheme: light)\").matches) {\n return ColorSchemePreference.Light;\n }\n }\n}\n","/*\nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport {createFetchRequest} from \"./dom/request/fetch.js\";\nimport {xhrRequest} from \"./dom/request/xhr.js\";\nimport {StorageFactory} from \"../../matrix/storage/idb/StorageFactory\";\nimport {SessionInfoStorage} from \"../../matrix/sessioninfo/localstorage/SessionInfoStorage\";\nimport {SettingsStorage} from \"./dom/SettingsStorage.js\";\nimport {Encoding} from \"./utils/Encoding.js\";\nimport {OlmWorker} from \"../../matrix/e2ee/OlmWorker.js\";\nimport {IDBLogger} from \"../../logging/IDBLogger\";\nimport {ConsoleLogger} from \"../../logging/ConsoleLogger\";\nimport {RootView} from \"./ui/RootView.js\";\nimport {Clock} from \"./dom/Clock.js\";\nimport {ServiceWorkerHandler} from \"./dom/ServiceWorkerHandler.js\";\nimport {NotificationService} from \"./dom/NotificationService.js\";\nimport {History} from \"./dom/History.js\";\nimport {OnlineStatus} from \"./dom/OnlineStatus.js\";\nimport {Crypto} from \"./dom/Crypto.js\";\nimport {estimateStorageUsage} from \"./dom/StorageEstimate.js\";\nimport {WorkerPool} from \"./dom/WorkerPool.js\";\nimport {BlobHandle} from \"./dom/BlobHandle.js\";\nimport {hasReadPixelPermission, ImageHandle, VideoHandle} from \"./dom/ImageHandle.js\";\nimport {downloadInIframe} from \"./dom/download.js\";\nimport {Disposables} from \"../../utils/Disposables\";\nimport {parseHTML} from \"./parsehtml.js\";\nimport {handleAvatarError} from \"./ui/avatar\";\nimport {ThemeLoader} from \"./theming/ThemeLoader\";\n\nfunction addScript(src) {\n return new Promise(function (resolve, reject) {\n var s = document.createElement(\"script\");\n s.setAttribute(\"src\", src );\n s.onload=resolve;\n s.onerror=reject;\n document.body.appendChild(s);\n });\n}\n\nasync function loadOlm(olmPaths) {\n // make crypto.getRandomValues available without\n // a prefix on IE11, needed by olm to work\n if (window.msCrypto && !window.crypto) {\n window.crypto = window.msCrypto;\n }\n if (olmPaths) {\n if (window.WebAssembly) {\n await addScript(olmPaths.wasmBundle);\n await window.Olm.init({locateFile: () => olmPaths.wasm});\n } else {\n await addScript(olmPaths.legacyBundle);\n await window.Olm.init();\n }\n return window.Olm;\n }\n return null;\n}\n// turn asset path to absolute path if it isn't already\n// so it can be loaded independent of base\nfunction assetAbsPath(assetPath) {\n if (!assetPath.startsWith(\"/\")) {\n return new URL(assetPath, document.location.href).pathname;\n }\n return assetPath;\n}\n\nasync function loadOlmWorker(assetPaths) {\n const workerPool = new WorkerPool(assetPaths.worker, 4);\n await workerPool.init();\n await workerPool.sendAll({\n type: \"load_olm\",\n path: assetAbsPath(assetPaths.olm.legacyBundle)\n });\n const olmWorker = new OlmWorker(workerPool);\n return olmWorker;\n}\n\n// needed for mobile Safari which shifts the layout viewport up without resizing it\n// when the keyboard shows (see https://bugs.webkit.org/show_bug.cgi?id=141832)\nfunction adaptUIOnVisualViewportResize(container) {\n if (!window.visualViewport) {\n return;\n }\n const handler = () => {\n const sessionView = container.querySelector('.SessionView');\n if (!sessionView) {\n return;\n }\n\n const scrollable = container.querySelector('.bottom-aligned-scroll');\n let scrollTopBefore, heightBefore, heightAfter;\n\n if (scrollable) {\n scrollTopBefore = scrollable.scrollTop;\n heightBefore = scrollable.offsetHeight;\n }\n\n // Ideally we'd use window.visualViewport.offsetTop but that seems to occasionally lag\n // behind (last tested on iOS 14.4 simulator) so we have to compute the offset manually\n const offsetTop = sessionView.offsetTop + sessionView.offsetHeight - window.visualViewport.height;\n\n container.style.setProperty('--ios-viewport-height', window.visualViewport.height.toString() + 'px');\n container.style.setProperty('--ios-viewport-top', offsetTop.toString() + 'px');\n\n if (scrollable) {\n heightAfter = scrollable.offsetHeight;\n scrollable.scrollTop = scrollTopBefore + heightBefore - heightAfter;\n }\n };\n window.visualViewport.addEventListener('resize', handler);\n return () => {\n window.visualViewport.removeEventListener('resize', handler);\n };\n}\n\nexport class Platform {\n constructor({ container, assetPaths, config, configURL, options = null, cryptoExtras = null }) {\n this._container = container;\n this._assetPaths = assetPaths;\n this._config = config;\n this._configURL = configURL;\n this.settingsStorage = new SettingsStorage(\"hydrogen_setting_v1_\");\n this.clock = new Clock();\n this.encoding = new Encoding();\n this.random = Math.random;\n this._createLogger(options?.development);\n this.history = new History();\n this.onlineStatus = new OnlineStatus();\n this._serviceWorkerHandler = null;\n if (assetPaths.serviceWorker && \"serviceWorker\" in navigator) {\n this._serviceWorkerHandler = new ServiceWorkerHandler();\n this._serviceWorkerHandler.registerAndStart(assetPaths.serviceWorker);\n }\n this.notificationService = undefined;\n // Only try to use crypto when olm is provided\n if(this._assetPaths.olm) {\n this.crypto = new Crypto(cryptoExtras);\n }\n this.storageFactory = new StorageFactory(this._serviceWorkerHandler);\n this.sessionInfoStorage = new SessionInfoStorage(\"hydrogen_sessions_v1\");\n this.estimateStorageUsage = estimateStorageUsage;\n if (typeof fetch === \"function\") {\n this.request = createFetchRequest(this.clock.createTimeout, this._serviceWorkerHandler);\n } else {\n this.request = xhrRequest;\n }\n const isIE11 = !!window.MSInputMethodContext && !!document.documentMode;\n this.isIE11 = isIE11;\n // From https://stackoverflow.com/questions/9038625/detect-if-device-is-ios/9039885\n const isIOS = /iPad|iPhone|iPod/.test(navigator.platform) || (navigator.platform === 'MacIntel' && navigator.maxTouchPoints > 1) && !window.MSStream;\n this.isIOS = isIOS;\n this._disposables = new Disposables();\n this._olmPromise = undefined;\n this._workerPromise = undefined;\n this._themeLoader = import.meta.env.DEV? null: new ThemeLoader(this);\n }\n\n async init() {\n try {\n await this.logger.run(\"Platform init\", async (log) => {\n if (!this._config) {\n if (!this._configURL) {\n throw new Error(\"Neither config nor configURL was provided!\");\n }\n const {status, body}= await this.request(this._configURL, {method: \"GET\", format: \"json\", cache: true}).response();\n if (status === 404) {\n throw new Error(`Could not find ${this._configURL}. Did you copy over config.sample.json?`);\n } else if (status >= 400) {\n throw new Error(`Got status ${status} while trying to fetch ${this._configURL}`);\n }\n this._config = body;\n }\n this.notificationService = new NotificationService(\n this._serviceWorkerHandler,\n this._config.push\n );\n if (this._themeLoader) {\n const manifests = this.config[\"themeManifests\"];\n await this._themeLoader?.init(manifests, log);\n const { themeName, themeVariant } = await this._themeLoader.getActiveTheme();\n log.log({ l: \"Active theme\", name: themeName, variant: themeVariant });\n this._themeLoader.setTheme(themeName, themeVariant, log);\n }\n });\n } catch (err) {\n this._container.innerText = err.message;\n throw err;\n }\n }\n\n _createLogger(isDevelopment) {\n // Make sure that loginToken does not end up in the logs\n const transformer = (item) => {\n if (item.e?.stack) {\n item.e.stack = item.e.stack.replace(/\\/\\?loginToken=(.+)/, \"?loginToken=\");\n }\n return item;\n };\n if (isDevelopment) {\n this.logger = new ConsoleLogger({platform: this});\n } else {\n this.logger = new IDBLogger({name: \"hydrogen_logs\", platform: this, serializedTransformer: transformer});\n }\n }\n\n get updateService() {\n return this._serviceWorkerHandler;\n }\n\n loadOlm() {\n if (!this._olmPromise) {\n this._olmPromise = loadOlm(this._assetPaths.olm);\n }\n return this._olmPromise;\n }\n\n get config() {\n return this._config;\n }\n\n async loadOlmWorker() {\n if (!window.WebAssembly) {\n if (!this._workerPromise) {\n this._workerPromise = loadOlmWorker(this._assetPaths);\n }\n return this._workerPromise;\n }\n }\n\n createAndMountRootView(vm) {\n if (this.isIE11) {\n this._container.className += \" legacy\";\n }\n if (this.isIOS) {\n this._container.className += \" ios\";\n const disposable = adaptUIOnVisualViewportResize(this._container);\n if (disposable) {\n this._disposables.track(disposable);\n }\n }\n this._container.addEventListener(\"error\", handleAvatarError, true);\n this._disposables.track(() => this._container.removeEventListener(\"error\", handleAvatarError, true));\n window.__hydrogenViewModel = vm;\n const view = new RootView(vm);\n this._container.appendChild(view.mount());\n }\n\n setNavigation(navigation) {\n this._serviceWorkerHandler?.setNavigation(navigation);\n }\n\n createBlob(buffer, mimetype) {\n return BlobHandle.fromBuffer(buffer, mimetype);\n }\n\n saveFileAs(blobHandle, filename) {\n if (navigator.msSaveBlob) {\n navigator.msSaveBlob(blobHandle.nativeBlob, filename);\n } else {\n downloadInIframe(this._container, this._assetPaths.downloadSandbox, blobHandle, filename, this.isIOS);\n }\n }\n\n openFile(mimeType = null) {\n const input = document.createElement(\"input\");\n input.setAttribute(\"type\", \"file\");\n input.className = \"hidden\";\n if (mimeType) {\n input.setAttribute(\"accept\", mimeType);\n }\n const promise = new Promise(resolve => {\n const checkFile = () => {\n input.removeEventListener(\"change\", checkFile, true);\n const file = input.files[0];\n this._container.removeChild(input);\n if (file) {\n resolve({name: file.name, blob: BlobHandle.fromBlob(file)});\n } else {\n resolve();\n }\n }\n input.addEventListener(\"change\", checkFile, true);\n });\n // IE11 needs the input to be attached to the document\n this._container.appendChild(input);\n input.click();\n return promise;\n }\n\n openUrl(url) {\n location.href = url;\n }\n\n parseHTML(html) {\n return parseHTML(html);\n }\n\n async loadImage(blob) {\n return ImageHandle.fromBlob(blob);\n }\n\n async loadVideo(blob) {\n return VideoHandle.fromBlob(blob);\n }\n\n hasReadPixelPermission() {\n return hasReadPixelPermission();\n }\n\n get devicePixelRatio() {\n return window.devicePixelRatio || 1;\n }\n\n get version() {\n return DEFINE_VERSION;\n }\n\n get themeLoader() {\n return this._themeLoader;\n }\n\n replaceStylesheet(newPath) {\n const head = document.querySelector(\"head\");\n // remove default theme \n document.querySelectorAll(\".theme\").forEach(e => e.remove());\n // add new theme\n const styleTag = document.createElement(\"link\");\n styleTag.href = newPath;\n styleTag.rel = \"stylesheet\";\n styleTag.type = \"text/css\";\n styleTag.className = \"theme\";\n head.appendChild(styleTag);\n }\n\n get description() {\n return navigator.userAgent ?? \"\";\n }\n\n dispose() {\n this._disposables.dispose();\n }\n}\n\nimport {LogItem} from \"../../logging/LogItem\";\nexport function tests() {\n return {\n \"loginToken should not be in logs\": (assert) => {\n const transformer = (item) => {\n if (item.e?.stack) {\n item.e.stack = item.e.stack.replace(/(?<=\\/\\?loginToken=).+/, \"\");\n }\n return item;\n };\n const logger = {\n _queuedItems: [],\n _serializedTransformer: transformer,\n _now: () => {}\n };\n logger.persist = IDBLogger.prototype._persistItem.bind(logger);\n const logItem = new LogItem(\"test\", 1, logger);\n logItem.error = new Error();\n logItem.error.stack = \"main http://localhost:3000/src/main.js:55\\n http://localhost:3000/?loginToken=secret:26\"\n logger.persist(logItem, null, false);\n const item = logger._queuedItems.pop();\n console.log(item);\n assert.strictEqual(item.json.search(\"secret\"), -1);\n }\n };\n}\n","export default \"__VITE_ASSET__e1b1bc02__\"","export default \"__VITE_ASSET__48a866e9__\"","export default \"__VITE_ASSET__bdb9a925__\"","export default \"__VITE_ASSET__b3e0f9b4__\"","export default \"__VITE_ASSET__92f1ccd0__\"","export default \"__VITE_ASSET__9dc48f49__\"","// @ts-ignore\nimport _downloadSandboxPath from \"../../assets/download-sandbox.html?url\";\n// @ts-ignore\nimport _workerPath from \"../../worker/main.js?url\";\n// @ts-ignore\nimport olmWasmPath from \"@matrix-org/olm/olm.wasm?url\";\n// @ts-ignore\nimport olmJsPath from \"@matrix-org/olm/olm.js?url\";\n// @ts-ignore\nimport olmLegacyJsPath from \"@matrix-org/olm/olm_legacy.js?url\";\n\nexport default {\n downloadSandbox: _downloadSandboxPath,\n worker: _workerPath,\n olm: {\n wasm: olmWasmPath,\n legacyBundle: olmLegacyJsPath,\n wasmBundle: olmJsPath,\n }\n};\n","\n import {main} from \"./main\";\n import {Platform} from \"./Platform\";\n import configURL from \"./assets/config.json?url\";\n import assetPaths from \"./sdk/paths/vite\";\n if (import.meta.env.PROD) {\n assetPaths.serviceWorker = \"sw.js\";\n }\n const platform = new Platform({\n container: document.body,\n assetPaths,\n configURL, \n options: {development: import.meta.env.DEV}\n });\n main(platform);\n "],"names":["Request","stringify","anotherjson","EVENT_TYPE","Range","encodeKey","decodeKey","MEMBER_EVENT_TYPE","NullLoggerInstance","EVENT_ENCRYPTED_TYPE","POWERLEVELS_EVENT_TYPE","Session","Decryption","DecryptionChanges","Encryption","DecryptionPreparation","Curve25519.Algorithm","Curve25519.BackupEncryption","OlmDecryption","OlmEncryption","MegOlmKeyLoader","MegOlmEncryption","MegOlmDecryption","ssssKeyFromCredential","ssssWriteKey","ssssRemoveKey","E2EEAccount","createSSSSKeyFromDehydratedDeviceKey","ssssReadKey","tileClassForEntry","defaultTileClassForEntry","RequestResult","base64","require$$0","text","DOMPurify","offColorModule","pkg.offColor","pkg.default"],"mappings":"smBAgBO,eAAuB,EAAgC,CAC1D,KAAM,GAAM,CAAA,EACZ,SAAW,KAAS,GAChB,EAAI,GAAS,EAEV,MAAA,QAAO,OAAO,CAAG,CAC5B,CCNA,YAA6B,EAAY,CACrC,GAAI,CACA,MAAO,IAAI,KAAI,CAAU,EAAE,MAC9B,MAAC,CACE,MAAO,IAAI,KAAI,WAAW,GAAY,EAAE,MAC3C,CACL,CAEA,kBAAoC,EAAY,EAAS,CACrD,KAAM,GAAiB,CAAC,OAAQ,OAAQ,QAAS,IAAO,OAAQ,KAAK,EACrE,GAAI,CACA,KAAM,GAAe,GAAG,8BACxB,MAAO,MAAM,GAAQ,EAAc,CAAc,EAAE,SAAQ,CAC9D,OAAQ,EAAP,CACE,GAAI,EAAI,OAAS,kBAIb,MAAO,MAEP,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,QAAQ,GAAK,EAAE,OAAM,CAAE,EAE3D,KAAM,GAAW,SAAS,cAAc,MAAM,EAC9C,EAAS,KAAO,EAChB,EAAS,IAAM,aACf,EAAS,KAAO,WAChB,EAAS,UAAY,QACrB,EAAK,YAAY,CAAQ,CAC5B,IAEG,cAAc,CtU3Uf,MsU4UC,MAAO,aAAU,YAAV,OAAuB,WACjC,CAED,SAAU,CACN,KAAK,aAAa,SACrB,CACL,CClWA,GAAe,IAAA,gBCAA,GAAA,0CCAA,GAAA,4BCAA,GAAA,6BCAA,GAAA,2BCAA,GAAA,kCCWA,GAAA,CACX,gBAAiB,GACjB,OAAQ,GACR,IAAK,CACD,KAAM,GACN,aAAc,GACd,WAAY,EACf,CACL,ECbgB,GAAW,cAAgB,QAE/B,KAAM,IAAW,GAAI,IAAS,CAC1B,UAAW,SAAS,KACpB,cACA,aACA,QAAS,CAAC,YAAa,EAAmB,CAC1D,CAAa,EACD,GAAK,EAAQ"} \ No newline at end of file diff --git a/assets/main.bdb9a925.js b/assets/main.bdb9a925.js new file mode 100644 index 00000000..9b5560ca --- /dev/null +++ b/assets/main.bdb9a925.js @@ -0,0 +1,177 @@ +/* +Copyright 2020 The Matrix.org Foundation C.I.C. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. +*/ + +function asErrorMessage(err) { + return { + type: "error", + message: err.message, + stack: err.stack + }; +} + +function asSuccessMessage(payload) { + return { + type: "success", + payload + }; +} + +class MessageHandler { + constructor() { + this._olm = null; + this._randomValues = self.crypto ? null : []; + } + + _feedRandomValues(randomValues) { + if (this._randomValues) { + this._randomValues.push(...randomValues); + } + } + + _checkRandomValuesUsed() { + if (this._randomValues && this._randomValues.length !== 0) { + throw new Error(`${this._randomValues.length} random values left`); + } + } + + _getRandomValues(typedArray) { + if (!(typedArray instanceof Uint8Array)) { + throw new Error("only Uint8Array is supported: " + JSON.stringify({ + Int8Array: typedArray instanceof Int8Array, + Uint8Array: typedArray instanceof Uint8Array, + Int16Array: typedArray instanceof Int16Array, + Uint16Array: typedArray instanceof Uint16Array, + Int32Array: typedArray instanceof Int32Array, + Uint32Array: typedArray instanceof Uint32Array, + })); + } + if (this._randomValues.length === 0) { + throw new Error("no more random values, needed one of length " + typedArray.length); + } + const precalculated = this._randomValues.shift(); + if (precalculated.length !== typedArray.length) { + throw new Error(`typedArray length (${typedArray.length}) does not match precalculated length (${precalculated.length})`); + } + // copy values + for (let i = 0; i < typedArray.length; ++i) { + typedArray[i] = precalculated[i]; + } + return typedArray; + } + + handleEvent(e) { + if (e.type === "message") { + this._handleMessage(e.data); + } + } + + _sendReply(refMessage, reply) { + reply.replyToId = refMessage.id; + self.postMessage(reply); + } + + _toMessage(fn) { + try { + const payload = fn(); + if (payload instanceof Promise) { + return payload.then( + payload => asSuccessMessage(payload), + err => asErrorMessage(err) + ); + } else { + return asSuccessMessage(payload); + } + } catch (err) { + return asErrorMessage(err); + } + } + + _loadOlm(path) { + return this._toMessage(async () => { + if (!self.crypto) { + self.crypto = {getRandomValues: this._getRandomValues.bind(this)}; + } + // mangle the globals enough to make olm believe it is running in a browser + self.window = self; + self.document = {}; + self.importScripts(path); + const olm = self.Olm; + await olm.init(); + this._olm = olm; + }); + } + + _megolmDecrypt(sessionKey, ciphertext) { + return this._toMessage(() => { + const session = new this._olm.InboundGroupSession(); + try { + session.import_session(sessionKey); + // returns object with plaintext and message_index + return session.decrypt(ciphertext); + } finally { + session.free(); + } + }); + } + + _olmCreateAccountAndOTKs(randomValues, otkAmount) { + return this._toMessage(() => { + this._feedRandomValues(randomValues); + const account = new this._olm.Account(); + try { + account.create(); + account.generate_one_time_keys(otkAmount); + this._checkRandomValuesUsed(); + return account.pickle(""); + } finally { + account.free(); + } + }); + } + + _olmCreateOutbound(randomValues, accountPickle, theirIdentityKey, theirOneTimeKey) { + return this._toMessage(() => { + this._feedRandomValues(randomValues); + const account = new this._olm.Account(); + const newSession = new this._olm.Session(); + try { + account.unpickle("", accountPickle); + newSession.create_outbound(account, theirIdentityKey, theirOneTimeKey); + return newSession.pickle(""); + } finally { + account.free(); + newSession.free(); + } + }); + } + + async _handleMessage(message) { + const {type} = message; + if (type === "ping") { + this._sendReply(message, {type: "success"}); + } else if (type === "load_olm") { + this._sendReply(message, await this._loadOlm(message.path)); + } else if (type === "megolm_decrypt") { + this._sendReply(message, this._megolmDecrypt(message.sessionKey, message.ciphertext)); + } else if (type === "olm_create_account_otks") { + this._sendReply(message, this._olmCreateAccountAndOTKs(message.randomValues, message.otkAmount)); + } else if (type === "olm_create_outbound") { + this._sendReply(message, this._olmCreateOutbound(message.randomValues, message.accountPickle, message.theirIdentityKey, message.theirOneTimeKey)); + } + } +} + +self.addEventListener("message", new MessageHandler()); diff --git a/assets/manifest.56e72e88.json b/assets/manifest.56e72e88.json new file mode 100644 index 00000000..1d776a32 --- /dev/null +++ b/assets/manifest.56e72e88.json @@ -0,0 +1 @@ +{"name":"Hydrogen","short_name":"Hydrogen","display":"standalone","description":"Lightweight matrix client with legacy and mobile browser support","start_url":"../index.html","icons":[{"src":"icon.2a39c64c.png","sizes":"384x384","type":"image/png"},{"src":"icon-maskable.965d12c4.png","sizes":"384x384","type":"image/png","purpose":"maskable"}],"theme_color":"#0DBD8B"} \ No newline at end of file diff --git a/assets/olm.92f1ccd0.js b/assets/olm.92f1ccd0.js new file mode 100644 index 00000000..bbf85c62 --- /dev/null +++ b/assets/olm.92f1ccd0.js @@ -0,0 +1,161 @@ +// @license magnet:?xt=urn:btih:8e4f440f4c65981c5bf93c76d35135ba5064d8b7&dn=apache-2.0.txt Apache-2.0 +// @source: https://gitlab.matrix.org/matrix-org/olm/-/tree/3.2.8 + +var Olm = (function() { +var olm_exports = {}; +var onInitSuccess; +var onInitFail; + +var Module = (function() { + var _scriptDir = typeof document !== 'undefined' && document.currentScript ? document.currentScript.src : undefined; + if (typeof __filename !== 'undefined') _scriptDir = _scriptDir || __filename; + return ( +function(Module) { + Module = Module || {}; + + +var a;a||(a=typeof Module !== 'undefined' ? Module : {});var aa,ba;a.ready=new Promise(function(b,c){aa=b;ba=c});var g;if("undefined"!==typeof window)g=function(b){window.crypto.getRandomValues(b)};else if(module.exports){var ca=require("crypto");g=function(b){var c=ca.randomBytes(b.length);b.set(c)};process=global.process}else throw Error("Cannot find global to attach library to"); +if("undefined"!==typeof OLM_OPTIONS)for(var da in OLM_OPTIONS)OLM_OPTIONS.hasOwnProperty(da)&&(a[da]=OLM_OPTIONS[da]);a.onRuntimeInitialized=function(){h=a._olm_error();olm_exports.PRIVATE_KEY_LENGTH=a._olm_pk_private_key_length();onInitSuccess&&onInitSuccess()};a.onAbort=function(b){onInitFail&&onInitFail(b)};var ea={},l;for(l in a)a.hasOwnProperty(l)&&(ea[l]=a[l]);var ha="object"===typeof window,ia="function"===typeof importScripts,m="",ja,ka,la,n,q; +if("object"===typeof process&&"object"===typeof process.versions&&"string"===typeof process.versions.node)m=ia?require("path").dirname(m)+"/":__dirname+"/",ja=function(b,c){n||(n=require("fs"));q||(q=require("path"));b=q.normalize(b);return n.readFileSync(b,c?null:"utf8")},la=function(b){b=ja(b,!0);b.buffer||(b=new Uint8Array(b));b.buffer||r("Assertion failed: undefined");return b},ka=function(b,c,d){n||(n=require("fs"));q||(q=require("path"));b=q.normalize(b);n.readFile(b,function(e,f){e?d(e):c(f.buffer)})}, +1>0]=0;break;case "i8":u[b>>0]=0;break;case "i16":oa[b>>1]=0;break;case "i32":v[b>>2]=0;break;case "i64":pa=[0,(x=0,1<=+Math.abs(x)?0>>0:~~+Math.ceil((x-+(~~x>>>0))/4294967296)>>>0:0)];v[b>>2]=pa[0];v[b+4>>2]=pa[1];break;case "float":qa[b>>2]=0;break;case "double":ra[b>>3]=0;break;default:r("invalid type for setValue: "+c)}} +function sa(b,c){c=c||"i8";"*"===c.charAt(c.length-1)&&(c="i32");switch(c){case "i1":return u[b>>0];case "i8":return u[b>>0];case "i16":return oa[b>>1];case "i32":return v[b>>2];case "i64":return v[b>>2];case "float":return qa[b>>2];case "double":return ra[b>>3];default:r("invalid type for getValue: "+c)}return null}var ta,ua=!1,va="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0; +function y(b,c){if(b){var d=z,e=b+c;for(c=b;d[c]&&!(c>=e);)++c;if(16f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}b=e}}else b="";return b} +function A(b,c,d,e){if(!(0=p){var w=b.charCodeAt(++k);p=65536+((p&1023)<<10)|w&1023}if(127>=p){if(d>=e)break;c[d++]=p}else{if(2047>=p){if(d+1>=e)break;c[d++]=192|p>>6}else{if(65535>=p){if(d+2>=e)break;c[d++]=224|p>>12}else{if(d+3>=e)break;c[d++]=240|p>>18;c[d++]=128|p>>12&63}c[d++]=128|p>>6&63}c[d++]=128|p&63}}c[d]=0;return d-f} +function B(b){for(var c=0,d=0;d=e&&(e=65536+((e&1023)<<10)|b.charCodeAt(++d)&1023);127>=e?++c:c=2047>=e?c+2:65535>=e?c+3:c+4}return c}function wa(b,c){for(var d=0;d>0]=b.charCodeAt(d)}var u,z,oa,v,qa,ra,xa,ya=[],za=[],Aa=[];function Ca(){var b=a.preRun.shift();ya.unshift(b)}var C=0,Da=null,Ea=null;a.preloadedImages={};a.preloadedAudios={}; +function r(b){if(a.onAbort)a.onAbort(b);ma(b);ua=!0;b=new WebAssembly.RuntimeError("abort("+b+"). Build with -s ASSERTIONS=1 for more info.");ba(b);throw b;}function Fa(){return D.startsWith("data:application/octet-stream;base64,")}var D;D="olm.wasm";if(!Fa()){var Ga=D;D=a.locateFile?a.locateFile(Ga,m):m+Ga}function Ha(){var b=D;try{if(b==D&&na)return new Uint8Array(na);if(la)return la(b);throw"both async and sync fetching of the wasm failed";}catch(c){r(c)}} +function Ia(){if(!na&&(ha||ia)){if("function"===typeof fetch&&!D.startsWith("file://"))return fetch(D,{credentials:"same-origin"}).then(function(b){if(!b.ok)throw"failed to load wasm binary file at '"+D+"'";return b.arrayBuffer()}).catch(function(){return Ha()});if(ka)return new Promise(function(b,c){ka(D,function(d){b(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return Ha()})}var x,pa; +function Ja(b){for(;0=0;--a){f[48+a]=52+a;f[65+a]=a;f[97+a]=26+a}f[43]=62;f[47]=63;function l(m,n,o){var g,h,a=0,i=n,j=o.length,k=n+(j*3>>2)-(o[j-2]=="=")-(o[j-1]=="=");for(;a>4;if(i>2;if(i>2]=G[b+24|0]|G[b+25|0]<<8|(G[b+26|0]<<16|G[b+27|0]<<24);F[g+28>>2]=d;d=G[b+20|0]|G[b+21|0]<<8|(G[b+22|0]<<16|G[b+23|0]<<24);F[g+16>>2]=G[b+16|0]|G[b+17|0]<<8|(G[b+18|0]<<16|G[b+19|0]<<24);F[g+20>>2]=d;d=G[b+4|0]|G[b+5|0]<<8|(G[b+6|0]<<16|G[b+7|0]<<24);f=G[b|0]|G[b+1|0]<<8|(G[b+2|0]<<16|G[b+3|0]<<24);F[g>>2]=f;F[g+4>>2]=d;d=G[b+12|0]|G[b+13|0]<<8|(G[b+14|0]<<16|G[b+15|0]<<24);F[g+8>>2]=G[b+8|0]|G[b+9|0]<<8|(G[b+10|0]<<16|G[b+11|0]<<24);F[g+12>>2]=d;D[g|0]=f&248;D[g+31|0]=G[g+31|0]&63|64;j=G[c+3|0];d=j;b=d<<24&50331648;f=G[c+2|0];d=f>>>16|0;F[g+112>>2]=b|(G[c|0]|G[c+1|0]<<8|f<<16);F[g+116>>2]=d;d=G[c+4|0];f=d>>>24|0;b=d<<8|j;e=G[c+5|0];d=e>>>16|0;e=b|e<<16;j=d|f;s=G[c+6|0];d=s;f=d>>>8|0;h=d<<24;d=f|j;f=e|h;F[g+120>>2]=((d&3)<<30|f>>>2)&33554431;F[g+124>>2]=0;d=G[c+7|0];f=d>>>24|0;b=d<<8|s;e=G[c+8|0];d=e>>>16|0;e=b|e<<16;j=d|f;s=G[c+9|0];d=s;f=d>>>8|0;h=d<<24;d=f|j;f=e|h;F[g+128>>2]=((d&7)<<29|f>>>3)&67108863;F[g+132>>2]=0;d=G[c+10|0];f=d>>>24|0;b=d<<8|s;e=G[c+11|0];d=e>>>16|0;e=b|e<<16;j=d|f;s=G[c+12|0];d=s;f=d>>>8|0;h=d<<24;d=f|j;f=e|h;F[g+136>>2]=((d&31)<<27|f>>>5)&33554431;F[g+140>>2]=0;d=G[c+13|0];f=d>>>24|0;b=d<<8|s;e=G[c+14|0];d=e>>>16|0;e=b|e<<16;j=d|f;d=G[c+15|0];f=d>>>8|0;e=d<<24|e;f=f|j;d=f>>>6|0;F[g+144>>2]=(f&63)<<26|e>>>6;F[g+148>>2]=d;j=G[c+19|0];d=j;b=d<<24&16777216;d=G[c+18|0];f=d>>>16|0;F[g+152>>2]=b|(G[c+16|0]|G[c+17|0]<<8|d<<16);F[g+156>>2]=f;f=G[c+20|0];d=f>>>24|0;e=f<<8|j;f=d;b=e;e=G[c+21|0];d=e>>>16|0;e=b|e<<16;j=d|f;s=G[c+22|0];f=s;d=f>>>8|0;f=f<<24|e;d=d|j;F[g+160>>2]=((d&1)<<31|f>>>1)&67108863;F[g+164>>2]=0;f=G[c+23|0];d=f>>>24|0;b=f<<8|s;e=G[c+24|0];f=e>>>16|0;e=b|e<<16;j=d|f;s=G[c+25|0];f=s;d=f>>>8|0;f=f<<24|e;d=d|j;F[g+168>>2]=((d&7)<<29|f>>>3)&33554431;F[g+172>>2]=0;f=G[c+26|0];d=f>>>24|0;e=f<<8|s;f=d;b=e;e=G[c+27|0];d=e>>>16|0;e=b|e<<16;j=d|f;s=G[c+28|0];f=s;d=f>>>8|0;f=f<<24|e;d=d|j;F[g+176>>2]=((d&15)<<28|f>>>4)&67108863;F[g+180>>2]=0;f=G[c+29|0];d=f>>>24|0;b=f<<8|s;e=G[c+30|0];f=e>>>16|0;e=b|e<<16;f=d|f;c=G[c+31|0];d=c>>>8|0;j=c<<24;c=d|f;d=e|j;F[g+184>>2]=((c&63)<<26|d>>>6)&33554431;F[g+188>>2]=0;z=g+1152|0;ra(z,0,152);F[g+1152>>2]=1;F[g+1156>>2]=0;b=g+992|0;ra(b,0,152);F[g+992>>2]=1;F[g+996>>2]=0;c=g+832|0;ra(c,0,152);j=g+672|0;ra(j,0,152);k=g+512|0;ra(k,0,152);F[g+512>>2]=1;F[g+516>>2]=0;r=g+352|0;ra(r,0,152);Q=g+192|0;ra(Q,0,152);F[g+192>>2]=1;F[g+196>>2]=0;ra(g+1392|0,0,72);t=g+1312|0;ja(t,g+112|0,80);Ma=g+2512|0;while(1){ua=G[(g-ta|0)+31|0];va=0;while(1){J=j;H=0-((ua&128)>>>7|0)|0;j=t;f=F[j>>2];e=F[b>>2];d=H&(f^e);s=b;e=d^e;F[b>>2]=e;F[b+4>>2]=e>>31;d=d^f;F[j>>2]=d;F[j+4>>2]=d>>31;f=F[j+8>>2];e=F[b+8>>2];d=H&(f^e);e=d^e;F[b+8>>2]=e;F[b+12>>2]=e>>31;d=d^f;F[j+8>>2]=d;F[j+12>>2]=d>>31;f=F[j+16>>2];e=F[b+16>>2];d=H&(f^e);e=d^e;F[b+16>>2]=e;F[b+20>>2]=e>>31;d=d^f;F[j+16>>2]=d;F[j+20>>2]=d>>31;f=F[j+24>>2];e=F[b+24>>2];d=H&(f^e);e=d^e;F[b+24>>2]=e;F[b+28>>2]=e>>31;d=d^f;F[j+24>>2]=d;F[j+28>>2]=d>>31;f=F[j+32>>2];e=F[b+32>>2];d=H&(f^e);e=d^e;F[b+32>>2]=e;F[b+36>>2]=e>>31;d=d^f;F[j+32>>2]=d;F[j+36>>2]=d>>31;f=F[j+40>>2];e=F[b+40>>2];d=H&(f^e);e=d^e;F[b+40>>2]=e;F[b+44>>2]=e>>31;d=d^f;F[j+40>>2]=d;F[j+44>>2]=d>>31;f=F[j+48>>2];e=F[b+48>>2];d=H&(f^e);e=d^e;F[b+48>>2]=e;F[b+52>>2]=e>>31;d=d^f;F[j+48>>2]=d;F[j+52>>2]=d>>31;f=F[j+56>>2];e=F[b+56>>2];d=H&(f^e);e=d^e;F[b+56>>2]=e;F[b+60>>2]=e>>31;d=d^f;F[j+56>>2]=d;F[j+60>>2]=d>>31;f=F[j+64>>2];e=F[b+64>>2];d=H&(f^e);e=d^e;F[b+64>>2]=e;F[b+68>>2]=e>>31;d=d^f;F[j+64>>2]=d;F[j+68>>2]=d>>31;f=F[j+72>>2];e=F[b+72>>2];d=H&(f^e);e=d^e;F[b+72>>2]=e;F[b+76>>2]=e>>31;d=d^f;F[j+72>>2]=d;F[j+76>>2]=d>>31;h=z;f=F[h>>2];e=F[c>>2];d=H&(f^e);e=d^e;F[c>>2]=e;F[c+4>>2]=e>>31;d=d^f;F[h>>2]=d;F[h+4>>2]=d>>31;f=F[h+8>>2];e=F[c+8>>2];d=H&(f^e);e=d^e;F[c+8>>2]=e;F[c+12>>2]=e>>31;d=d^f;F[h+8>>2]=d;F[h+12>>2]=d>>31;f=F[h+16>>2];e=F[c+16>>2];d=H&(f^e);e=d^e;F[c+16>>2]=e;F[c+20>>2]=e>>31;d=d^f;F[h+16>>2]=d;F[h+20>>2]=d>>31;f=F[h+24>>2];e=F[c+24>>2];d=H&(f^e);e=d^e;F[c+24>>2]=e;F[c+28>>2]=e>>31;d=d^f;F[h+24>>2]=d;F[h+28>>2]=d>>31;f=F[h+32>>2];e=F[c+32>>2];d=H&(f^e);e=d^e;F[c+32>>2]=e;F[c+36>>2]=e>>31;d=d^f;F[h+32>>2]=d;F[h+36>>2]=d>>31;d=F[h+40>>2];y=F[c+40>>2];p=H&(d^y);d=d^p;F[h+40>>2]=d;F[h+44>>2]=d>>31;d=F[h+48>>2];v=F[c+48>>2];A=H&(d^v);d=d^A;F[h+48>>2]=d;F[h+52>>2]=d>>31;d=F[h+56>>2];i=c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2]=l-c;F[h+4>>2]=K-((c>>>0>l>>>0)+R|0);xa=g+1952|0;sa(xa,b,i);da=g+1792|0;sa(da,s,h);Na=F[g+2024>>2];A=F[g+2028>>2];y=F[g+2016>>2];Oa=F[g+2020>>2];ea=F[g+2096>>2];ha=F[g+2100>>2];C=F[g+2008>>2];Pa=F[g+2012>>2];fa=F[g+2088>>2];ka=F[g+2092>>2];v=F[g+2e3>>2];Qa=F[g+2004>>2];la=F[g+2080>>2];ma=F[g+2084>>2];B=F[g+1992>>2];Ra=F[g+1996>>2];ia=F[g+2072>>2];oa=F[g+2076>>2];q=F[g+1984>>2];Sa=F[g+1988>>2];pa=F[g+2064>>2];ya=F[g+2068>>2];w=F[g+1976>>2];Ta=F[g+1980>>2];na=F[g+2056>>2];za=F[g+2060>>2];l=F[g+1968>>2];t=F[g+1972>>2];P=F[g+2048>>2];Z=F[g+2052>>2];z=F[g+1960>>2];qa=F[g+1964>>2];aa=F[g+2040>>2];ba=F[g+2044>>2];m=F[g+1952>>2];Ua=F[g+1956>>2];ca=F[g+2032>>2];W=F[g+2036>>2];F[g+2032>>2]=0;F[g+2036>>2]=0;Va=F[g+1864>>2];M=F[g+1868>>2];T=F[g+1856>>2];Wa=F[g+1860>>2];Aa=F[g+1936>>2];Ba=F[g+1940>>2];R=F[g+1848>>2];Xa=F[g+1852>>2];Ca=F[g+1928>>2];Da=F[g+1932>>2];K=F[g+1840>>2];Ya=F[g+1844>>2];Ea=F[g+1920>>2];Fa=F[g+1924>>2];S=F[g+1832>>2];Za=F[g+1836>>2];Ga=F[g+1912>>2];Ha=F[g+1916>>2];O=F[g+1824>>2];_a=F[g+1828>>2];Ia=F[g+1904>>2];Ja=F[g+1908>>2];I=F[g+1816>>2];$a=F[g+1820>>2];Ka=F[g+1896>>2];La=F[g+1900>>2];b=F[g+1808>>2];d=F[g+1812>>2];f=F[g+1888>>2];e=F[g+1892>>2];c=F[g+1800>>2];E=F[g+1804>>2];o=F[g+1880>>2];u=F[g+1884>>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l=d;n=e;d=e>>26;x=(e&67108863)<<6|l>>>26;e=x+p|0;f=d+v|0;f=e>>>0>>0?f+1|0:f;p=t+e|0;x=f;d=f+y|0;F[g+1960>>2]=p;F[g+1964>>2]=p>>>0>>0?d+1|0:d;f=o&-67108864;m=b-f|0;p=l&-67108864;l=c-p|0;o=m+l|0;b=u-((b>>>0>>0)+A|0)|0;c=z-((c>>>0

>>0)+n|0)|0;f=b+c|0;d=g;F[d+1952>>2]=o;F[d+1956>>2]=o>>>0>>0?f+1|0:f;F[d+1800>>2]=e-t;F[d+1804>>2]=x-((e>>>0>>0)+y|0);F[d+1792>>2]=l-m;F[d+1796>>2]=c-((l>>>0>>0)+b|0);P=d+1472|0;ga(P,xa);b=d+1632|0;ga(b,da);sa(da,b,d+112|0);m=F[d+1856>>2];Z=F[d+1860>>2];M=F[d+1936>>2];T=F[d+1940>>2];o=F[d+1848>>2];aa=F[d+1852>>2];R=F[d+1928>>2];K=F[d+1932>>2];u=F[d+1840>>2];ba=F[d+1844>>2];S=F[d+1920>>2];O=F[d+1924>>2];x=F[d+1832>>2];ca=F[d+1836>>2];I=F[d+1912>>2];V=F[d+1916>>2];p=F[d+1824>>2];W=F[d+1828>>2];E=F[d+1904>>2];X=F[d+1908>>2];A=F[d+1816>>2];ea=F[d+1820>>2];Y=F[d+1896>>2];N=F[d+1900>>2];b=F[d+1808>>2];d=F[d+1812>>2];f=F[g+1888>>2];e=F[g+1892>>2];c=F[g+1800>>2];B=F[g+1804>>2];t=F[g+1880>>2];n=F[g+1884>>2];l=F[g+1792>>2];q=F[g+1796>>2];C=F[g+1872>>2];v=F[g+1876>>2];F[g+1872>>2]=0;F[g+1876>>2]=0;d=d+e|0;y=b+f|0;d=y>>>0>>0?d+1|0:d;f=qe(f,e,18,0);b=f+y|0;e=$+d|0;w=b;y=b>>>0>>0?e+1|0:e;f=n+B|0;b=c+t|0;f=b>>>0>>0?f+1|0:f;c=qe(t,n,18,0);b=c+b|0;d=$+f|0;f=b;c=f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26;m=(d&67108863)<<6|f>>>26;d=m+F[g+1864>>2]|0;f=e+F[g+1868>>2]|0;f=d>>>0>>0?f+1|0:f;z=f;m=d;e=f;f=e>>31>>>7|0;d=f+d|0;e=d>>>0>>0?e+1|0:e;f=d&-33554432;F[g+1864>>2]=m-f;F[g+1868>>2]=z-((f>>>0>m>>>0)+e|0);f=n&-33554432;n=c-f|0;m=B-((c>>>0>>0)+q|0)|0;c=d;d=e>>25;e=(e&33554431)<<7|c>>>25;f=t&-67108864;z=b-f|0;c=e+z|0;f=(C-((b>>>0>>0)+v|0)|0)+d|0;f=c>>>0>>0?f+1|0:f;b=c;c=qe(e,d,18,0);b=b+c|0;e=$+f|0;e=b>>>0>>0?e+1|0:e;f=e;d=e;e=d>>31>>>6|0;c=e+b|0;d=c>>>0>>0?d+1|0:d;z=d;e=d>>26;t=(d&67108863)<<6|c>>>26;d=t+n|0;e=e+m|0;F[g+1800>>2]=d;F[g+1804>>2]=d>>>0>>0?e+1|0:e;c=c&-67108864;F[g+1792>>2]=b-c;F[g+1796>>2]=f-((b>>>0>>0)+z|0);t=ja(J,P,80);z=k;E=ja(k,da,80);c=g+2272|0;ga(c,s);X=g+2112|0;ga(X,i);b=r;sa(b,c,X);o=F[b+64>>2];aa=F[b+68>>2];M=F[b+144>>2];T=F[b+148>>2];u=F[b+56>>2];ba=F[b+60>>2];R=F[b+136>>2];K=F[b+140>>2];x=F[b+48>>2];ca=F[b+52>>2];S=F[b+128>>2];O=F[b+132>>2];p=F[b+40>>2];W=F[b+44>>2];I=F[b+120>>2];V=F[b+124>>2];J=F[b+32>>2];da=F[b+36>>2];Y=F[b+112>>2];N=F[b+116>>2];A=F[b+24>>2];ea=F[b+28>>2];U=F[b+104>>2];P=F[b+108>>2];c=F[b+16>>2];d=F[b+20>>2];e=F[b+96>>2];l=F[b+100>>2];f=F[b+8>>2];B=F[b+12>>2];n=F[b+88>>2];m=F[b+92>>2];k=F[b>>2];q=F[b+4>>2];y=F[b+80>>2];C=F[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0;d=e+f|0;f=l;d=f>>>0>>0?d+1|0:d;l=d;o=f;u=d>>31>>>6|0;f=u+f|0;d=f>>>0>>0?d+1|0:d;e=f;f=e&-67108864;F[b+64>>2]=o-f;F[b+68>>2]=l-((f>>>0>o>>>0)+d|0);r=e;e=d>>26;r=(d&67108863)<<6|r>>>26;f=b;d=r+F[f+72>>2]|0;e=e+F[f+76>>2]|0;e=d>>>0>>0?e+1|0:e;l=e;u=d;e=e>>31>>>7|0;d=e+d|0;f=l;f=d>>>0>>0?f+1|0:f;e=d&-33554432;F[b+72>>2]=u-e;F[b+76>>2]=l-((e>>>0>u>>>0)+f|0);e=m&-33554432;m=k-e|0;o=v-((e>>>0>k>>>0)+B|0)|0;e=d;d=f>>25;k=(f&33554431)<<7|e>>>25;e=n&-67108864;r=c-e|0;f=k+r|0;e=(y-((c>>>0>>0)+C|0)|0)+d|0;d=qe(k,d,18,0);c=d+f|0;e=$+(f>>>0>>0?e+1|0:e)|0;e=c>>>0>>0?e+1|0:e;r=e;d=e;e=d>>31>>>6|0;f=e+c|0;k=f;d=e>>>0>f>>>0?d+1|0:d;n=d;l=m;e=d>>26;m=(d&67108863)<<6|f>>>26;d=l+m|0;f=e+o|0;F[b+8>>2]=d;F[b+12>>2]=d>>>0>>0?f+1|0:f;d=k&-67108864;F[b>>2]=c-d;F[b+4>>2]=r-((c>>>0>>0)+n|0);m=F[g+2316>>2];ca=F[g+2312>>2];d=ca;f=F[g+2152>>2];c=m-(F[g+2156>>2]+(d>>>0>>0)|0)|0;Y=d-f|0;o=c;F[g+2152>>2]=Y;F[g+2156>>2]=c;u=F[g+2308>>2];W=F[g+2304>>2];d=W;f=F[g+2144>>2];c=u-(F[g+2148>>2]+(d>>>0>>0)|0)|0;N=d-f|0;x=c;F[g+2144>>2]=N;F[g+2148>>2]=c;p=F[g+2300>>2];da=F[g+2296>>2];d=da;f=F[g+2136>>2];c=p-(F[g+2140>>2]+(d>>>0>>0)|0)|0;U=d-f|0;J=c;F[g+2136>>2]=U;F[g+2140>>2]=c;d=F[g+2292>>2];f=F[g+2288>>2];k=F[g+2128>>2];e=d-(F[g+2132>>2]+(f>>>0>>0)|0)|0;n=f-k|0;F[g+2128>>2]=n;F[g+2132>>2]=e;ea=F[g+2284>>2];A=F[g+2280>>2];c=A;k=F[g+2120>>2];l=ea-(F[g+2124>>2]+(c>>>0>>0)|0)|0;O=c-k|0;F[g+2120>>2]=O;F[g+2124>>2]=l;ha=F[g+2276>>2];y=F[g+2272>>2];c=y;k=F[g+2112>>2];r=ha-(F[g+2116>>2]+(c>>>0>>0)|0)|0;I=c-k|0;F[g+2112>>2]=I;F[g+2116>>2]=r;C=F[g+2324>>2];fa=F[g+2320>>2];k=fa;v=F[g+2160>>2];c=C-(F[g+2164>>2]+(k>>>0>>0)|0)|0;P=k-v|0;v=c;F[g+2160>>2]=P;F[g+2164>>2]=c;B=F[g+2332>>2];ka=F[g+2328>>2];k=ka;q=F[g+2168>>2];c=B-(F[g+2172>>2]+(k>>>0>>0)|0)|0;Z=k-q|0;q=c;F[g+2168>>2]=Z;F[g+2172>>2]=c;w=F[g+2340>>2];la=F[g+2336>>2];k=la;M=F[g+2176>>2];c=w-(F[g+2180>>2]+(k>>>0>>0)|0)|0;aa=k-M|0;M=c;F[g+2176>>2]=aa;F[g+2180>>2]=c;T=F[g+2348>>2];ma=F[g+2344>>2];k=ma;R=F[g+2184>>2];c=T-(F[g+2188>>2]+(k>>>0>>0)|0)|0;ba=k-R|0;R=c;F[g+2184>>2]=ba;F[g+2188>>2]=c;ra(Ma,0,72);F[g+2512>>2]=0;F[g+2516>>2]=0;K=f;S=d;ia=qe(n,e,121665,0);oa=$;e=qe(O,l,121665,0);l=$;c=qe(I,r,121665,0);f=$;pa=f;d=f;r=d>>31>>>6|0;f=r+c|0;d=f>>>0>>0?d+1|0:d;r=f;O=d;n=e;e=d>>26;f=(d&67108863)<<6|f>>>26;d=n+f|0;e=e+l|0;l=d;e=d>>>0>>0?e+1|0:e;I=e;d=e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+1|0:d)|0;d=c>>>0>>0?d+1|0:d;l=d;f=d;k=d>>31>>>6|0;d=k+c|0;f=d>>>0>>0?f+1|0:f;k=d;r=f;e=m;d=f>>26;m=(f&67108863)<<6|k>>>26;f=e+m|0;e=d+o|0;F[g+2440>>2]=f;F[g+2444>>2]=f>>>0>>0?e+1|0:e;d=l+ha|0;c=c+y|0;d=c>>>0>>0?d+1|0:d;f=g;e=k&-67108864;F[f+2432>>2]=c-e;F[f+2436>>2]=d-((c>>>0>>0)+r|0);c=Q;sa(c,X,f+2432|0);o=F[c+64>>2];Z=F[c+68>>2];M=F[c+144>>2];T=F[c+148>>2];u=F[c+56>>2];aa=F[c+60>>2];R=F[c+136>>2];K=F[c+140>>2];x=F[c+48>>2];ba=F[c+52>>2];S=F[c+128>>2];O=F[c+132>>2];p=F[c+40>>2];ca=F[c+44>>2];I=F[c+120>>2];V=F[c+124>>2];J=F[c+32>>2];W=F[c+36>>2];X=F[c+112>>2];Y=F[c+116>>2];A=F[c+24>>2];da=F[c+28>>2];N=F[c+104>>2];U=F[c+108>>2];d=F[c+16>>2];f=F[c+20>>2];e=F[c+96>>2];r=F[c+100>>2];k=F[c+8>>2];B=F[c+12>>2];n=F[c+88>>2];m=F[c+92>>2];l=F[c>>2];q=F[c+4>>2];y=F[c+80>>2];C=F[c+84>>2];F[c+80>>2]=0;F[c+84>>2]=0;f=f+r|0;v=d+e|0;f=v>>>0>>0?f+1|0:f;r=qe(e,r,18,0);d=r+v|0;e=$+f|0;w=d;r=d>>>0>>0?e+1|0:e;d=m+B|0;f=k+n|0;d=f>>>0>>0?d+1|0:d;e=qe(n,m,18,0);f=e+f|0;d=$+d|0;d=e>>>0>f>>>0?d+1|0:d;m=f;e=q+C|0;f=l+y|0;e=f>>>0>>0?e+1|0:e;l=qe(y,C,18,0);k=l+f|0;f=$+e|0;f=k>>>0>>0?f+1|0:f;y=f;e=f;l=e>>31>>>6|0;f=l+k|0;n=f;e=f>>>0>>0?e+1|0:e;C=e;f=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(f^e);e=d^e;F[b+48>>2]=e;F[b+52>>2]=e>>31;d=d^f;F[t+48>>2]=d;F[t+52>>2]=d>>31;f=F[t+56>>2];e=F[b+56>>2];d=H&(f^e);e=d^e;F[b+56>>2]=e;F[b+60>>2]=e>>31;d=d^f;F[t+56>>2]=d;F[t+60>>2]=d>>31;f=F[t+64>>2];e=F[b+64>>2];d=H&(f^e);e=d^e;F[b+64>>2]=e;F[b+68>>2]=e>>31;d=d^f;F[t+64>>2]=d;F[t+68>>2]=d>>31;f=F[t+72>>2];e=F[b+72>>2];d=H&(f^e);e=d^e;F[b+72>>2]=e;F[b+76>>2]=e>>31;d=d^f;F[t+72>>2]=d;F[t+76>>2]=d>>31;f=F[E>>2];e=F[c>>2];d=H&(f^e);e=d^e;F[c>>2]=e;F[c+4>>2]=e>>31;d=d^f;F[E>>2]=d;F[E+4>>2]=d>>31;f=F[E+8>>2];e=F[c+8>>2];d=H&(f^e);e=d^e;F[c+8>>2]=e;F[c+12>>2]=e>>31;d=d^f;F[E+8>>2]=d;F[E+12>>2]=d>>31;f=F[E+16>>2];e=F[c+16>>2];d=H&(f^e);e=d^e;F[c+16>>2]=e;F[c+20>>2]=e>>31;d=d^f;F[E+16>>2]=d;F[E+20>>2]=d>>31;f=F[E+24>>2];e=F[c+24>>2];d=H&(f^e);e=d^e;F[c+24>>2]=e;F[c+28>>2]=e>>31;d=d^f;F[E+24>>2]=d;F[E+28>>2]=d>>31;f=F[E+32>>2];e=F[c+32>>2];d=H&(f^e);e=d^e;F[c+32>>2]=e;F[c+36>>2]=e>>31;d=d^f;F[E+32>>2]=d;F[E+36>>2]=d>>31;f=F[E+40>>2];e=F[c+40>>2];d=H&(f^e);e=d^e;F[c+40>>2]=e;F[c+44>>2]=e>>31;d=d^f;F[E+40>>2]=d;F[E+44>>2]=d>>31;f=F[E+48>>2];e=F[c+48>>2];d=H&(f^e);e=d^e;F[c+48>>2]=e;F[c+52>>2]=e>>31;d=d^f;F[E+48>>2]=d;F[E+52>>2]=d>>31;f=F[E+56>>2];e=F[c+56>>2];d=H&(f^e);e=d^e;F[c+56>>2]=e;F[c+60>>2]=e>>31;d=d^f;F[E+56>>2]=d;F[E+60>>2]=d>>31;f=F[E+64>>2];e=F[c+64>>2];d=H&(f^e);e=d^e;F[c+64>>2]=e;F[c+68>>2]=e>>31;d=d^f;F[E+64>>2]=d;F[E+68>>2]=d>>31;f=F[E+72>>2];e=F[c+72>>2];d=H&(f^e);e=d^e;F[c+72>>2]=e;F[c+76>>2]=e>>31;d=d^f;F[E+72>>2]=d;F[E+76>>2]=d>>31;ua=ua<<1;Q=i;r=s;k=h;va=va+1|0;if((va|0)!=8){continue}break}ta=ta+1|0;if((ta|0)!=32){continue}break}ja(g+32|0,b,80);b=g+2272|0;ja(b,c,80);h=g+2112|0;ga(h,b);j=g+672|0;ga(j,h);c=g+832|0;ga(c,j);s=g+2432|0;sa(s,c,b);e=F[g+2576>>2];i=F[g+2496>>2];d=e+i|0;k=F[g+2580>>2];f=k+F[g+2500>>2]|0;f=d>>>0>>0?f+1|0:f;i=qe(e,k,18,0);d=i+d|0;e=$+f|0;F[g+2496>>2]=d;F[g+2500>>2]=d>>>0>>0?e+1|0:e;e=F[g+2568>>2];i=F[g+2488>>2];f=e+i|0;k=F[g+2572>>2];d=k+F[g+2492>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);f=i+f|0;e=$+d|0;F[g+2488>>2]=f;F[g+2492>>2]=f>>>0>>0?e+1|0:e;e=F[g+2560>>2];i=F[g+2480>>2];f=e+i|0;k=F[g+2564>>2];d=k+F[g+2484>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);e=i+f|0;f=$+d|0;F[g+2480>>2]=e;F[g+2484>>2]=e>>>0>>0?f+1|0:f;f=F[g+2552>>2];i=F[g+2472>>2];d=f+i|0;k=F[g+2556>>2];e=k+F[g+2476>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2472>>2]=f;F[g+2476>>2]=f>>>0>>0?d+1|0:d;f=F[g+2544>>2];i=F[g+2464>>2];d=f+i|0;k=F[g+2548>>2];e=k+F[g+2468>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2464>>2]=f;F[g+2468>>2]=f>>>0>>0?d+1|0:d;e=F[g+2536>>2];i=F[g+2456>>2];d=e+i|0;k=F[g+2540>>2];f=k+F[g+2460>>2]|0;f=d>>>0>>0?f+1|0:f;i=qe(e,k,18,0);d=i+d|0;e=$+f|0;F[g+2456>>2]=d;F[g+2460>>2]=d>>>0>>0?e+1|0:e;e=F[g+2528>>2];i=F[g+2448>>2];f=e+i|0;k=F[g+2532>>2];d=k+F[g+2452>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);f=i+f|0;e=$+d|0;F[g+2448>>2]=f;F[g+2452>>2]=f>>>0>>0?e+1|0:e;e=F[g+2520>>2];i=F[g+2440>>2];f=e+i|0;k=F[g+2524>>2];d=k+F[g+2444>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);e=i+f|0;f=$+d|0;F[g+2440>>2]=e;F[g+2444>>2]=e>>>0>>0?f+1|0:f;f=F[g+2512>>2];i=F[g+2432>>2];d=f+i|0;k=F[g+2516>>2];e=k+F[g+2436>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2432>>2]=f;F[g+2436>>2]=f>>>0>>0?d+1|0:d;wa(s);i=g+1952|0;ja(i,s,80);sa(s,i,h);f=F[g+2576>>2];h=F[g+2496>>2];d=f+h|0;k=F[g+2580>>2];e=k+F[g+2500>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,k,18,0);f=h+d|0;d=$+e|0;F[g+2496>>2]=f;F[g+2500>>2]=f>>>0>>0?d+1|0:d;e=F[g+2568>>2];h=F[g+2488>>2];d=e+h|0;k=F[g+2572>>2];f=k+F[g+2492>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,k,18,0);d=h+d|0;e=$+f|0;F[g+2488>>2]=d;F[g+2492>>2]=d>>>0>>0?e+1|0:e;e=F[g+2560>>2];h=F[g+2480>>2];f=e+h|0;k=F[g+2564>>2];d=k+F[g+2484>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,k,18,0);f=h+f|0;e=$+d|0;F[g+2480>>2]=f;F[g+2484>>2]=f>>>0>>0?e+1|0:e;e=F[g+2552>>2];h=F[g+2472>>2];f=e+h|0;k=F[g+2556>>2];d=k+F[g+2476>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,k,18,0);e=h+f|0;f=$+d|0;F[g+2472>>2]=e;F[g+2476>>2]=e>>>0>>0?f+1|0:f;f=F[g+2544>>2];h=F[g+2464>>2];d=f+h|0;k=F[g+2548>>2];e=k+F[g+2468>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,k,18,0);f=h+d|0;d=$+e|0;F[g+2464>>2]=f;F[g+2468>>2]=f>>>0>>0?d+1|0:d;f=F[g+2536>>2];h=F[g+2456>>2];d=f+h|0;k=F[g+2540>>2];e=k+F[g+2460>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,k,18,0);f=h+d|0;d=$+e|0;F[g+2456>>2]=f;F[g+2460>>2]=f>>>0>>0?d+1|0:d;e=F[g+2528>>2];h=F[g+2448>>2];d=e+h|0;k=F[g+2532>>2];f=k+F[g+2452>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,k,18,0);d=h+d|0;e=$+f|0;F[g+2448>>2]=d;F[g+2452>>2]=d>>>0>>0?e+1|0:e;e=F[g+2520>>2];h=F[g+2440>>2];f=e+h|0;k=F[g+2524>>2];d=k+F[g+2444>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,k,18,0);f=h+f|0;e=$+d|0;F[g+2440>>2]=f;F[g+2444>>2]=f>>>0>>0?e+1|0:e;e=F[g+2512>>2];h=F[g+2432>>2];f=e+h|0;k=F[g+2516>>2];d=k+F[g+2436>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,k,18,0);e=h+f|0;f=$+d|0;F[g+2432>>2]=e;F[g+2436>>2]=e>>>0>>0?f+1|0:f;wa(s);b=g+1792|0;ja(b,s,80);ga(c,b);sa(s,c,i);f=F[g+2576>>2];h=F[g+2496>>2];d=f+h|0;i=F[g+2580>>2];e=i+F[g+2500>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2496>>2]=f;F[g+2500>>2]=f>>>0>>0?d+1|0:d;f=F[g+2568>>2];h=F[g+2488>>2];d=f+h|0;i=F[g+2572>>2];e=i+F[g+2492>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2488>>2]=f;F[g+2492>>2]=f>>>0>>0?d+1|0:d;e=F[g+2560>>2];h=F[g+2480>>2];d=e+h|0;i=F[g+2564>>2];f=i+F[g+2484>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2480>>2]=d;F[g+2484>>2]=d>>>0>>0?e+1|0:e;e=F[g+2552>>2];h=F[g+2472>>2];f=e+h|0;i=F[g+2556>>2];d=i+F[g+2476>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2472>>2]=f;F[g+2476>>2]=f>>>0>>0?e+1|0:e;e=F[g+2544>>2];h=F[g+2464>>2];f=e+h|0;i=F[g+2548>>2];d=i+F[g+2468>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2464>>2]=e;F[g+2468>>2]=e>>>0>>0?f+1|0:f;f=F[g+2536>>2];h=F[g+2456>>2];d=f+h|0;i=F[g+2540>>2];e=i+F[g+2460>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2456>>2]=f;F[g+2460>>2]=f>>>0>>0?d+1|0:d;f=F[g+2528>>2];h=F[g+2448>>2];d=f+h|0;i=F[g+2532>>2];e=i+F[g+2452>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2448>>2]=f;F[g+2452>>2]=f>>>0>>0?d+1|0:d;e=F[g+2520>>2];h=F[g+2440>>2];d=e+h|0;i=F[g+2524>>2];f=i+F[g+2444>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2440>>2]=d;F[g+2444>>2]=d>>>0>>0?e+1|0:e;e=F[g+2512>>2];h=F[g+2432>>2];f=e+h|0;i=F[g+2516>>2];d=i+F[g+2436>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2432>>2]=f;F[g+2436>>2]=f>>>0>>0?e+1|0:e;wa(s);b=g+1632|0;ja(b,s,80);ga(c,b);ga(j,c);ga(c,j);ga(j,c);ga(c,j);sa(s,c,b);e=F[g+2576>>2];h=F[g+2496>>2];f=e+h|0;i=F[g+2580>>2];d=i+F[g+2500>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2496>>2]=e;F[g+2500>>2]=e>>>0>>0?f+1|0:f;f=F[g+2568>>2];h=F[g+2488>>2];d=f+h|0;i=F[g+2572>>2];e=i+F[g+2492>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2488>>2]=f;F[g+2492>>2]=f>>>0>>0?d+1|0:d;f=F[g+2560>>2];h=F[g+2480>>2];d=f+h|0;i=F[g+2564>>2];e=i+F[g+2484>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2480>>2]=f;F[g+2484>>2]=f>>>0>>0?d+1|0:d;e=F[g+2552>>2];h=F[g+2472>>2];d=e+h|0;i=F[g+2556>>2];f=i+F[g+2476>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2472>>2]=d;F[g+2476>>2]=d>>>0>>0?e+1|0:e;e=F[g+2544>>2];h=F[g+2464>>2];f=e+h|0;i=F[g+2548>>2];d=i+F[g+2468>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2464>>2]=f;F[g+2468>>2]=f>>>0>>0?e+1|0:e;e=F[g+2536>>2];h=F[g+2456>>2];f=e+h|0;i=F[g+2540>>2];d=i+F[g+2460>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2456>>2]=e;F[g+2460>>2]=e>>>0>>0?f+1|0:f;f=F[g+2528>>2];h=F[g+2448>>2];d=f+h|0;i=F[g+2532>>2];e=i+F[g+2452>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2448>>2]=f;F[g+2452>>2]=f>>>0>>0?d+1|0:d;f=F[g+2520>>2];h=F[g+2440>>2];d=f+h|0;i=F[g+2524>>2];e=i+F[g+2444>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2440>>2]=f;F[g+2444>>2]=f>>>0>>0?d+1|0:d;e=F[g+2512>>2];h=F[g+2432>>2];d=e+h|0;i=F[g+2516>>2];f=i+F[g+2436>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2432>>2]=d;F[g+2436>>2]=d>>>0>>0?e+1|0:e;wa(s);h=g+1472|0;ja(h,s,80);ga(c,h);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);sa(s,j,h);e=F[g+2576>>2];i=F[g+2496>>2];f=e+i|0;k=F[g+2580>>2];d=k+F[g+2500>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);f=i+f|0;e=$+d|0;F[g+2496>>2]=f;F[g+2500>>2]=f>>>0>>0?e+1|0:e;e=F[g+2568>>2];i=F[g+2488>>2];f=e+i|0;k=F[g+2572>>2];d=k+F[g+2492>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);e=i+f|0;f=$+d|0;F[g+2488>>2]=e;F[g+2492>>2]=e>>>0>>0?f+1|0:f;f=F[g+2560>>2];i=F[g+2480>>2];d=f+i|0;k=F[g+2564>>2];e=k+F[g+2484>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2480>>2]=f;F[g+2484>>2]=f>>>0>>0?d+1|0:d;f=F[g+2552>>2];i=F[g+2472>>2];d=f+i|0;k=F[g+2556>>2];e=k+F[g+2476>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2472>>2]=f;F[g+2476>>2]=f>>>0>>0?d+1|0:d;e=F[g+2544>>2];i=F[g+2464>>2];d=e+i|0;k=F[g+2548>>2];f=k+F[g+2468>>2]|0;f=d>>>0>>0?f+1|0:f;i=qe(e,k,18,0);d=i+d|0;e=$+f|0;F[g+2464>>2]=d;F[g+2468>>2]=d>>>0>>0?e+1|0:e;e=F[g+2536>>2];i=F[g+2456>>2];f=e+i|0;k=F[g+2540>>2];d=k+F[g+2460>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);f=i+f|0;e=$+d|0;F[g+2456>>2]=f;F[g+2460>>2]=f>>>0>>0?e+1|0:e;e=F[g+2528>>2];i=F[g+2448>>2];f=e+i|0;k=F[g+2532>>2];d=k+F[g+2452>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);e=i+f|0;f=$+d|0;F[g+2448>>2]=e;F[g+2452>>2]=e>>>0>>0?f+1|0:f;f=F[g+2520>>2];i=F[g+2440>>2];d=f+i|0;k=F[g+2524>>2];e=k+F[g+2444>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2440>>2]=f;F[g+2444>>2]=f>>>0>>0?d+1|0:d;f=F[g+2512>>2];i=F[g+2432>>2];d=f+i|0;k=F[g+2516>>2];e=k+F[g+2436>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2432>>2]=f;F[g+2436>>2]=f>>>0>>0?d+1|0:d;wa(s);b=g+1312|0;ja(b,s,80);ga(c,b);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);sa(s,j,b);e=F[g+2576>>2];i=F[g+2496>>2];d=e+i|0;k=F[g+2580>>2];f=k+F[g+2500>>2]|0;f=d>>>0>>0?f+1|0:f;i=qe(e,k,18,0);d=i+d|0;e=$+f|0;F[g+2496>>2]=d;F[g+2500>>2]=d>>>0>>0?e+1|0:e;e=F[g+2568>>2];i=F[g+2488>>2];f=e+i|0;k=F[g+2572>>2];d=k+F[g+2492>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);f=i+f|0;e=$+d|0;F[g+2488>>2]=f;F[g+2492>>2]=f>>>0>>0?e+1|0:e;e=F[g+2560>>2];i=F[g+2480>>2];f=e+i|0;k=F[g+2564>>2];d=k+F[g+2484>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);e=i+f|0;f=$+d|0;F[g+2480>>2]=e;F[g+2484>>2]=e>>>0>>0?f+1|0:f;f=F[g+2552>>2];i=F[g+2472>>2];d=f+i|0;k=F[g+2556>>2];e=k+F[g+2476>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2472>>2]=f;F[g+2476>>2]=f>>>0>>0?d+1|0:d;f=F[g+2544>>2];i=F[g+2464>>2];d=f+i|0;k=F[g+2548>>2];e=k+F[g+2468>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2464>>2]=f;F[g+2468>>2]=f>>>0>>0?d+1|0:d;e=F[g+2536>>2];i=F[g+2456>>2];d=e+i|0;k=F[g+2540>>2];f=k+F[g+2460>>2]|0;f=d>>>0>>0?f+1|0:f;i=qe(e,k,18,0);d=i+d|0;e=$+f|0;F[g+2456>>2]=d;F[g+2460>>2]=d>>>0>>0?e+1|0:e;e=F[g+2528>>2];i=F[g+2448>>2];f=e+i|0;k=F[g+2532>>2];d=k+F[g+2452>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);f=i+f|0;e=$+d|0;F[g+2448>>2]=f;F[g+2452>>2]=f>>>0>>0?e+1|0:e;e=F[g+2520>>2];i=F[g+2440>>2];f=e+i|0;k=F[g+2524>>2];d=k+F[g+2444>>2]|0;d=f>>>0>>0?d+1|0:d;i=qe(e,k,18,0);e=i+f|0;f=$+d|0;F[g+2440>>2]=e;F[g+2444>>2]=e>>>0>>0?f+1|0:f;f=F[g+2512>>2];i=F[g+2432>>2];d=f+i|0;k=F[g+2516>>2];e=k+F[g+2436>>2]|0;e=d>>>0>>0?e+1|0:e;i=qe(f,k,18,0);f=i+d|0;d=$+e|0;F[g+2432>>2]=f;F[g+2436>>2]=f>>>0>>0?d+1|0:d;wa(s);ja(c,s,80);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);sa(s,c,h);f=F[g+2576>>2];h=F[g+2496>>2];d=f+h|0;i=F[g+2580>>2];e=i+F[g+2500>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2496>>2]=f;F[g+2500>>2]=f>>>0>>0?d+1|0:d;e=F[g+2568>>2];h=F[g+2488>>2];d=e+h|0;i=F[g+2572>>2];f=i+F[g+2492>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2488>>2]=d;F[g+2492>>2]=d>>>0>>0?e+1|0:e;e=F[g+2560>>2];h=F[g+2480>>2];f=e+h|0;i=F[g+2564>>2];d=i+F[g+2484>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2480>>2]=f;F[g+2484>>2]=f>>>0>>0?e+1|0:e;e=F[g+2552>>2];h=F[g+2472>>2];f=e+h|0;i=F[g+2556>>2];d=i+F[g+2476>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2472>>2]=e;F[g+2476>>2]=e>>>0>>0?f+1|0:f;f=F[g+2544>>2];h=F[g+2464>>2];d=f+h|0;i=F[g+2548>>2];e=i+F[g+2468>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2464>>2]=f;F[g+2468>>2]=f>>>0>>0?d+1|0:d;f=F[g+2536>>2];h=F[g+2456>>2];d=f+h|0;i=F[g+2540>>2];e=i+F[g+2460>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2456>>2]=f;F[g+2460>>2]=f>>>0>>0?d+1|0:d;e=F[g+2528>>2];h=F[g+2448>>2];d=e+h|0;i=F[g+2532>>2];f=i+F[g+2452>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2448>>2]=d;F[g+2452>>2]=d>>>0>>0?e+1|0:e;e=F[g+2520>>2];h=F[g+2440>>2];f=e+h|0;i=F[g+2524>>2];d=i+F[g+2444>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2440>>2]=f;F[g+2444>>2]=f>>>0>>0?e+1|0:e;e=F[g+2512>>2];h=F[g+2432>>2];f=e+h|0;i=F[g+2516>>2];d=i+F[g+2436>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2432>>2]=e;F[g+2436>>2]=e>>>0>>0?f+1|0:f;wa(s);b=g+1152|0;ja(b,s,80);ga(c,b);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);sa(s,j,b);f=F[g+2576>>2];h=F[g+2496>>2];d=f+h|0;i=F[g+2580>>2];e=i+F[g+2500>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2496>>2]=f;F[g+2500>>2]=f>>>0>>0?d+1|0:d;f=F[g+2568>>2];h=F[g+2488>>2];d=f+h|0;i=F[g+2572>>2];e=i+F[g+2492>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2488>>2]=f;F[g+2492>>2]=f>>>0>>0?d+1|0:d;e=F[g+2560>>2];h=F[g+2480>>2];d=e+h|0;i=F[g+2564>>2];f=i+F[g+2484>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2480>>2]=d;F[g+2484>>2]=d>>>0>>0?e+1|0:e;e=F[g+2552>>2];h=F[g+2472>>2];f=e+h|0;i=F[g+2556>>2];d=i+F[g+2476>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2472>>2]=f;F[g+2476>>2]=f>>>0>>0?e+1|0:e;e=F[g+2544>>2];h=F[g+2464>>2];f=e+h|0;i=F[g+2548>>2];d=i+F[g+2468>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2464>>2]=e;F[g+2468>>2]=e>>>0>>0?f+1|0:f;f=F[g+2536>>2];h=F[g+2456>>2];d=f+h|0;i=F[g+2540>>2];e=i+F[g+2460>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2456>>2]=f;F[g+2460>>2]=f>>>0>>0?d+1|0:d;f=F[g+2528>>2];h=F[g+2448>>2];d=f+h|0;i=F[g+2532>>2];e=i+F[g+2452>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2448>>2]=f;F[g+2452>>2]=f>>>0>>0?d+1|0:d;e=F[g+2520>>2];h=F[g+2440>>2];d=e+h|0;i=F[g+2524>>2];f=i+F[g+2444>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2440>>2]=d;F[g+2444>>2]=d>>>0>>0?e+1|0:e;e=F[g+2512>>2];h=F[g+2432>>2];f=e+h|0;i=F[g+2516>>2];d=i+F[g+2436>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2432>>2]=f;F[g+2436>>2]=f>>>0>>0?e+1|0:e;wa(s);b=g+992|0;ja(b,s,80);ga(j,b);ga(c,j);c=2;while(1){b=c>>>0<98;d=g+672|0;f=g+832|0;ga(d,f);ga(f,d);c=c+2|0;if(b){continue}break}s=g+2432|0;j=g+832|0;sa(s,j,g+992|0);f=F[g+2576>>2];e=F[g+2496>>2];c=f+e|0;h=F[g+2580>>2];d=h+F[g+2500>>2]|0;d=c>>>0>>0?d+1|0:d;e=qe(f,h,18,0);c=e+c|0;f=$+d|0;F[g+2496>>2]=c;F[g+2500>>2]=c>>>0>>0?f+1|0:f;d=F[g+2568>>2];f=F[g+2488>>2];c=d+f|0;h=F[g+2572>>2];e=h+F[g+2492>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,h,18,0);c=f+c|0;d=$+e|0;F[g+2488>>2]=c;F[g+2492>>2]=c>>>0>>0?d+1|0:d;d=F[g+2560>>2];f=F[g+2480>>2];c=d+f|0;h=F[g+2564>>2];e=h+F[g+2484>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,h,18,0);c=f+c|0;d=$+e|0;F[g+2480>>2]=c;F[g+2484>>2]=c>>>0>>0?d+1|0:d;d=F[g+2552>>2];e=F[g+2472>>2];c=d+e|0;h=F[g+2556>>2];f=h+F[g+2476>>2]|0;f=c>>>0>>0?f+1|0:f;d=qe(d,h,18,0);c=d+c|0;e=$+f|0;F[g+2472>>2]=c;F[g+2476>>2]=c>>>0>>0?e+1|0:e;f=F[g+2544>>2];e=F[g+2464>>2];c=f+e|0;h=F[g+2548>>2];d=h+F[g+2468>>2]|0;d=c>>>0>>0?d+1|0:d;f=qe(f,h,18,0);c=f+c|0;e=$+d|0;F[g+2464>>2]=c;F[g+2468>>2]=c>>>0>>0?e+1|0:e;f=F[g+2536>>2];e=F[g+2456>>2];c=f+e|0;h=F[g+2540>>2];d=h+F[g+2460>>2]|0;d=c>>>0>>0?d+1|0:d;e=qe(f,h,18,0);c=e+c|0;f=$+d|0;F[g+2456>>2]=c;F[g+2460>>2]=c>>>0>>0?f+1|0:f;d=F[g+2528>>2];f=F[g+2448>>2];c=d+f|0;h=F[g+2532>>2];e=h+F[g+2452>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,h,18,0);c=f+c|0;d=$+e|0;F[g+2448>>2]=c;F[g+2452>>2]=c>>>0>>0?d+1|0:d;d=F[g+2520>>2];f=F[g+2440>>2];c=d+f|0;h=F[g+2524>>2];e=h+F[g+2444>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,h,18,0);c=f+c|0;d=$+e|0;F[g+2440>>2]=c;F[g+2444>>2]=c>>>0>>0?d+1|0:d;d=F[g+2512>>2];e=F[g+2432>>2];c=d+e|0;h=F[g+2516>>2];f=h+F[g+2436>>2]|0;f=c>>>0>>0?f+1|0:f;d=qe(d,h,18,0);c=d+c|0;e=$+f|0;F[g+2432>>2]=c;F[g+2436>>2]=c>>>0>>0?e+1|0:e;wa(s);c=g+672|0;ja(c,s,80);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);sa(s,c,g+1152|0);e=F[g+2576>>2];h=F[g+2496>>2];f=e+h|0;i=F[g+2580>>2];d=i+F[g+2500>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2496>>2]=f;F[g+2500>>2]=f>>>0>>0?e+1|0:e;e=F[g+2568>>2];h=F[g+2488>>2];f=e+h|0;i=F[g+2572>>2];d=i+F[g+2492>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2488>>2]=e;F[g+2492>>2]=e>>>0>>0?f+1|0:f;f=F[g+2560>>2];h=F[g+2480>>2];d=f+h|0;i=F[g+2564>>2];e=i+F[g+2484>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2480>>2]=f;F[g+2484>>2]=f>>>0>>0?d+1|0:d;f=F[g+2552>>2];h=F[g+2472>>2];d=f+h|0;i=F[g+2556>>2];e=i+F[g+2476>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2472>>2]=f;F[g+2476>>2]=f>>>0>>0?d+1|0:d;e=F[g+2544>>2];h=F[g+2464>>2];d=e+h|0;i=F[g+2548>>2];f=i+F[g+2468>>2]|0;f=d>>>0>>0?f+1|0:f;h=qe(e,i,18,0);d=h+d|0;e=$+f|0;F[g+2464>>2]=d;F[g+2468>>2]=d>>>0>>0?e+1|0:e;e=F[g+2536>>2];h=F[g+2456>>2];f=e+h|0;i=F[g+2540>>2];d=i+F[g+2460>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);f=h+f|0;e=$+d|0;F[g+2456>>2]=f;F[g+2460>>2]=f>>>0>>0?e+1|0:e;e=F[g+2528>>2];h=F[g+2448>>2];f=e+h|0;i=F[g+2532>>2];d=i+F[g+2452>>2]|0;d=f>>>0>>0?d+1|0:d;h=qe(e,i,18,0);e=h+f|0;f=$+d|0;F[g+2448>>2]=e;F[g+2452>>2]=e>>>0>>0?f+1|0:f;f=F[g+2520>>2];h=F[g+2440>>2];d=f+h|0;i=F[g+2524>>2];e=i+F[g+2444>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2440>>2]=f;F[g+2444>>2]=f>>>0>>0?d+1|0:d;f=F[g+2512>>2];h=F[g+2432>>2];d=f+h|0;i=F[g+2516>>2];e=i+F[g+2436>>2]|0;e=d>>>0>>0?e+1|0:e;h=qe(f,i,18,0);f=h+d|0;d=$+e|0;F[g+2432>>2]=f;F[g+2436>>2]=f>>>0>>0?d+1|0:d;wa(s);ja(j,s,80);ga(c,j);ga(j,c);ga(c,j);ga(j,c);ga(c,j);sa(s,c,g+1792|0);d=F[g+2576>>2];e=F[g+2496>>2];c=d+e|0;j=F[g+2580>>2];f=j+F[g+2500>>2]|0;f=c>>>0>>0?f+1|0:f;d=qe(d,j,18,0);c=d+c|0;e=$+f|0;F[g+2496>>2]=c;F[g+2500>>2]=c>>>0>>0?e+1|0:e;f=F[g+2568>>2];e=F[g+2488>>2];c=f+e|0;j=F[g+2572>>2];d=j+F[g+2492>>2]|0;d=c>>>0>>0?d+1|0:d;f=qe(f,j,18,0);c=f+c|0;e=$+d|0;F[g+2488>>2]=c;F[g+2492>>2]=c>>>0>>0?e+1|0:e;f=F[g+2560>>2];e=F[g+2480>>2];c=f+e|0;j=F[g+2564>>2];d=j+F[g+2484>>2]|0;d=c>>>0>>0?d+1|0:d;e=qe(f,j,18,0);c=e+c|0;f=$+d|0;F[g+2480>>2]=c;F[g+2484>>2]=c>>>0>>0?f+1|0:f;d=F[g+2552>>2];f=F[g+2472>>2];c=d+f|0;j=F[g+2556>>2];e=j+F[g+2476>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,j,18,0);c=f+c|0;d=$+e|0;F[g+2472>>2]=c;F[g+2476>>2]=c>>>0>>0?d+1|0:d;d=F[g+2544>>2];f=F[g+2464>>2];c=d+f|0;j=F[g+2548>>2];e=j+F[g+2468>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,j,18,0);c=f+c|0;d=$+e|0;F[g+2464>>2]=c;F[g+2468>>2]=c>>>0>>0?d+1|0:d;d=F[g+2536>>2];e=F[g+2456>>2];c=d+e|0;j=F[g+2540>>2];f=j+F[g+2460>>2]|0;f=c>>>0>>0?f+1|0:f;d=qe(d,j,18,0);c=d+c|0;e=$+f|0;F[g+2456>>2]=c;F[g+2460>>2]=c>>>0>>0?e+1|0:e;f=F[g+2528>>2];e=F[g+2448>>2];c=f+e|0;j=F[g+2532>>2];d=j+F[g+2452>>2]|0;d=c>>>0>>0?d+1|0:d;f=qe(f,j,18,0);c=f+c|0;e=$+d|0;F[g+2448>>2]=c;F[g+2452>>2]=c>>>0>>0?e+1|0:e;f=F[g+2520>>2];e=F[g+2440>>2];c=f+e|0;j=F[g+2524>>2];d=j+F[g+2444>>2]|0;d=c>>>0>>0?d+1|0:d;e=qe(f,j,18,0);c=e+c|0;f=$+d|0;F[g+2440>>2]=c;F[g+2444>>2]=c>>>0>>0?f+1|0:f;d=F[g+2512>>2];f=F[g+2432>>2];c=d+f|0;j=F[g+2516>>2];e=j+F[g+2436>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,j,18,0);c=f+c|0;d=$+e|0;F[g+2432>>2]=c;F[g+2436>>2]=c>>>0>>0?d+1|0:d;wa(s);b=g+512|0;ja(b,s,80);sa(s,g+32|0,b);d=F[g+2576>>2];f=F[g+2496>>2];c=d+f|0;j=F[g+2580>>2];e=j+F[g+2500>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,j,18,0);c=f+c|0;d=$+e|0;F[g+2496>>2]=c;F[g+2500>>2]=c>>>0>>0?d+1|0:d;d=F[g+2568>>2];e=F[g+2488>>2];c=d+e|0;j=F[g+2572>>2];f=j+F[g+2492>>2]|0;f=c>>>0>>0?f+1|0:f;d=qe(d,j,18,0);c=d+c|0;e=$+f|0;F[g+2488>>2]=c;F[g+2492>>2]=c>>>0>>0?e+1|0:e;f=F[g+2560>>2];e=F[g+2480>>2];c=f+e|0;j=F[g+2564>>2];d=j+F[g+2484>>2]|0;d=c>>>0>>0?d+1|0:d;f=qe(f,j,18,0);c=f+c|0;e=$+d|0;F[g+2480>>2]=c;F[g+2484>>2]=c>>>0>>0?e+1|0:e;f=F[g+2552>>2];e=F[g+2472>>2];c=f+e|0;j=F[g+2556>>2];d=j+F[g+2476>>2]|0;d=c>>>0>>0?d+1|0:d;e=qe(f,j,18,0);c=e+c|0;f=$+d|0;F[g+2472>>2]=c;F[g+2476>>2]=c>>>0>>0?f+1|0:f;d=F[g+2544>>2];f=F[g+2464>>2];c=d+f|0;j=F[g+2548>>2];e=j+F[g+2468>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,j,18,0);c=f+c|0;d=$+e|0;F[g+2464>>2]=c;F[g+2468>>2]=c>>>0>>0?d+1|0:d;d=F[g+2536>>2];f=F[g+2456>>2];c=d+f|0;j=F[g+2540>>2];e=j+F[g+2460>>2]|0;e=c>>>0>>0?e+1|0:e;f=qe(d,j,18,0);c=f+c|0;d=$+e|0;F[g+2456>>2]=c;F[g+2460>>2]=c>>>0>>0?d+1|0:d;d=F[g+2528>>2];e=F[g+2448>>2];c=d+e|0;j=F[g+2532>>2];f=j+F[g+2452>>2]|0;f=c>>>0>>0?f+1|0:f;d=qe(d,j,18,0);c=d+c|0;e=$+f|0;F[g+2448>>2]=c;F[g+2452>>2]=c>>>0>>0?e+1|0:e;f=F[g+2520>>2];e=F[g+2440>>2];c=f+e|0;j=F[g+2524>>2];d=j+F[g+2444>>2]|0;d=c>>>0>>0?d+1|0:d;f=qe(f,j,18,0);c=f+c|0;e=$+d|0;F[g+2440>>2]=c;F[g+2444>>2]=c>>>0>>0?e+1|0:e;f=F[g+2512>>2];e=F[g+2432>>2];c=f+e|0;j=F[g+2516>>2];d=j+F[g+2436>>2]|0;d=c>>>0>>0?d+1|0:d;e=qe(f,j,18,0);c=e+c|0;f=$+d|0;F[g+2432>>2]=c;F[g+2436>>2]=c>>>0>>0?f+1|0:f;wa(s);ja(g+2272|0,s,80);b=F[g+2272>>2];l=b>>31&b;c=F[g+2280>>2]+(l>>26)|0;z=c>>31&c;d=F[g+2288>>2]+(z>>25)|0;r=d>>31&d;f=F[g+2296>>2]+(r>>26)|0;Q=f>>31&f;e=F[g+2304>>2]+(Q>>25)|0;t=e>>31&e;j=F[g+2312>>2]+(t>>26)|0;n=j>>31&j;s=F[g+2320>>2]+(n>>25)|0;m=s>>31&s;h=F[g+2328>>2]+(m>>26)|0;o=h>>31&h;i=F[g+2336>>2]+(o>>25)|0;u=i>>31&i;k=F[g+2344>>2]+(u>>26)|0;x=k>>31&k;b=L(x>>25,19)+(b-(l&-67108864)|0)|0;p=b>>31&b;c=(p>>26)+(c-(z&-33554432)|0)|0;l=c>>31&c;q=c-(l&-33554432)|0;w=b-(p&-67108864)|0;p=k-(x&-33554432)|0;b=(d-(r&-67108864)|0)+(l>>25)|0;k=b>>31&b;c=(f-(Q&-33554432)|0)+(k>>26)|0;l=c>>31&c;d=(e-(t&-67108864)|0)+(l>>25)|0;z=d>>31&d;f=(j-(n&-33554432)|0)+(z>>26)|0;r=f>>31&f;e=(s-(m&-67108864)|0)+(r>>25)|0;Q=e>>31&e;j=(h-(o&-33554432)|0)+(Q>>26)|0;t=j>>31&j;s=(i-(u&-67108864)|0)+(t>>25)|0;n=s>>31&s;h=p+(n>>26)|0;m=h>>31&h;i=w+L(m>>25,19)|0;o=i>>31&i;i=i-(o&-67108864)|0;o=(q+(o>>26)|0)+(i>>26)|0;b=(o>>25)+(b-(k&-67108864)|0)|0;k=(b>>26)+(c-(l&-33554432)|0)|0;l=(k>>25)+(d-(z&-67108864)|0)|0;z=(l>>26)+(f-(r&-33554432)|0)|0;r=(z>>25)+(e-(Q&-67108864)|0)|0;j=(r>>26)+(j-(t&-33554432)|0)|0;s=(j>>25)+(s-(n&-67108864)|0)|0;h=(s>>26)+(h-(m&-33554432)|0)|0;Q=L(h>>25,19)+(i&67108863)|0;c=(Q>>26)+(o&33554431)|0;d=(c>>25)+(b&67108863)|0;f=(d>>26)+(k&33554431)|0;e=(f>>25)+(l&67108863)|0;b=(e>>26)+(z&33554431)|0;o=b&33554431;l=h&33554431;m=s&67108863;n=j&33554431;j=(r&67108863)+(b>>25)|0;s=n+(j>>26)|0;h=m+(s>>25)|0;i=l+(h>>26)|0;l=L(i>>25,19)+(Q&67108863)|0;k=(d|-67108864)&d<<16;k=k<<8&k;k=k<<4&k;k=k<<2&k;m=k<<1&k;k=(c|-33554432)&c<<16;k=k<<8&k;k=k<<4&k;k=k<<2&k;m=m&(k<<1&k);k=(f|-33554432)&f<<16;k=k<<8&k;k=k<<4&k;k=k<<2&k;m=m&(k<<1&k);k=(e|-67108864)&e<<16;k=k<<8&k;k=k<<4&k;k=k<<2&k;b=(b|-33554432)&b<<16;b=b<<8&b;b=b<<4&b;b=b<<2&b;m=(l-67108845>>31^-1)&(m&(k<<1&k)&(b<<1&b))>>31;b=(j|-67108864)&j<<16;b=b<<8&b;b=b<<4&b;b=b<<2&b;m=m&(b<<1&b)>>31;b=(s|-33554432)&s<<16;b=b<<8&b;b=b<<4&b;b=b<<2&b;m=m&(b<<1&b)>>31;b=(h|-67108864)&h<<16;b=b<<8&b;b=b<<4&b;b=b<<2&b;m=m&(b<<1&b)>>31;b=(i|-33554432)&i<<16;b=b<<8&b;b=b<<4&b;b=b<<2&b;z=m&(b<<1&b)>>31;b=z&33554431;k=o-b|0;D[a+16|0]=k;l=l-(z&67108845)|0;D[a|0]=l;i=(i&33554431)-b|0;D[a+31|0]=i>>>18;D[a+30|0]=i>>>10;D[a+29|0]=i>>>2;o=h&67108863;h=z&67108863;z=o-h|0;D[a+27|0]=z>>>12;D[a+26|0]=z>>>4;s=(s&33554431)-b|0;D[a+24|0]=s>>>13;D[a+23|0]=s>>>5;j=(j&67108863)-h|0;D[a+21|0]=j>>>15;D[a+20|0]=j>>>7;D[a+18|0]=k>>>16;D[a+17|0]=k>>>8;e=(e&67108863)-h|0;D[a+15|0]=e>>>18;D[a+14|0]=e>>>10;D[a+13|0]=e>>>2;f=(f&33554431)-b|0;D[a+11|0]=f>>>11;D[a+10|0]=f>>>3;d=(d&67108863)-h|0;D[a+8|0]=d>>>13;D[a+7|0]=d>>>5;b=(c&33554431)-b|0;D[a+5|0]=b>>>14;D[a+4|0]=b>>>6;D[a+2|0]=l>>>16;D[a+1|0]=l>>>8;D[a+28|0]=i<<6|z>>>20;D[a+25|0]=z<<4|s>>>21;D[a+22|0]=s<<3|j>>>23;D[a+19|0]=j<<1|k>>>24;D[a+12|0]=e<<6|f>>>19;D[a+9|0]=f<<5|d>>>21;D[a+6|0]=d<<3|b>>>22;D[a+3|0]=b<<2|l>>>24;_=g+2592|0}function $a(a,b,c,d){var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,E=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0,ia=0,ja=0,ka=0,la=0,ma=0,na=0,oa=0,pa=0,qa=0,ra=0,sa=0,ua=0,va=0,wa=0,xa=0,ya=0,za=0,Aa=0,Ba=0,Ca=0,Da=0,Ea=0,Ga=0,Ha=0,Ia=0,Ja=0,Ka=0,La=0,Ma=0,Na=0,Oa=0,Pa=0,Qa=0,Ra=0,Sa=0,Ta=0,Ua=0,Va=0,Wa=0,Xa=0,Ya=0,Za=0,_a=0,$a=0,ab=0,bb=0,db=0,eb=0,fb=0,gb=0,hb=0,ib=0,jb=0,kb=0,lb=0,mb=0,nb=0,qb=0,rb=0,sb=0,tb=0,ub=0,vb=0,wb=0,xb=0,yb=0,zb=0,Ab=0,Bb=0;g=_-624|0;_=g;F[g+352>>2]=327033209;F[g+356>>2]=1541459225;F[g+344>>2]=-79577749;F[g+348>>2]=528734635;F[g+336>>2]=725511199;F[g+340>>2]=-1694144372;F[g+328>>2]=-1377402159;F[g+332>>2]=1359893119;F[g+320>>2]=1595750129;F[g+324>>2]=-1521486534;F[g+312>>2]=-23791573;F[g+316>>2]=1013904242;F[g+304>>2]=-2067093701;F[g+308>>2]=-1150833019;F[g+360>>2]=0;F[g+296>>2]=-205731576;F[g+300>>2]=1779033703;F[g+288>>2]=0;F[g+292>>2]=0;j=a;p=a+32|0;D[g+364|0]=G[p+32|0];D[g+365|0]=G[p+33|0];D[g+366|0]=G[p+34|0];n=g+364|0;D[(n+F[g+360>>2]|0)+3|0]=G[p+35|0];D[(F[g+360>>2]+n|0)+4|0]=G[p+36|0];D[(F[g+360>>2]+n|0)+5|0]=G[p+37|0];D[(F[g+360>>2]+n|0)+6|0]=G[p+38|0];D[(F[g+360>>2]+n|0)+7|0]=G[p+39|0];D[(F[g+360>>2]+n|0)+8|0]=G[p+40|0];D[(F[g+360>>2]+n|0)+9|0]=G[p+41|0];D[(F[g+360>>2]+n|0)+10|0]=G[p+42|0];D[(F[g+360>>2]+n|0)+11|0]=G[p+43|0];D[(F[g+360>>2]+n|0)+12|0]=G[p+44|0];D[(F[g+360>>2]+n|0)+13|0]=G[p+45|0];D[(F[g+360>>2]+n|0)+14|0]=G[p+46|0];D[(F[g+360>>2]+n|0)+15|0]=G[p+47|0];D[(F[g+360>>2]+n|0)+16|0]=G[p+48|0];D[(F[g+360>>2]+n|0)+17|0]=G[p+49|0];D[(F[g+360>>2]+n|0)+18|0]=G[p+50|0];D[(F[g+360>>2]+n|0)+19|0]=G[p+51|0];D[(F[g+360>>2]+n|0)+20|0]=G[p+52|0];D[(F[g+360>>2]+n|0)+21|0]=G[p+53|0];D[(F[g+360>>2]+n|0)+22|0]=G[p+54|0];D[(F[g+360>>2]+n|0)+23|0]=G[p+55|0];D[(F[g+360>>2]+n|0)+24|0]=G[p+56|0];D[(F[g+360>>2]+n|0)+25|0]=G[p+57|0];D[(F[g+360>>2]+n|0)+26|0]=G[p+58|0];D[(F[g+360>>2]+n|0)+27|0]=G[p+59|0];D[(F[g+360>>2]+n|0)+28|0]=G[p+60|0];D[(F[g+360>>2]+n|0)+29|0]=G[p+61|0];D[(F[g+360>>2]+n|0)+30|0]=G[p+62|0];D[(F[g+360>>2]+n|0)+31|0]=G[p+63|0];a=F[g+360>>2]+32|0;F[g+360>>2]=a;if((a|0)==128){ta(g+288|0,n);F[g+360>>2]=0;e=g;a=F[e+292>>2];i=F[e+288>>2]+1024|0;a=i>>>0<1024?a+1|0:a;F[e+288>>2]=i;F[e+292>>2]=a}a:{if(!b){break a}m=F[g+360>>2];if(!c|m>>>0>128){break a}f=c;a=b;while(1){b:{if(!(f>>>0<128|m)){ta(g+288|0,a);e=F[g+292>>2];k=F[g+288>>2]+1024|0;e=k>>>0<1024?e+1|0:e;F[g+288>>2]=k;F[g+292>>2]=e;f=f-128|0;a=a+128|0;break b}e=128-m|0;l=e>>>0>f>>>0?f:e;c:{if(!l){break c}k=l&3;o=0;if(l-1>>>0>=3){h=l&-4;while(1){i=g+364|0;D[i+(m+o|0)|0]=G[a+o|0];e=o|1;D[(e+F[g+360>>2]|0)+i|0]=G[a+e|0];e=o|2;D[(e+F[g+360>>2]|0)+i|0]=G[a+e|0];e=o|3;D[(e+F[g+360>>2]|0)+i|0]=G[a+e|0];o=o+4|0;m=F[g+360>>2];h=h-4|0;if(h){continue}break}}if(!k){break c}while(1){D[((m+o|0)+g|0)+364|0]=G[a+o|0];o=o+1|0;m=F[g+360>>2];k=k-1|0;if(k){continue}break}}f=f-l|0;a=a+l|0;e=l+m|0;F[g+360>>2]=e;if((e|0)!=128){break b}ta(g+288|0,n);F[g+360>>2]=0;e=F[g+292>>2];k=F[g+288>>2]+1024|0;e=k>>>0<1024?e+1|0:e;F[g+288>>2]=k;F[g+292>>2]=e}if(!f){break a}m=F[g+360>>2];continue}}a=g+160|0;cb(g+288|0,a);ob(a);Tb(g,a);i=g+224|0;pb(i,g+80|0);e=g+544|0;ha(e,g,i);a=g+496|0;ha(a,g+40|0,i);Fa(d,a);Fa(g+592|0,e);D[d+31|0]=G[d+31|0]^G[g+592|0]<<7;F[g+352>>2]=327033209;F[g+356>>2]=1541459225;F[g+344>>2]=-79577749;F[g+348>>2]=528734635;F[g+336>>2]=725511199;F[g+340>>2]=-1694144372;F[g+328>>2]=-1377402159;F[g+332>>2]=1359893119;F[g+320>>2]=1595750129;F[g+324>>2]=-1521486534;F[g+312>>2]=-23791573;F[g+316>>2]=1013904242;F[g+304>>2]=-2067093701;F[g+308>>2]=-1150833019;F[g+296>>2]=-205731576;F[g+300>>2]=1779033703;F[g+288>>2]=0;F[g+292>>2]=0;F[g+360>>2]=0;D[g+364|0]=G[d|0];D[g+365|0]=G[d+1|0];D[g+366|0]=G[d+2|0];D[g+367|0]=G[d+3|0];a=g+364|0;D[(a+F[g+360>>2]|0)+4|0]=G[d+4|0];D[(a+F[g+360>>2]|0)+5|0]=G[d+5|0];D[(a+F[g+360>>2]|0)+6|0]=G[d+6|0];D[(a+F[g+360>>2]|0)+7|0]=G[d+7|0];D[(a+F[g+360>>2]|0)+8|0]=G[d+8|0];D[(a+F[g+360>>2]|0)+9|0]=G[d+9|0];D[(a+F[g+360>>2]|0)+10|0]=G[d+10|0];D[(a+F[g+360>>2]|0)+11|0]=G[d+11|0];D[(a+F[g+360>>2]|0)+12|0]=G[d+12|0];D[(a+F[g+360>>2]|0)+13|0]=G[d+13|0];D[(a+F[g+360>>2]|0)+14|0]=G[d+14|0];D[(a+F[g+360>>2]|0)+15|0]=G[d+15|0];D[(a+F[g+360>>2]|0)+16|0]=G[d+16|0];D[(a+F[g+360>>2]|0)+17|0]=G[d+17|0];D[(a+F[g+360>>2]|0)+18|0]=G[d+18|0];D[(a+F[g+360>>2]|0)+19|0]=G[d+19|0];D[(a+F[g+360>>2]|0)+20|0]=G[d+20|0];D[(a+F[g+360>>2]|0)+21|0]=G[d+21|0];D[(a+F[g+360>>2]|0)+22|0]=G[d+22|0];D[(a+F[g+360>>2]|0)+23|0]=G[d+23|0];D[(a+F[g+360>>2]|0)+24|0]=G[d+24|0];D[(a+F[g+360>>2]|0)+25|0]=G[d+25|0];D[(a+F[g+360>>2]|0)+26|0]=G[d+26|0];D[(a+F[g+360>>2]|0)+27|0]=G[d+27|0];D[(a+F[g+360>>2]|0)+28|0]=G[d+28|0];D[(a+F[g+360>>2]|0)+29|0]=G[d+29|0];D[(a+F[g+360>>2]|0)+30|0]=G[d+30|0];D[(a+F[g+360>>2]|0)+31|0]=G[d+31|0];h=32;a=F[g+360>>2]+32|0;F[g+360>>2]=a;if((a|0)==128){ta(g+288|0,n);F[g+360>>2]=0;e=g;a=F[e+292>>2];i=F[e+288>>2]+1024|0;a=i>>>0<1024?a+1|0:a;F[e+288>>2]=i;F[e+292>>2]=a}a=F[g+360>>2];if(!(!j|a>>>0>128)){while(1){d:{if(!(h>>>0<128|a)){ta(g+288|0,j);a=g;e=F[a+292>>2];i=F[a+288>>2]+1024|0;e=i>>>0<1024?e+1|0:e;F[a+288>>2]=i;F[a+292>>2]=e;h=h-128|0;j=j+128|0;break d}e=128-a|0;i=e>>>0>h>>>0?h:e;e:{if(!i){break e}f=i&3;o=0;if(i-1>>>0>=3){k=i&-4;while(1){e=g+364|0;D[e+(a+o|0)|0]=G[j+o|0];a=o|1;D[e+(a+F[g+360>>2]|0)|0]=G[a+j|0];a=o|2;D[e+(a+F[g+360>>2]|0)|0]=G[a+j|0];a=o|3;D[e+(a+F[g+360>>2]|0)|0]=G[a+j|0];o=o+4|0;a=F[g+360>>2];k=k-4|0;if(k){continue}break}}if(!f){break e}while(1){D[((a+o|0)+g|0)+364|0]=G[j+o|0];o=o+1|0;a=F[g+360>>2];f=f-1|0;if(f){continue}break}}h=h-i|0;j=i+j|0;a=a+i|0;F[g+360>>2]=a;if((a|0)!=128){break d}ta(g+288|0,n);F[g+360>>2]=0;a=g;e=F[a+292>>2];i=F[a+288>>2]+1024|0;e=i>>>0<1024?e+1|0:e;F[a+288>>2]=i;F[a+292>>2]=e}a=F[g+360>>2];if(h){continue}break}}f:{if(!c|(!b|a>>>0>128)){break f}while(1){g:{if(!(c>>>0<128|a)){ta(g+288|0,b);e=g;a=F[e+292>>2];i=F[e+288>>2]+1024|0;a=i>>>0<1024?a+1|0:a;F[e+288>>2]=i;F[e+292>>2]=a;c=c-128|0;b=b+128|0;break g}e=128-a|0;i=c>>>0>>0?c:e;h:{if(!i){break h}m=i&3;o=0;if(i-1>>>0>=3){f=i&-4;while(1){e=g+364|0;D[e+(a+o|0)|0]=G[b+o|0];a=o|1;D[e+(a+F[g+360>>2]|0)|0]=G[a+b|0];a=o|2;D[e+(a+F[g+360>>2]|0)|0]=G[a+b|0];a=o|3;D[e+(a+F[g+360>>2]|0)|0]=G[a+b|0];o=o+4|0;a=F[g+360>>2];f=f-4|0;if(f){continue}break}}if(!m){break h}while(1){D[((a+o|0)+g|0)+364|0]=G[b+o|0];o=o+1|0;a=F[g+360>>2];m=m-1|0;if(m){continue}break}}c=c-i|0;b=b+i|0;a=a+i|0;F[g+360>>2]=a;if((a|0)!=128){break g}ta(g+288|0,n);F[g+360>>2]=0;a=g;e=F[a+292>>2];i=F[a+288>>2]+1024|0;e=i>>>0<1024?e+1|0:e;F[a+288>>2]=i;F[a+292>>2]=e}if(!c){break f}a=F[g+360>>2];continue}}s=g+224|0;cb(g+288|0,s);ob(s);a=G[p+24|0];b=a>>>24|0;f=G[p+23|0];e=f|a<<8;c=G[p+25|0];a=c>>>16|0;i=e|c<<16;e=a|b;n=G[p+26|0];c=n;b=c>>>8|0;c=c<<24;e=b|e;b=c|i;K=((e&31)<<27|b>>>5)&2097151;b=0;c=G[s+27|0];a=c>>>24|0;i=G[s+26|0];c=i|c<<8;j=b;h=G[s+28|0];b=h;e=b>>>16|0;b=b<<16;e=a|e;a=b|c;M=((e&3)<<30|a>>>2)&2097151;l=qe(K,j,M,0);k=$;c=0;N=c;O=f<<16&2031616|(G[p+21|0]|G[p+22|0]<<8);j=O;b=G[s+29|0];a=b>>>24|0;c=h|b<<8;e=G[s+30|0];b=e>>>16|0;f=c|e<<16;e=a|b;b=G[s+31|0];a=b>>>8|0;b=b<<24;c=a|e;a=b|f;P=(c&127)<<25|a>>>7;Q=c>>>7|0;a=qe(j,N,P,Q);b=a+l|0;e=$+k|0;m=b;c=a>>>0>b>>>0?e+1|0:e;a=G[p+27|0];e=a>>>24|0;j=n|a<<8;b=e;h=G[p+28|0];f=h;e=f>>>16|0;f=f<<16;e=b|e;b=f|j;la=((e&3)<<30|b>>>2)&2097151;l=la;k=0;a=G[s+24|0];e=a>>>24|0;f=G[s+23|0];j=f|a<<8;a=G[s+25|0];b=a>>>16|0;j=j|a<<16;b=b|e|i>>>8;R=((b&31)<<27|(i<<24|j)>>>5)&2097151;b=qe(l,k,R,0);e=b+m|0;a=$+c|0;j=e;b=b>>>0>e>>>0?a+1|0:a;c=G[p+29|0];a=c>>>24|0;h=h|c<<8;c=G[p+30|0];e=c>>>16|0;i=h|c<<16;e=a|e;c=G[p+31|0];a=c>>>8|0;c=c<<24;k=a|e;a=c|i;i=(k&127)<<25|a>>>7;e=k>>>7|0;c=e;S=f<<16&2031616|(G[s+21|0]|G[s+22|0]<<8);e=qe(i,e,S,0);f=e+j|0;a=$+b|0;h=f;k=e>>>0>f>>>0?a+1|0:a;a=qe(O,N,M,na);j=$;f=a;b=G[p+19|0];e=b>>>24|0;t=G[p+18|0];m=t|b<<8;b=G[p+20|0];a=b>>>16|0;b=m|b<<16;e=a|e;a=e>>>3|0;T=(e&7)<<29|b>>>3;A=a;a=qe(T,a,P,Q);e=f+a|0;b=$+j|0;b=a>>>0>e>>>0?b+1|0:b;a=qe(K,oa,R,pa);f=a+e|0;e=$+b|0;e=a>>>0>f>>>0?e+1|0:e;b=qe(l,qa,S,ra);f=b+f|0;a=$+e|0;l=f;f=b>>>0>f>>>0?a+1|0:a;j=G[s+19|0];b=j>>>24|0;q=G[s+18|0];j=q|j<<8;a=G[s+20|0];e=a>>>16|0;a=a<<16;e=b|e;b=a|j;U=(e&7)<<29|b>>>3;V=e>>>3|0;a=qe(i,c,U,V);b=a+l|0;e=$+f|0;j=b;e=a>>>0>b>>>0?e+1|0:e;n=e;a=b;e=e-((a>>>0<4293918720)-1|0)|0;E=a- -1048576|0;m=e;b=(e&2097151)<<11|E>>>21;f=b+h|0;e=(e>>21)+k|0;e=b>>>0>f>>>0?e+1|0:e;h=e;a=f;e=e-((a>>>0<4293918720)-1|0)|0;r=a- -1048576|0;l=e;v=(e&2097151)<<11|r>>>21;k=e>>21;a=qe(M,na,la,qa);b=$;e=a;a=qe(K,oa,P,Q);o=e+a|0;e=$+b|0;e=a>>>0>o>>>0?e+1|0:e;b=qe(R,pa,i,c);o=b+o|0;a=$+e|0;e=o;z=e- -1048576|0;a=b>>>0>e>>>0?a+1|0:a;b=a-((e>>>0<4293918720)-1|0)|0;o=v;w=z&-2097152;v=e-w|0;u=o+v|0;a=(a-((b&2147483647)+(e>>>0>>0)|0)|0)+k|0;Xa=u;a=u>>>0>>0?a+1|0:a;Ya=a;w=qe(u,a,470296,0);v=$;e=qe(M,na,i,c);a=$;k=e;e=qe(P,Q,la,qa);k=k+e|0;a=$+a|0;a=e>>>0>k>>>0?a+1|0:a;o=k;e=b;b=e>>>21|0;k=(e&2097151)<<11|z>>>21;o=o+k|0;e=a+b|0;b=o;a=b;Za=a- -1048576|0;e=k>>>0>a>>>0?e+1|0:e;o=e-((a>>>0<4293918720)-1|0)|0;H=o;a=r&-2097152;k=h-((a>>>0>f>>>0)+l|0)|0;Qa=f-a|0;_a=k;a=e;e=Za&-2097152;a=a-((o&2147483647)+(e>>>0>b>>>0)|0)|0;Ra=b-e|0;$a=a;b=qe(Ra,a,666643,0);e=b+w|0;a=$+v|0;a=b>>>0>e>>>0?a+1|0:a;b=qe(Qa,k,654183,0);f=b+e|0;e=$+a|0;u=f;o=b>>>0>f>>>0?e+1|0:e;a=E&-2097152;w=j-a|0;r=n-((a>>>0>j>>>0)+m|0)|0;l=qe(M,na,T,A);j=$;a=G[p+16|0];e=a>>>24|0;k=G[p+15|0];f=k|a<<8;a=G[p+17|0];b=a>>>16|0;f=f|a<<16;e=b|e|t>>>8;a=t<<24|f;W=((e&63)<<26|a>>>6)&2097151;b=qe(W,0,P,Q);e=b+l|0;a=$+j|0;a=b>>>0>e>>>0?a+1|0:a;b=qe(O,N,R,pa);f=b+e|0;e=$+a|0;e=b>>>0>f>>>0?e+1|0:e;a=qe(K,oa,S,ra);f=a+f|0;b=$+e|0;b=a>>>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ia,Ea);m=a+m|0;b=$+e|0;b=a>>>0>m>>>0?b+1|0:b;e=qe(da,Aa,ja,Ga);m=e+m|0;a=$+b|0;a=e>>>0>m>>>0?a+1|0:a;b=qe(ea,Ba,ka,Ha);e=b+m|0;a=$+a|0;o=e;e=b>>>0>e>>>0?a+1|0:a;a=G[g+171|0];b=a>>>24|0;Na=G[g+170|0];n=Na|a<<8;m=G[g+172|0];a=m>>>16|0;n=n|m<<16;m=a|b;b=j<<24;j=j>>>8|m;a=b|n;a=((j&15)<<28|a>>>4)&2097151;b=a+o|0;q=b;e=a>>>0>b>>>0?e+1|0:e;j=e;a=b;e=e-((a>>>0<4293918720)-1|0)|0;db=a- -1048576|0;fb=e;a=e>>>21|0;b=(e&2097151)<<11|db>>>21;e=b+u|0;a=a+f|0;o=e;a=b>>>0>e>>>0?a+1|0:a;C=a;a=e;e=C-((a>>>0<4293918720)-1|0)|0;eb=a- -1048576|0;Ia=e;b=(e&2097151)<<11|eb>>>21;f=b+B|0;e=(e>>>21|0)+y|0;e=b>>>0>f>>>0?e+1|0:e;a=f;b=a+z|0;e=e+h|0;e=a>>>0>b>>>0?e+1|0:e;a=qb&-2097152;p=e-((a>>>0>b>>>0)+Ja|0)|0;n=b-a|0;a=n;e=p-((a>>>0<4293918720)-1|0)|0;Ta=a- -1048576|0;s=e;b=(e&2097151)<<11|Ta>>>21;f=b+Bb|0;e=(e>>21)+ub|0;m=f;e=b>>>0>f>>>0?e+1|0:e;B=e;a=f;e=e-((a>>>0<4293918720)-1|0)|0;Ja=a- -1048576|0;y=e;a=e>>21;b=(e&2097151)<<11|Ja>>>21;e=b+Ab|0;a=a+w|0;a=b>>>0>e>>>0?a+1|0:a;f=e+H|0;b=a+x|0;b=e>>>0>f>>>0?b+1|0:b;e=f;a=rb&-2097152;x=b-((a>>>0>e>>>0)+ma|0)|0;h=e-a|0;a=h;e=x-((a>>>0<4293918720)-1|0)|0;ma=a- -1048576|0;z=e;a=e>>21;b=(e&2097151)<<11|ma>>>21;e=b+Sa|0;a=a+J|0;a=b>>>0>e>>>0?a+1|0:a;b=a;a=sb&-2097152;u=b-((a>>>0>e>>>0)+gb|0)|0;b=e-a|0;a=b;gb=u-((a>>>0<4293918720)-1|0)|0;J=a- -1048576|0;ub=v- -1048576|0;H=L-((v>>>0<4293918720)-1|0)|0;f=H;w=gb;v=(w&2097151)<<11|J>>>21;I=v+I|0;a=(w>>21)+L|0;a=v>>>0>I>>>0?a+1|0:a;v=I;e=ub&-2097152;qb=v-e|0;rb=a-((e>>>0>v>>>0)+f|0)|0;a=J&-2097152;sb=b-a|0;gb=u-((a>>>0>b>>>0)+w|0)|0;a=ma&-2097152;Sa=h-a|0;I=x-((a>>>0>h>>>0)+z|0)|0;a=qe(tb,mb,-997805,-1);b=$;e=a;a=qe(ib,jb,654183,0);h=e+a|0;e=$+b|0;e=a>>>0>h>>>0?e+1|0:e;b=qe(Wa,nb,136657,0);h=b+h|0;a=$+e|0;a=b>>>0>h>>>0?a+1|0:a;b=h+m|0;e=a+B|0;e=b>>>0>>0?e+1|0:e;a=Ja&-2097152;L=b-a|0;J=e-((a>>>0>b>>>0)+y|0)|0;a=Za&-2097152;H=t-a|0;B=La-((a>>>0>t>>>0)+Ka|0)|0;b=qe(kb,lb,-997805,-1);a=$;e=b;b=qe(Va,hb,654183,0);e=e+b|0;a=$+a|0;a=b>>>0>e>>>0?a+1|0:a;b=qe(Ra,$a,136657,0);h=b+e|0;e=$+a|0;e=b>>>0>h>>>0?e+1|0:e;a=qe(Xa,Ya,-683901,-1);h=a+h|0;b=$+e|0;b=a>>>0>h>>>0?b+1|0:b;a=h+r|0;e=b+Ua|0;e=a>>>0>>0?e+1|0:e;b=a;a=zb&-2097152;z=b-a|0;u=e-((a>>>0>b>>>0)+Pa|0)|0;b=qe(kb,lb,654183,0);a=$;e=b;b=qe(Va,hb,470296,0);e=e+b|0;a=$+a|0;a=b>>>0>e>>>0?a+1|0:a;b=e;e=qe(Ra,$a,-997805,-1);h=b+e|0;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(l&2097151)<<11|wb>>>21;c=a+b|0;a=(l>>>21|0)+e|0;h=c;a=b>>>0>c>>>0?a+1|0:a;w=a;a=c;c=w-((a>>>0<4293918720)-1|0)|0;y=a- -1048576|0;v=c;a=c>>21;b=(c&2097151)<<11|y>>>21;c=b+t|0;e=a+m|0;l=c;e=b>>>0>c>>>0?e+1|0:e;E=e;a=c;c=e-((a>>>0<4293918720)-1|0)|0;x=a- -1048576|0;r=c;a=c>>21;b=(c&2097151)<<11|x>>>21;c=b+z|0;a=a+u|0;a=b>>>0>c>>>0?a+1|0:a;b=c;m=a;a=b;e=m-((a>>>0<4293918720)-1|0)|0;t=a- -1048576|0;i=e;c=(e&2097151)<<11|t>>>21;u=c+H|0;e=(e>>21)+B|0;Ja=u;e=c>>>0>u>>>0?e+1|0:e;Ka=e;a=qe(u,e,-683901,-1);c=a+L|0;e=$+J|0;A=c;c=a>>>0>c>>>0?e+1|0:e;u=qe(tb,mb,654183,0);e=$;a=t&-2097152;i=m-((a>>>0>b>>>0)+i|0)|0;ma=b-a|0;J=i;b=qe(ib,jb,470296,0);m=b+u|0;a=$+e|0;a=b>>>0>m>>>0?a+1|0:a;e=qe(Wa,nb,-997805,-1);m=e+m|0;b=$+a|0;b=e>>>0>m>>>0?b+1|0:b;e=m+n|0;a=b+p|0;a=e>>>0>>0?a+1|0:a;b=qe(Ja,Ka,136657,0);m=e;e=Ta&-2097152;n=b+(m-e|0)|0;e=$+(a-((e>>>0>m>>>0)+s|0)|0)|0;e=b>>>0>n>>>0?e+1|0:e;b=qe(ma,i,-683901,-1);i=b+n|0;a=$+e|0;a=b>>>0>i>>>0?a+1|0:a;t=a;a=i;e=t-((a>>>0<4293918720)-1|0)|0;z=a- -1048576|0;n=e;a=(e&2097151)<<11|z>>>21;m=a+A|0;e=(e>>21)+c|0;c=m;e=a>>>0>c>>>0?e+1|0:e;m=e;a=c;A=e-((a>>>0<4293918720)-1|0)|0;u=a- -1048576|0;e=A;b=e>>21;A=(e&2097151)<<11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((e>>>0>i>>>0)+fb|0)|0)|0;a=b>>>0>h>>>0?a+1|0:a;b=qe(Wa,nb,470296,0);i=b+h|0;e=$+a|0;e=b>>>0>i>>>0?e+1|0:e;b=qe(I,H,136657,0);i=b+i|0;a=$+e|0;a=b>>>0>i>>>0?a+1|0:a;b=qe(Ja,Ka,654183,0);i=b+i|0;e=$+a|0;e=b>>>0>i>>>0?e+1|0:e;a=qe(ma,J,-997805,-1);i=a+i|0;b=$+e|0;s=i;b=a>>>0>i>>>0?b+1|0:b;o=b;a=i;b=b-((a>>>0<4293918720)-1|0)|0;y=a- -1048576|0;n=b;e=b>>21;a=(b&2097151)<<11|y>>>21;b=a+E|0;e=e+t|0;i=b;e=a>>>0>b>>>0?e+1|0:e;a=e;h=a-((b>>>0<4293918720)-1|0)|0;x=b- -1048576|0;m=h;e=h>>21;h=(h&2097151)<<11|x>>>21;t=h+Pa|0;b=e+La|0;Pa=t;E=h>>>0>t>>>0?b+1|0:b;h=i;i=a;b=B&-2097152;a=l-b|0;e=z-((b>>>0>l>>>0)+r|0)|0;l=a;b=f>>21;a=(f&2097151)<<11|ub>>>21;f=l+a|0;e=b+e|0;e=a>>>0>f>>>0?e+1|0:e;r=e;a=f;e=e-((a>>>0<4293918720)-1|0)|0;B=a- -1048576|0;t=e;b=e>>21;C=b;L=(e&2097151)<<11|B>>>21;b=qe(L,b,-683901,-1);e=b+h|0;a=$+i|0;a=b>>>0>e>>>0?a+1|0:a;b=x&-2097152;La=e-b|0;Na=a-((b>>>0>e>>>0)+m|0)|0;a=qe(L,C,136657,0);b=a+s|0;e=$+o|0;e=a>>>0>b>>>0?e+1|0:e;a=y&-2097152;fb=b-a|0;s=e-((a>>>0>b>>>0)+n|0)|0;b=qe(Wa,nb,666643,0);a=p&-2097152;e=b+(j-a|0)|0;a=$+(v-((a>>>0>j>>>0)+q|0)|0)|0;a=b>>>0>e>>>0?a+1|0:a;b=qe(I,H,-997805,-1);i=b+e|0;e=$+a|0;e=b>>>0>i>>>0?e+1|0:e;a=qe(Ja,Ka,470296,0);i=a+i|0;b=$+e|0;b=a>>>0>i>>>0?b+1|0:b;a=qe(ma,J,654183,0);i=a+i|0;e=$+b|0;v=i;m=a>>>0>i>>>0?e+1|0:e;j=c;b=qe(aa,xa,ka,Ha);a=$;c=b;b=qe(ba,ya,ja,Ga);c=c+b|0;a=$+a|0;h=c;c=b>>>0>c>>>0?a+1|0:a;a=qe(ba,ya,ka,Ha);l=G[g+162|0];b=l;b=b<<16&2031616|(G[g+160|0]|G[g+161|0]<<8);e=a+b|0;a=$;i=e;a=b>>>0>e>>>0?a+1|0:a;q=a;a=e;e=q-((a>>>0<4293918720)-1|0)|0;y=a- -1048576|0;o=e;a=e>>>21|0;e=(e&2097151)<<11|y>>>21;h=e+h|0;b=a+c|0;b=e>>>0>h>>>0?b+1|0:b;e=h;c=b;a=G[g+163|0];b=a>>>24|0;h=l|a<<8;l=G[g+164|0];a=l>>>16|0;l=h|l<<16;b=a|b|u>>>8;a=((b&31)<<27|(u<<24|l)>>>5)&2097151;b=a+e|0;e=c;c=b;e=a>>>0>b>>>0?e+1|0:e;n=e;a=b;b=e-((a>>>0<4293918720)-1|0)|0;x=a- -1048576|0;h=b;e=b>>>21|0;b=(b&2097151)<<11|x>>>21;k=b+k|0;a=e+j|0;a=b>>>0>k>>>0?a+1|0:a;b=qe(I,H,654183,0);j=k;e=Ia&-2097152;k=b+(j-e|0)|0;e=$+(a-((e>>>0>j>>>0)+w|0)|0)|0;e=b>>>0>k>>>0?e+1|0:e;a=qe(Ja,Ka,666643,0);b=a+k|0;e=$+e|0;e=a>>>0>b>>>0?e+1|0:e;a=b;b=qe(ma,J,470296,0);j=a+b|0;a=$+e|0;z=j;a=b>>>0>j>>>0?a+1|0:a;l=a;a=j;b=l-((a>>>0<4293918720)-1|0)|0;u=a- -1048576|0;k=b;a=(b&2097151)<<11|u>>>21;j=a+v|0;b=(b>>21)+m|0;w=j;b=a>>>0>j>>>0?b+1|0:b;j=b;a=w;m=b-((a>>>0<4293918720)-1|0)|0;v=a- -1048576|0;b=m;e=b>>21;m=(b&2097151)<<11|v>>>21;p=m+fb|0;a=e+s|0;Ia=p;m=m>>>0>p>>>0?a+1|0:a;e=qe(L,C,-997805,-1);w=e+w|0;a=$+j|0;a=e>>>0>w>>>0?a+1|0:a;j=w;e=v&-2097152;p=j-e|0;s=a-((e>>>0>j>>>0)+b|0)|0;a=qe(L,C,654183,0);b=a+z|0;e=$+l|0;e=a>>>0>b>>>0?e+1|0:e;a=u&-2097152;w=b-a|0;v=e-((a>>>0>b>>>0)+k|0)|0;a=qe(I,H,470296,0);b=x&-2097152;e=a+(c-b|0)|0;b=$+(n-((b>>>0>c>>>0)+h|0)|0)|0;b=a>>>0>e>>>0?b+1|0:b;a=qe(ma,J,666643,0);c=a+e|0;e=$+b|0;k=c;j=a>>>0>c>>>0?e+1|0:e;a=qe(I,H,666643,0);b=y&-2097152;c=a+(i-b|0)|0;e=$+(q-((o&4095)+(b>>>0>i>>>0)|0)|0)|0;e=a>>>0>c>>>0?e+1|0:e;h=e;a=c;e=e-((a>>>0<4293918720)-1|0)|0;q=a- -1048576|0;l=e;b=(e&2097151)<<11|q>>>21;i=b+k|0;e=(e>>21)+j|0;o=i;e=b>>>0>i>>>0?e+1|0:e;k=e;a=i;e=e-((a>>>0<4293918720)-1|0)|0;n=a- -1048576|0;j=e;b=(e&2097151)<<11|n>>>21;i=b+w|0;e=(e>>21)+v|0;v=i;i=b>>>0>i>>>0?e+1|0:e;a=qe(L,C,470296,0);e=a+o|0;b=$+k|0;b=a>>>0>e>>>0?b+1|0:b;k=e;e=n&-2097152;a=k-e|0;j=b-((e>>>0>k>>>0)+j|0)|0;n=a;a=qe(L,C,666643,0);b=q&-2097152;k=a+(c-b|0)|0;e=$+(h-((b>>>0>c>>>0)+l|0)|0)|0;e=a>>>0>k>>>0?e+1|0:e;a=k;b=e>>21;c=(e&2097151)<<11|a>>>21;e=n+c|0;a=b+j|0;x=e;b=e;a=c>>>0>e>>>0?a+1|0:a;e=a>>21;a=(a&2097151)<<11|b>>>21;b=a+v|0;e=e+i|0;e=a>>>0>b>>>0?e+1|0:e;j=b;b=(e&2097151)<<11|b>>>21;c=b+p|0;a=(e>>21)+s|0;a=b>>>0>c>>>0?a+1|0:a;h=c;b=c;e=a>>21;a=(a&2097151)<<11|b>>>21;c=a+Ia|0;b=e+m|0;b=a>>>0>c>>>0?b+1|0:b;z=c;a=b>>21;b=(b&2097151)<<11|c>>>21;c=b+La|0;e=a+Na|0;u=c;a=c;e=b>>>0>a>>>0?e+1|0:e;b=e>>21;c=(e&2097151)<<11|a>>>21;e=c+Pa|0;a=b+E|0;w=e;b=e;a=c>>>0>e>>>0?a+1|0:a;e=a>>21;a=(a&2097151)<<11|b>>>21;b=a+Oa|0;e=e+Ua|0;e=a>>>0>b>>>0?e+1|0:e;v=b;b=(e&2097151)<<11|b>>>21;c=b+Ma|0;a=(e>>21)+A|0;a=b>>>0>c>>>0?a+1|0:a;E=c;b=c;e=a>>21;a=(a&2097151)<<11|b>>>21;c=a+sb|0;b=e+gb|0;b=a>>>0>c>>>0?b+1|0:b;q=c;a=b>>21;b=(b&2097151)<<11|c>>>21;c=b+qb|0;e=a+rb|0;o=c;a=c;e=b>>>0>a>>>0?e+1|0:e;b=(e&2097151)<<11|a>>>21;c=B&-2097152;a=f-c|0;i=b+a|0;e=(r-((c>>>0>f>>>0)+t|0)|0)+(e>>21)|0;n=i;b=i;e=a>>>0>b>>>0?e+1|0:e;t=(e&2097151)<<11|b>>>21;a=e>>21;l=a;b=qe(t,a,666643,0);a=k&2097151;b=b+a|0;e=$;k=b;e=a>>>0>b>>>0?e+1|0:e;c=e;D[d+32|0]=b;D[d+33|0]=(e&255)<<24|b>>>8;i=d;a=x&2097151;e=qe(t,l,470296,0)+a|0;b=$;b=a>>>0>e>>>0?b+1|0:b;m=e;e=c;a=e>>21;f=(e&2097151)<<11|k>>>21;m=m+f|0;e=a+b|0;e=f>>>0>m>>>0?e+1|0:e;f=m;D[i+36|0]=(e&2047)<<21|f>>>11;a=e;e=f;D[i+35|0]=(a&7)<<29|e>>>3;b=i;i=j&2097151;j=qe(t,l,654183,0)+i|0;e=$;e=i>>>0>j>>>0?e+1|0:e;i=a;a=a>>21;i=(i&2097151)<<11|f>>>21;j=i+j|0;a=a+e|0;a=i>>>0>j>>>0?a+1|0:a;e=a;D[b+38|0]=(a&63)<<26|j>>>6;i=0;m=f&2097151;a=m;D[b+34|0]=((c&65535)<<16|k>>>16)&31|a<<5;c=b;a=h&2097151;f=qe(t,l,-997805,-1)+a|0;b=$;b=a>>>0>f>>>0?b+1|0:b;a=f;f=(e&2097151)<<11|j>>>21;k=a+f|0;e=(e>>21)+b|0;e=f>>>0>k>>>0?e+1|0:e;D[c+41|0]=(e&511)<<23|k>>>9;b=e;D[c+40|0]=(e&1)<<31|k>>>1;f=0;h=j&2097151;c=h;D[d+37|0]=(i&524287)<<13|m>>>19|c<<2;c=d;e=z&2097151;i=qe(t,l,136657,0)+e|0;a=$;a=e>>>0>i>>>0?a+1|0:a;e=b>>21;b=(b&2097151)<<11|k>>>21;i=b+i|0;e=a+e|0;j=i;e=b>>>0>i>>>0?e+1|0:e;D[c+44|0]=(e&4095)<<20|i>>>12;b=e;D[c+43|0]=(e&15)<<28|i>>>4;i=0;k=k&2097151;c=k;D[d+39|0]=(f&16383)<<18|h>>>14|c<<7;c=d;e=u&2097151;f=qe(t,l,-683901,-1)+e|0;a=$;a=e>>>0>f>>>0?a+1|0:a;e=f;f=(b&2097151)<<11|j>>>21;l=e+f|0;b=(b>>21)+a|0;b=f>>>0>l>>>0?b+1|0:b;f=l;a=b;D[c+46|0]=(a&127)<<25|f>>>7;c=0;l=j&2097151;e=l;D[d+42|0]=(i&131071)<<15|k>>>17|e<<4;b=d;e=a;a=a>>21;i=(e&2097151)<<11|f>>>21;k=i+(w&2097151)|0;e=i>>>0>k>>>0?a+1|0:a;i=k;D[b+49|0]=(e&1023)<<22|i>>>10;a=e;e=i;D[b+48|0]=(a&3)<<30|e>>>2;e=0;k=f&2097151;f=k;D[b+45|0]=(c&1048575)<<12|l>>>20|f<<1;c=a;a=a>>21;c=(c&2097151)<<11|i>>>21;f=c+(v&2097151)|0;j=f;a=c>>>0>f>>>0?a+1|0:a;b=f;D[d+52|0]=(a&8191)<<19|b>>>13;D[d+51|0]=(a&31)<<27|b>>>5;f=0;l=i&2097151;b=l;D[d+47|0]=(e&32767)<<17|k>>>15|b<<6;b=a;a=a>>21;b=(b&2097151)<<11|j>>>21;h=b+(E&2097151)|0;e=a;i=d;D[i+53|0]=h;a=j;D[i+50|0]=(f&262143)<<14|l>>>18|a<<3;b=b>>>0>h>>>0?e+1|0:e;D[i+54|0]=(b&255)<<24|h>>>8;a=b;e=a>>21;a=(a&2097151)<<11|h>>>21;i=a+(q&2097151)|0;j=i;e=a>>>0>i>>>0?e+1|0:e;D[d+57|0]=(e&2047)<<21|i>>>11;a=e;c=a;e=i;D[d+56|0]=(a&7)<<29|e>>>3;e=d;a=a>>21;c=(c&2097151)<<11|i>>>21;i=c+(o&2097151)|0;f=i;a=c>>>0>f>>>0?a+1|0:a;c=a;D[e+59|0]=(a&63)<<26|f>>>6;i=0;k=j&2097151;a=k;D[e+55|0]=((b&65535)<<16|h>>>16)&31|a<<5;a=c>>21;c=(c&2097151)<<11|f>>>21;l=c+(n&2097151)|0;j=l;b=c>>>0>j>>>0?a+1|0:a;c=j;D[e+63|0]=(b&131071)<<15|c>>>17;a=b;D[e+62|0]=(a&511)<<23|c>>>9;D[e+61|0]=(a&1)<<31|c>>>1;b=0;e=f&2097151;D[d+58|0]=(i&524287)<<13|k>>>19|e<<2;D[d+60|0]=(b&16383)<<18|e>>>14|c<<7;_=g+624|0}function fb(a,b,c,d){var e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,E=0,H=0,I=0,J=0,K=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0;k=_-768|0;_=k;a:{if(G[d+63|0]>31){break a}h=_-272|0;_=h;V=G[a+31|0];W=G[a+30|0];X=G[a+6|0];Q=G[a+5|0];R=G[a+9|0];S=G[a+8|0];m=G[a+12|0];E=G[a+11|0];B=G[a+15|0];y=G[a+14|0];C=G[a+28|0];z=G[a+27|0];w=G[a+25|0];t=G[a+24|0];M=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);x=G[a+29|0];A=G[a+4|0];v=G[a+7|0];s=G[a+10|0];n=G[a+13|0];q=G[a+26|0];o=G[a+23|0];r=k+128|0;T=r+40|0;j=T;e=G[a+21|0];i=e>>>17|0;f=e<<15;e=i;p=f;f=G[a+20|0];i=f>>>25|0;p=p|f<<7;f=e|i;e=G[a+22|0];i=e>>>9|0;e=e<<23|p;p=f|i;K=e;e=0;N=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);i=N+16777216|0;e=i>>>0<16777216?1:e;P=i;f=i;i=e>>>25|0;e=(e&33554431)<<7|f>>>25;f=K+e|0;i=i+p|0;i=e>>>0>f>>>0?i+1|0:i;e=f;f=e;e=e+33554432|0;i=e>>>0<33554432?i+1|0:i;U=e;e=i;i=f;f=U&-67108864;F[j+24>>2]=i-f;i=t>>>19|0;t=t<<13;f=i;i=o>>>27|0;K=o<<5|t|w<<21;i=f|i|w>>>11;w=((e&67108863)<<6|U>>>26)+K|0;f=w;e=K+16777216|0;i=e>>>0<16777216?i+1|0:i;t=e;e=i;i=f;f=t&1040187392;F[j+28>>2]=i-f;f=q>>>28|0;q=z<<12|q<<4;p=f|z>>>20|C>>>12;i=e>>>25|0;e=(e&33554431)<<7|t>>>25;f=e+(C<<20|q)|0;i=i+p|0;i=e>>>0>f>>>0?i+1|0:i;e=i;i=f+33554432|0;e=i>>>0<33554432?e+1|0:e;K=i;q=e;e=i&-67108864;F[j+32>>2]=f-e;f=y<<10|n<<2;i=y>>>22|n>>>30;n=B<<18|f;p=B>>>14|i;t=E<<11|s<<3|m<<19;f=E>>>21|s>>>29|m>>>13;i=t+16777216|0;f=i>>>0<16777216?f+1|0:f;z=i;e=i;i=f>>>25|0;e=(f&33554431)<<7|e>>>25;f=e+n|0;i=i+p|0;i=e>>>0>f>>>0?i+1|0:i;e=f;f=e+33554432|0;i=f>>>0<33554432?i+1|0:i;B=f;p=i;i=e;e=f&-67108864;F[j+16>>2]=i-e;s=S<<13|v<<5|R<<21;o=S>>>19|v>>>27|R>>>11;v=Q<<14|A<<6|X<<22;f=Q>>>18|A>>>26|X>>>10;i=v+16777216|0;f=i>>>0<16777216?f+1|0:f;w=i;e=f>>>25|0;f=(f&33554431)<<7|i>>>25;s=f+s|0;i=e+o|0;i=f>>>0>s>>>0?i+1|0:i;f=s;e=f;f=e+33554432|0;i=f>>>0<33554432?i+1|0:i;y=f;o=i;i=e;e=f&-67108864;F[j+8>>2]=i-e;s=j;e=W>>>22|0;i=x>>>30|0;x=V<<18&33292288|(W<<10|x<<2);e=e|i;i=q>>>26|0;q=(q&67108863)<<6|K>>>26;A=q+x|0;q=A;i=e;e=x+16777216|0;i=e>>>0<16777216?i+1|0:i;n=e;e=i;i=q;f=n&33554432;F[j+36>>2]=i-f;f=(p&67108863)<<6|B>>>26;p=f+N|0;F[j+20>>2]=p-(P&-33554432);f=t;o=f+((o&67108863)<<6|y>>>26)|0;F[j+12>>2]=o-(z&234881024);p=v-(w&2113929216)|0;e=qe((e&33554431)<<7|n>>>25,e>>>25|0,19,0);o=e+M|0;i=$;i=e>>>0>o>>>0?i+1|0:i;e=o;f=i;i=e+33554432|0;f=i>>>0<33554432?f+1|0:f;f=((f&67108863)<<6|i>>>26)+p|0;F[j+4>>2]=f;j=i&-67108864;F[s>>2]=e-j;F[r+84>>2]=0;F[r+88>>2]=0;F[r+80>>2]=1;F[r+92>>2]=0;F[r+96>>2]=0;F[r+100>>2]=0;F[r+104>>2]=0;F[r+108>>2]=0;F[r+112>>2]=0;F[r+116>>2]=0;K=h+192|0;fa(K,s);M=h+144|0;ha(M,K,1936);N=F[r+116>>2];P=F[r+112>>2];V=F[r+108>>2];W=F[r+104>>2];X=F[r+100>>2];Q=F[r+96>>2];R=F[r+92>>2];S=F[r+88>>2];m=F[r+84>>2];E=F[h+228>>2];v=F[h+224>>2];s=F[h+220>>2];n=F[h+216>>2];q=F[h+212>>2];p=F[h+208>>2];o=F[h+204>>2];f=F[h+200>>2];e=F[h+196>>2];j=F[h+192>>2];i=F[r+80>>2];F[h+144>>2]=i+F[h+144>>2];B=j-i|0;F[h+192>>2]=B;y=e-m|0;F[h+196>>2]=y;C=f-S|0;F[h+200>>2]=C;z=o-R|0;F[h+204>>2]=z;w=p-Q|0;F[h+208>>2]=w;t=q-X|0;F[h+212>>2]=t;x=n-W|0;F[h+216>>2]=x;A=s-V|0;F[h+220>>2]=A;v=v-P|0;F[h+224>>2]=v;s=E-N|0;F[h+228>>2]=s;n=F[h+148>>2];q=F[h+152>>2];p=F[h+156>>2];o=F[h+160>>2];f=F[h+164>>2];e=F[h+168>>2];j=F[h+172>>2];i=F[h+176>>2];F[h+180>>2]=N+F[h+180>>2];F[h+176>>2]=i+P;F[h+172>>2]=j+V;F[h+168>>2]=e+W;F[h+164>>2]=f+X;F[h+160>>2]=o+Q;F[h+156>>2]=p+R;F[h+152>>2]=q+S;F[h+148>>2]=m+n;i=h+96|0;fa(i,M);ha(i,i,M);fa(r,i);ha(r,r,M);ha(r,r,K);f=_-144|0;_=f;j=f+96|0;fa(j,r);e=f+48|0;fa(e,j);fa(e,e);ha(e,r,e);ha(j,j,e);fa(j,j);ha(j,e,j);fa(e,j);fa(e,e);fa(e,e);fa(e,e);fa(e,e);ha(j,e,j);fa(e,j);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);ha(e,e,j);fa(f,e);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);fa(f,f);ha(e,f,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);ha(j,e,j);fa(e,j);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);ha(e,e,j);fa(f,e);e=1;while(1){fa(f,f);e=e+1|0;if((e|0)!=100){continue}break}e=f+48|0;ha(e,f,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);fa(e,e);j=f+96|0;ha(j,e,j);fa(j,j);fa(j,j);ha(r,j,r);_=f+144|0;ha(r,r,i);ha(r,r,K);i=h+48|0;fa(i,r);ha(i,i,M);F[h+36>>2]=F[h+84>>2]-s;F[h+32>>2]=F[h+80>>2]-v;F[h+28>>2]=F[h+76>>2]-A;F[h+24>>2]=F[h+72>>2]-x;F[h+20>>2]=F[h+68>>2]-t;F[h+16>>2]=F[h+64>>2]-w;F[h+12>>2]=F[h+60>>2]-z;F[h+8>>2]=F[h+56>>2]-C;F[h+4>>2]=F[h+52>>2]-y;F[h>>2]=F[h+48>>2]-B;Fa(h+240|0,h);b:{if(G[h+271|0]|(G[h+270|0]|(G[h+269|0]|(G[h+268|0]|(G[h+267|0]|(G[h+266|0]|(G[h+265|0]|(G[h+264|0]|(G[h+263|0]|(G[h+262|0]|(G[h+261|0]|(G[h+260|0]|(G[h+259|0]|(G[h+258|0]|(G[h+257|0]|(G[h+256|0]|(G[h+255|0]|(G[h+254|0]|(G[h+253|0]|(G[h+252|0]|(G[h+251|0]|(G[h+250|0]|(G[h+249|0]|(G[h+248|0]|(G[h+247|0]|(G[h+246|0]|(G[h+245|0]|(G[h+244|0]|(G[h+243|0]|(G[h+242|0]|(G[h+241|0]|G[h+240|0]))))))))))))))))))))))))))))))){B=F[h+192>>2];y=F[h+48>>2];C=F[h+196>>2];z=F[h+52>>2];w=F[h+200>>2];t=F[h+56>>2];x=F[h+204>>2];A=F[h+60>>2];v=F[h+208>>2];s=F[h+64>>2];n=F[h+212>>2];q=F[h+68>>2];p=F[h+216>>2];o=F[h+72>>2];f=F[h+220>>2];e=F[h+76>>2];j=F[h+224>>2];i=F[h+80>>2];F[h+36>>2]=F[h+228>>2]+F[h+84>>2];F[h+32>>2]=i+j;F[h+28>>2]=e+f;F[h+24>>2]=o+p;F[h+20>>2]=n+q;F[h+16>>2]=s+v;F[h+12>>2]=x+A;F[h+8>>2]=t+w;F[h+4>>2]=C+z;F[h>>2]=y+B;Fa(h+240|0,h);i=-1;if(G[h+271|0]|(G[h+270|0]|(G[h+269|0]|(G[h+268|0]|(G[h+267|0]|(G[h+266|0]|(G[h+265|0]|(G[h+264|0]|(G[h+263|0]|(G[h+262|0]|(G[h+261|0]|(G[h+260|0]|(G[h+259|0]|(G[h+258|0]|(G[h+257|0]|(G[h+256|0]|(G[h+255|0]|(G[h+254|0]|(G[h+253|0]|(G[h+252|0]|(G[h+251|0]|(G[h+250|0]|(G[h+249|0]|(G[h+248|0]|(G[h+247|0]|(G[h+246|0]|(G[h+245|0]|(G[h+244|0]|(G[h+243|0]|(G[h+242|0]|(G[h+241|0]|G[h+240|0]))))))))))))))))))))))))))))))){break b}ha(r,r,1984)}Fa(h+240|0,r);if((D[h+240|0]&1)==(G[a+31|0]>>>7|0)){F[r+36>>2]=0-F[r+36>>2];F[r+32>>2]=0-F[r+32>>2];F[r+28>>2]=0-F[r+28>>2];F[r+24>>2]=0-F[r+24>>2];F[r+20>>2]=0-F[r+20>>2];F[r+16>>2]=0-F[r+16>>2];F[r+12>>2]=0-F[r+12>>2];F[r+8>>2]=0-F[r+8>>2];F[r+4>>2]=0-F[r+4>>2];F[r>>2]=0-F[r>>2]}ha(r+120|0,r,T);i=0}_=h+272|0;if(i){break a}F[k+352>>2]=327033209;F[k+356>>2]=1541459225;F[k+344>>2]=-79577749;F[k+348>>2]=528734635;F[k+336>>2]=725511199;F[k+340>>2]=-1694144372;F[k+328>>2]=-1377402159;F[k+332>>2]=1359893119;p=32;F[k+320>>2]=1595750129;F[k+324>>2]=-1521486534;F[k+312>>2]=-23791573;F[k+316>>2]=1013904242;F[k+304>>2]=-2067093701;F[k+308>>2]=-1150833019;F[k+296>>2]=-205731576;F[k+300>>2]=1779033703;F[k+288>>2]=0;F[k+292>>2]=0;F[k+360>>2]=0;D[k+364|0]=G[d|0];D[k+365|0]=G[d+1|0];D[k+366|0]=G[d+2|0];D[k+367|0]=G[d+3|0];n=k+364|0;D[(n+F[k+360>>2]|0)+4|0]=G[d+4|0];D[(n+F[k+360>>2]|0)+5|0]=G[d+5|0];D[(n+F[k+360>>2]|0)+6|0]=G[d+6|0];D[(n+F[k+360>>2]|0)+7|0]=G[d+7|0];D[(n+F[k+360>>2]|0)+8|0]=G[d+8|0];D[(n+F[k+360>>2]|0)+9|0]=G[d+9|0];D[(n+F[k+360>>2]|0)+10|0]=G[d+10|0];D[(n+F[k+360>>2]|0)+11|0]=G[d+11|0];D[(n+F[k+360>>2]|0)+12|0]=G[d+12|0];D[(n+F[k+360>>2]|0)+13|0]=G[d+13|0];D[(n+F[k+360>>2]|0)+14|0]=G[d+14|0];D[(n+F[k+360>>2]|0)+15|0]=G[d+15|0];D[(n+F[k+360>>2]|0)+16|0]=G[d+16|0];D[(n+F[k+360>>2]|0)+17|0]=G[d+17|0];D[(n+F[k+360>>2]|0)+18|0]=G[d+18|0];D[(n+F[k+360>>2]|0)+19|0]=G[d+19|0];D[(n+F[k+360>>2]|0)+20|0]=G[d+20|0];D[(n+F[k+360>>2]|0)+21|0]=G[d+21|0];D[(n+F[k+360>>2]|0)+22|0]=G[d+22|0];D[(n+F[k+360>>2]|0)+23|0]=G[d+23|0];D[(n+F[k+360>>2]|0)+24|0]=G[d+24|0];D[(n+F[k+360>>2]|0)+25|0]=G[d+25|0];D[(n+F[k+360>>2]|0)+26|0]=G[d+26|0];D[(n+F[k+360>>2]|0)+27|0]=G[d+27|0];D[(n+F[k+360>>2]|0)+28|0]=G[d+28|0];D[(n+F[k+360>>2]|0)+29|0]=G[d+29|0];D[(n+F[k+360>>2]|0)+30|0]=G[d+30|0];D[(n+F[k+360>>2]|0)+31|0]=G[d+31|0];i=F[k+360>>2]+32|0;F[k+360>>2]=i;if((i|0)==128){ta(k+288|0,n);F[k+360>>2]=0;i=F[k+292>>2];e=F[k+288>>2]+1024|0;i=e>>>0<1024?i+1|0:i;F[k+288>>2]=e;F[k+292>>2]=i}q=F[k+360>>2];if(!(!a|q>>>0>128)){while(1){c:{if(!(p>>>0<128|q)){ta(k+288|0,a);i=F[k+292>>2];e=F[k+288>>2]+1024|0;i=e>>>0<1024?i+1|0:i;F[k+288>>2]=e;F[k+292>>2]=i;p=p-128|0;a=a+128|0;break c}i=128-q|0;o=i>>>0>p>>>0?p:i;d:{if(!o){break d}f=o&3;u=0;if(o-1>>>0>=3){e=o&-4;while(1){j=k+364|0;D[j+(q+u|0)|0]=G[a+u|0];i=u|1;D[j+(i+F[k+360>>2]|0)|0]=G[a+i|0];i=u|2;D[j+(i+F[k+360>>2]|0)|0]=G[a+i|0];i=u|3;D[j+(i+F[k+360>>2]|0)|0]=G[a+i|0];u=u+4|0;q=F[k+360>>2];e=e-4|0;if(e){continue}break}}if(!f){break d}while(1){D[((q+u|0)+k|0)+364|0]=G[a+u|0];u=u+1|0;q=F[k+360>>2];f=f-1|0;if(f){continue}break}}p=p-o|0;a=a+o|0;i=o+q|0;F[k+360>>2]=i;if((i|0)!=128){break c}ta(k+288|0,n);F[k+360>>2]=0;e=F[k+292>>2];j=F[k+288>>2]+1024|0;e=j>>>0<1024?e+1|0:e;F[k+288>>2]=j;F[k+292>>2]=e}q=F[k+360>>2];if(p){continue}break}}e:{if(!c|(!b|q>>>0>128)){break e}while(1){f:{if(!(c>>>0<128|q)){ta(k+288|0,b);i=F[k+292>>2];j=F[k+288>>2]+1024|0;i=j>>>0<1024?i+1|0:i;F[k+288>>2]=j;F[k+292>>2]=i;c=c-128|0;b=b+128|0;break f}a=128-q|0;j=a>>>0>c>>>0?c:a;g:{if(!j){break g}p=j&3;u=0;if(j-1>>>0>=3){f=j&-4;while(1){i=k+364|0;D[i+(q+u|0)|0]=G[b+u|0];a=u|1;D[i+(a+F[k+360>>2]|0)|0]=G[a+b|0];a=u|2;D[i+(a+F[k+360>>2]|0)|0]=G[a+b|0];a=u|3;D[i+(a+F[k+360>>2]|0)|0]=G[a+b|0];u=u+4|0;q=F[k+360>>2];f=f-4|0;if(f){continue}break}}if(!p){break g}while(1){D[((q+u|0)+k|0)+364|0]=G[b+u|0];u=u+1|0;q=F[k+360>>2];p=p-1|0;if(p){continue}break}}c=c-j|0;b=b+j|0;a=j+q|0;F[k+360>>2]=a;if((a|0)!=128){break f}ta(k+288|0,n);F[k+360>>2]=0;i=F[k+292>>2];j=F[k+288>>2]+1024|0;i=j>>>0<1024?i+1|0:i;F[k+288>>2]=j;F[k+292>>2]=i}if(!c){break e}q=F[k+360>>2];continue}}f=k+528|0;cb(k+288|0,f);ob(f);V=k+8|0;i=V;c=k+128|0;q=d+32|0;b=0;a=0;l=_-2272|0;_=l;while(1){j=l+2016|0;e=f+(b>>>3|0)|0;D[j+b|0]=G[e|0]>>>(b&6)&1;o=j;j=b|1;D[o+j|0]=G[e|0]>>>(j&7)&1;b=b+2|0;if((b|0)!=256){continue}break}while(1){j=a;a=a+1|0;n=j+(l+2016|0)|0;h:{if(!G[n|0]|j>>>0>254){break h}o=(l+2016|0)+a|0;b=D[o|0];i:{if(!b){break i}f=b<<1;e=D[n|0];b=f+e|0;if((b|0)<=15){D[n|0]=b;D[o|0]=0;break i}b=e-f|0;if((b|0)<-15){break h}D[n|0]=b;b=a;while(1){e=(l+2016|0)+b|0;if(!G[e|0]){D[e|0]=1;break i}D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break}}if(j>>>0>=254){break h}b=j+2|0;p=b+(l+2016|0)|0;e=D[p|0];j:{if(!e){break j}o=e<<2;f=D[n|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break h}D[n|0]=e;while(1){e=(l+2016|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break j}break}D[e|0]=1;break j}D[n|0]=e;D[p|0]=0}if(j>>>0>252){break h}b=j+3|0;p=b+(l+2016|0)|0;e=D[p|0];k:{if(!e){break k}o=e<<3;f=D[n|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break h}D[n|0]=e;while(1){e=(l+2016|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break k}break}D[e|0]=1;break k}D[n|0]=e;D[p|0]=0}if(j>>>0>251){break h}b=j+4|0;p=b+(l+2016|0)|0;e=D[p|0];l:{if(!e){break l}o=e<<4;f=D[n|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break h}D[n|0]=e;while(1){e=(l+2016|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break l}break}D[e|0]=1;break l}D[n|0]=e;D[p|0]=0}if(j>>>0>250){break h}b=j+5|0;p=b+(l+2016|0)|0;e=D[p|0];m:{if(!e){break m}o=e<<5;f=D[n|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break h}D[n|0]=e;while(1){e=(l+2016|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break m}break}D[e|0]=1;break m}D[n|0]=e;D[p|0]=0}if(j>>>0>249){break h}b=j+6|0;o=b+(l+2016|0)|0;j=D[o|0];if(!j){break h}f=j<<6;e=D[n|0];j=f+e|0;if((j|0)>=16){j=e-f|0;if((j|0)<-15){break h}D[n|0]=j;while(1){j=(l+2016|0)+b|0;if(G[j|0]){D[j|0]=0;j=b>>>0<255;b=b+1|0;if(j){continue}break h}break}D[j|0]=1;break h}D[n|0]=j;D[o|0]=0}if((a|0)!=256){continue}break}b=0;while(1){a=l+1760|0;j=q+(b>>>3|0)|0;D[a+b|0]=G[j|0]>>>(b&6)&1;e=a;a=b|1;D[e+a|0]=G[j|0]>>>(a&7)&1;b=b+2|0;if((b|0)!=256){continue}break}a=0;while(1){j=a;a=a+1|0;q=j+(l+1760|0)|0;n:{if(!G[q|0]|j>>>0>254){break n}o=(l+1760|0)+a|0;b=D[o|0];o:{if(!b){break o}f=b<<1;e=D[q|0];b=f+e|0;if((b|0)<=15){D[q|0]=b;D[o|0]=0;break o}b=e-f|0;if((b|0)<-15){break n}D[q|0]=b;b=a;while(1){e=(l+1760|0)+b|0;if(!G[e|0]){D[e|0]=1;break o}D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break}}if(j>>>0>=254){break n}b=j+2|0;p=b+(l+1760|0)|0;e=D[p|0];p:{if(!e){break p}o=e<<2;f=D[q|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break n}D[q|0]=e;while(1){e=(l+1760|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break p}break}D[e|0]=1;break p}D[q|0]=e;D[p|0]=0}if(j>>>0>252){break n}b=j+3|0;p=b+(l+1760|0)|0;e=D[p|0];q:{if(!e){break q}o=e<<3;f=D[q|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break n}D[q|0]=e;while(1){e=(l+1760|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break q}break}D[e|0]=1;break q}D[q|0]=e;D[p|0]=0}if(j>>>0>251){break n}b=j+4|0;p=b+(l+1760|0)|0;e=D[p|0];r:{if(!e){break r}o=e<<4;f=D[q|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break n}D[q|0]=e;while(1){e=(l+1760|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break r}break}D[e|0]=1;break r}D[q|0]=e;D[p|0]=0}if(j>>>0>250){break n}b=j+5|0;p=b+(l+1760|0)|0;e=D[p|0];s:{if(!e){break s}o=e<<5;f=D[q|0];e=o+f|0;if((e|0)>=16){e=f-o|0;if((e|0)<-15){break n}D[q|0]=e;while(1){e=(l+1760|0)+b|0;if(G[e|0]){D[e|0]=0;e=b>>>0<255;b=b+1|0;if(e){continue}break s}break}D[e|0]=1;break s}D[q|0]=e;D[p|0]=0}if(j>>>0>249){break n}b=j+6|0;o=b+(l+1760|0)|0;j=D[o|0];if(!j){break n}f=j<<6;e=D[q|0];j=f+e|0;if((j|0)>=16){j=e-f|0;if((j|0)<-15){break n}D[q|0]=j;while(1){j=(l+1760|0)+b|0;if(G[j|0]){D[j|0]=0;j=b>>>0<255;b=b+1|0;if(j){continue}break n}break}D[j|0]=1;break n}D[q|0]=j;D[o|0]=0}if((a|0)!=256){continue}break}s=l+480|0;Ga(s,c);n=F[c>>2];q=F[c+4>>2];p=F[c+8>>2];o=F[c+12>>2];f=F[c+16>>2];e=F[c+20>>2];j=F[c+24>>2];b=F[c+28>>2];a=F[c+36>>2];F[l+192>>2]=F[c+32>>2];F[l+196>>2]=a;F[l+184>>2]=j;F[l+188>>2]=b;F[l+176>>2]=f;F[l+180>>2]=e;F[l+168>>2]=p;F[l+172>>2]=o;F[l+160>>2]=n;F[l+164>>2]=q;n=F[c+48>>2];q=F[c+52>>2];p=F[c+56>>2];o=F[c+60>>2];a=c- -64|0;f=F[a>>2];e=F[a+4>>2];j=F[c+40>>2];b=F[c+44>>2];a=F[c+76>>2];F[l+232>>2]=F[c+72>>2];F[l+236>>2]=a;F[l+224>>2]=f;F[l+228>>2]=e;F[l+216>>2]=p;F[l+220>>2]=o;F[l+208>>2]=n;F[l+212>>2]=q;F[l+200>>2]=j;F[l+204>>2]=b;n=F[c+88>>2];q=F[c+92>>2];p=F[c+96>>2];o=F[c+100>>2];f=F[c+104>>2];e=F[c+108>>2];j=F[c+80>>2];b=F[c+84>>2];a=F[c+116>>2];F[l+272>>2]=F[c+112>>2];F[l+276>>2]=a;F[l+264>>2]=f;F[l+268>>2]=e;F[l+256>>2]=p;F[l+260>>2]=o;F[l+248>>2]=n;F[l+252>>2]=q;F[l+240>>2]=j;F[l+244>>2]=b;c=l+320|0;b=l+160|0;Oa(c,b);H=l+440|0;ha(l,c,H);J=l+360|0;I=l+400|0;ha(l+40|0,J,I);ha(l+80|0,I,H);ha(l+120|0,c,J);Ha(c,l,s);ha(b,c,H);O=l+200|0;ha(O,J,I);h=l+240|0;ha(h,I,H);r=l+280|0;ha(r,c,J);a=l+640|0;Ga(a,b);Ha(c,l,a);ha(b,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);a=l+800|0;Ga(a,b);Ha(c,l,a);ha(b,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);a=l+960|0;Ga(a,b);Ha(c,l,a);ha(b,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);a=l+1120|0;Ga(a,b);Ha(c,l,a);ha(b,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);a=l+1280|0;Ga(a,b);Ha(c,l,a);ha(b,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);a=l+1440|0;Ga(a,b);Ha(c,l,a);ha(b,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);Ga(l+1600|0,b);a=i;F[a+32>>2]=0;F[a+36>>2]=0;F[a+24>>2]=0;F[a+28>>2]=0;F[a+16>>2]=0;F[a+20>>2]=0;F[a+8>>2]=0;F[a+12>>2]=0;F[a>>2]=0;F[a+4>>2]=0;F[a+44>>2]=0;F[a+48>>2]=0;F[a+40>>2]=1;F[a+52>>2]=0;F[a+56>>2]=0;F[a+60>>2]=0;F[a+64>>2]=0;F[a+68>>2]=0;F[a+72>>2]=0;F[a+84>>2]=0;F[a+88>>2]=0;F[a+76>>2]=0;F[a+80>>2]=1;F[a+92>>2]=0;F[a+96>>2]=0;F[a+100>>2]=0;F[a+104>>2]=0;F[a+108>>2]=0;F[a+112>>2]=0;F[a+116>>2]=0;W=a+80|0;X=a+40|0;a=255;t:{u:{while(1){if(G[(l+2016|0)+a|0]|G[(l+1760|0)+a|0]){break u}b=a-1|0;if(!(G[b+(l+2016|0)|0]|G[b+(l+1760|0)|0])){a=a-2|0;if(b){continue}break t}break}a=b}if((a|0)<0){break t}while(1){Oa(l+320|0,i);b=a;E=D[a+(l+2016|0)|0];v:{if((E|0)>=1){a=l+160|0;c=l+320|0;ha(a,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);Ha(c,a,(l+480|0)+L((E&254)>>>1|0,160)|0);break v}if((E|0)>-1){break v}m=l+160|0;g=l+320|0;ha(m,g,H);ha(O,J,I);ha(h,I,H);ha(r,g,J);y=F[m+44>>2];C=F[m+48>>2];z=F[m+52>>2];w=F[m+56>>2];t=F[m+60>>2];B=m- -64|0;x=F[B>>2];A=F[m+68>>2];v=F[m+72>>2];s=F[m+76>>2];n=F[m+4>>2];q=F[m+8>>2];p=F[m+12>>2];o=F[m+16>>2];f=F[m+20>>2];e=F[m+24>>2];j=F[m+28>>2];c=F[m+32>>2];a=F[m+36>>2];F[g>>2]=F[m>>2]+F[m+40>>2];F[g+36>>2]=a+s;F[g+32>>2]=c+v;F[g+28>>2]=j+A;F[g+24>>2]=e+x;F[g+20>>2]=f+t;F[g+16>>2]=o+w;F[g+12>>2]=p+z;F[g+8>>2]=q+C;F[g+4>>2]=n+y;y=F[m+44>>2];C=F[m+48>>2];z=F[m+52>>2];w=F[m+56>>2];t=F[m+60>>2];x=F[B>>2];A=F[m+68>>2];v=F[m+72>>2];s=F[m>>2];n=F[m+40>>2];q=F[m+4>>2];p=F[m+8>>2];o=F[m+12>>2];f=F[m+16>>2];e=F[m+20>>2];j=F[m+24>>2];c=F[m+28>>2];a=F[m+32>>2];F[g+76>>2]=F[m+76>>2]-F[m+36>>2];F[g+72>>2]=v-a;F[g+68>>2]=A-c;u=g- -64|0;F[u>>2]=x-j;F[g+60>>2]=t-e;F[g+56>>2]=w-f;F[g+52>>2]=z-o;F[g+48>>2]=C-p;F[g+44>>2]=y-q;F[g+40>>2]=n-s;c=(l+480|0)+L((0-E&254)>>>1|0,160)|0;ha(g+80|0,g,c+40|0);a=g+40|0;ha(a,a,c);ha(g+120|0,c+120|0,m+120|0);ha(g,m+80|0,c+80|0);T=F[g+44>>2];U=F[g+84>>2];M=F[g+48>>2];K=F[g+88>>2];N=F[g+52>>2];P=F[g+92>>2];E=F[g+56>>2];B=F[g+96>>2];y=F[g+60>>2];C=F[g+100>>2];z=F[u>>2];w=F[g+104>>2];t=F[g+68>>2];x=F[g+108>>2];A=F[g+72>>2];v=F[g+112>>2];Q=F[g>>2];R=F[g+4>>2];S=F[g+8>>2];m=F[g+12>>2];q=F[g+16>>2];p=F[g+20>>2];o=F[g+24>>2];f=F[g+28>>2];e=F[g+32>>2];j=F[g+36>>2];s=F[g+40>>2];n=F[g+80>>2];c=F[g+76>>2];a=F[g+116>>2];F[g+76>>2]=c+a;F[g+72>>2]=v+A;F[g+68>>2]=t+x;F[u>>2]=w+z;F[g+60>>2]=y+C;F[g+56>>2]=B+E;F[g+52>>2]=N+P;F[g+48>>2]=K+M;F[g+44>>2]=T+U;F[g+40>>2]=n+s;F[g+36>>2]=a-c;F[g+32>>2]=v-A;F[g+28>>2]=x-t;F[g+24>>2]=w-z;F[g+20>>2]=C-y;F[g+16>>2]=B-E;F[g+12>>2]=P-N;F[g+8>>2]=K-M;F[g+4>>2]=U-T;F[g>>2]=n-s;E=F[g+156>>2];B=j<<1;F[g+156>>2]=E+B;y=F[g+152>>2];C=e<<1;F[g+152>>2]=y+C;z=F[g+148>>2];w=f<<1;F[g+148>>2]=z+w;t=F[g+144>>2];x=o<<1;F[g+144>>2]=t+x;A=F[g+140>>2];v=p<<1;F[g+140>>2]=A+v;s=F[g+136>>2];n=q<<1;F[g+136>>2]=s+n;q=F[g+132>>2];p=m<<1;F[g+132>>2]=q+p;o=F[g+128>>2];f=S<<1;F[g+128>>2]=o+f;e=F[g+124>>2];j=R<<1;F[g+124>>2]=e+j;c=F[g+120>>2];a=Q<<1;F[g+120>>2]=c+a;F[g+112>>2]=C-y;F[g+108>>2]=w-z;F[g+104>>2]=x-t;F[g+100>>2]=v-A;F[g+96>>2]=n-s;F[g+92>>2]=p-q;F[g+88>>2]=f-o;F[g+84>>2]=j-e;F[g+80>>2]=a-c;F[g+116>>2]=B-E}E=D[b+(l+1760|0)|0];w:{if((E|0)>=1){a=l+160|0;c=l+320|0;ha(a,c,H);ha(O,J,I);ha(h,I,H);ha(r,c,J);nb(c,a,L((E&254)>>>1|0,120)+36560|0);break w}if((E|0)>-1){break w}m=l+160|0;g=l+320|0;ha(m,g,H);ha(O,J,I);ha(h,I,H);ha(r,g,J);y=F[m+44>>2];C=F[m+48>>2];z=F[m+52>>2];w=F[m+56>>2];t=F[m+60>>2];B=m- -64|0;x=F[B>>2];A=F[m+68>>2];v=F[m+72>>2];s=F[m+76>>2];n=F[m+4>>2];q=F[m+8>>2];p=F[m+12>>2];o=F[m+16>>2];f=F[m+20>>2];e=F[m+24>>2];j=F[m+28>>2];c=F[m+32>>2];a=F[m+36>>2];F[g>>2]=F[m>>2]+F[m+40>>2];F[g+36>>2]=a+s;F[g+32>>2]=c+v;F[g+28>>2]=j+A;F[g+24>>2]=e+x;F[g+20>>2]=f+t;F[g+16>>2]=o+w;F[g+12>>2]=p+z;F[g+8>>2]=q+C;F[g+4>>2]=n+y;y=F[m+44>>2];C=F[m+48>>2];z=F[m+52>>2];w=F[m+56>>2];t=F[m+60>>2];x=F[B>>2];A=F[m+68>>2];v=F[m+72>>2];s=F[m>>2];n=F[m+40>>2];q=F[m+4>>2];p=F[m+8>>2];o=F[m+12>>2];f=F[m+16>>2];e=F[m+20>>2];j=F[m+24>>2];c=F[m+28>>2];a=F[m+32>>2];F[g+76>>2]=F[m+76>>2]-F[m+36>>2];F[g+72>>2]=v-a;F[g+68>>2]=A-c;u=g- -64|0;F[u>>2]=x-j;F[g+60>>2]=t-e;F[g+56>>2]=w-f;F[g+52>>2]=z-o;F[g+48>>2]=C-p;F[g+44>>2]=y-q;F[g+40>>2]=n-s;c=L((0-E&254)>>>1|0,120)+36560|0;ha(g+80|0,g,c+40|0);a=g+40|0;ha(a,a,c);ha(g+120|0,c+80|0,m+120|0);Q=F[m+84>>2];R=F[m+88>>2];S=F[m+92>>2];q=F[m+96>>2];p=F[m+100>>2];o=F[m+104>>2];f=F[m+108>>2];e=F[m+112>>2];j=F[m+116>>2];T=F[g+44>>2];U=F[g+84>>2];M=F[g+48>>2];K=F[g+88>>2];N=F[g+52>>2];P=F[g+92>>2];E=F[g+56>>2];B=F[g+96>>2];y=F[g+60>>2];C=F[g+100>>2];z=F[u>>2];w=F[g+104>>2];t=F[g+68>>2];x=F[g+108>>2];A=F[g+72>>2];v=F[g+112>>2];m=F[m+80>>2];s=F[g+40>>2];n=F[g+80>>2];c=F[g+76>>2];a=F[g+116>>2];F[g+76>>2]=c+a;F[g+72>>2]=v+A;F[g+68>>2]=t+x;F[u>>2]=w+z;F[g+60>>2]=y+C;F[g+56>>2]=B+E;F[g+52>>2]=N+P;F[g+48>>2]=K+M;F[g+44>>2]=T+U;F[g+40>>2]=n+s;F[g+36>>2]=a-c;F[g+32>>2]=v-A;F[g+28>>2]=x-t;F[g+24>>2]=w-z;F[g+20>>2]=C-y;F[g+16>>2]=B-E;F[g+12>>2]=P-N;F[g+8>>2]=K-M;F[g+4>>2]=U-T;F[g>>2]=n-s;E=F[g+156>>2];B=j<<1;F[g+156>>2]=E+B;y=F[g+152>>2];C=e<<1;F[g+152>>2]=y+C;z=F[g+148>>2];w=f<<1;F[g+148>>2]=z+w;t=F[g+144>>2];x=o<<1;F[g+144>>2]=t+x;A=F[g+140>>2];v=p<<1;F[g+140>>2]=A+v;s=F[g+136>>2];n=q<<1;F[g+136>>2]=s+n;q=F[g+132>>2];p=S<<1;F[g+132>>2]=q+p;o=F[g+128>>2];f=R<<1;F[g+128>>2]=o+f;e=F[g+124>>2];j=Q<<1;F[g+124>>2]=e+j;c=F[g+120>>2];a=m<<1;F[g+120>>2]=c+a;F[g+112>>2]=C-y;F[g+108>>2]=w-z;F[g+104>>2]=x-t;F[g+100>>2]=v-A;F[g+96>>2]=n-s;F[g+92>>2]=p-q;F[g+88>>2]=f-o;F[g+84>>2]=j-e;F[g+80>>2]=a-c;F[g+116>>2]=B-E}ha(i,l+320|0,H);ha(X,J,I);ha(W,I,H);a=b-1|0;if((b|0)>0){continue}break}}_=l+2272|0;c=k+688|0;pb(c,k+88|0);b=k+640|0;ha(b,V,c);a=k+592|0;ha(a,k+48|0,c);Fa(k+496|0,a);Fa(k+736|0,b);u=!(G[d+1|0]^G[k+497|0]|G[d|0]^G[k+496|0]|G[d+2|0]^G[k+498|0]|G[d+3|0]^G[k+499|0]|G[d+4|0]^G[k+500|0]|G[d+5|0]^G[k+501|0]|G[d+6|0]^G[k+502|0]|G[d+7|0]^G[k+503|0]|G[d+8|0]^G[k+504|0]|G[d+9|0]^G[k+505|0]|G[d+10|0]^G[k+506|0]|G[d+11|0]^G[k+507|0]|G[d+12|0]^G[k+508|0]|G[d+13|0]^G[k+509|0]|G[d+14|0]^G[k+510|0]|G[d+15|0]^G[k+511|0]|G[d+16|0]^G[k+512|0]|G[d+17|0]^G[k+513|0]|G[d+18|0]^G[k+514|0]|G[d+19|0]^G[k+515|0]|G[d+20|0]^G[k+516|0]|G[d+21|0]^G[k+517|0]|G[d+22|0]^G[k+518|0]|G[d+23|0]^G[k+519|0]|G[d+24|0]^G[k+520|0]|G[d+25|0]^G[k+521|0]|G[d+26|0]^G[k+522|0]|G[d+27|0]^G[k+523|0]|G[d+28|0]^G[k+524|0]|G[d+29|0]^G[k+525|0]|G[d+30|0]^G[k+526|0]|G[d+31|0]^(G[k+527|0]^G[k+736|0]<<7&128))}_=k+768|0;return(u|0)!=0}function ob(a){var b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,E=0,F=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0,P=0,Q=0,R=0,S=0,T=0,U=0,V=0,W=0,X=0,Y=0,Z=0,_=0,aa=0,ba=0,ca=0,da=0,ea=0,fa=0,ga=0;c=G[a+48|0];b=c>>>24|0;m=G[a+47|0];e=m|c<<8;g=G[a+49|0];d=g>>>16|0;i=g<<16;d=b|d;c=e|i;F=((d&3)<<30|c>>>2)&2097151;c=qe(F,0,136657,0);d=G[a+27|0];b=d>>>24|0;f=G[a+26|0];i=f|d<<8;e=c;ba=G[a+28|0];d=ba;c=d>>>16|0;d=d<<16;c=b|c;b=d|i;c=((c&3)<<30|b>>>2)&2097151;d=e+c|0;b=$;i=d;d=c>>>0>d>>>0?b+1|0:b;c=G[a+50|0];b=c>>>24|0;g=g|c<<8;e=G[a+51|0];c=e>>>16|0;h=g|e<<16;g=b|c;c=i;e=G[a+52|0];b=e>>>8|0;i=e<<24;g=b|g;b=i|h;H=((g&127)<<25|b>>>7)&2097151;b=qe(H,0,-997805,-1);i=c+b|0;c=$+d|0;c=b>>>0>i>>>0?c+1|0:c;d=c;b=G[a+53|0];c=b>>>24|0;g=e|b<<8;e=G[a+54|0];b=e>>>16|0;h=g|e<<16;g=b|c;b=i;e=G[a+55|0];c=e>>>8|0;i=e<<24;g=c|g;c=i|h;I=((g&15)<<28|c>>>4)&2097151;c=qe(I,0,654183,0);i=b+c|0;b=$+d|0;b=c>>>0>i>>>0?b+1|0:b;c=i;i=b;d=G[a+56|0];b=d>>>24|0;h=e|d<<8;j=c;g=G[a+57|0];e=g;c=e>>>16|0;e=e<<16;d=b|c;c=e|h;J=((d&1)<<31|c>>>1)&2097151;b=qe(J,0,470296,0);d=j+b|0;c=$+i|0;h=d;d=b>>>0>d>>>0?c+1|0:c;b=G[a+58|0];c=b>>>24|0;i=g|b<<8;b=c;e=i;i=G[a+59|0];c=i>>>16|0;g=e|i<<16;e=b|c;o=G[a+60|0];i=o;c=i>>>8|0;i=i<<24;e=c|e;c=g|i;K=((e&63)<<26|c>>>6)&2097151;c=qe(K,0,666643,0);i=c+h|0;b=$+d|0;b=c>>>0>i>>>0?b+1|0:b;j=i;h=b;n=qe(F,S,-997805,-1);b=G[a+24|0];d=b>>>24|0;e=G[a+23|0];g=e|b<<8;b=G[a+25|0];c=b>>>16|0;g=g|b<<16;d=c|d|f>>>8;b=f<<24|g;c=((d&31)<<27|b>>>5)&2097151;d=c+n|0;b=$;b=c>>>0>d>>>0?b+1|0:b;c=d;d=qe(H,T,654183,0);f=c+d|0;c=$+b|0;c=d>>>0>f>>>0?c+1|0:c;b=qe(I,U,470296,0);d=b+f|0;c=$+c|0;c=b>>>0>d>>>0?c+1|0:c;b=qe(J,V,666643,0);f=b+d|0;d=$+c|0;g=f;f=b>>>0>f>>>0?d+1|0:d;d=qe(F,S,654183,0);c=e<<16&2031616|(G[a+21|0]|G[a+22|0]<<8);d=d+c|0;b=$;b=c>>>0>d>>>0?b+1|0:b;c=qe(H,T,470296,0);d=c+d|0;b=$+b|0;b=c>>>0>d>>>0?b+1|0:b;c=qe(I,U,666643,0);e=c+d|0;d=$+b|0;k=e;d=c>>>0>e>>>0?d+1|0:d;e=d;b=k;d=d-((b>>>0<4293918720)-1|0)|0;C=b- -1048576|0;s=d;b=d>>>21|0;d=(d&2097151)<<11|C>>>21;g=d+g|0;c=b+f|0;c=d>>>0>g>>>0?c+1|0:c;p=c;b=g;d=c-((b>>>0<4293918720)-1|0)|0;q=b- -1048576|0;n=d;ca=i- -1048576|0;f=h-((i>>>0<4293918720)-1|0)|0;i=f;c=(d&2097151)<<11|q>>>21;j=c+j|0;d=(d>>21)+h|0;d=c>>>0>j>>>0?d+1|0:d;c=j;b=ca&-2097152;v=c-b|0;u=d-((b>>>0>c>>>0)+f|0)|0;b=G[a+61|0];c=b>>>24|0;f=o|b<<8;d=G[a+62|0];b=d>>>16|0;f=f|d<<16;d=b|c;b=G[a+63|0];c=b>>>8|0;b=b<<24|f;d=c|d;c=d>>>3|0;L=(d&7)<<29|b>>>3;z=c;d=qe(L,c,-683901,-1);l=G[a+44|0];c=l;c=c<<16&2031616|(G[a+42|0]|G[a+43|0]<<8);d=d+c|0;b=$;f=d;b=c>>>0>d>>>0?b+1|0:b;r=b;b=d;d=r-((b>>>0<4293918720)-1|0)|0;o=b- -1048576|0;j=d;w=(d&2097151)<<11|o>>>21;h=d>>21;b=G[a+45|0];c=b>>>24|0;l=l|b<<8;b=G[a+46|0];d=b>>>16|0;l=l|b<<16;d=c|d|m>>>8;b=m<<24|l;b=((d&31)<<27|b>>>5)&2097151;d=b+w|0;c=h;P=d;c=b>>>0>d>>>0?c+1|0:c;x=c;c=qe(d,c,-683901,-1);d=c+v|0;b=$+u|0;b=c>>>0>d>>>0?b+1|0:b;c=d;da=c- -1048576|0;h=b-((c>>>0<4293918720)-1|0)|0;M=h;d=da&-2097152;_=c-d|0;aa=b-((c>>>0>>0)+h|0)|0;c=qe(P,x,136657,0);b=q&-2097152;d=c+(g-b|0)|0;b=$+(p-((b>>>0>g>>>0)+n|0)|0)|0;q=d;n=c>>>0>d>>>0?b+1|0:b;b=o&-2097152;o=f-b|0;m=r-((b>>>0>f>>>0)+j|0)|0;c=qe(K,W,-683901,-1);d=G[a+40|0];b=d>>>24|0;g=G[a+39|0];f=g|d<<8;h=c;c=G[a+41|0];d=c>>>16|0;c=c<<16;d=b|d;b=c|f;c=d>>>3|0;b=(d&7)<<29|b>>>3;d=h+b|0;c=c+$|0;c=b>>>0>d>>>0?c+1|0:c;b=d;d=qe(L,z,136657,0);f=b+d|0;b=$+c|0;p=f;f=d>>>0>f>>>0?b+1|0:b;r=qe(J,V,-683901,-1);b=G[a+37|0];c=b>>>24|0;A=G[a+36|0];d=A|b<<8;b=c;h=d;d=G[a+38|0];c=d>>>16|0;h=h|d<<16;d=b|c|g>>>8;b=g<<24|h;b=((d&63)<<26|b>>>6)&2097151;c=b+r|0;d=$;d=b>>>0>c>>>0?d+1|0:d;b=c;c=qe(K,W,136657,0);g=b+c|0;b=$+d|0;b=c>>>0>g>>>0?b+1|0:b;d=qe(L,z,-997805,-1);g=d+g|0;c=$+b|0;j=g;c=d>>>0>g>>>0?c+1|0:c;t=c;b=g;d=c-((b>>>0<4293918720)-1|0)|0;X=b- -1048576|0;v=d;b=d>>21;c=(d&2097151)<<11|X>>>21;d=c+p|0;b=b+f|0;h=d;b=c>>>0>d>>>0?b+1|0:b;u=b;b=d;d=u-((b>>>0<4293918720)-1|0)|0;B=b- -1048576|0;r=d;b=d>>21;d=(d&2097151)<<11|B>>>21;f=d+o|0;c=b+m|0;Q=f;c=d>>>0>f>>>0?c+1|0:c;E=c;b=qe(f,c,-683901,-1);d=b+q|0;c=$+n|0;R=d;o=b>>>0>d>>>0?c+1|0:c;n=k;k=e;c=qe(F,S,470296,0);e=G[a+19|0];b=e>>>24|0;d=G[a+18|0];f=d|e<<8;g=c;e=G[a+20|0];c=e>>>16|0;e=e<<16;p=b|c;b=e|f;e=(p&7)<<29|b>>>3;f=g+e|0;b=$+(p>>>3|0)|0;y=f;e=e>>>0>f>>>0?b+1|0:b;m=qe(F,S,666643,0);c=G[a+16|0];b=c>>>24|0;w=G[a+15|0];g=w|c<<8;f=G[a+17|0];c=f>>>16|0;g=g|f<<16;f=b|c;c=d<<24;d=d>>>8|f;b=c|g;b=((d&63)<<26|b>>>6)&2097151;c=b+m|0;d=$;g=c;d=b>>>0>c>>>0?d+1|0:d;l=d;b=c;d=d-((b>>>0<4293918720)-1|0)|0;Y=b- -1048576|0;q=d;b=d>>>21|0;d=(d&2097151)<<11|Y>>>21;f=d+y|0;c=b+e|0;c=d>>>0>f>>>0?c+1|0:c;d=qe(H,T,666643,0);e=d+f|0;b=$+c|0;f=e;b=d>>>0>e>>>0?b+1|0:b;m=b;b=e;e=m-((b>>>0<4293918720)-1|0)|0;y=b- -1048576|0;p=e;b=B&-2097152;d=u-((b>>>0>h>>>0)+r|0)|0;N=h-b|0;B=d;c=e>>>21|0;b=(e&2097151)<<11|y>>>21;e=b+n|0;c=c+k|0;c=b>>>0>e>>>0?c+1|0:c;h=e;b=C&-2097152;e=qe(P,x,-997805,-1);k=(h-b|0)+e|0;b=$+(c-((s&8191)+(b>>>0>h>>>0)|0)|0)|0;b=e>>>0>k>>>0?b+1|0:b;e=qe(Q,E,136657,0);h=e+k|0;c=$+b|0;c=e>>>0>h>>>0?c+1|0:c;b=qe(N,d,-683901,-1);e=b+h|0;d=$+c|0;d=b>>>0>e>>>0?d+1|0:d;r=d;b=e;d=d-((b>>>0<4293918720)-1|0)|0;s=b- -1048576|0;n=d;c=d>>21;b=(d&2097151)<<11|s>>>21;d=b+R|0;c=c+o|0;c=b>>>0>d>>>0?c+1|0:c;b=d;k=c;h=c-((b>>>0<4293918720)-1|0)|0;c=h>>21;u=b- -1048576|0;o=(h&2097151)<<11|u>>>21;C=o+_|0;d=c+aa|0;ea=C;o=o>>>0>C>>>0?d+1|0:d;c=u&-2097152;fa=b-c|0;ga=k-((b>>>0>>0)+h|0)|0;b=s&-2097152;R=e-b|0;C=r-((b>>>0>e>>>0)+n|0)|0;c=qe(P,x,654183,0);b=y&-2097152;d=c+(f-b|0)|0;b=$+(m-((b>>>0>f>>>0)+p|0)|0)|0;b=c>>>0>d>>>0?b+1|0:b;c=qe(Q,E,-997805,-1);e=c+d|0;d=$+b|0;d=c>>>0>e>>>0?d+1|0:d;b=qe(N,B,136657,0);e=b+e|0;c=$+d|0;y=e;h=b>>>0>e>>>0?c+1|0:c;b=X&-2097152;s=j-b|0;v=t-((b>>>0>j>>>0)+v|0)|0;b=qe(I,U,-683901,-1);d=G[a+35|0];c=d>>>24|0;f=G[a+34|0];e=f|d<<8;d=b;c=A>>>16|c;b=A<<16|e;b=((c&1)<<31|b>>>1)&2097151;d=d+b|0;c=$;c=b>>>0>d>>>0?c+1|0:c;b=qe(J,V,136657,0);e=b+d|0;d=$+c|0;d=b>>>0>e>>>0?d+1|0:d;b=qe(K,W,-997805,-1);e=b+e|0;c=$+d|0;c=b>>>0>e>>>0?c+1|0:c;d=qe(L,z,654183,0);e=d+e|0;b=$+c|0;m=e;e=d>>>0>e>>>0?b+1|0:b;n=qe(H,T,-683901,-1);b=G[a+32|0];d=b>>>24|0;p=G[a+31|0];j=p|b<<8;b=G[a+33|0];c=b>>>16|0;j=j|b<<16;d=c|d|f>>>8;b=f<<24|j;c=((d&15)<<28|b>>>4)&2097151;d=c+n|0;b=$;b=c>>>0>d>>>0?b+1|0:b;c=d;d=qe(I,U,136657,0);f=c+d|0;c=$+b|0;c=d>>>0>f>>>0?c+1|0:c;b=qe(J,V,-997805,-1);d=b+f|0;c=$+c|0;c=b>>>0>d>>>0?c+1|0:c;b=qe(K,W,654183,0);f=b+d|0;d=$+c|0;d=b>>>0>f>>>0?d+1|0:d;c=qe(L,z,470296,0);f=c+f|0;b=$+d|0;b=c>>>0>f>>>0?b+1|0:b;r=b;b=f;c=r-((b>>>0<4293918720)-1|0)|0;u=b- -1048576|0;n=c;b=(c&2097151)<<11|u>>>21;j=b+m|0;c=(c>>21)+e|0;e=j;c=b>>>0>e>>>0?c+1|0:c;j=c;b=e;m=c-((b>>>0<4293918720)-1|0)|0;k=b- -1048576|0;c=m;d=c>>21;m=(c&2097151)<<11|k>>>21;t=m+s|0;b=d+v|0;Z=t;b=m>>>0>t>>>0?b+1|0:b;s=b;d=qe(t,b,-683901,-1);m=d+y|0;b=$+h|0;b=d>>>0>m>>>0?b+1|0:b;h=b;b=k&-2097152;j=j-((b>>>0>e>>>0)+c|0)|0;O=e-b|0;A=j;b=qe(P,x,470296,0);c=Y&-2097152;d=b+(g-c|0)|0;c=$+(l-((q&2047)+(c>>>0>g>>>0)|0)|0)|0;c=b>>>0>d>>>0?c+1|0:c;b=d;d=qe(Q,E,654183,0);e=b+d|0;b=$+c|0;b=d>>>0>e>>>0?b+1|0:b;c=qe(N,B,-997805,-1);d=c+e|0;b=$+b|0;b=c>>>0>d>>>0?b+1|0:b;c=qe(t,s,136657,0);e=c+d|0;d=$+b|0;d=c>>>0>e>>>0?d+1|0:d;b=qe(O,j,-683901,-1);e=b+e|0;c=$+d|0;c=b>>>0>e>>>0?c+1|0:c;k=c;b=e;d=c-((b>>>0<4293918720)-1|0)|0;l=b- -1048576|0;j=d;b=(d&2097151)<<11|l>>>21;g=b+m|0;d=(d>>21)+h|0;d=b>>>0>g>>>0?d+1|0:d;b=g;h=d;g=d-((b>>>0<4293918720)-1|0)|0;c=g>>21;q=b- -1048576|0;d=(g&2097151)<<11|q>>>21;m=d+R|0;c=c+C|0;_=m;m=d>>>0>m>>>0?c+1|0:c;c=q&-2097152;aa=b-c|0;R=h-((b>>>0>>0)+g|0)|0;b=l&-2097152;y=e-b|0;v=k-((b>>>0>e>>>0)+j|0)|0;c=qe(P,x,666643,0);d=G[a+14|0];b=d>>>24|0;g=G[a+13|0];e=g|d<<8;d=w>>>16|b;b=w<<16|e;b=((d&1)<<31|b>>>1)&2097151;d=b+c|0;c=$;c=b>>>0>d>>>0?c+1|0:c;b=d;d=qe(Q,E,470296,0);e=b+d|0;b=$+c|0;b=d>>>0>e>>>0?b+1|0:b;c=qe(N,B,654183,0);d=c+e|0;b=$+b|0;l=d;e=c>>>0>d>>>0?b+1|0:b;b=u&-2097152;q=f-b|0;k=r-((b>>>0>f>>>0)+n|0)|0;j=qe(F,S,-683901,-1);b=G[a+29|0];c=b>>>24|0;d=ba|b<<8;b=c;f=d;d=G[a+30|0];c=d>>>16|0;f=f|d<<16;d=b|c|p>>>8;b=p<<24|f;b=((d&127)<<25|b>>>7)&2097151;c=b+j|0;d=$;d=b>>>0>c>>>0?d+1|0:d;b=c;c=qe(H,T,136657,0);f=b+c|0;b=$+d|0;b=c>>>0>f>>>0?b+1|0:b;d=qe(I,U,-997805,-1);f=d+f|0;c=$+b|0;c=d>>>0>f>>>0?c+1|0:c;b=qe(J,V,654183,0);d=b+f|0;c=$+c|0;c=b>>>0>d>>>0?c+1|0:c;b=d;d=qe(K,W,470296,0);f=b+d|0;b=$+c|0;b=d>>>0>f>>>0?b+1|0:b;c=qe(L,z,666643,0);f=c+f|0;d=$+b|0;d=c>>>0>f>>>0?d+1|0:d;c=i>>21;i=(i&2097151)<<11|ca>>>21;f=i+f|0;b=c+d|0;b=f>>>0>>0?b+1|0:b;r=b;b=f;d=r-((b>>>0<4293918720)-1|0)|0;u=b- -1048576|0;n=d;c=d>>21;d=(d&2097151)<<11|u>>>21;i=d+q|0;b=c+k|0;z=i;b=d>>>0>i>>>0?b+1|0:b;t=b;b=qe(i,b,-683901,-1);c=b+l|0;d=$+e|0;d=b>>>0>c>>>0?d+1|0:d;b=c;c=qe(Z,s,-997805,-1);i=b+c|0;b=$+d|0;b=c>>>0>i>>>0?b+1|0:b;d=qe(O,A,136657,0);i=d+i|0;c=$+b|0;p=i;i=d>>>0>i>>>0?c+1|0:c;c=qe(Q,E,666643,0);b=G[a+11|0];d=b>>>24|0;k=G[a+10|0];h=k|b<<8;e=G[a+12|0];b=e>>>16|0;e=h|e<<16;h=c;c=b|d|g>>>8;b=((c&15)<<28|(g<<24|e)>>>4)&2097151;d=h+b|0;c=$;c=b>>>0>d>>>0?c+1|0:c;b=d;d=qe(N,B,470296,0);e=b+d|0;b=$+c|0;b=d>>>0>e>>>0?b+1|0:b;c=qe(z,t,136657,0);d=c+e|0;b=$+b|0;b=c>>>0>d>>>0?b+1|0:b;c=qe(Z,s,654183,0);e=c+d|0;d=$+b|0;d=c>>>0>e>>>0?d+1|0:d;b=qe(O,A,-997805,-1);e=b+e|0;c=$+d|0;w=e;c=b>>>0>e>>>0?c+1|0:c;j=c;b=e;c=c-((b>>>0<4293918720)-1|0)|0;l=b- -1048576|0;h=c;d=c>>21;c=(c&2097151)<<11|l>>>21;e=c+p|0;b=d+i|0;b=c>>>0>e>>>0?b+1|0:b;i=b;b=e;c=i-((b>>>0<4293918720)-1|0)|0;q=b- -1048576|0;g=c;b=(c&2097151)<<11|q>>>21;p=b+y|0;c=(c>>21)+v|0;E=p;p=b>>>0>p>>>0?c+1|0:c;d=i;c=u&-2097152;b=f-c|0;f=r-((c>>>0>f>>>0)+n|0)|0;i=(M&2097151)<<11|da>>>21;n=i+b|0;b=(M>>21)+f|0;b=i>>>0>n>>>0?b+1|0:b;i=n;r=b;b=i;f=r-((b>>>0<4293918720)-1|0)|0;u=b- -1048576|0;n=f;c=f>>21;v=c;x=(f&2097151)<<11|u>>>21;c=qe(x,c,-683901,-1);e=c+e|0;b=$+d|0;b=c>>>0>e>>>0?b+1|0:b;d=e;c=q&-2097152;C=d-c|0;X=b-((c>>>0>d>>>0)+g|0)|0;c=qe(x,v,136657,0);d=c+w|0;b=$+j|0;b=c>>>0>d>>>0?b+1|0:b;c=l&-2097152;y=d-c|0;M=b-((c>>>0>d>>>0)+h|0)|0;h=qe(N,B,666643,0);c=G[a+8|0];b=c>>>24|0;e=G[a+7|0];f=e|c<<8;c=G[a+9|0];d=c>>>16|0;f=f|c<<16;c=b|d|k>>>8;c=((c&127)<<25|(k<<24|f)>>>7)&2097151;d=c+h|0;b=$;b=c>>>0>d>>>0?b+1|0:b;c=d;d=qe(z,t,-997805,-1);f=c+d|0;c=$+b|0;c=d>>>0>f>>>0?c+1|0:c;b=qe(Z,s,470296,0);f=b+f|0;d=$+c|0;d=b>>>0>f>>>0?d+1|0:d;c=qe(O,A,654183,0);f=c+f|0;b=$+d|0;j=f;d=c>>>0>f>>>0?b+1|0:b;b=qe(z,t,654183,0);f=G[a+6|0];c=f>>>24|0;h=G[a+5|0];f=h|f<<8;g=b;b=e>>>16|0;e=e<<16;c=b|c;b=e|f;b=((c&3)<<30|b>>>2)&2097151;e=g+b|0;c=$;c=b>>>0>e>>>0?c+1|0:c;b=e;e=qe(Z,s,666643,0);f=b+e|0;b=$+c|0;b=e>>>0>f>>>0?b+1|0:b;e=qe(O,A,470296,0);f=e+f|0;c=$+b|0;w=f;c=e>>>0>f>>>0?c+1|0:c;g=c;b=f;e=c-((b>>>0<4293918720)-1|0)|0;l=b- -1048576|0;f=e;b=e>>21;c=(e&2097151)<<11|l>>>21;e=c+j|0;b=b+d|0;q=e;b=c>>>0>e>>>0?b+1|0:b;d=b;b=e;k=d-((b>>>0<4293918720)-1|0)|0;j=b- -1048576|0;e=k;b=e>>21;k=(e&2097151)<<11|j>>>21;s=k+y|0;c=b+M|0;B=s;k=k>>>0>s>>>0?c+1|0:c;b=qe(x,v,-997805,-1);c=b+q|0;d=$+d|0;d=b>>>0>c>>>0?d+1|0:d;b=j&-2097152;Y=c-b|0;y=d-((b>>>0>c>>>0)+e|0)|0;b=qe(x,v,654183,0);d=b+w|0;c=$+g|0;c=b>>>0>d>>>0?c+1|0:c;b=l&-2097152;s=d-b|0;M=c-((b>>>0>d>>>0)+f|0)|0;j=qe(z,t,470296,0);b=G[a+3|0];c=b>>>24|0;f=G[a+2|0];e=f|b<<8;d=G[a+4|0];b=d>>>16|0;e=e|d<<16;c=b|c|h>>>8;b=((c&31)<<27|(h<<24|e)>>>5)&2097151;c=b+j|0;d=$;d=b>>>0>c>>>0?d+1|0:d;b=c;c=qe(O,A,666643,0);e=b+c|0;b=$+d|0;g=e;e=c>>>0>e>>>0?b+1|0:b;d=qe(z,t,666643,0);c=f<<16&2031616|(G[a|0]|G[a+1|0]<<8);d=d+c|0;b=$;b=c>>>0>d>>>0?b+1|0:b;j=b;b=d;f=j-((b>>>0<4293918720)-1|0)|0;w=b- -1048576|0;h=f;c=f>>21;f=(f&2097151)<<11|w>>>21;g=f+g|0;b=c+e|0;l=g;b=f>>>0>g>>>0?b+1|0:b;g=b;b=l;e=g-((b>>>0<4293918720)-1|0)|0;q=b- -1048576|0;f=e;c=e>>21;e=(e&2097151)<<11|q>>>21;t=e+s|0;b=c+M|0;b=e>>>0>t>>>0?b+1|0:b;e=b;b=qe(x,v,470296,0);l=b+l|0;c=$+g|0;c=b>>>0>l>>>0?c+1|0:c;g=q&-2097152;b=l-g|0;f=c-((g>>>0>l>>>0)+f|0)|0;l=b;c=qe(x,v,666643,0);b=w&-2097152;g=c+(d-b|0)|0;b=$+(j-((b>>>0>d>>>0)+h|0)|0)|0;h=g;d=g;b=c>>>0>d>>>0?b+1|0:b;c=b>>21;b=(b&2097151)<<11|d>>>21;d=l+b|0;c=c+f|0;c=b>>>0>d>>>0?c+1|0:c;f=d;b=c>>21;c=(c&2097151)<<11|d>>>21;d=c+t|0;b=b+e|0;b=c>>>0>d>>>0?b+1|0:b;g=d;c=b>>21;b=(b&2097151)<<11|d>>>21;e=b+Y|0;d=c+y|0;A=e;c=e;d=b>>>0>c>>>0?d+1|0:d;b=d>>21;d=(d&2097151)<<11|c>>>21;e=d+B|0;c=b+k|0;t=e;b=e;c=d>>>0>b>>>0?c+1|0:c;d=c>>21;c=(c&2097151)<<11|b>>>21;e=c+C|0;b=d+X|0;v=e;d=e;b=c>>>0>d>>>0?b+1|0:b;c=b>>21;b=(b&2097151)<<11|d>>>21;d=b+E|0;c=c+p|0;c=b>>>0>d>>>0?c+1|0:c;w=d;b=c>>21;c=(c&2097151)<<11|d>>>21;d=c+aa|0;b=b+R|0;b=c>>>0>d>>>0?b+1|0:b;l=d;c=b>>21;b=(b&2097151)<<11|d>>>21;e=b+_|0;d=c+m|0;q=e;c=e;d=b>>>0>c>>>0?d+1|0:d;b=d>>21;d=(d&2097151)<<11|c>>>21;e=d+fa|0;c=b+ga|0;m=e;b=e;c=d>>>0>b>>>0?c+1|0:c;d=c>>21;c=(c&2097151)<<11|b>>>21;e=c+ea|0;b=d+o|0;p=e;d=e;b=c>>>0>d>>>0?b+1|0:b;c=b>>21;e=(b&2097151)<<11|d>>>21;b=u&-2097152;d=i-b|0;e=e+d|0;b=(r-((b>>>0>i>>>0)+n|0)|0)+c|0;r=e;c=e;b=d>>>0>c>>>0?b+1|0:b;o=(b&2097151)<<11|c>>>21;d=b>>21;k=d;c=h&2097151;d=qe(o,d,666643,0)+c|0;b=$;j=d;b=c>>>0>d>>>0?b+1|0:b;i=b;D[a|0]=d;D[a+1|0]=(b&255)<<24|d>>>8;e=a;b=f&2097151;d=qe(o,k,470296,0)+b|0;c=$;c=b>>>0>d>>>0?c+1|0:c;h=d;b=i;d=b>>21;f=(b&2097151)<<11|j>>>21;h=h+f|0;b=c+d|0;b=f>>>0>h>>>0?b+1|0:b;d=h;D[e+4|0]=(b&2047)<<21|d>>>11;c=b;D[e+3|0]=(b&7)<<29|d>>>3;d=g&2097151;f=qe(o,k,654183,0)+d|0;b=$;b=d>>>0>f>>>0?b+1|0:b;d=f;f=(c&2097151)<<11|h>>>21;g=d+f|0;c=(c>>21)+b|0;c=f>>>0>g>>>0?c+1|0:c;b=c;D[e+6|0]=(b&63)<<26|g>>>6;f=0;h=h&2097151;c=h;D[e+2|0]=((i&65535)<<16|j>>>16)&31|c<<5;d=A&2097151;e=qe(o,k,-997805,-1)+d|0;c=$;c=d>>>0>e>>>0?c+1|0:c;d=e;e=(b&2097151)<<11|g>>>21;j=d+e|0;b=(b>>21)+c|0;b=e>>>0>j>>>0?b+1|0:b;d=j;D[a+9|0]=(b&511)<<23|d>>>9;c=b;D[a+8|0]=(b&1)<<31|d>>>1;e=0;g=g&2097151;d=g;D[a+5|0]=(f&524287)<<13|h>>>19|d<<2;b=t&2097151;f=qe(o,k,136657,0)+b|0;d=$;d=b>>>0>f>>>0?d+1|0:d;b=c>>21;c=(c&2097151)<<11|j>>>21;f=c+f|0;b=b+d|0;h=f;b=c>>>0>f>>>0?b+1|0:b;c=f;D[a+12|0]=(b&4095)<<20|c>>>12;d=b;D[a+11|0]=(b&15)<<28|c>>>4;f=0;n=j&2097151;c=n;D[a+7|0]=(e&16383)<<18|g>>>14|c<<7;b=v&2097151;e=qe(o,k,-683901,-1)+b|0;c=$;c=b>>>0>e>>>0?c+1|0:c;b=d>>21;d=(d&2097151)<<11|h>>>21;e=d+e|0;c=b+c|0;g=e;c=d>>>0>e>>>0?c+1|0:c;b=c;D[a+14|0]=(b&127)<<25|e>>>7;e=0;j=h&2097151;d=j;D[a+10|0]=(f&131071)<<15|n>>>17|d<<4;i=(b&2097151)<<11|g>>>21;h=i+(w&2097151)|0;b=b>>21;b=i>>>0>h>>>0?b+1|0:b;d=h;D[a+17|0]=(b&1023)<<22|d>>>10;c=b;D[a+16|0]=(b&3)<<30|d>>>2;i=0;k=g&2097151;d=k;D[a+13|0]=(e&1048575)<<12|j>>>20|d<<1;b=a;d=c;c=c>>21;e=(d&2097151)<<11|h>>>21;g=e+(l&2097151)|0;d=e>>>0>g>>>0?c+1|0:c;D[b+20|0]=(d&8191)<<19|g>>>13;e=d;D[b+19|0]=(d&31)<<27|g>>>5;j=h&2097151;c=j;D[b+15|0]=(i&32767)<<17|k>>>15|c<<6;d=b;b=e;c=b>>21;i=(b&2097151)<<11|g>>>21;k=i+(q&2097151)|0;b=c;b=i>>>0>k>>>0?b+1|0:b;i=b;D[d+21|0]=k;b=g;D[d+18|0]=(f&262143)<<14|j>>>18|b<<3;b=i;D[d+22|0]=(b&255)<<24|k>>>8;c=b;b=b>>21;c=(c&2097151)<<11|k>>>21;e=c+(m&2097151)|0;g=e;b=c>>>0>e>>>0?b+1|0:b;d=e;D[a+25|0]=(b&2047)<<21|d>>>11;D[a+24|0]=(b&7)<<29|d>>>3;e=a;c=b>>21;b=(b&2097151)<<11|d>>>21;h=b+(p&2097151)|0;f=h;d=b>>>0>f>>>0?c+1|0:c;b=d;D[e+27|0]=(b&63)<<26|f>>>6;e=0;h=g&2097151;c=h;D[a+23|0]=((i&65535)<<16|k>>>16)&31|c<<5;c=b>>21;b=(b&2097151)<<11|f>>>21;i=b+(r&2097151)|0;c=b>>>0>i>>>0?c+1|0:c;d=i;D[a+31|0]=(c&131071)<<15|d>>>17;b=c;D[a+30|0]=(b&511)<<23|d>>>9;D[a+29|0]=(b&1)<<31|d>>>1;c=0;f=f&2097151;D[a+26|0]=(e&524287)<<13|h>>>19|f<<2;D[a+28|0]=(c&16383)<<18|f>>>14|d<<7}function tc(a,b,c,d,e,f,g,h,i){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;var j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0;k=_-160|0;_=k;l=-1;if(!(e>>>0<8|g>>>0>i>>>0)){i=F[a+4>>2];j=F[a+8>>2];a=k+80|0;Aa(b,c,0,0,i,j,a,80);b=F[k+108>>2];F[k+24>>2]=F[k+104>>2];F[k+28>>2]=b;b=F[k+100>>2];F[k+16>>2]=F[k+96>>2];F[k+20>>2]=b;b=F[k+92>>2];F[k+8>>2]=F[k+88>>2];F[k+12>>2]=b;b=F[k+124>>2];F[k+40>>2]=F[k+120>>2];F[k+44>>2]=b;b=F[k+132>>2];F[k+48>>2]=F[k+128>>2];F[k+52>>2]=b;b=F[k+140>>2];F[k+56>>2]=F[k+136>>2];F[k+60>>2]=b;b=F[k+156>>2];F[k+72>>2]=F[k+152>>2];F[k+76>>2]=b;b=F[k+84>>2];F[k>>2]=F[k+80>>2];F[k+4>>2]=b;b=F[k+116>>2];F[k+32>>2]=F[k+112>>2];F[k+36>>2]=b;b=F[k+148>>2];F[k+64>>2]=F[k+144>>2];F[k+68>>2]=b;ia(a,80);ka(k+32|0,32,d,e-8|0,a);if(La((d+e|0)-8|0,a,8)){b=_-272|0;_=b;Kb(k,b+32|0);a=k- -64|0;c=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);F[b+16>>2]=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);F[b+20>>2]=c;c=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);F[b+24>>2]=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);F[b+28>>2]=c;if(g){e=0;while(1){c=e+f|0;a=G[c+4|0]|G[c+5|0]<<8|(G[c+6|0]<<16|G[c+7|0]<<24);F[b>>2]=G[c|0]|G[c+1|0]<<8|(G[c+2|0]<<16|G[c+3|0]<<24);F[b+4>>2]=a;a=G[c+12|0]|G[c+13|0]<<8|(G[c+14|0]<<16|G[c+15|0]<<24);F[b+8>>2]=G[c+8|0]|G[c+9|0]<<8|(G[c+10|0]<<16|G[c+11|0]<<24);F[b+12>>2]=a;a=_-16|0;_=a;n=G[c+15|0];o=G[c+14|0];p=G[c+13|0];q=G[c+12|0];s=G[c+11|0];r=G[c+10|0];t=G[c+9|0];u=G[c+8|0];m=G[c+6|0];v=G[c+5|0];w=G[c+4|0];x=G[c+3|0];y=G[c+2|0];z=G[c+1|0];A=G[c|0];d=F[b+256>>2];i=F[b+268>>2];l=F[b+264>>2];j=F[b+240>>2];B=G[c+7|0];c=F[b+260>>2];D[a+12|0]=j^G[((B^c)&255)+34128|0];D[a+8|0]=G[((r^l>>>8)&255)+34128|0]^j>>>8;D[a+4|0]=G[((p^i>>>16)&255)+34128|0]^j>>>16;D[a|0]=G[(A^d>>>24)+34128|0]^j>>>24;j=F[b+244>>2];D[a+13|0]=j^G[((l^s)&255)+34128|0];D[a+9|0]=G[((o^i>>>8)&255)+34128|0]^j>>>8;D[a+5|0]=G[((z^d>>>16)&255)+34128|0]^j>>>16;D[a+1|0]=G[(w^c>>>24)+34128|0]^j>>>24;j=F[b+248>>2];D[a+14|0]=j^G[((i^n)&255)+34128|0];D[a+10|0]=G[((y^d>>>8)&255)+34128|0]^j>>>8;D[a+6|0]=G[((v^c>>>16)&255)+34128|0]^j>>>16;D[a+2|0]=G[(u^l>>>24)+34128|0]^j>>>24;j=G[((d^x)&255)+34128|0];d=F[b+252>>2];D[a+15|0]=j^d;D[a+11|0]=G[((m^c>>>8)&255)+34128|0]^d>>>8;D[a+7|0]=G[((t^l>>>16)&255)+34128|0]^d>>>16;D[a+3|0]=G[(q^i>>>24)+34128|0]^d>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+224>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+228>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+232>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+236>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+2|0];i=G[a+1|0];l=G[a|0];j=G[a+14|0];n=G[a+12|0];o=G[a+15|0];p=G[a+8|0];q=G[a+10|0];s=G[a+9|0];r=G[a+11|0];t=G[a+4|0];u=G[a+5|0];m=G[a+6|0];v=G[a+7|0];w=G[a+3|0];c=F[b+208>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[q+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[l+34128|0]^c>>>24;c=F[b+212>>2];D[a+13|0]=c^G[j+34128|0];D[a+9|0]=G[r+34128|0]^c>>>8;D[a+5|0]=G[t+34128|0]^c>>>16;D[a+1|0]=G[i+34128|0]^c>>>24;c=F[b+216>>2];D[a+14|0]=c^G[o+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[u+34128|0]^c>>>16;D[a+2|0]=G[d+34128|0]^c>>>24;c=F[b+220>>2];D[a+15|0]=c^G[n+34128|0];D[a+11|0]=G[s+34128|0]^c>>>8;D[a+7|0]=G[m+34128|0]^c>>>16;D[a+3|0]=G[w+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+192>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+196>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+200>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+204>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+2|0];i=G[a+1|0];l=G[a|0];j=G[a+14|0];n=G[a+12|0];o=G[a+15|0];p=G[a+8|0];q=G[a+10|0];s=G[a+9|0];r=G[a+11|0];t=G[a+4|0];u=G[a+5|0];m=G[a+6|0];v=G[a+7|0];w=G[a+3|0];c=F[b+176>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[q+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[l+34128|0]^c>>>24;c=F[b+180>>2];D[a+13|0]=c^G[j+34128|0];D[a+9|0]=G[r+34128|0]^c>>>8;D[a+5|0]=G[t+34128|0]^c>>>16;D[a+1|0]=G[i+34128|0]^c>>>24;c=F[b+184>>2];D[a+14|0]=c^G[o+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[u+34128|0]^c>>>16;D[a+2|0]=G[d+34128|0]^c>>>24;c=F[b+188>>2];D[a+15|0]=c^G[n+34128|0];D[a+11|0]=G[s+34128|0]^c>>>8;D[a+7|0]=G[m+34128|0]^c>>>16;D[a+3|0]=G[w+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+160>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+164>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+168>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+172>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+144>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+148>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+152>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+156>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+128>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+132>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+136>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+140>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+112>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+116>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+120>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+124>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+96>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+100>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+104>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+108>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+80>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+84>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+88>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+92>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+3|0];i=G[a+6|0];l=G[a+9|0];j=G[a+12|0];n=G[a+2|0];o=G[a+5|0];p=G[a+8|0];q=G[a+15|0];s=G[a+1|0];r=G[a+4|0];t=G[a+11|0];u=G[a+14|0];m=G[a|0];v=G[a+7|0];w=G[a+10|0];c=F[b+64>>2];D[a+12|0]=c^G[G[a+13|0]+34128|0];D[a+8|0]=G[w+34128|0]^c>>>8;D[a+4|0]=G[v+34128|0]^c>>>16;D[a|0]=G[m+34128|0]^c>>>24;c=F[b+68>>2];D[a+13|0]=c^G[u+34128|0];D[a+9|0]=G[t+34128|0]^c>>>8;D[a+5|0]=G[r+34128|0]^c>>>16;D[a+1|0]=G[s+34128|0]^c>>>24;c=F[b+72>>2];D[a+14|0]=c^G[q+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=G[o+34128|0]^c>>>16;D[a+2|0]=G[n+34128|0]^c>>>24;c=F[b+76>>2];D[a+15|0]=c^G[j+34128|0];D[a+11|0]=G[l+34128|0]^c>>>8;D[a+7|0]=G[i+34128|0]^c>>>16;D[a+3|0]=G[d+34128|0]^c>>>24;xa(a);d=G[a+15|0];i=G[a+12|0];D[a+15|0]=i;l=G[G[a+2|0]+34128|0];D[a+2|0]=l;j=G[G[a+1|0]+34128|0];D[a+1|0]=j;n=G[G[a|0]+34128|0];D[a|0]=n;o=G[a+9|0];p=G[a+8|0];q=G[a+4|0];s=G[a+11|0];r=G[a+14|0];t=G[a+7|0];u=G[a+10|0];c=G[a+13|0];m=G[a+5|0];v=G[a+3|0];D[a+7|0]=G[G[a+6|0]+34128|0];D[a+6|0]=G[m+34128|0];D[a+3|0]=G[v+34128|0];m=G[c+34128|0];c=F[b+48>>2];D[a+12|0]=m^c;D[a+8|0]=G[u+34128|0]^c>>>8;D[a+4|0]=G[t+34128|0]^c>>>16;D[a|0]=n^c>>>24;c=F[b+52>>2];D[a+13|0]=c^G[r+34128|0];D[a+1|0]=j^c>>>24;D[a+9|0]=G[s+34128|0]^c>>>8;D[a+5|0]=G[q+34128|0]^c>>>16;c=F[b+56>>2];D[a+2|0]=l^c>>>24;l=G[a+6|0];D[a+14|0]=c^G[d+34128|0];D[a+10|0]=G[p+34128|0]^c>>>8;D[a+6|0]=l^c>>>16;c=F[b+60>>2];D[a+3|0]=G[a+3|0]^c>>>24;d=G[a+7|0];D[a+15|0]=c^G[i+34128|0];D[a+11|0]=G[o+34128|0]^c>>>8;D[a+7|0]=d^c>>>16;xa(a);n=G[a+15|0];j=G[a+12|0];D[a+15|0]=j;o=G[G[a+1|0]+34128|0];D[a+1|0]=o;p=G[G[a+2|0]+34128|0];D[a+2|0]=p;q=G[G[a+3|0]+34128|0];D[a+3|0]=q;s=G[a+7|0];r=G[G[a+6|0]+34128|0];D[a+7|0]=r;d=F[b+32>>2];i=F[b+36>>2];l=F[b+40>>2];t=G[a|0];u=G[a+10|0];m=G[a+4|0];v=G[a+11|0];w=G[a+5|0];x=G[a+8|0];y=G[a+9|0];z=G[a+13|0];A=G[a+14|0];c=e+h|0;B=G[j+34128|0];j=F[b+44>>2];D[c+15|0]=B^j;D[c+11|0]=l^G[n+34128|0];D[c+7|0]=i^G[A+34128|0];D[c+3|0]=d^G[z+34128|0];D[c+14|0]=G[y+34128|0]^j>>>8;D[c+13|0]=r^j>>>16;D[c+12|0]=q^j>>>24;D[c+10|0]=G[x+34128|0]^l>>>8;D[c+9|0]=G[w+34128|0]^l>>>16;D[c+8|0]=p^l>>>24;D[c+6|0]=G[v+34128|0]^i>>>8;D[c+5|0]=G[m+34128|0]^i>>>16;D[c+4|0]=o^i>>>24;D[c+2|0]=G[u+34128|0]^d>>>8;D[c+1|0]=G[s+34128|0]^d>>>16;D[c|0]=G[t+34128|0]^d>>>24;_=a+16|0;D[c|0]=G[c|0]^G[b+16|0];D[c+1|0]=G[c+1|0]^G[b+17|0];D[c+2|0]=G[c+2|0]^G[b+18|0];D[c+3|0]=G[c+3|0]^G[b+19|0];D[c+4|0]=G[c+4|0]^G[b+20|0];D[c+5|0]=G[c+5|0]^G[b+21|0];D[c+6|0]=G[c+6|0]^G[b+22|0];D[c+7|0]=G[c+7|0]^G[b+23|0];D[c+8|0]=G[c+8|0]^G[b+24|0];D[c+9|0]=G[c+9|0]^G[b+25|0];D[c+10|0]=G[c+10|0]^G[b+26|0];D[c+11|0]=G[c+11|0]^G[b+27|0];D[c+12|0]=G[c+12|0]^G[b+28|0];D[c+13|0]=G[c+13|0]^G[b+29|0];D[c+14|0]=G[c+14|0]^G[b+30|0];D[c+15|0]=G[c+15|0]^G[b+31|0];a=F[b+12>>2];F[b+24>>2]=F[b+8>>2];F[b+28>>2]=a;a=F[b+4>>2];F[b+16>>2]=F[b>>2];F[b+20>>2]=a;e=e+16|0;if(g>>>0>e>>>0){continue}break}}ia(b+32|0,240);ia(b+16|0,16);ia(b,16);_=b+272|0;a=G[(g+h|0)-1|0];l=a>>>0>g>>>0?-1:g-a|0}ia(k,80)}_=k+160|0;return l|0}function Lb(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0;d=_-16|0;_=d;h=G[a+14|0];k=G[a+6|0];l=G[a+5|0];s=G[a+9|0];q=G[a+13|0];m=G[a+1|0];n=G[a+10|0];i=G[a+2|0];j=G[a+3|0];o=G[a+7|0];p=G[a+15|0];r=G[a+11|0];u=G[a|0];f=F[c>>2];v=G[a+4|0];e=F[c+4>>2];t=G[a+8|0];g=F[c+8>>2];w=G[a+12|0];a=F[c+12>>2];D[d+3|0]=G[(w^a>>>24)+33808|0];D[d+2|0]=G[(t^g>>>24)+33808|0];D[d+1|0]=G[(v^e>>>24)+33808|0];D[d|0]=G[(u^f>>>24)+33808|0];D[d+15|0]=G[((g^r)&255)+33808|0];D[d+12|0]=G[((a^p)&255)+33808|0];D[d+14|0]=G[((e^o)&255)+33808|0];D[d+13|0]=G[((f^j)&255)+33808|0];D[d+10|0]=G[(i^f>>>8&255)+33808|0];D[d+8|0]=G[(n^g>>>8&255)+33808|0];D[d+7|0]=G[(m^f>>>16&255)+33808|0];D[d+6|0]=G[(q^a>>>16&255)+33808|0];D[d+5|0]=G[(s^g>>>16&255)+33808|0];D[d+4|0]=G[(l^e>>>16&255)+33808|0];D[d+11|0]=G[(k^e>>>8&255)+33808|0];D[d+9|0]=G[(h^a>>>8&255)+33808|0];ya(d);a=F[c+16>>2];f=F[c+20>>2];e=F[c+24>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+28>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+32>>2];f=F[c+36>>2];e=F[c+40>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+44>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+48>>2];f=F[c+52>>2];e=F[c+56>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+60>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+64>>2];f=F[c+68>>2];e=F[c+72>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+76>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+80>>2];f=F[c+84>>2];e=F[c+88>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+92>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+96>>2];f=F[c+100>>2];e=F[c+104>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+108>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+112>>2];f=F[c+116>>2];e=F[c+120>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+124>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+128>>2];f=F[c+132>>2];e=F[c+136>>2];h=G[d+11|0];k=G[d+9|0];l=G[d+5|0];s=G[d+6|0];q=G[d+7|0];m=G[d+4|0];n=G[d+10|0];i=G[d+8|0];j=G[d+12|0];o=G[d+13|0];p=G[d+15|0];r=G[d+14|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+140>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];D[d+15|0]=G[((e^r)&255)+33808|0];D[d+12|0]=G[((g^p)&255)+33808|0];D[d+14|0]=G[((f^o)&255)+33808|0];D[d+13|0]=G[((a^j)&255)+33808|0];D[d+10|0]=G[(i^a>>>8&255)+33808|0];D[d+8|0]=G[(n^e>>>8&255)+33808|0];D[d+7|0]=G[(m^a>>>16&255)+33808|0];D[d+6|0]=G[(q^g>>>16&255)+33808|0];D[d+5|0]=G[(s^e>>>16&255)+33808|0];D[d+4|0]=G[(l^f>>>16&255)+33808|0];D[d+11|0]=G[(k^f>>>8&255)+33808|0];D[d+9|0]=G[(h^g>>>8&255)+33808|0];ya(d);a=F[c+156>>2];h=a^G[d+15|0];f=F[c+152>>2];k=f^G[d+14|0];e=F[c+148>>2];l=e^G[d+13|0];g=F[c+144>>2];s=g^G[d+12|0];q=G[d+11|0]^a>>>8;m=G[d+7|0]^a>>>16;a=G[d+3|0]^a>>>24;n=G[d+10|0]^f>>>8;i=G[d+6|0]^f>>>16;f=G[d+2|0]^f>>>24;j=G[d+9|0]^e>>>8;o=G[d+5|0]^e>>>16;e=G[d+1|0]^e>>>24;p=G[d+8|0]^g>>>8;r=G[d+4|0]^g>>>16;D[d|0]=G[(G[d|0]^g>>>24)+33808|0];D[d+10|0]=G[(p&255)+33808|0];D[d+8|0]=G[(n&255)+33808|0];D[d+7|0]=G[(r&255)+33808|0];D[d+6|0]=G[(m&255)+33808|0];D[d+5|0]=G[(i&255)+33808|0];D[d+4|0]=G[(o&255)+33808|0];D[d+3|0]=G[a+33808|0];D[d+2|0]=G[f+33808|0];D[d+1|0]=G[e+33808|0];D[d+15|0]=G[(k&255)+33808|0];D[d+12|0]=G[(h&255)+33808|0];D[d+11|0]=G[(j&255)+33808|0];D[d+9|0]=G[(q&255)+33808|0];D[d+14|0]=G[(l&255)+33808|0];D[d+13|0]=G[(s&255)+33808|0];ya(d);f=F[c+160>>2];D[d+12|0]=f^G[d+12|0];D[d+8|0]=G[d+8|0]^f>>>8;e=F[c+164>>2];h=e^G[d+13|0];D[d+13|0]=h;k=G[d+9|0]^e>>>8;D[d+9|0]=k;g=F[c+168>>2];l=g^G[d+14|0];D[d+14|0]=l;a=F[c+172>>2];D[d+1|0]=G[(G[d+1|0]^e>>>24)+33808|0];D[d|0]=G[(G[d|0]^f>>>24)+33808|0];D[d+2|0]=G[(G[d+2|0]^g>>>24)+33808|0];s=G[d+5|0];q=G[d+6|0];m=G[d+4|0];n=G[d+10|0];D[d+3|0]=G[(G[d+3|0]^a>>>24)+33808|0];D[d+6|0]=G[(G[d+7|0]^a>>>16&255)+33808|0];i=G[d+11|0];j=G[d+15|0];o=G[d+12|0];p=G[d+8|0];D[d+8|0]=G[(n^g>>>8&255)+33808|0];D[d+7|0]=G[(m^f>>>16&255)+33808|0];D[d+5|0]=G[(q^g>>>16&255)+33808|0];D[d+4|0]=G[(s^e>>>16&255)+33808|0];D[d+10|0]=G[p+33808|0];D[d+15|0]=G[(l&255)+33808|0];D[d+12|0]=G[((a^j)&255)+33808|0];D[d+11|0]=G[(k&255)+33808|0];D[d+9|0]=G[(i^a>>>8&255)+33808|0];D[d+14|0]=G[(h&255)+33808|0];D[d+13|0]=G[o+33808|0];ya(d);a=F[c+176>>2];f=F[c+180>>2];e=F[c+184>>2];h=G[d+4|0];k=G[d+5|0];l=G[d+6|0];s=G[d+7|0];q=G[d+8|0];m=G[d+9|0];n=G[d+10|0];i=G[d+11|0];j=G[d+12|0];o=G[d+13|0];p=G[d+14|0];r=G[d+15|0];u=G[d|0];v=G[d+1|0];t=G[d+2|0];g=F[c+188>>2];D[d+3|0]=G[(G[d+3|0]^g>>>24)+33808|0];D[d+2|0]=G[(t^e>>>24)+33808|0];D[d+1|0]=G[(v^f>>>24)+33808|0];D[d|0]=G[(u^a>>>24)+33808|0];r=G[((g^r)&255)+33808|0];p=G[((e^p)&255)+33808|0];o=G[((f^o)&255)+33808|0];j=G[((a^j)&255)+33808|0];i=G[(i^g>>>8&255)+33808|0];n=G[(n^e>>>8&255)+33808|0];m=G[(m^f>>>8&255)+33808|0];g=G[(s^g>>>16&255)+33808|0];e=G[(l^e>>>16&255)+33808|0];f=G[(k^f>>>16&255)+33808|0];h=G[(h^a>>>16&255)+33808|0];D[d+10|0]=G[(q^a>>>8&255)+33808|0];D[d+8|0]=n;D[d+7|0]=h;D[d+6|0]=g;D[d+5|0]=e;D[d+4|0]=f;D[d+15|0]=p;D[d+12|0]=r;D[d+11|0]=m;D[d+9|0]=i;D[d+14|0]=o;D[d+13|0]=j;ya(d);f=F[c+192>>2];D[d+12|0]=f^G[d+12|0];D[d+8|0]=G[d+8|0]^f>>>8;e=F[c+196>>2];h=e^G[d+13|0];D[d+13|0]=h;k=G[d+9|0]^e>>>8;D[d+9|0]=k;g=F[c+200>>2];l=g^G[d+14|0];D[d+14|0]=l;a=F[c+204>>2];D[d+1|0]=G[(G[d+1|0]^e>>>24)+33808|0];D[d|0]=G[(G[d|0]^f>>>24)+33808|0];D[d+2|0]=G[(G[d+2|0]^g>>>24)+33808|0];s=G[d+5|0];q=G[d+6|0];m=G[d+4|0];n=G[d+10|0];D[d+3|0]=G[(G[d+3|0]^a>>>24)+33808|0];i=G[d+11|0];j=G[d+15|0];o=G[d+7|0];p=G[d+12|0];r=G[d+8|0];D[d+8|0]=G[(n^g>>>8&255)+33808|0];D[d+7|0]=G[(m^f>>>16&255)+33808|0];D[d+6|0]=G[(o^a>>>16&255)+33808|0];D[d+5|0]=G[(q^g>>>16&255)+33808|0];D[d+4|0]=G[(s^e>>>16&255)+33808|0];D[d+10|0]=G[r+33808|0];D[d+15|0]=G[(l&255)+33808|0];D[d+12|0]=G[((a^j)&255)+33808|0];D[d+11|0]=G[(k&255)+33808|0];D[d+9|0]=G[(i^a>>>8&255)+33808|0];D[d+14|0]=G[(h&255)+33808|0];D[d+13|0]=G[p+33808|0];ya(d);f=F[c+208>>2];D[d+12|0]=f^G[d+12|0];D[d+8|0]=G[d+8|0]^f>>>8;e=F[c+212>>2];k=e^G[d+13|0];D[d+13|0]=k;h=G[d+9|0]^e>>>8;D[d+9|0]=h;g=F[c+216>>2];l=g^G[d+14|0];D[d+14|0]=l;a=F[c+220>>2];D[d+2|0]=G[(G[d+2|0]^g>>>24)+33808|0];s=G[d+4|0];q=G[d+6|0];m=G[d+5|0];n=G[d+10|0];i=G[d|0];j=G[d+1|0];D[d+3|0]=G[(G[d+3|0]^a>>>24)+33808|0];j=G[(j^e>>>24)+33808|0];D[d+1|0]=j;i=G[(i^f>>>24)+33808|0];D[d|0]=i;o=G[d+7|0];p=G[d+11|0];r=G[d+15|0];u=G[d+8|0];v=G[d+12|0];l=G[(l&255)+33808|0];D[d+15|0]=l;t=G[(h&255)+33808|0];D[d+11|0]=t;h=F[c+224>>2];r=h^G[((a^r)&255)+33808|0];D[d+12|0]=r;n=G[(n^g>>>8&255)+33808|0]^h>>>8;D[d+8|0]=n;m=G[(m^e>>>16&255)+33808|0]^h>>>16;D[d+4|0]=m;h=i^h>>>24;D[d|0]=h;e=F[c+228>>2];i=e^G[v+33808|0];D[d+13|0]=i;p=G[(p^a>>>8&255)+33808|0]^e>>>8;D[d+9|0]=p;g=G[(q^g>>>16&255)+33808|0]^e>>>16;D[d+5|0]=g;q=j^e>>>24;D[d+1|0]=q;e=F[c+232>>2];k=e^G[(k&255)+33808|0];D[d+14|0]=k;j=G[u+33808|0]^e>>>8;D[d+10|0]=j;o=G[(o^a>>>16&255)+33808|0]^e>>>16;D[d+6|0]=o;e=G[d+2|0]^e>>>24;D[d+2|0]=e;a=F[c+236>>2];c=G[(s^f>>>16&255)+33808|0]^a>>>16;D[d+7|0]=c;f=G[d+3|0]^a>>>24;D[d+3|0]=f;D[b+13|0]=c;D[b+12|0]=f;D[b+11|0]=k;D[b+10|0]=j;D[b+9|0]=o;D[b+8|0]=e;D[b+7|0]=i;D[b+6|0]=p;D[b+5|0]=g;D[b+4|0]=q;D[b+3|0]=r;D[b+2|0]=n;D[b+1|0]=m;D[b|0]=h;D[b+15|0]=a^l;D[b+14|0]=t^a>>>8;_=d+16|0}function Yc(a){a=a|0;var b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;l=_-16|0;_=l;a:{b:{c:{d:{e:{f:{g:{h:{i:{j:{k:{if(a>>>0<=244){e=F[9456];h=a>>>0<11?16:a+11&-8;c=h>>>3|0;b=e>>>c|0;if(b&3){d=c+((b^-1)&1)|0;b=d<<3;f=F[b+37872>>2];a=f+8|0;c=F[f+8>>2];b=b+37864|0;l:{if((c|0)==(b|0)){F[9456]=se(-2,d)&e;break l}F[c+12>>2]=b;F[b+8>>2]=c}b=d<<3;F[f+4>>2]=b|3;b=b+f|0;F[b+4>>2]=F[b+4>>2]|1;break a}k=F[9458];if(k>>>0>=h>>>0){break k}if(b){a=2<>>12&16;c=a;b=b>>>a|0;a=b>>>5&8;c=c|a;b=b>>>a|0;a=b>>>2&4;c=c|a;b=b>>>a|0;a=b>>>1&2;c=c|a;b=b>>>a|0;a=b>>>1&1;c=(c|a)+(b>>>a|0)|0;a=c<<3;g=F[a+37872>>2];b=F[g+8>>2];a=a+37864|0;m:{if((b|0)==(a|0)){e=se(-2,c)&e;F[9456]=e;break m}F[b+12>>2]=a;F[a+8>>2]=b}a=g+8|0;F[g+4>>2]=h|3;d=g+h|0;b=c<<3;f=b-h|0;F[d+4>>2]=f|1;F[b+g>>2]=f;if(k){b=k>>>3|0;c=(b<<3)+37864|0;g=F[9461];b=1<>2]}F[c+8>>2]=g;F[b+12>>2]=g;F[g+12>>2]=c;F[g+8>>2]=b}F[9461]=d;F[9458]=f;break a}j=F[9457];if(!j){break k}b=(j&0-j)-1|0;a=b>>>12&16;c=a;b=b>>>a|0;a=b>>>5&8;c=c|a;b=b>>>a|0;a=b>>>2&4;c=c|a;b=b>>>a|0;a=b>>>1&2;c=c|a;b=b>>>a|0;a=b>>>1&1;b=F[((c|a)+(b>>>a|0)<<2)+38128>>2];d=(F[b+4>>2]&-8)-h|0;c=b;while(1){o:{a=F[c+16>>2];if(!a){a=F[c+20>>2];if(!a){break o}}c=(F[a+4>>2]&-8)-h|0;f=c>>>0>>0;d=f?c:d;b=f?a:b;c=a;continue}break}i=F[b+24>>2];f=F[b+12>>2];if((f|0)!=(b|0)){a=F[b+8>>2];F[a+12>>2]=f;F[f+8>>2]=a;break b}c=b+20|0;a=F[c>>2];if(!a){a=F[b+16>>2];if(!a){break j}c=b+16|0}while(1){g=c;f=a;c=a+20|0;a=F[c>>2];if(a){continue}c=f+16|0;a=F[f+16>>2];if(a){continue}break}F[g>>2]=0;break b}h=-1;if(a>>>0>4294967231){break k}a=a+11|0;h=a&-8;j=F[9457];if(!j){break k}d=0-h|0;e=0;p:{if(h>>>0<256){break p}e=31;if(h>>>0>16777215){break p}a=a>>>8|0;g=a+1048320>>>16&8;a=a<>>16&4;a=a<>>16&2;a=(a<>>15|0)-(b|(c|g))|0;e=(a<<1|h>>>a+21&1)+28|0}c=F[(e<<2)+38128>>2];q:{r:{s:{if(!c){a=0;break s}a=0;b=h<<((e|0)==31?0:25-(e>>>1|0)|0);while(1){t:{g=(F[c+4>>2]&-8)-h|0;if(g>>>0>=d>>>0){break t}f=c;d=g;if(d){break t}d=0;a=c;break r}g=F[c+20>>2];c=F[((b>>>29&4)+c|0)+16>>2];a=g?(g|0)==(c|0)?a:g:a;b=b<<1;if(c){continue}break}}if(!(a|f)){f=0;a=2<>>12&16;c=a;b=b>>>a|0;a=b>>>5&8;c=c|a;b=b>>>a|0;a=b>>>2&4;c=c|a;b=b>>>a|0;a=b>>>1&2;c=c|a;b=b>>>a|0;a=b>>>1&1;a=F[((c|a)+(b>>>a|0)<<2)+38128>>2]}if(!a){break q}}while(1){b=(F[a+4>>2]&-8)-h|0;c=b>>>0>>0;d=c?b:d;f=c?a:f;b=F[a+16>>2];if(b){a=b}else{a=F[a+20>>2]}if(a){continue}break}}if(!f|F[9458]-h>>>0<=d>>>0){break k}e=F[f+24>>2];b=F[f+12>>2];if((f|0)!=(b|0)){a=F[f+8>>2];F[a+12>>2]=b;F[b+8>>2]=a;break c}c=f+20|0;a=F[c>>2];if(!a){a=F[f+16>>2];if(!a){break i}c=f+16|0}while(1){g=c;b=a;c=a+20|0;a=F[c>>2];if(a){continue}c=b+16|0;a=F[b+16>>2];if(a){continue}break}F[g>>2]=0;break c}c=F[9458];if(c>>>0>=h>>>0){d=F[9461];b=c-h|0;u:{if(b>>>0>=16){F[9458]=b;a=d+h|0;F[9461]=a;F[a+4>>2]=b|1;F[c+d>>2]=b;F[d+4>>2]=h|3;break u}F[9461]=0;F[9458]=0;F[d+4>>2]=c|3;a=c+d|0;F[a+4>>2]=F[a+4>>2]|1}a=d+8|0;break a}i=F[9459];if(i>>>0>h>>>0){b=i-h|0;F[9459]=b;c=F[9462];a=c+h|0;F[9462]=a;F[a+4>>2]=b|1;F[c+4>>2]=h|3;a=c+8|0;break a}a=0;j=h+47|0;b=j;if(F[9574]){c=F[9576]}else{F[9577]=-1;F[9578]=-1;F[9575]=4096;F[9576]=4096;F[9574]=l+12&-16^1431655768;F[9579]=0;F[9567]=0;c=4096}g=b+c|0;f=0-c|0;c=g&f;if(c>>>0<=h>>>0){break a}d=F[9566];if(d){b=F[9564];e=b+c|0;if(d>>>0>>0|b>>>0>=e>>>0){break a}}if(G[38268]&4){break f}v:{w:{d=F[9462];if(d){a=38272;while(1){b=F[a>>2];if(d>>>0>2]>>>0?b>>>0<=d>>>0:0){break w}a=F[a+8>>2];if(a){continue}break}}b=Ia(0);if((b|0)==-1){break g}e=c;d=F[9575];a=d-1|0;if(a&b){e=(c-b|0)+(a+b&0-d)|0}if(e>>>0<=h>>>0|e>>>0>2147483646){break g}d=F[9566];if(d){a=F[9564];f=a+e|0;if(d>>>0>>0|a>>>0>=f>>>0){break g}}a=Ia(e);if((b|0)!=(a|0)){break v}break e}e=f&g-i;if(e>>>0>2147483646){break g}b=Ia(e);if((b|0)==(F[a>>2]+F[a+4>>2]|0)){break h}a=b}if(!((a|0)==-1|h+48>>>0<=e>>>0)){b=F[9576];b=b+(j-e|0)&0-b;if(b>>>0>2147483646){b=a;break e}if((Ia(b)|0)!=-1){e=b+e|0;b=a;break e}Ia(0-e|0);break g}b=a;if((a|0)!=-1){break e}break g}f=0;break b}b=0;break c}if((b|0)!=-1){break e}}F[9567]=F[9567]|4}if(c>>>0>2147483646){break d}b=Ia(c);a=Ia(0);if((b|0)==-1|(a|0)==-1|a>>>0<=b>>>0){break d}e=a-b|0;if(e>>>0<=h+40>>>0){break d}}a=F[9564]+e|0;F[9564]=a;if(a>>>0>I[9565]){F[9565]=a}x:{y:{z:{g=F[9462];if(g){a=38272;while(1){d=F[a>>2];c=F[a+4>>2];if((d+c|0)==(b|0)){break z}a=F[a+8>>2];if(a){continue}break}break y}a=F[9460];if(!(a>>>0<=b>>>0?a:0)){F[9460]=b}a=0;F[9569]=e;F[9568]=b;F[9464]=-1;F[9465]=F[9574];F[9571]=0;while(1){d=a<<3;c=d+37864|0;F[d+37872>>2]=c;F[d+37876>>2]=c;a=a+1|0;if((a|0)!=32){continue}break}d=e-40|0;a=b+8&7?-8-b&7:0;c=d-a|0;F[9459]=c;a=a+b|0;F[9462]=a;F[a+4>>2]=c|1;F[(b+d|0)+4>>2]=40;F[9463]=F[9578];break x}if(G[a+12|0]&8|d>>>0>g>>>0|b>>>0<=g>>>0){break y}F[a+4>>2]=c+e;a=g+8&7?-8-g&7:0;c=a+g|0;F[9462]=c;b=F[9459]+e|0;a=b-a|0;F[9459]=a;F[c+4>>2]=a|1;F[(b+g|0)+4>>2]=40;F[9463]=F[9578];break x}if(I[9460]>b>>>0){F[9460]=b}c=b+e|0;a=38272;A:{B:{C:{D:{E:{F:{while(1){if((c|0)!=F[a>>2]){a=F[a+8>>2];if(a){continue}break F}break}if(!(G[a+12|0]&8)){break E}}a=38272;while(1){c=F[a>>2];if(c>>>0<=g>>>0){f=c+F[a+4>>2]|0;if(f>>>0>g>>>0){break D}}a=F[a+8>>2];continue}}F[a>>2]=b;F[a+4>>2]=F[a+4>>2]+e;j=(b+8&7?-8-b&7:0)+b|0;F[j+4>>2]=h|3;e=c+(c+8&7?-8-c&7:0)|0;i=h+j|0;c=e-i|0;if((e|0)==(g|0)){F[9462]=i;a=F[9459]+c|0;F[9459]=a;F[i+4>>2]=a|1;break B}if(F[9461]==(e|0)){F[9461]=i;a=F[9458]+c|0;F[9458]=a;F[i+4>>2]=a|1;F[a+i>>2]=a;break B}a=F[e+4>>2];if((a&3)==1){g=a&-8;G:{if(a>>>0<=255){d=F[e+8>>2];a=a>>>3|0;b=F[e+12>>2];if((b|0)==(d|0)){F[9456]=F[9456]&se(-2,a);break G}F[d+12>>2]=b;F[b+8>>2]=d;break G}h=F[e+24>>2];b=F[e+12>>2];H:{if((e|0)!=(b|0)){a=F[e+8>>2];F[a+12>>2]=b;F[b+8>>2]=a;break H}I:{a=e+20|0;d=F[a>>2];if(d){break I}a=e+16|0;d=F[a>>2];if(d){break I}b=0;break H}while(1){f=a;b=d;a=b+20|0;d=F[a>>2];if(d){continue}a=b+16|0;d=F[b+16>>2];if(d){continue}break}F[f>>2]=0}if(!h){break G}d=F[e+28>>2];a=(d<<2)+38128|0;J:{if(F[a>>2]==(e|0)){F[a>>2]=b;if(b){break J}F[9457]=F[9457]&se(-2,d);break G}F[h+(F[h+16>>2]==(e|0)?16:20)>>2]=b;if(!b){break G}}F[b+24>>2]=h;a=F[e+16>>2];if(a){F[b+16>>2]=a;F[a+24>>2]=b}a=F[e+20>>2];if(!a){break G}F[b+20>>2]=a;F[a+24>>2]=b}e=e+g|0;c=c+g|0}F[e+4>>2]=F[e+4>>2]&-2;F[i+4>>2]=c|1;F[c+i>>2]=c;if(c>>>0<=255){a=c>>>3|0;b=(a<<3)+37864|0;c=F[9456];a=1<>2]}F[b+8>>2]=i;F[a+12>>2]=i;F[i+12>>2]=b;F[i+8>>2]=a;break B}a=31;if(c>>>0<=16777215){a=c>>>8|0;f=a+1048320>>>16&8;a=a<>>16&4;a=a<>>16&2;a=(a<>>15|0)-(b|(d|f))|0;a=(a<<1|c>>>a+21&1)+28|0}F[i+28>>2]=a;F[i+16>>2]=0;F[i+20>>2]=0;f=(a<<2)+38128|0;d=F[9457];b=1<>2]=i;F[i+24>>2]=f;break L}a=c<<((a|0)==31?0:25-(a>>>1|0)|0);b=F[f>>2];while(1){d=b;if((F[b+4>>2]&-8)==(c|0)){break C}b=a>>>29|0;a=a<<1;f=d+(b&4)|0;b=F[f+16>>2];if(b){continue}break}F[f+16>>2]=i;F[i+24>>2]=d}F[i+12>>2]=i;F[i+8>>2]=i;break B}d=e-40|0;a=b+8&7?-8-b&7:0;c=d-a|0;F[9459]=c;a=a+b|0;F[9462]=a;F[a+4>>2]=c|1;F[(b+d|0)+4>>2]=40;F[9463]=F[9578];a=(f+(f-39&7?39-f&7:0)|0)-47|0;c=a>>>0>>0?g:a;F[c+4>>2]=27;a=F[9571];F[c+16>>2]=F[9570];F[c+20>>2]=a;a=F[9569];F[c+8>>2]=F[9568];F[c+12>>2]=a;F[9570]=c+8;F[9569]=e;F[9568]=b;F[9571]=0;a=c+24|0;while(1){F[a+4>>2]=7;b=a+8|0;a=a+4|0;if(b>>>0>>0){continue}break}if((c|0)==(g|0)){break x}F[c+4>>2]=F[c+4>>2]&-2;f=c-g|0;F[g+4>>2]=f|1;F[c>>2]=f;if(f>>>0<=255){a=f>>>3|0;b=(a<<3)+37864|0;c=F[9456];a=1<>2]}F[b+8>>2]=g;F[a+12>>2]=g;F[g+12>>2]=b;F[g+8>>2]=a;break x}a=31;F[g+16>>2]=0;F[g+20>>2]=0;if(f>>>0<=16777215){a=f>>>8|0;d=a+1048320>>>16&8;a=a<>>16&4;a=a<>>16&2;a=(a<>>15|0)-(b|(c|d))|0;a=(a<<1|f>>>a+21&1)+28|0}F[g+28>>2]=a;d=(a<<2)+38128|0;c=F[9457];b=1<>2]=g;F[g+24>>2]=d;break N}a=f<<((a|0)==31?0:25-(a>>>1|0)|0);b=F[d>>2];while(1){c=b;if((f|0)==(F[b+4>>2]&-8)){break A}b=a>>>29|0;a=a<<1;d=c+(b&4)|0;b=F[d+16>>2];if(b){continue}break}F[d+16>>2]=g;F[g+24>>2]=c}F[g+12>>2]=g;F[g+8>>2]=g;break x}a=F[d+8>>2];F[a+12>>2]=i;F[d+8>>2]=i;F[i+24>>2]=0;F[i+12>>2]=d;F[i+8>>2]=a}a=j+8|0;break a}a=F[c+8>>2];F[a+12>>2]=g;F[c+8>>2]=g;F[g+24>>2]=0;F[g+12>>2]=c;F[g+8>>2]=a}a=F[9459];if(a>>>0<=h>>>0){break d}b=a-h|0;F[9459]=b;c=F[9462];a=c+h|0;F[9462]=a;F[a+4>>2]=b|1;F[c+4>>2]=h|3;a=c+8|0;break a}F[9439]=48;a=0;break a}O:{if(!e){break O}c=F[f+28>>2];a=(c<<2)+38128|0;P:{if(F[a>>2]==(f|0)){F[a>>2]=b;if(b){break P}j=se(-2,c)&j;F[9457]=j;break O}F[e+(F[e+16>>2]==(f|0)?16:20)>>2]=b;if(!b){break O}}F[b+24>>2]=e;a=F[f+16>>2];if(a){F[b+16>>2]=a;F[a+24>>2]=b}a=F[f+20>>2];if(!a){break O}F[b+20>>2]=a;F[a+24>>2]=b}Q:{if(d>>>0<=15){a=d+h|0;F[f+4>>2]=a|3;a=a+f|0;F[a+4>>2]=F[a+4>>2]|1;break Q}F[f+4>>2]=h|3;e=f+h|0;F[e+4>>2]=d|1;F[d+e>>2]=d;if(d>>>0<=255){a=d>>>3|0;b=(a<<3)+37864|0;c=F[9456];a=1<>2]}F[b+8>>2]=e;F[a+12>>2]=e;F[e+12>>2]=b;F[e+8>>2]=a;break Q}a=31;if(d>>>0<=16777215){a=d>>>8|0;g=a+1048320>>>16&8;a=a<>>16&4;a=a<>>16&2;a=(a<>>15|0)-(b|(c|g))|0;a=(a<<1|d>>>a+21&1)+28|0}F[e+28>>2]=a;F[e+16>>2]=0;F[e+20>>2]=0;b=(a<<2)+38128|0;S:{c=1<>2]=e;break T}a=d<<((a|0)==31?0:25-(a>>>1|0)|0);h=F[b>>2];while(1){b=h;if((F[b+4>>2]&-8)==(d|0)){break S}c=a>>>29|0;a=a<<1;c=(c&4)+b|0;h=F[c+16>>2];if(h){continue}break}F[c+16>>2]=e}F[e+24>>2]=b;F[e+12>>2]=e;F[e+8>>2]=e;break Q}a=F[b+8>>2];F[a+12>>2]=e;F[b+8>>2]=e;F[e+24>>2]=0;F[e+12>>2]=b;F[e+8>>2]=a}a=f+8|0;break a}U:{if(!i){break U}c=F[b+28>>2];a=(c<<2)+38128|0;V:{if(F[a>>2]==(b|0)){F[a>>2]=f;if(f){break V}F[9457]=se(-2,c)&j;break U}F[i+(F[i+16>>2]==(b|0)?16:20)>>2]=f;if(!f){break U}}F[f+24>>2]=i;a=F[b+16>>2];if(a){F[f+16>>2]=a;F[a+24>>2]=f}a=F[b+20>>2];if(!a){break U}F[f+20>>2]=a;F[a+24>>2]=f}W:{if(d>>>0<=15){a=d+h|0;F[b+4>>2]=a|3;a=a+b|0;F[a+4>>2]=F[a+4>>2]|1;break W}F[b+4>>2]=h|3;f=b+h|0;F[f+4>>2]=d|1;F[d+f>>2]=d;if(k){a=k>>>3|0;c=(a<<3)+37864|0;g=F[9461];a=1<>2]}F[c+8>>2]=g;F[a+12>>2]=g;F[g+12>>2]=c;F[g+8>>2]=a}F[9461]=f;F[9458]=d}a=b+8|0}_=l+16|0;return a|0}function Rb(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,G=0,H=0,I=0,J=0,K=0,M=0;F[a+4>>2]=0;F[a+8>>2]=0;F[a>>2]=1;F[a+12>>2]=0;F[a+16>>2]=0;F[a+20>>2]=0;F[a+24>>2]=0;F[a+28>>2]=0;F[a+32>>2]=0;F[a+36>>2]=0;F[a+40>>2]=1;M=ra(a+44|0,0,76);J=c-((c>>7&c)<<1)|0;K=0-(((J^1)&255)>>>0<1)|0;d=K>>31;b=L(b,960);I=d&F[b+2156>>2];F[a+76>>2]=I;m=d&F[b+2152>>2];F[a+72>>2]=m;g=d&F[b+2148>>2];F[a+68>>2]=g;K=a- -64|0;n=d&F[b+2144>>2];F[K>>2]=n;o=d&F[b+2140>>2];F[a+60>>2]=o;p=d&F[b+2136>>2];F[a+56>>2]=p;q=d&F[b+2132>>2];F[a+52>>2]=q;r=d&F[b+2128>>2];F[a+48>>2]=r;s=d&F[b+2124>>2];F[M>>2]=s;t=d&F[b+2116>>2];F[a+36>>2]=t;u=d&F[b+2112>>2];F[a+32>>2]=u;v=d&F[b+2108>>2];F[a+28>>2]=v;h=d&F[b+2104>>2];F[a+24>>2]=h;i=d&F[b+2100>>2];F[a+20>>2]=i;j=d&F[b+2096>>2];F[a+16>>2]=j;k=d&F[b+2092>>2];F[a+12>>2]=k;l=d&F[b+2088>>2];F[a+8>>2]=l;e=d&F[b+2084>>2];F[a+4>>2]=e;w=d&(F[b+2120>>2]^1)^1;F[a+40>>2]=w;x=d&(F[b+2080>>2]^1)^1;F[a>>2]=x;y=F[a+80>>2];y=d&(y^F[b+2160>>2])^y;F[a+80>>2]=y;z=F[a+84>>2];z=d&(z^F[b+2164>>2])^z;F[a+84>>2]=z;A=F[a+88>>2];A=d&(A^F[b+2168>>2])^A;F[a+88>>2]=A;B=F[a+92>>2];B=d&(B^F[b+2172>>2])^B;F[a+92>>2]=B;C=F[a+96>>2];C=d&(C^F[b+2176>>2])^C;F[a+96>>2]=C;D=F[a+100>>2];D=d&(D^F[b+2180>>2])^D;F[a+100>>2]=D;E=F[a+104>>2];E=d&(E^F[b+2184>>2])^E;F[a+104>>2]=E;G=F[a+108>>2];G=d&(G^F[b+2188>>2])^G;F[a+108>>2]=G;H=F[a+112>>2];H=d&(H^F[b+2192>>2])^H;F[a+112>>2]=H;f=d;d=F[a+116>>2];f=f&(d^F[b+2196>>2])^d;F[a+116>>2]=f;d=0-(((J^2)&255)>>>0<1)|0;d=d>>31;s=s^d&(s^F[b+2244>>2]);F[M>>2]=s;w=w^d&(w^F[b+2240>>2]);F[a+40>>2]=w;t=t^d&(t^F[b+2236>>2]);F[a+36>>2]=t;u=u^d&(u^F[b+2232>>2]);F[a+32>>2]=u;v=v^d&(v^F[b+2228>>2]);F[a+28>>2]=v;h=h^d&(h^F[b+2224>>2]);F[a+24>>2]=h;i=i^d&(i^F[b+2220>>2]);F[a+20>>2]=i;j=j^d&(j^F[b+2216>>2]);F[a+16>>2]=j;k=k^d&(k^F[b+2212>>2]);F[a+12>>2]=k;l=l^d&(l^F[b+2208>>2]);F[a+8>>2]=l;e=e^d&(e^F[b+2204>>2]);F[a+4>>2]=e;x=x^d&(x^F[b+2200>>2]);F[a>>2]=x;I=I^d&(I^F[b+2276>>2]);F[a+76>>2]=I;m=m^d&(m^F[b+2272>>2]);F[a+72>>2]=m;g=g^d&(g^F[b+2268>>2]);F[a+68>>2]=g;n=n^d&(n^F[b+2264>>2]);F[K>>2]=n;o=o^d&(o^F[b+2260>>2]);F[a+60>>2]=o;p=p^d&(p^F[b+2256>>2]);F[a+56>>2]=p;q=q^d&(q^F[b+2252>>2]);F[a+52>>2]=q;r=r^d&(r^F[b+2248>>2]);F[a+48>>2]=r;B=B^d&(B^F[b+2292>>2]);F[a+92>>2]=B;A=A^d&(A^F[b+2288>>2]);F[a+88>>2]=A;z=z^d&(z^F[b+2284>>2]);F[a+84>>2]=z;y=y^d&(y^F[b+2280>>2]);F[a+80>>2]=y;f=f^d&(f^F[b+2316>>2]);F[a+116>>2]=f;H=H^d&(H^F[b+2312>>2]);F[a+112>>2]=H;G=G^d&(G^F[b+2308>>2]);F[a+108>>2]=G;E=E^d&(E^F[b+2304>>2]);F[a+104>>2]=E;D=D^d&(D^F[b+2300>>2]);F[a+100>>2]=D;C=C^d&(C^F[b+2296>>2]);F[a+96>>2]=C;d=0-(((J^3)&255)>>>0<1)|0;d=d>>31;s=s^d&(s^F[b+2364>>2]);F[M>>2]=s;w=w^d&(w^F[b+2360>>2]);F[a+40>>2]=w;t=t^d&(t^F[b+2356>>2]);F[a+36>>2]=t;u=u^d&(u^F[b+2352>>2]);F[a+32>>2]=u;v=v^d&(v^F[b+2348>>2]);F[a+28>>2]=v;h=h^d&(h^F[b+2344>>2]);F[a+24>>2]=h;i=i^d&(i^F[b+2340>>2]);F[a+20>>2]=i;j=j^d&(j^F[b+2336>>2]);F[a+16>>2]=j;k=k^d&(k^F[b+2332>>2]);F[a+12>>2]=k;l=l^d&(l^F[b+2328>>2]);F[a+8>>2]=l;e=e^d&(e^F[b+2324>>2]);F[a+4>>2]=e;x=x^d&(x^F[b+2320>>2]);F[a>>2]=x;B=B^d&(B^F[b+2412>>2]);F[a+92>>2]=B;A=A^d&(A^F[b+2408>>2]);F[a+88>>2]=A;z=z^d&(z^F[b+2404>>2]);F[a+84>>2]=z;y=y^d&(y^F[b+2400>>2]);F[a+80>>2]=y;I=I^d&(I^F[b+2396>>2]);F[a+76>>2]=I;m=m^d&(m^F[b+2392>>2]);F[a+72>>2]=m;g=g^d&(g^F[b+2388>>2]);F[a+68>>2]=g;n=n^d&(n^F[b+2384>>2]);F[K>>2]=n;o=o^d&(o^F[b+2380>>2]);F[a+60>>2]=o;p=p^d&(p^F[b+2376>>2]);F[a+56>>2]=p;q=q^d&(q^F[b+2372>>2]);F[a+52>>2]=q;r=r^d&(r^F[b+2368>>2]);F[a+48>>2]=r;f=f^d&(f^F[b+2436>>2]);F[a+116>>2]=f;H=H^d&(H^F[b+2432>>2]);F[a+112>>2]=H;G=G^d&(G^F[b+2428>>2]);F[a+108>>2]=G;E=E^d&(E^F[b+2424>>2]);F[a+104>>2]=E;D=D^d&(D^F[b+2420>>2]);F[a+100>>2]=D;C=C^d&(C^F[b+2416>>2]);F[a+96>>2]=C;d=0-(((J^4)&255)>>>0<1)|0;d=d>>31;s=s^d&(s^F[b+2484>>2]);F[M>>2]=s;w=w^d&(w^F[b+2480>>2]);F[a+40>>2]=w;t=t^d&(t^F[b+2476>>2]);F[a+36>>2]=t;u=u^d&(u^F[b+2472>>2]);F[a+32>>2]=u;v=v^d&(v^F[b+2468>>2]);F[a+28>>2]=v;h=h^d&(h^F[b+2464>>2]);F[a+24>>2]=h;i=i^d&(i^F[b+2460>>2]);F[a+20>>2]=i;j=j^d&(j^F[b+2456>>2]);F[a+16>>2]=j;k=k^d&(k^F[b+2452>>2]);F[a+12>>2]=k;l=l^d&(l^F[b+2448>>2]);F[a+8>>2]=l;e=e^d&(e^F[b+2444>>2]);F[a+4>>2]=e;x=x^d&(x^F[b+2440>>2]);F[a>>2]=x;B=B^d&(B^F[b+2532>>2]);F[a+92>>2]=B;A=A^d&(A^F[b+2528>>2]);F[a+88>>2]=A;z=z^d&(z^F[b+2524>>2]);F[a+84>>2]=z;y=y^d&(y^F[b+2520>>2]);F[a+80>>2]=y;I=I^d&(I^F[b+2516>>2]);F[a+76>>2]=I;m=m^d&(m^F[b+2512>>2]);F[a+72>>2]=m;g=g^d&(g^F[b+2508>>2]);F[a+68>>2]=g;n=n^d&(n^F[b+2504>>2]);F[K>>2]=n;o=o^d&(o^F[b+2500>>2]);F[a+60>>2]=o;p=p^d&(p^F[b+2496>>2]);F[a+56>>2]=p;q=q^d&(q^F[b+2492>>2]);F[a+52>>2]=q;r=r^d&(r^F[b+2488>>2]);F[a+48>>2]=r;C=C^d&(C^F[b+2536>>2]);F[a+96>>2]=C;D=D^d&(D^F[b+2540>>2]);F[a+100>>2]=D;E=E^d&(E^F[b+2544>>2]);F[a+104>>2]=E;G=G^d&(G^F[b+2548>>2]);F[a+108>>2]=G;H=H^d&(H^F[b+2552>>2]);F[a+112>>2]=H;f=f^d&(f^F[b+2556>>2]);F[a+116>>2]=f;d=0-(((J^5)&255)>>>0<1)|0;d=d>>31;s=s^d&(s^F[b+2604>>2]);F[M>>2]=s;w=w^d&(w^F[b+2600>>2]);F[a+40>>2]=w;t=t^d&(t^F[b+2596>>2]);F[a+36>>2]=t;u=u^d&(u^F[b+2592>>2]);F[a+32>>2]=u;v=v^d&(v^F[b+2588>>2]);F[a+28>>2]=v;h=h^d&(h^F[b+2584>>2]);F[a+24>>2]=h;i=i^d&(i^F[b+2580>>2]);F[a+20>>2]=i;j=j^d&(j^F[b+2576>>2]);F[a+16>>2]=j;k=k^d&(k^F[b+2572>>2]);F[a+12>>2]=k;l=l^d&(l^F[b+2568>>2]);F[a+8>>2]=l;e=e^d&(e^F[b+2564>>2]);F[a+4>>2]=e;x=x^d&(x^F[b+2560>>2]);F[a>>2]=x;D=D^d&(D^F[b+2660>>2]);F[a+100>>2]=D;C=C^d&(C^F[b+2656>>2]);F[a+96>>2]=C;B=B^d&(B^F[b+2652>>2]);F[a+92>>2]=B;E=E^d&(E^F[b+2664>>2]);F[a+104>>2]=E;G=G^d&(G^F[b+2668>>2]);F[a+108>>2]=G;H=H^d&(H^F[b+2672>>2]);F[a+112>>2]=H;f=f^d&(f^F[b+2676>>2]);F[a+116>>2]=f;A=A^d&(A^F[b+2648>>2]);F[a+88>>2]=A;z=z^d&(z^F[b+2644>>2]);F[a+84>>2]=z;y=y^d&(y^F[b+2640>>2]);F[a+80>>2]=y;I=I^d&(I^F[b+2636>>2]);F[a+76>>2]=I;m=m^d&(m^F[b+2632>>2]);F[a+72>>2]=m;g=g^d&(g^F[b+2628>>2]);F[a+68>>2]=g;n=n^d&(n^F[b+2624>>2]);F[K>>2]=n;o=o^d&(o^F[b+2620>>2]);F[a+60>>2]=o;p=p^d&(p^F[b+2616>>2]);F[a+56>>2]=p;q=q^d&(q^F[b+2612>>2]);F[a+52>>2]=q;r=r^d&(r^F[b+2608>>2]);F[a+48>>2]=r;d=0-(((J^6)&255)>>>0<1)|0;d=d>>31;s=s^d&(s^F[b+2724>>2]);F[M>>2]=s;w=w^d&(w^F[b+2720>>2]);F[a+40>>2]=w;t=t^d&(t^F[b+2716>>2]);F[a+36>>2]=t;u=u^d&(u^F[b+2712>>2]);F[a+32>>2]=u;v=v^d&(v^F[b+2708>>2]);F[a+28>>2]=v;h=h^d&(h^F[b+2704>>2]);F[a+24>>2]=h;i=i^d&(i^F[b+2700>>2]);F[a+20>>2]=i;j=j^d&(j^F[b+2696>>2]);F[a+16>>2]=j;k=k^d&(k^F[b+2692>>2]);F[a+12>>2]=k;l=l^d&(l^F[b+2688>>2]);F[a+8>>2]=l;e=e^d&(e^F[b+2684>>2]);F[a+4>>2]=e;x=x^d&(x^F[b+2680>>2]);F[a>>2]=x;r=r^d&(r^F[b+2728>>2]);F[a+48>>2]=r;q=q^d&(q^F[b+2732>>2]);F[a+52>>2]=q;p=p^d&(p^F[b+2736>>2]);F[a+56>>2]=p;o=o^d&(o^F[b+2740>>2]);F[a+60>>2]=o;n=n^d&(n^F[b+2744>>2]);F[K>>2]=n;g=g^d&(g^F[b+2748>>2]);F[a+68>>2]=g;m=m^d&(m^F[b+2752>>2]);F[a+72>>2]=m;I=I^d&(I^F[b+2756>>2]);F[a+76>>2]=I;y=y^d&(y^F[b+2760>>2]);F[a+80>>2]=y;z=z^d&(z^F[b+2764>>2]);F[a+84>>2]=z;A=A^d&(A^F[b+2768>>2]);F[a+88>>2]=A;B=B^d&(B^F[b+2772>>2]);F[a+92>>2]=B;C=C^d&(C^F[b+2776>>2]);F[a+96>>2]=C;D=D^d&(D^F[b+2780>>2]);F[a+100>>2]=D;E=E^d&(E^F[b+2784>>2]);F[a+104>>2]=E;G=G^d&(G^F[b+2788>>2]);F[a+108>>2]=G;H=H^d&(H^F[b+2792>>2]);F[a+112>>2]=H;f=f^d&(f^F[b+2796>>2]);F[a+116>>2]=f;d=0-(((J^7)&255)>>>0<1)|0;d=d>>31;s=s^d&(s^F[b+2844>>2]);F[M>>2]=s;r=r^d&(r^F[b+2848>>2]);F[a+48>>2]=r;q=q^d&(q^F[b+2852>>2]);F[a+52>>2]=q;p=p^d&(p^F[b+2856>>2]);F[a+56>>2]=p;o=o^d&(o^F[b+2860>>2]);F[a+60>>2]=o;n=n^d&(n^F[b+2864>>2]);F[K>>2]=n;g=g^d&(g^F[b+2868>>2]);F[a+68>>2]=g;m=m^d&(m^F[b+2872>>2]);F[a+72>>2]=m;I=I^d&(I^F[b+2876>>2]);F[a+76>>2]=I;y=y^d&(y^F[b+2880>>2]);F[a+80>>2]=y;z=z^d&(z^F[b+2884>>2]);F[a+84>>2]=z;A=A^d&(A^F[b+2888>>2]);F[a+88>>2]=A;B=B^d&(B^F[b+2892>>2]);F[a+92>>2]=B;C=C^d&(C^F[b+2896>>2]);F[a+96>>2]=C;D=D^d&(D^F[b+2900>>2]);F[a+100>>2]=D;E=E^d&(E^F[b+2904>>2]);F[a+104>>2]=E;G=G^d&(G^F[b+2908>>2]);F[a+108>>2]=G;H=H^d&(H^F[b+2912>>2]);F[a+112>>2]=H;f=f^d&(f^F[b+2916>>2]);F[a+116>>2]=f;w=w^d&(w^F[b+2840>>2]);F[a+40>>2]=w;t=t^d&(t^F[b+2836>>2]);F[a+36>>2]=t;u=u^d&(u^F[b+2832>>2]);F[a+32>>2]=u;v=v^d&(v^F[b+2828>>2]);F[a+28>>2]=v;h=h^d&(h^F[b+2824>>2]);F[a+24>>2]=h;i=i^d&(i^F[b+2820>>2]);F[a+20>>2]=i;j=j^d&(j^F[b+2816>>2]);F[a+16>>2]=j;k=k^d&(k^F[b+2812>>2]);F[a+12>>2]=k;l=l^d&(l^F[b+2808>>2]);F[a+8>>2]=l;e=e^d&(e^F[b+2804>>2]);F[a+4>>2]=e;x=x^d&(x^F[b+2800>>2]);F[a>>2]=x;J=0-(((J^8)&255)>>>0<1)|0;d=J>>31;J=e^d&(e^F[b+2924>>2]);F[a+4>>2]=J;e=x^d&(x^F[b+2920>>2]);F[a>>2]=e;l=l^d&(l^F[b+2928>>2]);F[a+8>>2]=l;k=k^d&(k^F[b+2932>>2]);F[a+12>>2]=k;j=j^d&(j^F[b+2936>>2]);F[a+16>>2]=j;i=i^d&(i^F[b+2940>>2]);F[a+20>>2]=i;h=h^d&(h^F[b+2944>>2]);F[a+24>>2]=h;v=v^d&(v^F[b+2948>>2]);F[a+28>>2]=v;u=u^d&(u^F[b+2952>>2]);F[a+32>>2]=u;t=t^d&(t^F[b+2956>>2]);F[a+36>>2]=t;w=w^d&(w^F[b+2960>>2]);F[a+40>>2]=w;s=s^d&(s^F[b+2964>>2]);F[M>>2]=s;r=r^d&(r^F[b+2968>>2]);F[a+48>>2]=r;q=q^d&(q^F[b+2972>>2]);F[a+52>>2]=q;p=p^d&(p^F[b+2976>>2]);F[a+56>>2]=p;o=o^d&(o^F[b+2980>>2]);F[a+60>>2]=o;n=n^d&(n^F[b+2984>>2]);F[K>>2]=n;g=g^d&(g^F[b+2988>>2]);F[a+68>>2]=g;m=m^d&(m^F[b+2992>>2]);F[a+72>>2]=m;c=0-((c&128)>>>7|0)|0;x=c&(e^w);F[a>>2]=x^e;e=f^d&(f^F[b+3036>>2]);F[a+116>>2]=c&(0-e^e)^e;e=H^d&(H^F[b+3032>>2]);F[a+112>>2]=c&(0-e^e)^e;e=G^d&(G^F[b+3028>>2]);F[a+108>>2]=c&(0-e^e)^e;e=E^d&(E^F[b+3024>>2]);F[a+104>>2]=c&(0-e^e)^e;e=D^d&(D^F[b+3020>>2]);F[a+100>>2]=c&(0-e^e)^e;e=C^d&(C^F[b+3016>>2]);F[a+96>>2]=c&(0-e^e)^e;e=B^d&(B^F[b+3012>>2]);F[a+92>>2]=c&(0-e^e)^e;e=A^d&(A^F[b+3008>>2]);F[a+88>>2]=c&(0-e^e)^e;e=z^d&(z^F[b+3004>>2]);F[a+84>>2]=c&(0-e^e)^e;e=y^d&(y^F[b+3e3>>2]);F[a+80>>2]=c&(0-e^e)^e;f=l;l=c&(l^r);F[a+8>>2]=f^l;f=g;g=c&(g^v);F[a+68>>2]=f^g;f=k;k=c&(k^q);F[a+12>>2]=f^k;f=j;j=c&(j^p);F[a+16>>2]=f^j;f=i;i=c&(i^o);F[a+20>>2]=f^i;f=h;h=c&(h^n);F[a+24>>2]=f^h;F[K>>2]=h^n;F[a+28>>2]=g^v;F[a+60>>2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|0;c=d>>>0<33554432?c+1|0:c;c=((c&67108863)<<6|d>>>26)+A|0;F[a+140>>2]=c;c=d&-67108864;F[a+136>>2]=g-c;c=qe(C,I,h,N);d=$;h=qe(n,Z,ja,ha);c=h+c|0;d=$+d|0;d=c>>>0>>0?d+1|0:d;i=qe(U,R,H,da);h=i+c|0;c=$+d|0;c=i>>>0>h>>>0?c+1|0:c;i=qe(D,t,p,aa);h=i+h|0;d=$+c|0;d=i>>>0>h>>>0?d+1|0:d;i=qe(E,v,j,e);h=i+h|0;c=$+d|0;d=h;c=(i>>>0>d>>>0?c+1|0:c)<<1|d>>>31;g=d<<1;d=f>>26;h=(f&67108863)<<6|o>>>26;f=g+h|0;c=c+d|0;c=f>>>0>>0?c+1|0:c;g=f;d=c;c=f+16777216|0;d=c>>>0<16777216?d+1|0:d;f=c&-33554432;F[a+156>>2]=g-f;i=qe((d&33554431)<<7|c>>>25,d>>25,19,0);h=u&-67108864;c=i+(k-h|0)|0;d=$+(O-((h>>>0>k>>>0)+P|0)|0)|0;d=c>>>0>>0?d+1|0:d;f=c+33554432|0;if(f>>>0<33554432){d=d+1|0}d=(l-(r&-33554432)|0)+((d&67108863)<<6|f>>>26)|0;F[a+124>>2]=d;d=f&-67108864;F[a+120>>2]=c-d;c=F[b+44>>2];d=F[b+48>>2];f=F[b+52>>2];g=F[b+56>>2];h=F[b+60>>2];i=F[b- -64>>2];k=F[b+68>>2];n=F[b+72>>2];p=F[b+40>>2];l=F[b>>2];u=F[b+4>>2];H=F[b+8>>2];j=F[b+12>>2];o=F[b+16>>2];y=F[b+20>>2];z=F[b+24>>2];m=F[b+28>>2];A=F[b+32>>2];F[a+76>>2]=F[b+76>>2]+F[b+36>>2];F[a+72>>2]=n+A;F[a+68>>2]=k+m;A=a- -64|0;F[A>>2]=i+z;F[a+60>>2]=h+y;F[a+56>>2]=g+o;F[a+52>>2]=f+j;F[a+48>>2]=d+H;F[a+44>>2]=c+u;F[a+40>>2]=l+p;fa(s,a+40|0);b=F[a+84>>2];c=F[a+88>>2];d=F[a+92>>2];f=F[a+96>>2];g=F[a+100>>2];h=F[a+104>>2];i=F[a+108>>2];k=F[a+112>>2];n=F[a>>2];p=F[a+80>>2];l=F[a+4>>2];u=F[a+8>>2];H=F[a+12>>2];j=F[a+16>>2];o=F[a+20>>2];y=F[a+24>>2];z=F[a+28>>2];m=F[a+32>>2];O=F[a+116>>2];X=F[a+36>>2];Y=O-X|0;F[a+116>>2]=Y;P=k-m|0;F[a+112>>2]=P;e=i-z|0;F[a+108>>2]=e;D=h-y|0;F[a+104>>2]=D;t=g-o|0;F[a+100>>2]=t;E=f-j|0;F[a+96>>2]=E;v=d-H|0;F[a+92>>2]=v;w=c-u|0;F[a+88>>2]=w;x=b-l|0;F[a+84>>2]=x;C=p-n|0;F[a+80>>2]=C;O=O+X|0;F[a+76>>2]=O;k=k+m|0;F[a+72>>2]=k;i=i+z|0;F[a+68>>2]=i;h=h+y|0;F[A>>2]=h;g=g+o|0;F[a+60>>2]=g;f=f+j|0;F[a+56>>2]=f;d=d+H|0;F[a+52>>2]=d;c=c+u|0;F[a+48>>2]=c;b=b+l|0;F[a+44>>2]=b;n=n+p|0;F[a+40>>2]=n;p=F[s>>2];l=F[s+4>>2];u=F[s+8>>2];H=F[s+12>>2];j=F[s+16>>2];o=F[s+20>>2];y=F[s+24>>2];z=F[s+28>>2];m=F[s+32>>2];F[a+36>>2]=F[s+36>>2]-O;F[a+32>>2]=m-k;F[a+28>>2]=z-i;F[a+24>>2]=y-h;F[a+20>>2]=o-g;F[a+16>>2]=j-f;F[a+12>>2]=H-d;F[a+8>>2]=u-c;F[a+4>>2]=l-b;F[a>>2]=p-n;b=F[a+124>>2];c=F[a+128>>2];d=F[a+132>>2];f=F[a+136>>2];g=F[a+140>>2];h=F[a+144>>2];i=F[a+148>>2];k=F[a+152>>2];n=F[a+120>>2];F[a+156>>2]=F[a+156>>2]-Y;F[a+152>>2]=k-P;F[a+148>>2]=i-e;F[a+144>>2]=h-D;F[a+140>>2]=g-t;F[a+136>>2]=f-E;F[a+132>>2]=d-v;F[a+128>>2]=c-w;F[a+124>>2]=b-x;F[a+120>>2]=n-C;_=s+48|0}function Aa(a,b,c,d,e,f,g,h){var i=0,j=0,k=0,l=0,m=0;i=_-432|0;_=i;j=i- -64|0;F[j>>2]=0;F[j+4>>2]=0;F[i+72>>2]=0;F[i+76>>2]=0;F[i+80>>2]=0;F[i+84>>2]=0;F[i+88>>2]=0;F[i+92>>2]=0;F[i+96>>2]=0;F[i+100>>2]=0;F[i+104>>2]=0;F[i+108>>2]=0;F[i+48>>2]=0;F[i+52>>2]=0;F[i+56>>2]=0;F[i+60>>2]=0;D[i+15|0]=1;j=c?c:1824;d=c?d:32;a:{if(d>>>0>=65){c=i+224|0;F[c+80>>2]=1779033703;F[c+84>>2]=-1150833019;F[c+72>>2]=0;F[c+76>>2]=0;F[c+64>>2]=0;F[c+104>>2]=528734635;F[c+108>>2]=1541459225;F[c+96>>2]=1359893119;F[c+100>>2]=-1694144372;F[c+88>>2]=1013904242;F[c+92>>2]=-1521486534;pa(c,j,d);Ba(c,i+48|0);break a}ja(i+48|0,j,d)}c=F[i+108>>2];F[i+280>>2]=F[i+104>>2];F[i+284>>2]=c;c=F[i+100>>2];F[i+272>>2]=F[i+96>>2];F[i+276>>2]=c;c=F[i+92>>2];F[i+264>>2]=F[i+88>>2];F[i+268>>2]=c;c=F[i+84>>2];F[i+256>>2]=F[i+80>>2];F[i+260>>2]=c;c=F[i+76>>2];F[i+248>>2]=F[i+72>>2];F[i+252>>2]=c;c=i- -64|0;d=F[c+4>>2];F[i+240>>2]=F[c>>2];F[i+244>>2]=d;c=F[i+60>>2];F[i+232>>2]=F[i+56>>2];F[i+236>>2]=c;c=F[i+52>>2];F[i+224>>2]=F[i+48>>2];F[i+228>>2]=c;c=0;while(1){d=i+224|0;j=d+c|0;D[j|0]=G[j|0]^54;j=d+(c|1)|0;D[j|0]=G[j|0]^54;j=d+(c|2)|0;D[j|0]=G[j|0]^54;d=d+(c|3)|0;D[d|0]=G[d|0]^54;c=c+4|0;if((c|0)!=64){continue}break}c=i+112|0;F[c+80>>2]=1779033703;F[c+84>>2]=-1150833019;F[c+72>>2]=0;F[c+76>>2]=0;F[c+64>>2]=0;F[c+104>>2]=528734635;F[c+108>>2]=1541459225;F[c+96>>2]=1359893119;F[c+100>>2]=-1694144372;F[c+88>>2]=1013904242;F[c+92>>2]=-1521486534;d=i+224|0;pa(c,d,64);ia(d,64);pa(c,a,b);a=F[i+108>>2];F[i+392>>2]=F[i+104>>2];F[i+396>>2]=a;a=F[i+100>>2];F[i+384>>2]=F[i+96>>2];F[i+388>>2]=a;a=F[i+92>>2];F[i+376>>2]=F[i+88>>2];F[i+380>>2]=a;a=F[i+84>>2];F[i+368>>2]=F[i+80>>2];F[i+372>>2]=a;a=F[i+76>>2];F[i+360>>2]=F[i+72>>2];F[i+364>>2]=a;a=i- -64|0;b=F[a+4>>2];F[i+352>>2]=F[a>>2];F[i+356>>2]=b;a=F[i+60>>2];F[i+344>>2]=F[i+56>>2];F[i+348>>2]=a;a=F[i+52>>2];F[i+336>>2]=F[i+48>>2];F[i+340>>2]=a;c=0;while(1){a=i+336|0;b=a+c|0;D[b|0]=G[b|0]^92;b=a+(c|1)|0;D[b|0]=G[b|0]^92;b=a+(c|2)|0;D[b|0]=G[b|0]^92;a=a+(c|3)|0;D[a|0]=G[a|0]^92;c=c+4|0;if((c|0)!=64){continue}break}Ba(i+112|0,i+400|0);a=i+224|0;F[a+80>>2]=1779033703;F[a+84>>2]=-1150833019;F[a+72>>2]=0;F[a+76>>2]=0;F[a+64>>2]=0;F[a+104>>2]=528734635;F[a+108>>2]=1541459225;F[a+96>>2]=1359893119;F[a+100>>2]=-1694144372;F[a+88>>2]=1013904242;F[a+92>>2]=-1521486534;b=i+336|0;pa(a,b,96);Ba(a,i+16|0);ia(a,112);ia(b,96);F[i+80>>2]=0;F[i+84>>2]=0;F[i+88>>2]=0;F[i+92>>2]=0;F[i+96>>2]=0;F[i+100>>2]=0;F[i+104>>2]=0;F[i+108>>2]=0;a=F[i+44>>2];j=F[i+40>>2];F[i+72>>2]=j;F[i+76>>2]=a;b=F[i+36>>2];c=i- -64|0;k=F[i+32>>2];F[c>>2]=k;F[c+4>>2]=b;c=F[i+20>>2];l=F[i+16>>2];F[i+48>>2]=l;F[i+52>>2]=c;d=F[i+28>>2];m=F[i+24>>2];F[i+56>>2]=m;F[i+60>>2]=d;F[i+280>>2]=0;F[i+284>>2]=0;F[i+272>>2]=0;F[i+276>>2]=0;F[i+264>>2]=0;F[i+268>>2]=0;F[i+256>>2]=0;F[i+260>>2]=0;F[i+248>>2]=j;F[i+252>>2]=a;F[i+240>>2]=k;F[i+244>>2]=b;F[i+232>>2]=m;F[i+236>>2]=d;F[i+224>>2]=l;F[i+228>>2]=c;c=0;while(1){a=i+224|0;b=a+c|0;D[b|0]=G[b|0]^54;b=a+(c|1)|0;D[b|0]=G[b|0]^54;b=a+(c|2)|0;D[b|0]=G[b|0]^54;a=a+(c|3)|0;D[a|0]=G[a|0]^54;c=c+4|0;if((c|0)!=64){continue}break}a=i+112|0;F[a+80>>2]=1779033703;F[a+84>>2]=-1150833019;F[a+72>>2]=0;F[a+76>>2]=0;F[a+64>>2]=0;F[a+104>>2]=528734635;F[a+108>>2]=1541459225;F[a+96>>2]=1359893119;F[a+100>>2]=-1694144372;F[a+88>>2]=1013904242;F[a+92>>2]=-1521486534;b=i+224|0;pa(a,b,64);ia(b,64);pa(a,e,f);pa(a,i+15|0,1);a=F[i+108>>2];F[i+392>>2]=F[i+104>>2];F[i+396>>2]=a;a=F[i+100>>2];F[i+384>>2]=F[i+96>>2];F[i+388>>2]=a;a=F[i+92>>2];F[i+376>>2]=F[i+88>>2];F[i+380>>2]=a;a=F[i+84>>2];F[i+368>>2]=F[i+80>>2];F[i+372>>2]=a;a=F[i+76>>2];F[i+360>>2]=F[i+72>>2];F[i+364>>2]=a;a=i- -64|0;b=F[a+4>>2];F[i+352>>2]=F[a>>2];F[i+356>>2]=b;a=F[i+60>>2];F[i+344>>2]=F[i+56>>2];F[i+348>>2]=a;a=F[i+52>>2];F[i+336>>2]=F[i+48>>2];F[i+340>>2]=a;c=0;while(1){a=i+336|0;b=a+c|0;D[b|0]=G[b|0]^92;b=a+(c|1)|0;D[b|0]=G[b|0]^92;b=a+(c|2)|0;D[b|0]=G[b|0]^92;a=a+(c|3)|0;D[a|0]=G[a|0]^92;c=c+4|0;if((c|0)!=64){continue}break}d=i+400|0;Ba(i+112|0,d);a=i+224|0;F[a+80>>2]=1779033703;F[a+84>>2]=-1150833019;F[a+72>>2]=0;F[a+76>>2]=0;F[a+64>>2]=0;F[a+104>>2]=528734635;F[a+108>>2]=1541459225;F[a+96>>2]=1359893119;F[a+100>>2]=-1694144372;F[a+88>>2]=1013904242;F[a+92>>2]=-1521486534;b=i+336|0;pa(a,b,96);Ba(a,i+16|0);ia(a,112);ia(b,96);if(h>>>0>=33){while(1){a=F[i+20>>2];b=F[i+16>>2];D[g|0]=b;D[g+1|0]=b>>>8;D[g+2|0]=b>>>16;D[g+3|0]=b>>>24;D[g+4|0]=a;D[g+5|0]=a>>>8;D[g+6|0]=a>>>16;D[g+7|0]=a>>>24;a=F[i+28>>2];b=F[i+24>>2];D[g+8|0]=b;D[g+9|0]=b>>>8;D[g+10|0]=b>>>16;D[g+11|0]=b>>>24;D[g+12|0]=a;D[g+13|0]=a>>>8;D[g+14|0]=a>>>16;D[g+15|0]=a>>>24;a=F[i+44>>2];b=F[i+40>>2];D[g+24|0]=b;D[g+25|0]=b>>>8;D[g+26|0]=b>>>16;D[g+27|0]=b>>>24;D[g+28|0]=a;D[g+29|0]=a>>>8;D[g+30|0]=a>>>16;D[g+31|0]=a>>>24;a=F[i+36>>2];b=F[i+32>>2];D[g+16|0]=b;D[g+17|0]=b>>>8;D[g+18|0]=b>>>16;D[g+19|0]=b>>>24;D[g+20|0]=a;D[g+21|0]=a>>>8;D[g+22|0]=a>>>16;D[g+23|0]=a>>>24;D[i+15|0]=G[i+15|0]+1;a=F[i+108>>2];F[i+280>>2]=F[i+104>>2];F[i+284>>2]=a;a=F[i+100>>2];F[i+272>>2]=F[i+96>>2];F[i+276>>2]=a;a=F[i+92>>2];F[i+264>>2]=F[i+88>>2];F[i+268>>2]=a;a=F[i+84>>2];F[i+256>>2]=F[i+80>>2];F[i+260>>2]=a;a=F[i+76>>2];F[i+248>>2]=F[i+72>>2];F[i+252>>2]=a;b=i- -64|0;a=F[b+4>>2];F[i+240>>2]=F[b>>2];F[i+244>>2]=a;a=F[i+60>>2];F[i+232>>2]=F[i+56>>2];F[i+236>>2]=a;a=F[i+52>>2];F[i+224>>2]=F[i+48>>2];F[i+228>>2]=a;g=g+32|0;c=0;while(1){a=i+224|0;j=a+c|0;D[j|0]=G[j|0]^54;j=a+(c|1)|0;D[j|0]=G[j|0]^54;j=a+(c|2)|0;D[j|0]=G[j|0]^54;a=a+(c|3)|0;D[a|0]=G[a|0]^54;c=c+4|0;if((c|0)!=64){continue}break}a=i+112|0;F[a+80>>2]=1779033703;F[a+84>>2]=-1150833019;F[a+72>>2]=0;F[a+76>>2]=0;F[a+64>>2]=0;F[a+104>>2]=528734635;F[a+108>>2]=1541459225;F[a+96>>2]=1359893119;F[a+100>>2]=-1694144372;F[a+88>>2]=1013904242;F[a+92>>2]=-1521486534;c=i+224|0;pa(a,c,64);ia(c,64);pa(a,i+16|0,32);pa(a,e,f);pa(a,i+15|0,1);a=F[i+108>>2];F[i+392>>2]=F[i+104>>2];F[i+396>>2]=a;a=F[i+100>>2];F[i+384>>2]=F[i+96>>2];F[i+388>>2]=a;a=F[i+92>>2];F[i+376>>2]=F[i+88>>2];F[i+380>>2]=a;a=F[i+84>>2];F[i+368>>2]=F[i+80>>2];F[i+372>>2]=a;a=F[i+76>>2];F[i+360>>2]=F[i+72>>2];F[i+364>>2]=a;a=F[b+4>>2];F[i+352>>2]=F[b>>2];F[i+356>>2]=a;a=F[i+60>>2];F[i+344>>2]=F[i+56>>2];F[i+348>>2]=a;a=F[i+52>>2];F[i+336>>2]=F[i+48>>2];F[i+340>>2]=a;c=0;while(1){a=i+336|0;b=a+c|0;D[b|0]=G[b|0]^92;b=a+(c|1)|0;D[b|0]=G[b|0]^92;b=a+(c|2)|0;D[b|0]=G[b|0]^92;a=a+(c|3)|0;D[a|0]=G[a|0]^92;c=c+4|0;if((c|0)!=64){continue}break}Ba(i+112|0,d);a=i+224|0;F[a+80>>2]=1779033703;F[a+84>>2]=-1150833019;F[a+72>>2]=0;F[a+76>>2]=0;F[a+64>>2]=0;F[a+104>>2]=528734635;F[a+108>>2]=1541459225;F[a+96>>2]=1359893119;F[a+100>>2]=-1694144372;F[a+88>>2]=1013904242;F[a+92>>2]=-1521486534;b=i+336|0;pa(a,b,96);Ba(a,i+16|0);ia(a,112);ia(b,96);h=h-32|0;if(h>>>0>32){continue}break}}a=i+16|0;ja(g,a,h);ia(i+112|0,112);ia(i+48|0,64);ia(a,32);_=i+432|0}function ta(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,H=0;B=_-640|0;_=B;c=a- -64|0;i=F[c>>2];l=F[c+4>>2];w=F[a+56>>2];f=F[a+60>>2];r=F[a+48>>2];n=F[a+52>>2];p=F[a+40>>2];h=F[a+44>>2];t=F[a+32>>2];m=F[a+36>>2];s=F[a+24>>2];k=F[a+28>>2];o=F[a+16>>2];u=F[a+20>>2];e=F[a+8>>2];q=F[a+12>>2];while(1){c=x<<3;v=c+B|0;c=b+c|0;d=G[c+4|0]|G[c+5|0]<<8|(G[c+6|0]<<16|G[c+7|0]<<24);j=G[c|0]|G[c+1|0]<<8|(G[c+2|0]<<16|G[c+3|0]<<24);y=j<<24|j<<8&16711680;c=d<<24|j>>>8;A=c&65280;c=d<<8|j>>>24;y=c&255|A|y;c=d;F[v>>2]=((c&255)<<24|j>>>8)&-16777216|((c&16777215)<<8|j>>>24)&16711680|(c>>>8&65280|c>>>24)|g;F[v+4>>2]=y;x=x+1|0;if((x|0)!=16){continue}break}b=16;j=F[B>>2];g=j;z=F[B+4>>2];d=z;while(1){x=(b<<3)+B|0;v=x;y=d;c=v-56|0;d=F[c>>2];C=F[c+4>>2];A=v-16|0;c=F[A+4>>2];A=F[A>>2];D=te(A,c,45);H=$;E=g;x=d;g=te(A,c,3)^D;d=c;c=c>>>6|0;g=g^((d&63)<<26|A>>>6);d=x+g|0;c=(c^($^H))+C|0;c=d>>>0>>0?c+1|0:c;g=d;d=E+d|0;c=c+y|0;A=d;y=d>>>0>>0?c+1|0:c;d=v-120|0;c=F[d+4>>2];g=F[d>>2];d=te(g,c,63);x=$;E=d;d=c;C=E^te(g,c,56);D=$^x;x=v;v=A;c=c>>>7|0;A=((d&127)<<25|g>>>7)^C;v=v+A|0;c=(c^D)+y|0;F[x>>2]=v;F[x+4>>2]=v>>>0>>0?c+1|0:c;b=b+1|0;if((b|0)!=80){continue}break}b=0;while(1){x=b<<3;c=x+32800|0;d=F[c>>2];v=F[c+4>>2];c=te(p,h,50);y=$;c=te(p,h,46)^c;y=$^y;g=d;d=i+(te(p,h,23)^c)|0;c=l+($^y)|0;c=d>>>0>>0?c+1|0:c;i=d;d=g+d|0;c=c+v|0;c=d>>>0>>0?c+1|0:c;d=d+j|0;c=c+z|0;c=d>>>0>>0?c+1|0:c;i=w^p&(r^w);d=i+d|0;c=(f^h&(f^n))+c|0;c=d>>>0>>0?c+1|0:c;i=d;d=te(e,q,36);l=$;d=te(e,q,30)^d;j=$^l;v=te(e,q,25)^d;l=v+i|0;d=c;c=c+($^j)|0;c=l>>>0>>0?c+1|0:c;j=s&(e|o)|e&o;l=j+l|0;c=(k&(q|u)|q&u)+c|0;y=l;c=j>>>0>l>>>0?c+1|0:c;l=te(l,c,36);v=$;j=c;l=te(y,c,30)^l;v=$^v;g=o&(e|y)|e&y;l=g+(te(y,c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_=B+640|0}function Vd(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0;m=xb(a,c);i=m+2|0;h=(i>>>0)/3|0;if(((i-L(h,3)|0)+(h<<2)|0)-2>>>0>g>>>0){F[a+3216>>2]=2;return-1}g=b;n=d;p=e;e=m+2|0;b=(e>>>0)/3|0;j=((((e-L(b,3)|0)+(b<<2)|0)-2|0)+f|0)-m|0;k=_-16|0;_=k;o=c;b=db(a,c);if(!G[a+3220|0]){b=Ib(b)}a:{b:{if(b>>>0>m>>>0){F[a+3216>>2]=2;break b}c=db(a,o);e=a;if(!G[a+3220|0]){D[j+1|0]=10;D[j|0]=3;a=j+2|0;D[a|0]=32;a=a+1|0;F[k+8>>2]=a;a=a+32|0;D[a|0]=18;a=a+1|0;D[a|0]=32;a=a+1|0;F[k+4>>2]=a;a=a+32|0;D[a|0]=26;a=a+1|0;D[a|0]=32;a=a+1|0;F[k>>2]=a;a=a+32|0;D[a|0]=34;j=a+1|0;a=c;c:{if(a>>>0<128){b=a;break c}while(1){D[j|0]=a|128;j=j+1|0;h=a>>>0>16383;b=a>>>7|0;a=b;if(h){continue}break}}D[j|0]=b;F[k+12>>2]=j+1;b=G[e+3289|0]|G[e+3290|0]<<8|(G[e+3291|0]<<16|G[e+3292|0]<<24);a=F[k+8>>2];h=G[e+3285|0]|G[e+3286|0]<<8|(G[e+3287|0]<<16|G[e+3288|0]<<24);D[a|0]=h;D[a+1|0]=h>>>8;D[a+2|0]=h>>>16;D[a+3|0]=h>>>24;D[a+4|0]=b;D[a+5|0]=b>>>8;D[a+6|0]=b>>>16;D[a+7|0]=b>>>24;b=e+3309|0;h=G[b+4|0]|G[b+5|0]<<8|(G[b+6|0]<<16|G[b+7|0]<<24);b=G[b|0]|G[b+1|0]<<8|(G[b+2|0]<<16|G[b+3|0]<<24);D[a+24|0]=b;D[a+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24;b=e+3277|0;h=G[b+4|0]|G[b+5|0]<<8|(G[b+6|0]<<16|G[b+7|0]<<24);b=G[b|0]|G[b+1|0]<<8|(G[b+2|0]<<16|G[b+3|0]<<24);D[a+24|0]=b;D[a+25|0]=b>>>8;D[a+26|0]=b>>>16;D[a+27|0]=b>>>24;D[a+28|0]=h;D[a+29|0]=h>>>8;D[a+30|0]=h>>>16;D[a+31|0]=h>>>24;j=F[k+12>>2]}s=g;h=_-96|0;_=h;i=e+48|0;b=(i|0)==F[e+44>>2]?0:F[e+112>>2];a=F[e+4>>2];g=aa[F[F[a>>2]+4>>2]](a,o)|0;a=F[e+4>>2];g=Mb(b,g,aa[F[F[a>>2]>>2]](a)|0);a=F[e+44>>2];d:{if(((a|0)==(i|0))<<5>>>0>p>>>0){F[e+8>>2]=1;g=-1;break d}if(c>>>0>>0){F[e+8>>2]=2;g=-1;break d}if((a|0)==(i|0)){F[e+44>>2]=e+148;Ea(n,i);a=F[e>>2];b=h- -64|0;za(i,e+152|0,b);Aa(b,32,e+12|0,32,F[a+8>>2],F[a+12>>2],h,64);a=h;c=F[a+28>>2];F[e+36>>2]=F[a+24>>2];F[e+40>>2]=c;c=F[a+20>>2];F[e+28>>2]=F[a+16>>2];F[e+32>>2]=c;c=F[a+12>>2];F[e+20>>2]=F[a+8>>2];F[e+24>>2]=c;c=F[a+4>>2];F[e+12>>2]=F[a>>2];F[e+16>>2]=c;c=F[a+36>>2];F[e+116>>2]=F[a+32>>2];F[e+120>>2]=c;c=F[a+44>>2];F[e+124>>2]=F[a+40>>2];F[e+128>>2]=c;c=F[a+52>>2];F[e+132>>2]=F[a+48>>2];F[e+136>>2]=c;c=F[a+60>>2];F[e+140>>2]=F[a+56>>2];F[e+144>>2]=c;F[e+112>>2]=0;ia(a,64);ia(b,32)}a=e+116|0;q=h|4;ka(a,32,1920,1,q);F[h>>2]=F[e+112>>2];ka(a,32,1921,1,a);F[e+112>>2]=F[e+112>>2]+1;a=F[e+4>>2];n=aa[F[F[a>>2]+4>>2]](a,o)|0;b=F[h>>2];a=n;D[j+1|0]=10;D[j|0]=3;c=j+2|0;D[c|0]=32;r=h- -64|0;c=c+1|0;F[r>>2]=c;c=c+32|0;D[c|0]=16;l=c+1|0;e:{if(b>>>0<128){c=b;break e}while(1){D[l|0]=b|128;l=l+1|0;t=b>>>0>16383;c=b>>>7|0;b=c;if(t){continue}break}}D[l+1|0]=34;D[l|0]=c;b=l+2|0;f:{if(a>>>0<128){c=a;break f}while(1){D[b|0]=a|128;b=b+1|0;l=a>>>0>16383;c=a>>>7|0;a=c;if(l){continue}break}}D[b|0]=c;F[r+4>>2]=b+1;a=i;c=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);b=F[h+64>>2];i=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[b|0]=i;D[b+1|0]=i>>>8;D[b+2|0]=i>>>16;D[b+3|0]=i>>>24;D[b+4|0]=c;D[b+5|0]=c>>>8;D[b+6|0]=c>>>16;D[b+7|0]=c>>>24;c=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);i=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[b+24|0]=i;D[b+25|0]=i>>>8;D[b+26|0]=i>>>16;D[b+27|0]=i>>>24;D[b+28|0]=c;D[b+29|0]=c>>>8;D[b+30|0]=c>>>16;D[b+31|0]=c>>>24;c=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);i=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[b+16|0]=i;D[b+17|0]=i>>>8;D[b+18|0]=i>>>16;D[b+19|0]=i>>>24;D[b+20|0]=c;D[b+21|0]=c>>>8;D[b+22|0]=c>>>16;D[b+23|0]=c>>>24;c=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);a=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[b+8|0]=a;D[b+9|0]=a>>>8;D[b+10|0]=a>>>16;D[b+11|0]=a>>>24;D[b+12|0]=c;D[b+13|0]=c>>>8;D[b+14|0]=c>>>16;D[b+15|0]=c>>>24;a=F[e+4>>2];aa[F[F[a>>2]+8>>2]](a,q,32,s,o,F[h+68>>2],n,j,g)|0;ia(h,36)}_=h+96|0;if((g|0)!=-1){break a}F[e+3216>>2]=F[e+8>>2];F[e+8>>2]=0}g=-1}_=k+16|0;ia(d,p);a=-1;if((g|0)!=-1){b=m+2|0;a=(b>>>0)/3|0;a=((b-L(a,3)|0)+(a<<2)|0)-2|0;na((f+a|0)-m|0,m,f)}return a|0}function Ab(a,b,c,d,e){var f=0,g=0,h=0,i=0,j=0;h=_-208|0;_=h;ab(h+168|0,d,e);f=F[h+172>>2];d=(f|c)!=0;a:{b:{c:{d:{if(f){if(!d){break c}if(F[h+176>>2]==32){break d}break c}if(!d){break c}}j=F[h+196>>2];if(!j){break c}e=F[h+180>>2];if(!e|F[h+184>>2]!=32){break c}d=F[h+188>>2];if(!d){break c}if(F[h+192>>2]==32){break b}}F[a+3216>>2]=4;a=-1;break a}e:{if(!f|!c){break e}if(!Ja(c,f)){break e}F[a+3216>>2]=6;a=-1;break a}g=G[f+4|0]|G[f+5|0]<<8|(G[f+6|0]<<16|G[f+7|0]<<24);c=G[f|0]|G[f+1|0]<<8|(G[f+2|0]<<16|G[f+3|0]<<24);D[a+3221|0]=c;D[a+3222|0]=c>>>8;D[a+3223|0]=c>>>16;D[a+3224|0]=c>>>24;D[a+3225|0]=g;D[a+3226|0]=g>>>8;D[a+3227|0]=g>>>16;D[a+3228|0]=g>>>24;g=G[f+28|0]|G[f+29|0]<<8|(G[f+30|0]<<16|G[f+31|0]<<24);i=a+3245|0;c=G[f+24|0]|G[f+25|0]<<8|(G[f+26|0]<<16|G[f+27|0]<<24);D[i|0]=c;D[i+1|0]=c>>>8;D[i+2|0]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G[d+7|0]<<24);c=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);D[a+3285|0]=c;D[a+3286|0]=c>>>8;D[a+3287|0]=c>>>16;D[a+3288|0]=c>>>24;D[a+3289|0]=e;D[a+3290|0]=e>>>8;D[a+3291|0]=e>>>16;D[a+3292|0]=e>>>24;c=F[a+4>>2];ib(h+136|0,j,F[h+200>>2],aa[F[F[c>>2]>>2]](c)|0);c=F[h+152>>2];if(!(F[h+156>>2]==32?c:0)){F[a+3216>>2]=4;a=-1;break a}d=G[c+28|0]|G[c+29|0]<<8|(G[c+30|0]<<16|G[c+31|0]<<24);F[h+128>>2]=G[c+24|0]|G[c+25|0]<<8|(G[c+26|0]<<16|G[c+27|0]<<24);F[h+132>>2]=d;d=G[c+20|0]|G[c+21|0]<<8|(G[c+22|0]<<16|G[c+23|0]<<24);F[h+120>>2]=G[c+16|0]|G[c+17|0]<<8|(G[c+18|0]<<16|G[c+19|0]<<24);F[h+124>>2]=d;d=G[c+12|0]|G[c+13|0]<<8|(G[c+14|0]<<16|G[c+15|0]<<24);F[h+112>>2]=G[c+8|0]|G[c+9|0]<<8|(G[c+10|0]<<16|G[c+11|0]<<24);F[h+116>>2]=d;d=G[c+4|0]|G[c+5|0]<<8|(G[c+6|0]<<16|G[c+7|0]<<24);F[h+104>>2]=G[c|0]|G[c+1|0]<<8|(G[c+2|0]<<16|G[c+3|0]<<24);F[h+108>>2]=d;e=a+3285|0;c=b+164|0;d=F[b+160>>2];f:{g:{if((c|0)!=(d|0)){while(1){if(La(c+5|0,e,32)){break g}c=c+72|0;if((d|0)!=(c|0)){continue}break}}c=0;if(!G[b+7364|0]){break g}d=b+7368|0;if(La(b+7373|0,e,32)){break f}if(G[b+7364|0]<2){break g}c=La(b+7445|0,e,32)?b+7440|0:0}d=c}if(!d){F[a+3216>>2]=6;a=-1;break a}c=d+5|0;za(c,a+3221|0,h);d=b+96|0;b=a+3253|0;za(d,b,h+32|0);za(c,b,h- -64|0);e=_+-64|0;_=e;b=F[a>>2];Aa(h,96,0,0,F[b>>2],F[b+4>>2],e,64);d=a+152|0;c=F[a+148>>2];h:{if((c|0)!=(a+492|0)){c=c+68|0;F[a+148>>2]=c;b=d;break h}b=(((c|0)==(d|0)?-68:0)+a|0)+152|0}c=c-68|0;if((b|0)!=(c|0)){while(1){f=c;c=c-68|0;ja(f,c,68);if((b|0)!=(c|0)){continue}break}}F[a+184>>2]=0;b=F[e+28>>2];F[a+36>>2]=F[e+24>>2];F[a+40>>2]=b;b=F[e+20>>2];F[a+28>>2]=F[e+16>>2];F[a+32>>2]=b;b=F[e+12>>2];F[a+20>>2]=F[e+8>>2];F[a+24>>2]=b;b=F[e+4>>2];F[a+12>>2]=F[e>>2];F[a+16>>2]=b;b=F[e+60>>2];F[a+212>>2]=F[e+56>>2];F[a+216>>2]=b;b=F[e+52>>2];F[a+204>>2]=F[e+48>>2];F[a+208>>2]=b;b=F[e+44>>2];F[a+196>>2]=F[e+40>>2];F[a+200>>2]=b;b=F[e+36>>2];F[a+188>>2]=F[e+32>>2];F[a+192>>2]=b;a=h;c=G[a+124|0]|G[a+125|0]<<8|(G[a+126|0]<<16|G[a+127|0]<<24);b=G[a+120|0]|G[a+121|0]<<8|(G[a+122|0]<<16|G[a+123|0]<<24);D[d+16|0]=b;D[d+17|0]=b>>>8;D[d+18|0]=b>>>16;D[d+19|0]=b>>>24;D[d+20|0]=c;D[d+21|0]=c>>>8;D[d+22|0]=c>>>16;D[d+23|0]=c>>>24;c=G[a+116|0]|G[a+117|0]<<8|(G[a+118|0]<<16|G[a+119|0]<<24);b=G[a+112|0]|G[a+113|0]<<8|(G[a+114|0]<<16|G[a+115|0]<<24);D[d+8|0]=b;D[d+9|0]=b>>>8;D[d+10|0]=b>>>16;D[d+11|0]=b>>>24;D[d+12|0]=c;D[d+13|0]=c>>>8;D[d+14|0]=c>>>16;D[d+15|0]=c>>>24;c=G[a+108|0]|G[a+109|0]<<8|(G[a+110|0]<<16|G[a+111|0]<<24);b=G[a+104|0]|G[a+105|0]<<8|(G[a+106|0]<<16|G[a+107|0]<<24);D[d|0]=b;D[d+1|0]=b>>>8;D[d+2|0]=b>>>16;D[d+3|0]=b>>>24;D[d+4|0]=c;D[d+5|0]=c>>>8;D[d+6|0]=c>>>16;D[d+7|0]=c>>>24;c=G[a+132|0]|G[a+133|0]<<8|(G[a+134|0]<<16|G[a+135|0]<<24);b=G[a+128|0]|G[a+129|0]<<8|(G[a+130|0]<<16|G[a+131|0]<<24);D[d+24|0]=b;D[d+25|0]=b>>>8;D[d+26|0]=b>>>16;D[d+27|0]=b>>>24;D[d+28|0]=c;D[d+29|0]=c>>>8;D[d+30|0]=c>>>16;D[d+31|0]=c>>>24;ia(e,64);_=e- -64|0;ia(a,96);a=0}_=h+208|0;return a}function de(a,b,c,d,e,f,g,h){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;var i=0,j=0,k=0,l=0,m=0;k=_+-64|0;_=k;a:{b:{if((oa(d)|0)==32){if((oa(f)|0)==32){break b}}F[a+3216>>2]=7;d=-1;break a}m=k+32|0;qa(c,d,m);qa(e,f,k);j=_-224|0;_=j;c:{if(h>>>0<=63){F[a+3216>>2]=1;d=-1;break c}l=j+160|0;Ea(g,l);c=j+96|0;Ea(g+32|0,c);D[a+3220|0]=0;e=G[b+124|0]|G[b+125|0]<<8|(G[b+126|0]<<16|G[b+127|0]<<24);f=a+3245|0;d=G[b+120|0]|G[b+121|0]<<8|(G[b+122|0]<<16|G[b+123|0]<<24);D[f|0]=d;D[f+1|0]=d>>>8;D[f+2|0]=d>>>16;D[f+3|0]=d>>>24;D[f+4|0]=e;D[f+5|0]=e>>>8;D[f+6|0]=e>>>16;D[f+7|0]=e>>>24;e=G[b+116|0]|G[b+117|0]<<8|(G[b+118|0]<<16|G[b+119|0]<<24);f=a+3237|0;d=G[b+112|0]|G[b+113|0]<<8|(G[b+114|0]<<16|G[b+115|0]<<24);D[f|0]=d;D[f+1|0]=d>>>8;D[f+2|0]=d>>>16;D[f+3|0]=d>>>24;D[f+4|0]=e;D[f+5|0]=e>>>8;D[f+6|0]=e>>>16;D[f+7|0]=e>>>24;e=G[b+108|0]|G[b+109|0]<<8|(G[b+110|0]<<16|G[b+111|0]<<24);f=a+3229|0;d=G[b+104|0]|G[b+105|0]<<8|(G[b+106|0]<<16|G[b+107|0]<<24);D[f|0]=d;D[f+1|0]=d>>>8;D[f+2|0]=d>>>16;D[f+3|0]=d>>>24;D[f+4|0]=e;D[f+5|0]=e>>>8;D[f+6|0]=e>>>16;D[f+7|0]=e>>>24;e=G[b+100|0]|G[b+101|0]<<8|(G[b+102|0]<<16|G[b+103|0]<<24);d=G[b+96|0]|G[b+97|0]<<8|(G[b+98|0]<<16|G[b+99|0]<<24);D[a+3221|0]=d;D[a+3222|0]=d>>>8;D[a+3223|0]=d>>>16;D[a+3224|0]=d>>>24;D[a+3225|0]=e;D[a+3226|0]=e>>>8;D[a+3227|0]=e>>>16;D[a+3228|0]=e>>>24;e=F[j+164>>2];d=F[j+160>>2];D[a+3253|0]=d;D[a+3254|0]=d>>>8;D[a+3255|0]=d>>>16;D[a+3256|0]=d>>>24;D[a+3257|0]=e;D[a+3258|0]=e>>>8;D[a+3259|0]=e>>>16;D[a+3260|0]=e>>>24;e=F[j+172>>2];f=a+3261|0;d=F[j+168>>2];D[f|0]=d;D[f+1|0]=d>>>8;D[f+2|0]=d>>>16;D[f+3|0]=d>>>24;D[f+4|0]=e;D[f+5|0]=e>>>8;D[f+6|0]=e>>>16;D[f+7|0]=e>>>24;e=F[j+180>>2];f=a+3269|0;d=F[j+176>>2];D[f|0]=d;D[f+1|0]=d>>>8;D[f+2|0]=d>>>16;D[f+3|0]=d>>>24;D[f+4|0]=e;D[f+5|0]=e>>>8;D[f+6|0]=e>>>16;D[f+7|0]=e>>>24;e=F[j+188>>2];f=a+3277|0;d=F[j+184>>2];D[f|0]=d;D[f+1|0]=d>>>8;D[f+2|0]=d>>>16;D[f+3|0]=d>>>24;D[f+4|0]=e;D[f+5|0]=e>>>8;D[f+6|0]=e>>>16;D[f+7|0]=e>>>24;d=k;f=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);e=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);D[a+3285|0]=e;D[a+3286|0]=e>>>8;D[a+3287|0]=e>>>16;D[a+3288|0]=e>>>24;D[a+3289|0]=f;D[a+3290|0]=f>>>8;D[a+3291|0]=f>>>16;D[a+3292|0]=f>>>24;f=G[d+12|0]|G[d+13|0]<<8|(G[d+14|0]<<16|G[d+15|0]<<24);i=a+3293|0;e=G[d+8|0]|G[d+9|0]<<8|(G[d+10|0]<<16|G[d+11|0]<<24);D[i|0]=e;D[i+1|0]=e>>>8;D[i+2|0]=e>>>16;D[i+3|0]=e>>>24;D[i+4|0]=f;D[i+5|0]=f>>>8;D[i+6|0]=f>>>16;D[i+7|0]=f>>>24;f=G[d+20|0]|G[d+21|0]<<8|(G[d+22|0]<<16|G[d+23|0]<<24);i=a+3301|0;e=G[d+16|0]|G[d+17|0]<<8|(G[d+18|0]<<16|G[d+19|0]<<24);D[i|0]=e;D[i+1|0]=e>>>8;D[i+2|0]=e>>>16;D[i+3|0]=e>>>24;D[i+4|0]=f;D[i+5|0]=f>>>8;D[i+6|0]=f>>>16;D[i+7|0]=f>>>24;f=G[d+28|0]|G[d+29|0]<<8|(G[d+30|0]<<16|G[d+31|0]<<24);i=a+3309|0;e=G[d+24|0]|G[d+25|0]<<8|(G[d+26|0]<<16|G[d+27|0]<<24);D[i|0]=e;D[i+1|0]=e>>>8;D[i+2|0]=e>>>16;D[i+3|0]=e>>>24;D[i+4|0]=f;D[i+5|0]=f>>>8;D[i+6|0]=f>>>16;D[i+7|0]=f>>>24;za(b+96|0,d,j);za(l,m,j+32|0);za(l,d,j- -64|0);d=_+-64|0;_=d;b=F[a>>2];Aa(j,96,0,0,F[b>>2],F[b+4>>2],d,64);e=a+48|0;f=F[a+44>>2];d:{if((f|0)!=(a+148|0)){f=f+100|0;F[a+44>>2]=f;b=e;break d}b=(((e|0)==(f|0)?-100:0)+a|0)+48|0}f=f-100|0;if((b|0)!=(f|0)){while(1){i=f;f=f-100|0;ja(i,f,100);if((b|0)!=(f|0)){continue}break}}F[a+112>>2]=0;b=F[d+28>>2];F[a+36>>2]=F[d+24>>2];F[a+40>>2]=b;b=F[d+20>>2];F[a+28>>2]=F[d+16>>2];F[a+32>>2]=b;b=F[d+12>>2];F[a+20>>2]=F[d+8>>2];F[a+24>>2]=b;b=F[d+4>>2];F[a+12>>2]=F[d>>2];F[a+16>>2]=b;b=F[d+60>>2];F[a+140>>2]=F[d+56>>2];F[a+144>>2]=b;b=F[d+52>>2];F[a+132>>2]=F[d+48>>2];F[a+136>>2]=b;b=F[d+44>>2];F[a+124>>2]=F[d+40>>2];F[a+128>>2]=b;b=F[d+36>>2];F[a+116>>2]=F[d+32>>2];F[a+120>>2]=b;b=G[c+52|0]|G[c+53|0]<<8|(G[c+54|0]<<16|G[c+55|0]<<24);a=G[c+48|0]|G[c+49|0]<<8|(G[c+50|0]<<16|G[c+51|0]<<24);D[e+48|0]=a;D[e+49|0]=a>>>8;D[e+50|0]=a>>>16;D[e+51|0]=a>>>24;D[e+52|0]=b;D[e+53|0]=b>>>8;D[e+54|0]=b>>>16;D[e+55|0]=b>>>24;b=G[c+44|0]|G[c+45|0]<<8|(G[c+46|0]<<16|G[c+47|0]<<24);a=G[c+40|0]|G[c+41|0]<<8|(G[c+42|0]<<16|G[c+43|0]<<24);D[e+40|0]=a;D[e+41|0]=a>>>8;D[e+42|0]=a>>>16;D[e+43|0]=a>>>24;D[e+44|0]=b;D[e+45|0]=b>>>8;D[e+46|0]=b>>>16;D[e+47|0]=b>>>24;b=G[c+36|0]|G[c+37|0]<<8|(G[c+38|0]<<16|G[c+39|0]<<24);a=G[c+32|0]|G[c+33|0]<<8|(G[c+34|0]<<16|G[c+35|0]<<24);D[e+32|0]=a;D[e+33|0]=a>>>8;D[e+34|0]=a>>>16;D[e+35|0]=a>>>24;D[e+36|0]=b;D[e+37|0]=b>>>8;D[e+38|0]=b>>>16;D[e+39|0]=b>>>24;b=G[c+28|0]|G[c+29|0]<<8|(G[c+30|0]<<16|G[c+31|0]<<24);a=G[c+24|0]|G[c+25|0]<<8|(G[c+26|0]<<16|G[c+27|0]<<24);D[e+24|0]=a;D[e+25|0]=a>>>8;D[e+26|0]=a>>>16;D[e+27|0]=a>>>24;D[e+28|0]=b;D[e+29|0]=b>>>8;D[e+30|0]=b>>>16;D[e+31|0]=b>>>24;b=G[c+20|0]|G[c+21|0]<<8|(G[c+22|0]<<16|G[c+23|0]<<24);a=G[c+16|0]|G[c+17|0]<<8|(G[c+18|0]<<16|G[c+19|0]<<24);D[e+16|0]=a;D[e+17|0]=a>>>8;D[e+18|0]=a>>>16;D[e+19|0]=a>>>24;D[e+20|0]=b;D[e+21|0]=b>>>8;D[e+22|0]=b>>>16;D[e+23|0]=b>>>24;b=G[c+12|0]|G[c+13|0]<<8|(G[c+14|0]<<16|G[c+15|0]<<24);a=G[c+8|0]|G[c+9|0]<<8|(G[c+10|0]<<16|G[c+11|0]<<24);D[e+8|0]=a;D[e+9|0]=a>>>8;D[e+10|0]=a>>>16;D[e+11|0]=a>>>24;D[e+12|0]=b;D[e+13|0]=b>>>8;D[e+14|0]=b>>>16;D[e+15|0]=b>>>24;b=G[c+4|0]|G[c+5|0]<<8|(G[c+6|0]<<16|G[c+7|0]<<24);a=G[c|0]|G[c+1|0]<<8|(G[c+2|0]<<16|G[c+3|0]<<24);D[e|0]=a;D[e+1|0]=a>>>8;D[e+2|0]=a>>>16;D[e+3|0]=a>>>24;D[e+4|0]=b;D[e+5|0]=b>>>8;D[e+6|0]=b>>>16;D[e+7|0]=b>>>24;b=G[c+60|0]|G[c+61|0]<<8|(G[c+62|0]<<16|G[c+63|0]<<24);a=G[c+56|0]|G[c+57|0]<<8|(G[c+58|0]<<16|G[c+59|0]<<24);D[e+56|0]=a;D[e+57|0]=a>>>8;D[e+58|0]=a>>>16;D[e+59|0]=a>>>24;D[e+60|0]=b;D[e+61|0]=b>>>8;D[e+62|0]=b>>>16;D[e+63|0]=b>>>24;ia(d,64);_=d- -64|0;ia(l,64);ia(c,64);ia(j,96);d=0}_=j+224|0;ia(g,h)}_=k- -64|0;return d|0}function Td(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;g=oa(d);if((g|0)==-1){F[a+3216>>2]=7;return-1}qa(c,d,c);d=g;g=e;k=_-48|0;_=k;a:{if((b|0)!=1){ab(k+8|0,c,d);c=F[k+36>>2];if(!c){F[a+3216>>2]=4;l=-1;break a}d=F[k+40>>2]}l=-1;i=_-32|0;_=i;e=a;a=F[a+4>>2];ib(i,c,d,aa[F[F[a>>2]>>2]](a)|0);b:{if(G[i|0]!=3){F[e+8>>2]=3;d=-1;break b}if(F[i+24>>2]?!G[i+1|0]|!F[i+16>>2]:1){F[e+8>>2]=4;d=-1;break b}a=F[e+4>>2];if(aa[F[F[a>>2]+12>>2]](a,F[i+28>>2])>>>0>f>>>0){F[e+8>>2]=2;d=-1;break b}if(F[i+20>>2]!=32){F[e+8>>2]=4;d=-1;break b}c:{d:{e:{f:{g:{b=e+152|0;a=F[e+148>>2];if((b|0)!=(a|0)){d=F[i+16>>2];c=b;while(1){if(!Ja(c,d)){break g}c=c+68|0;if((a|0)!=(c|0)){continue}break}}c=_-208|0;_=c;a=-1;d=e+48|0;if(!((d|0)==F[e+44>>2]|I[i+4>>2]>2e3)){a=F[i+16>>2];j=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);F[c+32>>2]=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);F[c+36>>2]=j;j=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);F[c+24>>2]=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);F[c+28>>2]=j;j=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);F[c+16>>2]=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);F[c+20>>2]=j;j=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);F[c+8>>2]=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);F[c+12>>2]=j;a=F[e>>2];h=d;j=c+8|0;d=c+176|0;za(h,j,d);h=F[a+8>>2];m=F[a+12>>2];a=c+112|0;Aa(d,32,e+12|0,32,h,m,a,64);h=F[c+140>>2];F[c+104>>2]=F[c+136>>2];F[c+108>>2]=h;h=F[c+132>>2];F[c+96>>2]=F[c+128>>2];F[c+100>>2]=h;h=F[c+148>>2];F[c+44>>2]=F[c+144>>2];F[c+48>>2]=h;h=F[c+156>>2];F[c+52>>2]=F[c+152>>2];F[c+56>>2]=h;h=F[c+164>>2];F[c+60>>2]=F[c+160>>2];F[c+64>>2]=h;h=F[c+172>>2];F[c+68>>2]=F[c+168>>2];F[c+72>>2]=h;F[c+40>>2]=0;h=F[c+124>>2];F[c+88>>2]=F[c+120>>2];F[c+92>>2]=h;h=F[c+116>>2];F[c+80>>2]=F[c+112>>2];F[c+84>>2]=h;ia(a,64);ia(d,32);a=sb(e,c+40|0,i,g,f);ia(c+80|0,32);ia(j,68)}_=c+208|0;d=a;if((a|0)==-1){break f}a=F[e+148>>2];if((a|0)==(e+492|0)){break e}a=a+68|0;F[e+148>>2]=a;break d}b=F[i+4>>2];if(b>>>0>2]){a=e+496|0;c=F[e+492>>2];if((a|0)==(c|0)){break f}while(1){h:{if(F[a+32>>2]!=(b|0)){break h}if(Ja(a,F[i+16>>2])){break h}b=F[e+4>>2];d=aa[F[F[b>>2]+16>>2]](b,a+36|0,32,F[i+8>>2],F[i+12>>2],F[i+24>>2],F[i+28>>2],g,f)|0;if((d|0)==-1){break h}ia(a,68);b=F[e+492>>2]-68|0;F[e+492>>2]=b;if((a|0)==(b|0)){break b}while(1){b=a;a=a+68|0;ja(b,a,68);if(F[e+492>>2]!=(a|0)){continue}break}break b}a=a+68|0;if((c|0)==(a|0)){break f}b=F[i+4>>2];continue}}d=sb(e,c+32|0,i,g,f);if((d|0)!=-1){break c}}F[e+8>>2]=5;d=-1;break b}b=(e+((a|0)==(b|0)?-68:0)|0)+152|0}a=a-68|0;if((b|0)!=(a|0)){while(1){c=a;a=a-68|0;ja(c,a,68);if((a|0)!=(b|0)){continue}break}}a=F[i+16>>2];c=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);f=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[b|0]=f;D[b+1|0]=f>>>8;D[b+2|0]=f>>>16;D[b+3|0]=f>>>24;D[b+4|0]=c;D[b+5|0]=c>>>8;D[b+6|0]=c>>>16;D[b+7|0]=c>>>24;c=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);f=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[b+24|0]=f;D[b+25|0]=f>>>8;D[b+26|0]=f>>>16;D[b+27|0]=f>>>24;D[b+28|0]=c;D[b+29|0]=c>>>8;D[b+30|0]=c>>>16;D[b+31|0]=c>>>24;c=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);f=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[b+16|0]=f;D[b+17|0]=f>>>8;D[b+18|0]=f>>>16;D[b+19|0]=f>>>24;D[b+20|0]=c;D[b+21|0]=c>>>8;D[b+22|0]=c>>>16;D[b+23|0]=c>>>24;c=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);a=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[b+8|0]=a;D[b+9|0]=a>>>8;D[b+10|0]=a>>>16;D[b+11|0]=a>>>24;D[b+12|0]=c;D[b+13|0]=c>>>8;D[b+14|0]=c>>>16;D[b+15|0]=c>>>24;f=F[e>>2];c=_-96|0;_=c;a=e+48|0;j=c- -64|0;za(a,b,j);Aa(j,32,e+12|0,32,F[f+8>>2],F[f+12>>2],c,64);f=F[c+28>>2];g=F[c+24>>2];D[e+36|0]=g;D[e+37|0]=g>>>8;D[e+38|0]=g>>>16;D[e+39|0]=g>>>24;D[e+40|0]=f;D[e+41|0]=f>>>8;D[e+42|0]=f>>>16;D[e+43|0]=f>>>24;f=F[c+20>>2];g=F[c+16>>2];D[e+28|0]=g;D[e+29|0]=g>>>8;D[e+30|0]=g>>>16;D[e+31|0]=g>>>24;D[e+32|0]=f;D[e+33|0]=f>>>8;D[e+34|0]=f>>>16;D[e+35|0]=f>>>24;f=F[c+12>>2];g=F[c+8>>2];D[e+20|0]=g;D[e+21|0]=g>>>8;D[e+22|0]=g>>>16;D[e+23|0]=g>>>24;D[e+24|0]=f;D[e+25|0]=f>>>8;D[e+26|0]=f>>>16;D[e+27|0]=f>>>24;f=F[c+4>>2];g=F[c>>2];D[e+12|0]=g;D[e+13|0]=g>>>8;D[e+14|0]=g>>>16;D[e+15|0]=g>>>24;D[e+16|0]=f;D[e+17|0]=f>>>8;D[e+18|0]=f>>>16;D[e+19|0]=f>>>24;f=F[c+40>>2];g=F[c+44>>2];h=F[c+48>>2];m=F[c+52>>2];n=F[c+56>>2];o=F[c+60>>2];p=F[c+32>>2];q=F[c+36>>2];F[b+32>>2]=0;F[b+60>>2]=n;F[b+64>>2]=o;F[b+52>>2]=h;F[b+56>>2]=m;F[b+44>>2]=f;F[b+48>>2]=g;F[b+36>>2]=p;F[b+40>>2]=q;ia(c,64);ia(j,32);_=c+96|0;ia(a,100);c=F[e+44>>2]-100|0;F[e+44>>2]=c;if((a|0)!=(c|0)){while(1){c=a;a=a+100|0;ja(c,a,100);if(F[e+44>>2]!=(a|0)){continue}break}}c=b}g=c+36|0;if(I[c+32>>2]>2]){b=e+3216|0;f=e+496|0;j=e+532|0;while(1){a=b;h=F[e+492>>2];if((a|0)!=(h|0)){a=h+68|0;F[e+492>>2]=a}a=a-68|0;if((f|0)!=(a|0)){while(1){h=a;a=a-68|0;ja(h,a,68);if((a|0)!=(f|0)){continue}break}}ka(g,32,1920,1,j);F[e+528>>2]=F[c+32>>2];a=F[c+28>>2];F[f+24>>2]=F[c+24>>2];F[f+28>>2]=a;a=F[c+20>>2];F[f+16>>2]=F[c+16>>2];F[f+20>>2]=a;a=F[c+12>>2];F[f+8>>2]=F[c+8>>2];F[f+12>>2]=a;a=F[c+4>>2];F[f>>2]=F[c>>2];F[f+4>>2]=a;ka(g,32,1921,1,g);a=F[c+32>>2]+1|0;F[c+32>>2]=a;if(a>>>0>2]){continue}break}}ka(g,32,1921,1,g);F[c+32>>2]=F[c+32>>2]+1}_=i+32|0;if((d|0)==-1){F[e+3216>>2]=F[e+8>>2];F[e+8>>2]=0;break a}D[e+3220|0]=1;l=d}_=k+48|0;return l|0}function ac(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0;j=wb(a);if(Da(j)>>>0>e>>>0){F[a+3216>>2]=2;return-1}e=la(Za(d,j),1);D[e|0]=G[a+3220|0];f=a+3221|0;h=G[f+4|0]|G[f+5|0]<<8|(G[f+6|0]<<16|G[f+7|0]<<24);e=e+1|0;i=G[f|0]|G[f+1|0]<<8|(G[f+2|0]<<16|G[f+3|0]<<24);D[e|0]=i;D[e+1|0]=i>>>8;D[e+2|0]=i>>>16;D[e+3|0]=i>>>24;D[e+4|0]=h;D[e+5|0]=h>>>8;D[e+6|0]=h>>>16;D[e+7|0]=h>>>24;g=G[f+28|0]|G[f+29|0]<<8|(G[f+30|0]<<16|G[f+31|0]<<24);h=G[f+24|0]|G[f+25|0]<<8|(G[f+26|0]<<16|G[f+27|0]<<24);D[e+24|0]=h;D[e+25|0]=h>>>8;D[e+26|0]=h>>>16;D[e+27|0]=h>>>24;D[e+28|0]=g;D[e+29|0]=g>>>8;D[e+30|0]=g>>>16;D[e+31|0]=g>>>24;g=G[f+20|0]|G[f+21|0]<<8|(G[f+22|0]<<16|G[f+23|0]<<24);h=G[f+16|0]|G[f+17|0]<<8|(G[f+18|0]<<16|G[f+19|0]<<24);D[e+16|0]=h;D[e+17|0]=h>>>8;D[e+18|0]=h>>>16;D[e+19|0]=h>>>24;D[e+20|0]=g;D[e+21|0]=g>>>8;D[e+22|0]=g>>>16;D[e+23|0]=g>>>24;g=G[f+12|0]|G[f+13|0]<<8|(G[f+14|0]<<16|G[f+15|0]<<24);f=G[f+8|0]|G[f+9|0]<<8|(G[f+10|0]<<16|G[f+11|0]<<24);D[e+8|0]=f;D[e+9|0]=f>>>8;D[e+10|0]=f>>>16;D[e+11|0]=f>>>24;D[e+12|0]=g;D[e+13|0]=g>>>8;D[e+14|0]=g>>>16;D[e+15|0]=g>>>24;f=a+3253|0;h=G[f+4|0]|G[f+5|0]<<8|(G[f+6|0]<<16|G[f+7|0]<<24);e=e+32|0;i=G[f|0]|G[f+1|0]<<8|(G[f+2|0]<<16|G[f+3|0]<<24);D[e|0]=i;D[e+1|0]=i>>>8;D[e+2|0]=i>>>16;D[e+3|0]=i>>>24;D[e+4|0]=h;D[e+5|0]=h>>>8;D[e+6|0]=h>>>16;D[e+7|0]=h>>>24;g=G[f+28|0]|G[f+29|0]<<8|(G[f+30|0]<<16|G[f+31|0]<<24);h=G[f+24|0]|G[f+25|0]<<8|(G[f+26|0]<<16|G[f+27|0]<<24);D[e+24|0]=h;D[e+25|0]=h>>>8;D[e+26|0]=h>>>16;D[e+27|0]=h>>>24;D[e+28|0]=g;D[e+29|0]=g>>>8;D[e+30|0]=g>>>16;D[e+31|0]=g>>>24;g=G[f+20|0]|G[f+21|0]<<8|(G[f+22|0]<<16|G[f+23|0]<<24);h=G[f+16|0]|G[f+17|0]<<8|(G[f+18|0]<<16|G[f+19|0]<<24);D[e+16|0]=h;D[e+17|0]=h>>>8;D[e+18|0]=h>>>16;D[e+19|0]=h>>>24;D[e+20|0]=g;D[e+21|0]=g>>>8;D[e+22|0]=g>>>16;D[e+23|0]=g>>>24;g=G[f+12|0]|G[f+13|0]<<8|(G[f+14|0]<<16|G[f+15|0]<<24);f=G[f+8|0]|G[f+9|0]<<8|(G[f+10|0]<<16|G[f+11|0]<<24);D[e+8|0]=f;D[e+9|0]=f>>>8;D[e+10|0]=f>>>16;D[e+11|0]=f>>>24;D[e+12|0]=g;D[e+13|0]=g>>>8;D[e+14|0]=g>>>16;D[e+15|0]=g>>>24;f=a+3285|0;h=G[f+4|0]|G[f+5|0]<<8|(G[f+6|0]<<16|G[f+7|0]<<24);e=e+32|0;i=G[f|0]|G[f+1|0]<<8|(G[f+2|0]<<16|G[f+3|0]<<24);D[e|0]=i;D[e+1|0]=i>>>8;D[e+2|0]=i>>>16;D[e+3|0]=i>>>24;D[e+4|0]=h;D[e+5|0]=h>>>8;D[e+6|0]=h>>>16;D[e+7|0]=h>>>24;g=G[f+28|0]|G[f+29|0]<<8|(G[f+30|0]<<16|G[f+31|0]<<24);h=G[f+24|0]|G[f+25|0]<<8|(G[f+26|0]<<16|G[f+27|0]<<24);D[e+24|0]=h;D[e+25|0]=h>>>8;D[e+26|0]=h>>>16;D[e+27|0]=h>>>24;D[e+28|0]=g;D[e+29|0]=g>>>8;D[e+30|0]=g>>>16;D[e+31|0]=g>>>24;g=G[f+20|0]|G[f+21|0]<<8|(G[f+22|0]<<16|G[f+23|0]<<24);h=G[f+16|0]|G[f+17|0]<<8|(G[f+18|0]<<16|G[f+19|0]<<24);D[e+16|0]=h;D[e+17|0]=h>>>8;D[e+18|0]=h>>>16;D[e+19|0]=h>>>24;D[e+20|0]=g;D[e+21|0]=g>>>8;D[e+22|0]=g>>>16;D[e+23|0]=g>>>24;g=G[f+12|0]|G[f+13|0]<<8|(G[f+14|0]<<16|G[f+15|0]<<24);f=G[f+8|0]|G[f+9|0]<<8|(G[f+10|0]<<16|G[f+11|0]<<24);D[e+8|0]=f;D[e+9|0]=f>>>8;D[e+10|0]=f>>>16;D[e+11|0]=f>>>24;D[e+12|0]=g;D[e+13|0]=g>>>8;D[e+14|0]=g>>>16;D[e+15|0]=g>>>24;g=Ta(e+32|0,a+12|0,32);e=a+48|0;f=la(g,(F[a+44>>2]-e|0)/100|0);g=F[a+44>>2];if((g|0)!=(e|0)){while(1){f=la(Ta(Pa(f,e),e+68|0,32),F[e+64>>2]);e=e+100|0;if((g|0)!=(e|0)){continue}break}}e=a+152|0;f=la(f,(F[a+148>>2]-e|0)/68|0);i=F[a+148>>2];if((i|0)!=(e|0)){while(1){g=G[e+4|0]|G[e+5|0]<<8|(G[e+6|0]<<16|G[e+7|0]<<24);h=G[e|0]|G[e+1|0]<<8|(G[e+2|0]<<16|G[e+3|0]<<24);D[f|0]=h;D[f+1|0]=h>>>8;D[f+2|0]=h>>>16;D[f+3|0]=h>>>24;D[f+4|0]=g;D[f+5|0]=g>>>8;D[f+6|0]=g>>>16;D[f+7|0]=g>>>24;g=G[e+28|0]|G[e+29|0]<<8|(G[e+30|0]<<16|G[e+31|0]<<24);h=G[e+24|0]|G[e+25|0]<<8|(G[e+26|0]<<16|G[e+27|0]<<24);D[f+24|0]=h;D[f+25|0]=h>>>8;D[f+26|0]=h>>>16;D[f+27|0]=h>>>24;D[f+28|0]=g;D[f+29|0]=g>>>8;D[f+30|0]=g>>>16;D[f+31|0]=g>>>24;g=G[e+20|0]|G[e+21|0]<<8|(G[e+22|0]<<16|G[e+23|0]<<24);h=G[e+16|0]|G[e+17|0]<<8|(G[e+18|0]<<16|G[e+19|0]<<24);D[f+16|0]=h;D[f+17|0]=h>>>8;D[f+18|0]=h>>>16;D[f+19|0]=h>>>24;D[f+20|0]=g;D[f+21|0]=g>>>8;D[f+22|0]=g>>>16;D[f+23|0]=g>>>24;g=G[e+12|0]|G[e+13|0]<<8|(G[e+14|0]<<16|G[e+15|0]<<24);h=G[e+8|0]|G[e+9|0]<<8|(G[e+10|0]<<16|G[e+11|0]<<24);D[f+8|0]=h;D[f+9|0]=h>>>8;D[f+10|0]=h>>>16;D[f+11|0]=h>>>24;D[f+12|0]=g;D[f+13|0]=g>>>8;D[f+14|0]=g>>>16;D[f+15|0]=g>>>24;f=la(Ta(f+32|0,e+36|0,32),F[e+32>>2]);e=e+68|0;if((i|0)!=(e|0)){continue}break}}e=a+496|0;f=la(f,(F[a+492>>2]-e|0)/68|0);h=F[a+492>>2];if((h|0)!=(e|0)){while(1){a=G[e+4|0]|G[e+5|0]<<8|(G[e+6|0]<<16|G[e+7|0]<<24);g=G[e|0]|G[e+1|0]<<8|(G[e+2|0]<<16|G[e+3|0]<<24);D[f|0]=g;D[f+1|0]=g>>>8;D[f+2|0]=g>>>16;D[f+3|0]=g>>>24;D[f+4|0]=a;D[f+5|0]=a>>>8;D[f+6|0]=a>>>16;D[f+7|0]=a>>>24;a=G[e+28|0]|G[e+29|0]<<8|(G[e+30|0]<<16|G[e+31|0]<<24);g=G[e+24|0]|G[e+25|0]<<8|(G[e+26|0]<<16|G[e+27|0]<<24);D[f+24|0]=g;D[f+25|0]=g>>>8;D[f+26|0]=g>>>16;D[f+27|0]=g>>>24;D[f+28|0]=a;D[f+29|0]=a>>>8;D[f+30|0]=a>>>16;D[f+31|0]=a>>>24;a=G[e+20|0]|G[e+21|0]<<8|(G[e+22|0]<<16|G[e+23|0]<<24);g=G[e+16|0]|G[e+17|0]<<8|(G[e+18|0]<<16|G[e+19|0]<<24);D[f+16|0]=g;D[f+17|0]=g>>>8;D[f+18|0]=g>>>16;D[f+19|0]=g>>>24;D[f+20|0]=a;D[f+21|0]=a>>>8;D[f+22|0]=a>>>16;D[f+23|0]=a>>>24;a=G[e+12|0]|G[e+13|0]<<8|(G[e+14|0]<<16|G[e+15|0]<<24);g=G[e+8|0]|G[e+9|0]<<8|(G[e+10|0]<<16|G[e+11|0]<<24);D[f+8|0]=g;D[f+9|0]=g>>>8;D[f+10|0]=g>>>16;D[f+11|0]=g>>>24;D[f+12|0]=a;D[f+13|0]=a>>>8;D[f+14|0]=a>>>16;D[f+15|0]=a>>>24;f=la(Ta(f+32|0,e+36|0,32),F[e+32>>2]);e=e+68|0;if((h|0)!=(e|0)){continue}break}}return Ya(b,c,d,j)|0}function _c(a,b,c,d,e,f){a=a|0;b=+b;c=c|0;d=d|0;e=e|0;f=f|0;var g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,w=0,x=0,y=0,z=0,B=0,C=0;m=_-560|0;_=m;F[m+44>>2]=0;A(+b);g=v(1)|0;v(0)|0;a:{if((g|0)<-1?1:(g|0)<=-1){u=1;y=1226;b=-b;A(+b);g=v(1)|0;v(0)|0;break a}if(e&2048){u=1;y=1229;break a}u=e&1;y=u?1232:1227;B=!u}b:{if((g&2146435072)==2146435072){i=u+3|0;va(a,32,c,i,e&-65537);ma(a,y,u);d=f&32;ma(a,b!=b?d?1245:1440:d?1249:1513,3);break b}s=m+16|0;c:{d:{e:{b=Fb(b,m+44|0);b=b+b;if(b!=0){g=F[m+44>>2];F[m+44>>2]=g-1;r=f|32;if((r|0)!=97){break e}break c}r=f|32;if((r|0)==97){break c}j=F[m+44>>2];k=(d|0)<0?6:d;break d}j=g-29|0;F[m+44>>2]=j;b=b*268435456;k=(d|0)<0?6:d}n=(j|0)<0?m+48|0:m+336|0;h=n;while(1){d=h;if(b<4294967296&b>=0){g=~~b>>>0}else{g=0}F[d>>2]=g;h=h+4|0;b=(b-+(g>>>0))*1e9;if(b!=0){continue}break}f:{if((j|0)<1){d=j;g=h;l=n;break f}l=n;d=j;while(1){o=(d|0)<29?d:29;g=h-4|0;g:{if(l>>>0>g>>>0){break g}d=o;i=0;while(1){q=g;w=i;x=F[g>>2];p=d&31;if((d&63)>>>0>=32){i=x<>>32-p;x=x<>>0>>0?i+1|0:i;i=re(p,i,1e9);w=q;q=qe(i,$,1e9,0);F[w>>2]=p-q;g=g-4|0;if(l>>>0<=g>>>0){continue}break}if(!i){break g}l=l-4|0;F[l>>2]=i}while(1){g=h;if(l>>>0>>0){h=g-4|0;if(!F[h>>2]){continue}}break}d=F[m+44>>2]-o|0;F[m+44>>2]=d;h=g;if((d|0)>0){continue}break}}h=(k+25|0)/9|0;if((d|0)<=-1){o=h+1|0;z=(r|0)==102;while(1){d=0-d|0;i=(d|0)<9?d:9;h:{if(g>>>0>l>>>0){q=1e9>>>i|0;p=-1<>2];F[h>>2]=w+(d>>>i|0);d=L(q,d&p);h=h+4|0;if(h>>>0>>0){continue}break}h=F[l>>2];if(!d){break h}F[g>>2]=d;g=g+4|0;break h}h=F[l>>2]}d=i+F[m+44>>2]|0;F[m+44>>2]=d;l=(!h<<2)+l|0;h=z?n:l;g=(o|0)>2?h+(o<<2)|0:g;if((d|0)<0){continue}break}}h=0;i:{if(g>>>0<=l>>>0){break i}h=L(n-l>>2,9);d=10;i=F[l>>2];if(i>>>0<10){break i}while(1){h=h+1|0;d=L(d,10);if(i>>>0>=d>>>0){continue}break}}d=(k-((r|0)==102?0:h)|0)-((r|0)==103&(k|0)!=0)|0;if((d|0)<(L(g-n>>2,9)-9|0)){q=((j|0)<0?4:292)+m|0;j=d+9216|0;o=(j|0)/9|0;i=(q+(o<<2)|0)-4048|0;d=10;j=j-L(o,9)|0;if((j|0)<=7){while(1){d=L(d,10);j=j+1|0;if((j|0)!=8){continue}break}}o=F[i>>2];q=(o>>>0)/(d>>>0)|0;j=o-L(d,q)|0;p=i+4|0;j:{if(!((p|0)==(g|0)?j:1)){break j}b=(g|0)==(p|0)?1:1.5;p=d>>>1|0;t=j>>>0

>>0?.5:(p|0)==(j|0)?b:1.5;b=q&1?9007199254740994:9007199254740992;if(!(G[y|0]!=45|B)){t=-t;b=-b}j=o-j|0;F[i>>2]=j;if(b+t==b){break j}d=d+j|0;F[i>>2]=d;if(d>>>0>=1e9){while(1){F[i>>2]=0;i=i-4|0;if(i>>>0>>0){l=l-4|0;F[l>>2]=0}d=F[i>>2]+1|0;F[i>>2]=d;if(d>>>0>999999999){continue}break}}h=L(n-l>>2,9);d=10;j=F[l>>2];if(j>>>0<10){break j}while(1){h=h+1|0;d=L(d,10);if(j>>>0>=d>>>0){continue}break}}d=i+4|0;g=d>>>0>>0?d:g}while(1){j=g;d=g>>>0<=l>>>0;if(!d){g=j-4|0;if(!F[g>>2]){continue}}break}k:{if((r|0)!=103){r=e&8;break k}g=k?k:1;i=(g|0)>(h|0)&(h|0)>-5;k=(i?h^-1:-1)+g|0;f=(i?-1:-2)+f|0;r=e&8;if(r){break k}g=-9;l:{if(d){break l}o=F[j-4>>2];if(!o){break l}d=10;g=0;if((o>>>0)%10|0){break l}while(1){i=g;g=g+1|0;d=L(d,10);if(!((o>>>0)%(d>>>0)|0)){continue}break}g=i^-1}d=L(j-n>>2,9);if((f&-33)==70){r=0;d=(d+g|0)-9|0;d=(d|0)>0?d:0;k=(d|0)>(k|0)?k:d;break k}r=0;d=((d+h|0)+g|0)-9|0;d=(d|0)>0?d:0;k=(d|0)>(k|0)?k:d}o=(k|r)!=0;w=a;d=c;q=f&-33;if((q|0)==70){f=(h|0)>0?h:0}else{g=h>>31;g=Na(g+h^g,0,s);if((s-g|0)<=1){while(1){g=g-1|0;D[g|0]=48;if((s-g|0)<2){continue}break}}z=g-2|0;D[z|0]=f;D[g-1|0]=(h|0)<0?45:43;f=s-z|0}i=(f+(o+(k+u|0)|0)|0)+1|0;va(w,32,d,i,e);ma(a,y,u);va(a,48,c,i,e^65536);m:{n:{o:{if((q|0)==70){f=m+16|0;d=f|8;f=f|9;l=l>>>0>n>>>0?n:l;h=l;while(1){g=Na(F[h>>2],0,f);p:{if((h|0)!=(l|0)){if(m+16>>>0>=g>>>0){break p}while(1){g=g-1|0;D[g|0]=48;if(m+16>>>0>>0){continue}break}break p}if((f|0)!=(g|0)){break p}D[m+24|0]=48;g=d}ma(a,g,f-g|0);h=h+4|0;if(n>>>0>=h>>>0){continue}break}g=0;if(!o){break n}ma(a,1718,1);if((k|0)<1|h>>>0>=j>>>0){break o}while(1){g=Na(F[h>>2],0,f);if(g>>>0>m+16>>>0){while(1){g=g-1|0;D[g|0]=48;if(m+16>>>0>>0){continue}break}}ma(a,g,(k|0)<9?k:9);g=k-9|0;h=h+4|0;if(j>>>0<=h>>>0){break n}d=(k|0)>9;k=g;if(d){continue}break}break n}q:{if((k|0)<0){break q}n=l>>>0>>0?j:l+4|0;d=m+16|0;f=d|9;d=d|8;h=l;while(1){g=Na(F[h>>2],0,f);if((f|0)==(g|0)){D[m+24|0]=48;g=d}r:{if((h|0)!=(l|0)){if(m+16>>>0>=g>>>0){break r}while(1){g=g-1|0;D[g|0]=48;if(m+16>>>0>>0){continue}break}break r}ma(a,g,1);g=g+1|0;if(r?0:(k|0)<=0){break r}ma(a,1718,1)}j=g;g=f-g|0;ma(a,j,(g|0)<(k|0)?g:k);k=k-g|0;h=h+4|0;if(n>>>0<=h>>>0){break q}if((k|0)>-1){continue}break}}va(a,48,k+18|0,18,0);ma(a,z,s-z|0);break m}g=k}va(a,48,g+9|0,9,0)}break b}j=(f<<26>>31&9)+y|0;s:{if(d>>>0>11){break s}g=12-d|0;if(!g){break s}t=8;while(1){t=t*16;g=g-1|0;if(g){continue}break}if(G[j|0]==45){b=-(t+(-b-t));break s}b=b+t-t}h=F[m+44>>2];g=h>>31;g=Na(g^g+h,0,s);if((s|0)==(g|0)){D[m+15|0]=48;g=m+15|0}l=u|2;k=f&32;h=F[m+44>>2];n=g-2|0;D[n|0]=f+15;D[g-1|0]=(h|0)<0?45:43;i=e&8;h=m+16|0;while(1){f=h;q=h;h=k;if(N(b)<2147483648){g=~~b}else{g=-2147483648}D[q|0]=h|G[g+36528|0];b=(b-+(g|0))*16;h=f+1|0;if(!(!(i?1:(d|0)>0|b!=0)|(h-(m+16|0)|0)!=1)){D[f+1|0]=46;h=f+2|0}if(b!=0){continue}break}g=a;f=c;if(!d|((h-m|0)-18|0)>=(d|0)){k=(s-(n+(m+16|0)|0)|0)+h|0}else{k=((d+s|0)-n|0)+2|0}d=k;i=d+l|0;va(g,32,f,i,e);ma(a,j,l);va(a,48,c,i,e^65536);g=m+16|0;f=h-g|0;ma(a,g,f);d=s-n|0;va(a,48,k-(d+f|0)|0,0,0);ma(a,n,d)}va(a,32,c,i,e^8192);_=m+560|0;return((c|0)>(i|0)?c:i)|0}function hb(a,b,c,d,e){var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0;g=_-80|0;_=g;F[g+76>>2]=b;t=g+55|0;r=g+56|0;b=0;a:{b:while(1){c:{if((n|0)<0){break c}if((2147483647-n|0)<(b|0)){F[9439]=61;n=-1;break c}n=b+n|0}d:{e:{f:{j=F[g+76>>2];b=j;f=G[b|0];if(f){while(1){g:{f=f&255;h:{if(!f){f=b;break h}if((f|0)!=37){break g}f=b;while(1){if(G[b+1|0]!=37){break h}h=b+2|0;F[g+76>>2]=h;f=f+1|0;k=G[b+2|0];b=h;if((k|0)==37){continue}break}}b=f-j|0;if(a){ma(a,j,b)}if(b){continue b}p=-1;f=1;h=g;b=F[g+76>>2];if(!(D[b+1|0]-48>>>0>=10|G[b+2|0]!=36)){p=D[b+1|0]-48|0;s=1;f=3}b=f+b|0;F[h+76>>2]=b;o=0;i=D[b|0];h=i-32|0;i:{if(h>>>0>31){f=b;break i}f=b;h=1<>2]=f;o=h|o;i=D[b+1|0];h=i-32|0;if(h>>>0>=32){break i}b=f;h=1<>>0>=10){break l}b=F[g+76>>2];if(G[b+2|0]!=36){break l}F[((D[b+1|0]<<2)+e|0)-192>>2]=10;l=F[((D[b+1|0]<<3)+d|0)-384>>2];s=1;b=b+3|0;break k}if(s){break f}s=0;l=0;if(a){b=F[c>>2];F[c>>2]=b+4;l=F[b>>2]}b=F[g+76>>2]+1|0}F[h+76>>2]=b;if((l|0)>-1){break j}l=0-l|0;o=o|8192;break j}l=Hb(g+76|0);if((l|0)<0){break f}b=F[g+76>>2]}k=-1;m:{if(G[b|0]!=46){break m}if(G[b+1|0]==42){n:{if(D[b+2|0]-48>>>0>=10){break n}b=F[g+76>>2];if(G[b+3|0]!=36){break n}F[((D[b+2|0]<<2)+e|0)-192>>2]=10;k=F[((D[b+2|0]<<3)+d|0)-384>>2];b=b+4|0;F[g+76>>2]=b;break m}if(s){break f}if(a){b=F[c>>2];F[c>>2]=b+4;k=F[b>>2]}else{k=0}b=F[g+76>>2]+2|0;F[g+76>>2]=b;break m}F[g+76>>2]=b+1;k=Hb(g+76|0);b=F[g+76>>2]}f=0;while(1){q=f;m=-1;if(D[b|0]-65>>>0>57){break a}i=b+1|0;F[g+76>>2]=i;f=D[b|0];b=i;f=G[(f+L(q,58)|0)+35999|0];if(f-1>>>0<8){continue}break}o:{p:{if((f|0)!=19){if(!f){break a}if((p|0)>=0){F[(p<<2)+e>>2]=f;b=(p<<3)+d|0;f=F[b+4>>2];F[g+64>>2]=F[b>>2];F[g+68>>2]=f;break p}if(!a){break d}Gb(g- -64|0,f,c);i=F[g+76>>2];break o}if((p|0)>-1){break a}}b=0;if(!a){continue b}}h=o&-65537;f=o&8192?h:o;m=0;p=1216;o=r;q:{r:{s:{t:{u:{v:{w:{x:{y:{z:{A:{B:{C:{D:{E:{F:{b=D[i-1|0];b=q?(b&15)==3?b&-33:b:b;switch(b-88|0){case 11:break q;case 9:case 13:case 14:case 15:break r;case 27:break w;case 12:case 17:break z;case 23:break A;case 0:case 32:break B;case 24:break C;case 22:break D;case 29:break E;case 1:case 2:case 3:case 4:case 5:case 6:case 7:case 8:case 10:case 16:case 18:case 19:case 20:case 21:case 25:case 26:case 28:case 30:case 31:break e;default:break F}}G:{switch(b-65|0){case 0:case 4:case 5:case 6:break r;case 2:break u;case 1:case 3:break e;default:break G}}if((b|0)==83){break v}break e}i=F[g+64>>2];h=F[g+68>>2];p=1216;break y}b=0;H:{switch(q&255){case 0:F[F[g+64>>2]>>2]=n;continue b;case 1:F[F[g+64>>2]>>2]=n;continue b;case 2:f=F[g+64>>2];F[f>>2]=n;F[f+4>>2]=n>>31;continue b;case 3:E[F[g+64>>2]>>1]=n;continue b;case 4:D[F[g+64>>2]]=n;continue b;case 6:F[F[g+64>>2]>>2]=n;continue b;case 7:break H;default:continue b}}f=F[g+64>>2];F[f>>2]=n;F[f+4>>2]=n>>31;continue b}k=k>>>0>8?k:8;f=f|8;b=120}j=r;u=b&32;q=F[g+68>>2];h=q;i=F[g+64>>2];if(h|i){while(1){j=j-1|0;D[j|0]=u|G[(i&15)+36528|0];v=!h&i>>>0>15|(h|0)!=0;q=h;h=h>>>4|0;i=(q&15)<<28|i>>>4;if(v){continue}break}}if(!(F[g+64>>2]|F[g+68>>2])|!(f&8)){break x}p=(b>>>4|0)+1216|0;m=2;break x}b=r;j=F[g+68>>2];h=j;i=F[g+64>>2];if(h|i){while(1){b=b-1|0;D[b|0]=i&7|48;q=!h&i>>>0>7|(h|0)!=0;j=h;h=h>>>3|0;i=(j&7)<<29|i>>>3;if(q){continue}break}}j=b;if(!(f&8)){break x}b=r-j|0;k=(b|0)<(k|0)?k:b+1|0;break x}b=F[g+68>>2];h=b;i=F[g+64>>2];if((b|0)<-1?1:(b|0)<=-1){h=0-(h+((i|0)!=0)|0)|0;i=0-i|0;F[g+64>>2]=i;F[g+68>>2]=h;m=1;p=1216;break y}if(f&2048){m=1;p=1217;break y}m=f&1;p=m?1218:1216}j=Na(i,h,r)}f=(k|0)>-1?f&-65537:f;b=F[g+68>>2];h=b;i=F[g+64>>2];if(!(k|((i|0)!=0|(b|0)!=0))){k=0;j=r;break e}b=!(h|i)+(r-j|0)|0;k=(b|0)<(k|0)?k:b;break e}b=k;o=(b|0)!=0;f=F[g+64>>2];j=f?f:1720;f=j;I:{J:{K:{L:{if(!(f&3)|!b){break L}while(1){if(!G[f|0]){break K}b=b-1|0;o=(b|0)!=0;f=f+1|0;if(!(f&3)){break L}if(b){continue}break}}if(!o){break J}}M:{if(!G[f|0]|b>>>0<4){break M}while(1){i=F[f>>2];if((i^-1)&i-16843009&-2139062144){break M}f=f+4|0;b=b-4|0;if(b>>>0>3){continue}break}}if(!b){break J}while(1){i=f;if(!G[f|0]){break I}f=f+1|0;b=b-1|0;if(b){continue}break}}i=0}o=i?i:k+j|0;f=h;k=i?i-j|0:k;break e}if(k){b=F[g+64>>2];break t}b=0;va(a,32,l,0,f);break s}F[g+12>>2]=0;F[g+8>>2]=F[g+64>>2];b=g+8|0;F[g+64>>2]=b;k=-1}h=b;b=0;N:{while(1){j=F[h>>2];if(!j){break N}j=Eb(g+4|0,j);i=(j|0)<0;if(!(i|j>>>0>k-b>>>0)){h=h+4|0;b=b+j|0;if(k>>>0>b>>>0){continue}break N}break}m=-1;if(i){break a}}va(a,32,l,b,f);if(!b){b=0;break s}h=0;i=F[g+64>>2];while(1){j=F[i>>2];if(!j){break s}j=Eb(g+4|0,j);h=j+h|0;if((h|0)>(b|0)){break s}ma(a,g+4|0,j);i=i+4|0;if(b>>>0>h>>>0){continue}break}}va(a,32,l,b,f^8192);b=(b|0)<(l|0)?l:b;continue b}b=aa[7](a,K[g+64>>3],l,k,f,b)|0;continue b}D[g+55|0]=F[g+64>>2];k=1;j=t;f=h;break e}h=b+1|0;F[g+76>>2]=h;f=G[b+1|0];b=h;continue}}m=n;if(a){break a}if(!s){break d}b=1;while(1){a=F[(b<<2)+e>>2];if(a){Gb((b<<3)+d|0,a,c);m=1;b=b+1|0;if((b|0)!=10){continue}break a}break}m=1;if(b>>>0>=10){break a}while(1){if(F[(b<<2)+e>>2]){break f}b=b+1|0;if((b|0)!=10){continue}break}break a}m=-1;break a}i=o-j|0;k=(i|0)>(k|0)?i:k;h=k+m|0;b=(h|0)>(l|0)?h:l;va(a,32,b,h,f);ma(a,p,m);va(a,48,b,h,f^65536);va(a,48,k,i,0);ma(a,j,i);va(a,32,b,h,f^8192);continue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432;F[a+28>>2]=b-c;b=qe(v,p,j,S);d=$;e=qe(u,o,e,M);c=e+b|0;b=$+d|0;b=c>>>0>>0?b+1|0:b;e=qe(O,y,R,N);c=e+c|0;d=$+b|0;d=c>>>0>>0?d+1|0:d;e=qe(G,z,D,E);b=e+c|0;c=$+d|0;c=b>>>0>>0?c+1|0:c;d=qe(w,q,n,t);b=d+b|0;c=$+c|0;c=b>>>0>>0?c+1|0:c;d=g>>26;g=(g&67108863)<<6|i>>>26;b=g+b|0;c=c+d|0;c=b>>>0>>0?c+1|0:c;d=b;b=c;c=d+16777216|0;b=c>>>0<16777216?b+1|0:b;i=c;g=b;b=c&-33554432;F[a+12>>2]=d-b;e=a;b=qe(O,y,I,C);c=$;d=qe(n,t,n,t);b=d+b|0;c=$+c|0;c=b>>>0>>0?c+1|0:c;d=qe(x,s,D,E);b=d+b|0;c=$+c|0;c=b>>>0>>0?c+1|0:c;j=qe(u,o,Z,V);d=j+b|0;b=$+c|0;b=d>>>0>>0?b+1|0:b;j=qe(v,p,U,P);c=j+d|0;d=$+b|0;d=c>>>0>>0?d+1|0:d;j=A;r=j>>31;A=qe(w,q,j,r);b=A+c|0;c=$+d|0;c=b>>>0>>0?c+1|0:c;a=b;b=f>>25;f=(f&33554431)<<7|k>>>25;d=a+f|0;c=b+c|0;c=d>>>0>>0?c+1|0:c;b=d;d=b+33554432|0;c=d>>>0<33554432?c+1|0:c;A=d;f=c;c=d&-67108864;F[e+32>>2]=b-c;K=K-(ea&-33554432)|0;c=g>>25;g=(g&33554431)<<7|i>>>25;b=aa&-67108864;d=g+(X-b|0)|0;b=c+(ca-((b>>>0>X>>>0)+da|0)|0)|0;b=d>>>0>>0?b+1|0:b;c=b;b=d+33554432|0;c=b>>>0<33554432?c+1|0:c;g=b;b=((c&67108863)<<6|b>>>26)+K|0;F[e+20>>2]=b;b=g&-67108864;F[e+16>>2]=d-b;g=e;b=qe(x,s,O,y);d=$;e=qe(_,Q,ba,Y);c=e+b|0;b=$+d|0;b=c>>>0>>0?b+1|0:b;e=qe(I,C,l,W);d=e+c|0;c=$+b|0;c=d>>>0>>0?c+1|0:c;e=qe(u,o,U,P);b=e+d|0;d=$+c|0;d=b>>>0>>0?d+1|0:d;e=qe(v,p,j,r);b=e+b|0;c=$+d|0;d=b;b=b>>>0>>0?c+1|0:c;c=f>>26;f=(f&67108863)<<6|A>>>26;d=f+d|0;c=b+c|0;c=d>>>0>>0?c+1|0:c;f=d;b=c;c=d+16777216|0;b=c>>>0<16777216?b+1|0:b;d=c&-33554432;F[g+36>>2]=f-d;e=qe((b&33554431)<<7|c>>>25,b>>25,19,0);d=J&-67108864;b=e+(m-d|0)|0;c=$+(B-((d>>>0>m>>>0)+T|0)|0)|0;d=b;b=b>>>0>>0?c+1|0:c;c=d+33554432|0;b=c>>>0<33554432?b+1|0:b;b=(h-(H&-33554432)|0)+((b&67108863)<<6|c>>>26)|0;F[g+4>>2]=b;a=c&-67108864;F[g>>2]=d-a}function ga(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,G=0,H=0,I=0,J=0,K=0,L=0,M=0,N=0,O=0;p=_-160|0;_=p;c=b;z=F[c>>2];d=F[c+16>>2];q=d;r=d>>31;d=F[c+24>>2];s=d;t=d>>31;J=F[c+8>>2];d=F[c+32>>2];u=d;v=d>>31;l=F[c+40>>2];f=p;d=F[c+72>>2];i=d;I=d;n=d>>31;c=F[c+48>>2];A=c;w=c>>31;x=qe(d,n,c,w);o=$;c=F[b+64>>2];d=c>>31;m=d;e=d;d=F[b+56>>2];g=d;j=c;H=d;B=d>>31;d=qe(c,e,d,B);c=d+x|0;b=$+o|0;k=c;b=c>>>0>>0?b+1|0:b;e=b;d=b<<1|c>>>31;F[f+120>>2]=c<<1;F[f+124>>2]=d;d=f;c=l;y=c;o=c>>31;b=qe(j,m,c,o);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|0)==(e|0)){d=0;break c}i=c-e|0;h=i&3;d=0;b=c;if(b+(e^-1)>>>0>=3){e=i&-4;while(1){d=(G[b-2|0]&127|(d<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;d=d|G[b|0]&127;e=e-4|0;if(e){continue}break}}if(h){while(1){b=b-1|0;d=G[b|0]&127|d<<7;h=h-1|0;if(h){continue}break}}if(f-c>>>0>>0){break a}}F[a+24>>2]=d;F[a+20>>2]=c;b=c+d|0}if((b|0)==(f|0)){break a}if(G[b|0]==18){e=b+1|0;b=e;while(1){d:{if((b|0)==(f|0)){c=f;break d}d=D[b|0];c=b+1|0;b=c;if((d|0)<0){continue}}break}e:{if((c|0)==(e|0)){d=0;break e}i=c-e|0;h=i&3;d=0;b=c;if(b+(e^-1)>>>0>=3){e=i&-4;while(1){d=(G[b-2|0]&127|(d<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;d=d|G[b|0]&127;e=e-4|0;if(e){continue}break}}if(h){while(1){b=b-1|0;d=G[b|0]&127|d<<7;h=h-1|0;if(h){continue}break}}if(f-c>>>0>>0){break a}}F[a+16>>2]=d;F[a+12>>2]=c;b=c+d|0}if((b|0)==(f|0)){break a}if(G[b|0]==26){e=b+1|0;b=e;while(1){f:{if((b|0)==(f|0)){c=f;break f}d=D[b|0];c=b+1|0;b=c;if((d|0)<0){continue}}break}g:{if((c|0)==(e|0)){d=0;break g}i=c-e|0;h=i&3;d=0;b=c;if(b+(e^-1)>>>0>=3){e=i&-4;while(1){d=(G[b-2|0]&127|(d<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;d=d|G[b|0]&127;e=e-4|0;if(e){continue}break}}if(h){while(1){b=b-1|0;d=G[b|0]&127|d<<7;h=h-1|0;if(h){continue}break}}if(f-c>>>0>>0){break a}}F[a+8>>2]=d;F[a+4>>2]=c;b=c+d|0}if((b|0)==(f|0)){break a}if(G[b|0]==34){e=b+1|0;b=e;while(1){h:{if((b|0)==(f|0)){c=f;break h}d=D[b|0];c=b+1|0;b=c;if((d|0)<0){continue}}break}i:{if((c|0)==(e|0)){d=0;break i}i=c-e|0;h=i&3;d=0;b=c;if(b+(e^-1)>>>0>=3){e=i&-4;while(1){d=(G[b-2|0]&127|(d<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;d=d|G[b|0]&127;e=e-4|0;if(e){continue}break}}if(h){while(1){b=b-1|0;d=G[b|0]&127|d<<7;h=h-1|0;if(h){continue}break}}if(f-c>>>0>>0){break a}}F[a+32>>2]=d;F[a+28>>2]=c;b=c+d|0}j:{if((b|0)==(f|0)|(b|0)!=(g|0)){break j}k:{switch(G[g|0]&7){case 0:while(1){l:{if((f|0)==(g|0)){d=f;break l}b=D[g|0];d=g+1|0;g=d;if((b|0)<0){continue}}break};while(1){if((d|0)==(f|0)){b=f;break j}c=D[d|0];b=d+1|0;d=b;if((c|0)<=-1){continue}break};break j;case 2:break k;default:break a}}while(1){m:{if((f|0)==(g|0)){b=f;break m}c=D[g|0];b=g+1|0;g=b;if((c|0)<0){continue}}break}g=b;while(1){n:{if((f|0)==(g|0)){c=f;break n}d=D[g|0];c=g+1|0;g=c;if((d|0)<0){continue}}break}if((b|0)==(c|0)){break j}e=c-b|0;h=e&3;d=0;g=c;if((b^-1)+c>>>0>=3){b=e&-4;while(1){e=(G[g-2|0]&127|(d<<14|(G[g-1|0]&127)<<7))<<14|(G[g-3|0]&127)<<7;g=g-4|0;d=e|G[g|0]&127;b=b-4|0;if(b){continue}break}}if(h){while(1){g=g-1|0;d=G[g|0]&127|d<<7;h=h-1|0;if(h){continue}break}}if(f-c>>>0>>0){break a}b=c+d|0}if((b|0)!=(f|0)){continue}break}}}function Qb(a,b,c){var d=0,e=0,f=0,g=0;a:{if(!a){break a}d=a+32|0;if(d>>>0>b>>>0){break a}f=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);g=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[c|0]=g;D[c+1|0]=g>>>8;D[c+2|0]=g>>>16;D[c+3|0]=g>>>24;D[c+4|0]=f;D[c+5|0]=f>>>8;D[c+6|0]=f>>>16;D[c+7|0]=f>>>24;f=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);g=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[c+24|0]=g;D[c+25|0]=g>>>8;D[c+26|0]=g>>>16;D[c+27|0]=g>>>24;D[c+28|0]=f;D[c+29|0]=f>>>8;D[c+30|0]=f>>>16;D[c+31|0]=f>>>24;f=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);g=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[c+16|0]=g;D[c+17|0]=g>>>8;D[c+18|0]=g>>>16;D[c+19|0]=g>>>24;D[c+20|0]=f;D[c+21|0]=f>>>8;D[c+22|0]=f>>>16;D[c+23|0]=f>>>24;f=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);g=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[c+8|0]=g;D[c+9|0]=g>>>8;D[c+10|0]=g>>>16;D[c+11|0]=g>>>24;D[c+12|0]=f;D[c+13|0]=f>>>8;D[c+14|0]=f>>>16;D[c+15|0]=f>>>24;f=b;b=a+96|0;if(f>>>0>>0){break a}a=d;d=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);e=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[c+32|0]=e;D[c+33|0]=e>>>8;D[c+34|0]=e>>>16;D[c+35|0]=e>>>24;D[c+36|0]=d;D[c+37|0]=d>>>8;D[c+38|0]=d>>>16;D[c+39|0]=d>>>24;d=G[a+60|0]|G[a+61|0]<<8|(G[a+62|0]<<16|G[a+63|0]<<24);e=G[a+56|0]|G[a+57|0]<<8|(G[a+58|0]<<16|G[a+59|0]<<24);D[c+88|0]=e;D[c+89|0]=e>>>8;D[c+90|0]=e>>>16;D[c+91|0]=e>>>24;D[c+92|0]=d;D[c+93|0]=d>>>8;D[c+94|0]=d>>>16;D[c+95|0]=d>>>24;d=G[a+52|0]|G[a+53|0]<<8|(G[a+54|0]<<16|G[a+55|0]<<24);e=G[a+48|0]|G[a+49|0]<<8|(G[a+50|0]<<16|G[a+51|0]<<24);D[c+80|0]=e;D[c+81|0]=e>>>8;D[c+82|0]=e>>>16;D[c+83|0]=e>>>24;D[c+84|0]=d;D[c+85|0]=d>>>8;D[c+86|0]=d>>>16;D[c+87|0]=d>>>24;d=G[a+44|0]|G[a+45|0]<<8|(G[a+46|0]<<16|G[a+47|0]<<24);e=G[a+40|0]|G[a+41|0]<<8|(G[a+42|0]<<16|G[a+43|0]<<24);D[c+72|0]=e;D[c+73|0]=e>>>8;D[c+74|0]=e>>>16;D[c+75|0]=e>>>24;D[c+76|0]=d;D[c+77|0]=d>>>8;D[c+78|0]=d>>>16;D[c+79|0]=d>>>24;e=G[a+36|0]|G[a+37|0]<<8|(G[a+38|0]<<16|G[a+39|0]<<24);d=c- -64|0;f=G[a+32|0]|G[a+33|0]<<8|(G[a+34|0]<<16|G[a+35|0]<<24);D[d|0]=f;D[d+1|0]=f>>>8;D[d+2|0]=f>>>16;D[d+3|0]=f>>>24;D[d+4|0]=e;D[d+5|0]=e>>>8;D[d+6|0]=e>>>16;D[d+7|0]=e>>>24;d=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);e=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[c+56|0]=e;D[c+57|0]=e>>>8;D[c+58|0]=e>>>16;D[c+59|0]=e>>>24;D[c+60|0]=d;D[c+61|0]=d>>>8;D[c+62|0]=d>>>16;D[c+63|0]=d>>>24;d=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);e=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[c+48|0]=e;D[c+49|0]=e>>>8;D[c+50|0]=e>>>16;D[c+51|0]=e>>>24;D[c+52|0]=d;D[c+53|0]=d>>>8;D[c+54|0]=d>>>16;D[c+55|0]=d>>>24;d=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);a=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[c+40|0]=a;D[c+41|0]=a>>>8;D[c+42|0]=a>>>16;D[c+43|0]=a>>>24;D[c+44|0]=d;D[c+45|0]=d>>>8;D[c+46|0]=d>>>16;D[c+47|0]=d>>>24;e=b}return e}function Xc(a){a=a|0;var b=0,c=0,d=0,e=0,f=0,g=0,h=0;a:{if(!a){break a}d=a-8|0;b=F[a-4>>2];a=b&-8;f=d+a|0;b:{if(b&1){break b}if(!(b&3)){break a}b=F[d>>2];d=d-b|0;if(d>>>0>>0<=255){e=F[d+8>>2];b=b>>>3|0;c=F[d+12>>2];if((c|0)==(e|0)){F[9456]=F[9456]&se(-2,b);break b}F[e+12>>2]=c;F[c+8>>2]=e;break b}h=F[d+24>>2];b=F[d+12>>2];c:{if((d|0)!=(b|0)){c=F[d+8>>2];F[c+12>>2]=b;F[b+8>>2]=c;break c}d:{e=d+20|0;c=F[e>>2];if(c){break d}e=d+16|0;c=F[e>>2];if(c){break d}b=0;break c}while(1){g=e;b=c;e=b+20|0;c=F[e>>2];if(c){continue}e=b+16|0;c=F[b+16>>2];if(c){continue}break}F[g>>2]=0}if(!h){break b}e=F[d+28>>2];c=(e<<2)+38128|0;e:{if(F[c>>2]==(d|0)){F[c>>2]=b;if(b){break e}F[9457]=F[9457]&se(-2,e);break b}F[h+(F[h+16>>2]==(d|0)?16:20)>>2]=b;if(!b){break b}}F[b+24>>2]=h;c=F[d+16>>2];if(c){F[b+16>>2]=c;F[c+24>>2]=b}c=F[d+20>>2];if(!c){break b}F[b+20>>2]=c;F[c+24>>2]=b;break b}b=F[f+4>>2];if((b&3)!=3){break b}F[9458]=a;F[f+4>>2]=b&-2;F[d+4>>2]=a|1;F[a+d>>2]=a;return}if(d>>>0>=f>>>0){break a}b=F[f+4>>2];if(!(b&1)){break a}f:{if(!(b&2)){if(F[9462]==(f|0)){F[9462]=d;a=F[9459]+a|0;F[9459]=a;F[d+4>>2]=a|1;if(F[9461]!=(d|0)){break a}F[9458]=0;F[9461]=0;return}if(F[9461]==(f|0)){F[9461]=d;a=F[9458]+a|0;F[9458]=a;F[d+4>>2]=a|1;F[a+d>>2]=a;return}a=(b&-8)+a|0;g:{if(b>>>0<=255){e=F[f+8>>2];b=b>>>3|0;c=F[f+12>>2];if((c|0)==(e|0)){F[9456]=F[9456]&se(-2,b);break g}F[e+12>>2]=c;F[c+8>>2]=e;break g}h=F[f+24>>2];b=F[f+12>>2];h:{if((f|0)!=(b|0)){c=F[f+8>>2];F[c+12>>2]=b;F[b+8>>2]=c;break h}i:{e=f+20|0;c=F[e>>2];if(c){break i}e=f+16|0;c=F[e>>2];if(c){break i}b=0;break h}while(1){g=e;b=c;e=b+20|0;c=F[e>>2];if(c){continue}e=b+16|0;c=F[b+16>>2];if(c){continue}break}F[g>>2]=0}if(!h){break g}e=F[f+28>>2];c=(e<<2)+38128|0;j:{if(F[c>>2]==(f|0)){F[c>>2]=b;if(b){break j}F[9457]=F[9457]&se(-2,e);break g}F[h+(F[h+16>>2]==(f|0)?16:20)>>2]=b;if(!b){break g}}F[b+24>>2]=h;c=F[f+16>>2];if(c){F[b+16>>2]=c;F[c+24>>2]=b}c=F[f+20>>2];if(!c){break g}F[b+20>>2]=c;F[c+24>>2]=b}F[d+4>>2]=a|1;F[a+d>>2]=a;if(F[9461]!=(d|0)){break f}F[9458]=a;return}F[f+4>>2]=b&-2;F[d+4>>2]=a|1;F[a+d>>2]=a}if(a>>>0<=255){a=a>>>3|0;b=(a<<3)+37864|0;c=F[9456];a=1<>2]}F[b+8>>2]=d;F[a+12>>2]=d;F[d+12>>2]=b;F[d+8>>2]=a;return}e=31;F[d+16>>2]=0;F[d+20>>2]=0;if(a>>>0<=16777215){b=a>>>8|0;g=b+1048320>>>16&8;b=b<>>16&4;b=b<>>16&2;b=(b<>>15|0)-(c|(e|g))|0;e=(b<<1|a>>>b+21&1)+28|0}F[d+28>>2]=e;g=(e<<2)+38128|0;l:{m:{c=F[9457];b=1<>2]=d;F[d+24>>2]=g;break n}e=a<<((e|0)==31?0:25-(e>>>1|0)|0);b=F[g>>2];while(1){c=b;if((F[b+4>>2]&-8)==(a|0)){break m}b=e>>>29|0;e=e<<1;g=c+(b&4)|0;b=F[g+16>>2];if(b){continue}break}F[g+16>>2]=d;F[d+24>>2]=c}F[d+12>>2]=d;F[d+8>>2]=d;break l}a=F[c+8>>2];F[a+12>>2]=d;F[c+8>>2]=d;F[d+24>>2]=0;F[d+12>>2]=c;F[d+8>>2]=a}a=F[9464]-1|0;F[9464]=a?a:-1}}function Sb(a,b){var c=0,d=0,e=0;c=G[b+4|0]|G[b+5|0]<<8|(G[b+6|0]<<16|G[b+7|0]<<24);d=G[b|0]|G[b+1|0]<<8|(G[b+2|0]<<16|G[b+3|0]<<24);D[a|0]=d;D[a+1|0]=d>>>8;D[a+2|0]=d>>>16;D[a+3|0]=d>>>24;D[a+4|0]=c;D[a+5|0]=c>>>8;D[a+6|0]=c>>>16;D[a+7|0]=c>>>24;c=G[b+28|0]|G[b+29|0]<<8|(G[b+30|0]<<16|G[b+31|0]<<24);d=G[b+24|0]|G[b+25|0]<<8|(G[b+26|0]<<16|G[b+27|0]<<24);D[a+24|0]=d;D[a+25|0]=d>>>8;D[a+26|0]=d>>>16;D[a+27|0]=d>>>24;D[a+28|0]=c;D[a+29|0]=c>>>8;D[a+30|0]=c>>>16;D[a+31|0]=c>>>24;c=G[b+20|0]|G[b+21|0]<<8|(G[b+22|0]<<16|G[b+23|0]<<24);d=G[b+16|0]|G[b+17|0]<<8|(G[b+18|0]<<16|G[b+19|0]<<24);D[a+16|0]=d;D[a+17|0]=d>>>8;D[a+18|0]=d>>>16;D[a+19|0]=d>>>24;D[a+20|0]=c;D[a+21|0]=c>>>8;D[a+22|0]=c>>>16;D[a+23|0]=c>>>24;c=G[b+12|0]|G[b+13|0]<<8|(G[b+14|0]<<16|G[b+15|0]<<24);d=G[b+8|0]|G[b+9|0]<<8|(G[b+10|0]<<16|G[b+11|0]<<24);D[a+8|0]=d;D[a+9|0]=d>>>8;D[a+10|0]=d>>>16;D[a+11|0]=d>>>24;D[a+12|0]=c;D[a+13|0]=c>>>8;D[a+14|0]=c>>>16;D[a+15|0]=c>>>24;c=G[b+36|0]|G[b+37|0]<<8|(G[b+38|0]<<16|G[b+39|0]<<24);d=G[b+32|0]|G[b+33|0]<<8|(G[b+34|0]<<16|G[b+35|0]<<24);D[a+32|0]=d;D[a+33|0]=d>>>8;D[a+34|0]=d>>>16;D[a+35|0]=d>>>24;D[a+36|0]=c;D[a+37|0]=c>>>8;D[a+38|0]=c>>>16;D[a+39|0]=c>>>24;c=G[b+44|0]|G[b+45|0]<<8|(G[b+46|0]<<16|G[b+47|0]<<24);d=G[b+40|0]|G[b+41|0]<<8|(G[b+42|0]<<16|G[b+43|0]<<24);D[a+40|0]=d;D[a+41|0]=d>>>8;D[a+42|0]=d>>>16;D[a+43|0]=d>>>24;D[a+44|0]=c;D[a+45|0]=c>>>8;D[a+46|0]=c>>>16;D[a+47|0]=c>>>24;c=G[b+52|0]|G[b+53|0]<<8|(G[b+54|0]<<16|G[b+55|0]<<24);d=G[b+48|0]|G[b+49|0]<<8|(G[b+50|0]<<16|G[b+51|0]<<24);D[a+48|0]=d;D[a+49|0]=d>>>8;D[a+50|0]=d>>>16;D[a+51|0]=d>>>24;D[a+52|0]=c;D[a+53|0]=c>>>8;D[a+54|0]=c>>>16;D[a+55|0]=c>>>24;c=G[b+60|0]|G[b+61|0]<<8|(G[b+62|0]<<16|G[b+63|0]<<24);d=G[b+56|0]|G[b+57|0]<<8|(G[b+58|0]<<16|G[b+59|0]<<24);D[a+56|0]=d;D[a+57|0]=d>>>8;D[a+58|0]=d>>>16;D[a+59|0]=d>>>24;D[a+60|0]=c;D[a+61|0]=c>>>8;D[a+62|0]=c>>>16;D[a+63|0]=c>>>24;d=b- -64|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);c=a- -64|0;d=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);D[c|0]=d;D[c+1|0]=d>>>8;D[c+2|0]=d>>>16;D[c+3|0]=d>>>24;D[c+4|0]=e;D[c+5|0]=e>>>8;D[c+6|0]=e>>>16;D[c+7|0]=e>>>24;c=G[b+76|0]|G[b+77|0]<<8|(G[b+78|0]<<16|G[b+79|0]<<24);d=G[b+72|0]|G[b+73|0]<<8|(G[b+74|0]<<16|G[b+75|0]<<24);D[a+72|0]=d;D[a+73|0]=d>>>8;D[a+74|0]=d>>>16;D[a+75|0]=d>>>24;D[a+76|0]=c;D[a+77|0]=c>>>8;D[a+78|0]=c>>>16;D[a+79|0]=c>>>24;c=G[b+84|0]|G[b+85|0]<<8|(G[b+86|0]<<16|G[b+87|0]<<24);d=G[b+80|0]|G[b+81|0]<<8|(G[b+82|0]<<16|G[b+83|0]<<24);D[a+80|0]=d;D[a+81|0]=d>>>8;D[a+82|0]=d>>>16;D[a+83|0]=d>>>24;D[a+84|0]=c;D[a+85|0]=c>>>8;D[a+86|0]=c>>>16;D[a+87|0]=c>>>24;c=G[b+92|0]|G[b+93|0]<<8|(G[b+94|0]<<16|G[b+95|0]<<24);b=G[b+88|0]|G[b+89|0]<<8|(G[b+90|0]<<16|G[b+91|0]<<24);D[a+88|0]=b;D[a+89|0]=b>>>8;D[a+90|0]=b>>>16;D[a+91|0]=b>>>24;D[a+92|0]=c;D[a+93|0]=c>>>8;D[a+94|0]=c>>>16;D[a+95|0]=c>>>24;return a+96|0}function cb(a,b){var c=0,d=0,e=0,f=0,g=0,h=0;a:{if(!a|!b){break a}c=F[a+72>>2];if(c>>>0>127){break a}F[a+72>>2]=c+1;e=F[a+4>>2]+(c>>>29|0)|0;d=c<<3;f=d+F[a>>2]|0;F[a>>2]=f;F[a+4>>2]=d>>>0>f>>>0?e+1|0:e;f=a+76|0;D[f+c|0]=128;c=F[a+72>>2];if(c>>>0>=113){if(c>>>0<=127){while(1){F[a+72>>2]=c+1;D[(a+c|0)+76|0]=0;c=F[a+72>>2];if(c>>>0<128){continue}break}}ta(a,f);c=0}while(1){F[a+72>>2]=c+1;D[(a+c|0)+76|0]=0;c=F[a+72>>2];if(c>>>0<120){continue}break}c=F[a>>2];g=c<<24|c<<8&16711680;d=c>>>8|0;e=F[a+4>>2];h=d|e<<24;c=c>>>24|0;d=(d|(e&255)<<24)&-16777216|(c|(e&16777215)<<8)&16711680|(e>>>8&65280|e>>>24);D[a+196|0]=d;D[a+197|0]=d>>>8;D[a+198|0]=d>>>16;D[a+199|0]=d>>>24;c=h&65280|(c|e<<8)&255|g;D[a+200|0]=c;D[a+201|0]=c>>>8;D[a+202|0]=c>>>16;D[a+203|0]=c>>>24;ta(a,f);D[b|0]=G[a+15|0];D[b+1|0]=H[a+14>>1];D[b+2|0]=F[a+12>>2]>>>8;D[b+3|0]=F[a+12>>2];D[b+4|0]=(F[a+12>>2]&16777215)<<8|F[a+8>>2]>>>24;D[b+5|0]=(F[a+12>>2]&65535)<<16|F[a+8>>2]>>>16;D[b+6|0]=(F[a+12>>2]&255)<<24|F[a+8>>2]>>>8;D[b+7|0]=F[a+8>>2];D[b+8|0]=G[a+23|0];D[b+9|0]=H[a+22>>1];D[b+10|0]=F[a+20>>2]>>>8;D[b+11|0]=F[a+20>>2];D[b+12|0]=(F[a+20>>2]&16777215)<<8|F[a+16>>2]>>>24;D[b+13|0]=(F[a+20>>2]&65535)<<16|F[a+16>>2]>>>16;D[b+14|0]=(F[a+20>>2]&255)<<24|F[a+16>>2]>>>8;D[b+15|0]=F[a+16>>2];D[b+16|0]=G[a+31|0];D[b+17|0]=H[a+30>>1];D[b+18|0]=F[a+28>>2]>>>8;D[b+19|0]=F[a+28>>2];D[b+20|0]=(F[a+28>>2]&16777215)<<8|F[a+24>>2]>>>24;D[b+21|0]=(F[a+28>>2]&65535)<<16|F[a+24>>2]>>>16;D[b+22|0]=(F[a+28>>2]&255)<<24|F[a+24>>2]>>>8;D[b+23|0]=F[a+24>>2];D[b+24|0]=G[a+39|0];D[b+25|0]=H[a+38>>1];D[b+26|0]=F[a+36>>2]>>>8;D[b+27|0]=F[a+36>>2];D[b+28|0]=(F[a+36>>2]&16777215)<<8|F[a+32>>2]>>>24;D[b+29|0]=(F[a+36>>2]&65535)<<16|F[a+32>>2]>>>16;D[b+30|0]=(F[a+36>>2]&255)<<24|F[a+32>>2]>>>8;D[b+31|0]=F[a+32>>2];D[b+32|0]=G[a+47|0];D[b+33|0]=H[a+46>>1];D[b+34|0]=F[a+44>>2]>>>8;D[b+35|0]=F[a+44>>2];D[b+36|0]=(F[a+44>>2]&16777215)<<8|F[a+40>>2]>>>24;D[b+37|0]=(F[a+44>>2]&65535)<<16|F[a+40>>2]>>>16;D[b+38|0]=(F[a+44>>2]&255)<<24|F[a+40>>2]>>>8;D[b+39|0]=F[a+40>>2];D[b+40|0]=G[a+55|0];D[b+41|0]=H[a+54>>1];D[b+42|0]=F[a+52>>2]>>>8;D[b+43|0]=F[a+52>>2];D[b+44|0]=(F[a+52>>2]&16777215)<<8|F[a+48>>2]>>>24;D[b+45|0]=(F[a+52>>2]&65535)<<16|F[a+48>>2]>>>16;D[b+46|0]=(F[a+52>>2]&255)<<24|F[a+48>>2]>>>8;D[b+47|0]=F[a+48>>2];D[b+48|0]=G[a+63|0];D[b+49|0]=H[a+62>>1];D[b+50|0]=F[a+60>>2]>>>8;D[b+51|0]=F[a+60>>2];D[b+52|0]=(F[a+60>>2]&16777215)<<8|F[a+56>>2]>>>24;D[b+53|0]=(F[a+60>>2]&65535)<<16|F[a+56>>2]>>>16;D[b+54|0]=(F[a+60>>2]&255)<<24|F[a+56>>2]>>>8;D[b+55|0]=F[a+56>>2];D[b+56|0]=G[a+71|0];D[b+57|0]=H[a+70>>1];c=a- -64|0;D[b+58|0]=F[c+4>>2]>>>8;D[b+59|0]=F[a+68>>2];D[b+60|0]=(F[c+4>>2]&16777215)<<8|F[c>>2]>>>24;D[b+61|0]=(F[c+4>>2]&65535)<<16|F[c>>2]>>>16;D[b+62|0]=(F[c+4>>2]&255)<<24|F[c>>2]>>>8;D[b+63|0]=F[c>>2]}}function vc(a,b,c,d,e,f,g,h,i){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;var j=0,k=0,l=0,m=0;j=_-160|0;_=j;l=-1;if(!(i>>>0<8|(e+16&-16)>>>0>g>>>0)){m=j+80|0;Aa(b,c,0,0,F[a+4>>2],F[a+8>>2],m,80);a=F[j+108>>2];F[j+24>>2]=F[j+104>>2];F[j+28>>2]=a;a=F[j+100>>2];F[j+16>>2]=F[j+96>>2];F[j+20>>2]=a;a=F[j+92>>2];F[j+8>>2]=F[j+88>>2];F[j+12>>2]=a;a=F[j+124>>2];F[j+40>>2]=F[j+120>>2];F[j+44>>2]=a;a=F[j+132>>2];F[j+48>>2]=F[j+128>>2];F[j+52>>2]=a;a=F[j+140>>2];F[j+56>>2]=F[j+136>>2];F[j+60>>2]=a;a=F[j+156>>2];F[j+72>>2]=F[j+152>>2];F[j+76>>2]=a;a=F[j+84>>2];F[j>>2]=F[j+80>>2];F[j+4>>2]=a;a=F[j+116>>2];F[j+32>>2]=F[j+112>>2];F[j+36>>2]=a;a=F[j+148>>2];F[j+64>>2]=F[j+144>>2];F[j+68>>2]=a;ia(m,80);g=_-256|0;_=g;Kb(j,g+16|0);a=j- -64|0;b=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);F[g+8>>2]=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);F[g+12>>2]=b;b=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);F[g>>2]=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);F[g+4>>2]=b;if(e>>>0>15){while(1){D[g|0]=G[g|0]^G[d|0];D[g+1|0]=G[g+1|0]^G[d+1|0];D[g+2|0]=G[g+2|0]^G[d+2|0];D[g+3|0]=G[g+3|0]^G[d+3|0];D[g+4|0]=G[g+4|0]^G[d+4|0];D[g+5|0]=G[g+5|0]^G[d+5|0];D[g+6|0]=G[g+6|0]^G[d+6|0];D[g+7|0]=G[g+7|0]^G[d+7|0];D[g+8|0]=G[g+8|0]^G[d+8|0];D[g+9|0]=G[g+9|0]^G[d+9|0];D[g+10|0]=G[g+10|0]^G[d+10|0];D[g+11|0]=G[g+11|0]^G[d+11|0];D[g+12|0]=G[g+12|0]^G[d+12|0];D[g+13|0]=G[g+13|0]^G[d+13|0];D[g+14|0]=G[g+14|0]^G[d+14|0];D[g+15|0]=G[g+15|0]^G[d+15|0];Lb(g,f,g+16|0);a=G[f+12|0]|G[f+13|0]<<8|(G[f+14|0]<<16|G[f+15|0]<<24);F[g+8>>2]=G[f+8|0]|G[f+9|0]<<8|(G[f+10|0]<<16|G[f+11|0]<<24);F[g+12>>2]=a;a=G[f+4|0]|G[f+5|0]<<8|(G[f+6|0]<<16|G[f+7|0]<<24);F[g>>2]=G[f|0]|G[f+1|0]<<8|(G[f+2|0]<<16|G[f+3|0]<<24);F[g+4>>2]=a;f=f+16|0;d=d+16|0;e=e-16|0;if(e>>>0>15){continue}break}}a:{b:{if(!e){e=0;a=16;break b}c=e&3;b=0;if(e-1>>>0>=3){l=e&-4;while(1){a=b+g|0;D[a|0]=G[a|0]^G[b+d|0];a=b|1;k=a+g|0;D[k|0]=G[k|0]^G[a+d|0];a=b|2;k=a+g|0;D[k|0]=G[k|0]^G[a+d|0];a=b|3;k=a+g|0;D[k|0]=G[k|0]^G[a+d|0];b=b+4|0;l=l-4|0;if(l){continue}break}}if(c){while(1){a=b+g|0;D[a|0]=G[a|0]^G[b+d|0];b=b+1|0;c=c-1|0;if(c){continue}break}}if(e>>>0>15){break a}a=16-e|0}c=15-e|0;b=0-e&3;if(b){while(1){d=e+g|0;D[d|0]=a^G[d|0];e=e+1|0;b=b-1|0;if(b){continue}break}}if(c>>>0<3){break a}while(1){b=e+g|0;D[b|0]=a^G[b|0];D[b+1|0]=a^G[b+1|0];D[b+2|0]=a^G[b+2|0];D[b+3|0]=a^G[b+3|0];e=e+4|0;if((e|0)!=16){continue}break}}a=g+16|0;Lb(g,f,a);ia(a,240);ia(g,16);_=g+256|0;ka(j+32|0,32,h,i-8|0,m);b=F[j+84>>2];a=(h+i|0)-8|0;c=F[j+80>>2];D[a|0]=c;D[a+1|0]=c>>>8;D[a+2|0]=c>>>16;D[a+3|0]=c>>>24;D[a+4|0]=b;D[a+5|0]=b>>>8;D[a+6|0]=b>>>16;D[a+7|0]=b>>>24;ia(j,80);l=i}_=j+160|0;return l|0}function wa(a){var b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0;F[a+80>>2]=0;F[a+84>>2]=0;c=a;e=F[c+4>>2];g=e;h=F[c>>2];d=h;b=e;e=b>>31>>>6|0;h=e+d|0;b=e>>>0>h>>>0?b+1|0:b;f=h;h=f&-67108864;i=d-h|0;e=g-((d>>>0>>0)+b|0)|0;h=e;F[c>>2]=i;F[c+4>>2]=e;c=b;b=b>>26;g=(c&67108863)<<6|f>>>26;c=g+F[a+8>>2]|0;b=b+F[a+12>>2]|0;b=c>>>0>>0?b+1|0:b;g=b;f=c;e=b>>31>>>7|0;c=e+c|0;b=c>>>0>>0?b+1|0:b;d=c;c=c&-33554432;F[a+8>>2]=f-c;F[a+12>>2]=g-((c>>>0>f>>>0)+b|0);c=b;b=b>>25;d=(c&33554431)<<7|d>>>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+1|0:b;d=c;c=c&-33554432;F[a+56>>2]=f-c;F[a+60>>2]=g-((c>>>0>f>>>0)+b|0);c=b;b=b>>25;d=(c&33554431)<<7|d>>>25;c=d+F[a+64>>2]|0;b=b+F[a+68>>2]|0;b=c>>>0>>0?b+1|0:b;g=b;f=c;e=b>>31>>>6|0;c=e+c|0;b=c>>>0>>0?b+1|0:b;d=c;c=c&-67108864;F[a+64>>2]=f-c;F[a+68>>2]=g-((c>>>0>f>>>0)+b|0);c=b;b=b>>26;d=(c&67108863)<<6|d>>>26;c=d+F[a+72>>2]|0;b=b+F[a+76>>2]|0;b=c>>>0>>0?b+1|0:b;g=b;f=c;e=b>>31>>>7|0;c=e+c|0;b=c>>>0>>0?b+1|0:b;e=c;c=c&-33554432;F[a+72>>2]=f-c;F[a+76>>2]=g-((c>>>0>f>>>0)+b|0);g=F[a+80>>2];c=F[a+84>>2];F[a+80>>2]=0;F[a+84>>2]=0;d=c;f=g;c=b;b=b>>25;g=(c&33554431)<<7|e>>>25;c=f+g|0;b=b+d|0;b=c>>>0>>0?b+1|0:b;f=c;d=c+i|0;c=b;b=b+h|0;h=qe(f,c,18,0);c=h+d|0;b=$+(d>>>0>>0?b+1|0:b)|0;b=c>>>0>>0?b+1|0:b;d=b;g=c;f=b>>31>>>6|0;c=f+c|0;b=c>>>0>>0?b+1|0:b;h=c;c=c&-67108864;F[a>>2]=g-c;F[a+4>>2]=d-((c>>>0>g>>>0)+b|0);e=F[a+12>>2];c=a;a=b;b=b>>26;h=(a&67108863)<<6|h>>>26;a=h+F[c+8>>2]|0;b=b+e|0;F[c+8>>2]=a;F[c+12>>2]=a>>>0>>0?b+1|0:b}function ib(a,b,c,d){var e=0,f=0,g=0,h=0,i=0;F[a+16>>2]=0;F[a+20>>2]=0;F[a+12>>2]=c;F[a+8>>2]=b;F[a+4>>2]=0;E[a>>1]=0;F[a+24>>2]=0;F[a+28>>2]=0;a:{if(c>>>0<=d>>>0){break a}D[a|0]=G[b|0];c=c-d|0;if((c|0)==1){break a}h=b+c|0;e=b+1|0;while(1){d=e;if(G[e|0]==10){f=d+1|0;b=f;while(1){b:{if((b|0)==(h|0)){c=h;break b}e=D[b|0];c=b+1|0;b=c;if((e|0)<0){continue}}break}c:{if((c|0)==(f|0)){e=0;break c}i=c-f|0;g=i&3;e=0;b=c;if(b+(f^-1)>>>0>=3){f=i&-4;while(1){e=(G[b-2|0]&127|(e<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;e=e|G[b|0]&127;f=f-4|0;if(f){continue}break}}if(g){while(1){b=b-1|0;e=G[b|0]&127|e<<7;g=g-1|0;if(g){continue}break}}if(h-c>>>0>>0){break a}}F[a+20>>2]=e;F[a+16>>2]=c;e=c+e|0}if((e|0)==(h|0)){break a}if(G[e|0]==16){f=e+1|0;b=f;while(1){d:{if((b|0)==(h|0)){e=h;break d}c=D[b|0];e=b+1|0;b=e;if((c|0)<0){continue}}break}e:{if((e|0)==(f|0)){g=0;break e}i=e-f|0;c=i&3;g=0;b=e;if(b+(f^-1)>>>0>=3){f=i&-4;while(1){g=(G[b-2|0]&127|(g<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;g=g|G[b|0]&127;f=f-4|0;if(f){continue}break}}if(!c){break e}while(1){b=b-1|0;g=G[b|0]&127|g<<7;c=c-1|0;if(c){continue}break}}D[a+1|0]=1;F[a+4>>2]=g}if((e|0)==(h|0)){break a}if(G[e|0]==34){f=e+1|0;b=f;while(1){f:{if((b|0)==(h|0)){c=h;break f}e=D[b|0];c=b+1|0;b=c;if((e|0)<0){continue}}break}g:{if((c|0)==(f|0)){e=0;break g}i=c-f|0;g=i&3;e=0;b=c;if(b+(f^-1)>>>0>=3){f=i&-4;while(1){e=(G[b-2|0]&127|(e<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;e=e|G[b|0]&127;f=f-4|0;if(f){continue}break}}if(g){while(1){b=b-1|0;e=G[b|0]&127|e<<7;g=g-1|0;if(g){continue}break}}if(h-c>>>0>>0){break a}}F[a+28>>2]=e;F[a+24>>2]=c;e=c+e|0}h:{if((e|0)==(h|0)|(d|0)!=(e|0)){break h}i:{switch(G[d|0]&7){case 0:while(1){j:{if((d|0)==(h|0)){b=h;break j}c=D[d|0];b=d+1|0;d=b;if((c|0)<0){continue}}break};while(1){if((b|0)==(h|0)){e=h;break h}c=D[b|0];e=b+1|0;b=e;if((c|0)<=-1){continue}break};break h;case 2:break i;default:break a}}while(1){k:{if((d|0)==(h|0)){e=h;break k}b=D[d|0];e=d+1|0;d=e;if((b|0)<0){continue}}break}b=e;while(1){l:{if((b|0)==(h|0)){c=h;break l}d=D[b|0];c=b+1|0;b=c;if((d|0)<0){continue}}break}if((c|0)==(e|0)){break h}f=c-e|0;g=f&3;d=0;b=c;if(b+(e^-1)>>>0>=3){e=f&-4;while(1){d=(G[b-2|0]&127|(d<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;d=d|G[b|0]&127;e=e-4|0;if(e){continue}break}}if(g){while(1){b=b-1|0;d=G[b|0]&127|d<<7;g=g-1|0;if(g){continue}break}}if(h-c>>>0>>0){break a}e=c+d|0}if((e|0)!=(h|0)){continue}break}}}function ka(a,b,c,d,e){var f=0,g=0;f=_-384|0;_=f;F[f+128>>2]=0;F[f+132>>2]=0;F[f+136>>2]=0;F[f+140>>2]=0;F[f+144>>2]=0;F[f+148>>2]=0;F[f+152>>2]=0;F[f+156>>2]=0;F[f+160>>2]=0;F[f+164>>2]=0;F[f+168>>2]=0;F[f+172>>2]=0;F[f+112>>2]=0;F[f+116>>2]=0;F[f+120>>2]=0;F[f+124>>2]=0;a:{if(b>>>0>=65){g=f+176|0;F[g+80>>2]=1779033703;F[g+84>>2]=-1150833019;F[g+72>>2]=0;F[g+76>>2]=0;F[g+64>>2]=0;F[g+104>>2]=528734635;F[g+108>>2]=1541459225;F[g+96>>2]=1359893119;F[g+100>>2]=-1694144372;F[g+88>>2]=1013904242;F[g+92>>2]=-1521486534;pa(g,a,b);Ba(g,f+112|0);break a}ja(f+112|0,a,b)}a=F[f+172>>2];F[f+232>>2]=F[f+168>>2];F[f+236>>2]=a;a=F[f+164>>2];F[f+224>>2]=F[f+160>>2];F[f+228>>2]=a;a=F[f+156>>2];F[f+216>>2]=F[f+152>>2];F[f+220>>2]=a;a=F[f+148>>2];F[f+208>>2]=F[f+144>>2];F[f+212>>2]=a;a=F[f+140>>2];F[f+200>>2]=F[f+136>>2];F[f+204>>2]=a;a=F[f+132>>2];F[f+192>>2]=F[f+128>>2];F[f+196>>2]=a;a=F[f+124>>2];F[f+184>>2]=F[f+120>>2];F[f+188>>2]=a;a=F[f+116>>2];F[f+176>>2]=F[f+112>>2];F[f+180>>2]=a;b=0;while(1){a=f+176|0;g=a+b|0;D[g|0]=G[g|0]^54;g=a+(b|1)|0;D[g|0]=G[g|0]^54;g=a+(b|2)|0;D[g|0]=G[g|0]^54;a=a+(b|3)|0;D[a|0]=G[a|0]^54;b=b+4|0;if((b|0)!=64){continue}break}F[f+80>>2]=1779033703;F[f+84>>2]=-1150833019;F[f+72>>2]=0;F[f+76>>2]=0;F[f+64>>2]=0;F[f+104>>2]=528734635;F[f+108>>2]=1541459225;F[f+96>>2]=1359893119;F[f+100>>2]=-1694144372;F[f+88>>2]=1013904242;F[f+92>>2]=-1521486534;a=f+176|0;pa(f,a,64);ia(a,64);pa(f,c,d);a=F[f+172>>2];F[f+344>>2]=F[f+168>>2];F[f+348>>2]=a;a=F[f+164>>2];F[f+336>>2]=F[f+160>>2];F[f+340>>2]=a;a=F[f+156>>2];F[f+328>>2]=F[f+152>>2];F[f+332>>2]=a;a=F[f+148>>2];F[f+320>>2]=F[f+144>>2];F[f+324>>2]=a;a=F[f+140>>2];F[f+312>>2]=F[f+136>>2];F[f+316>>2]=a;a=F[f+132>>2];F[f+304>>2]=F[f+128>>2];F[f+308>>2]=a;a=F[f+124>>2];F[f+296>>2]=F[f+120>>2];F[f+300>>2]=a;a=F[f+116>>2];F[f+288>>2]=F[f+112>>2];F[f+292>>2]=a;b=0;while(1){a=f+288|0;c=a+b|0;D[c|0]=G[c|0]^92;c=a+(b|1)|0;D[c|0]=G[c|0]^92;c=a+(b|2)|0;D[c|0]=G[c|0]^92;a=a+(b|3)|0;D[a|0]=G[a|0]^92;b=b+4|0;if((b|0)!=64){continue}break}Ba(f,f+352|0);a=f+176|0;F[a+80>>2]=1779033703;F[a+84>>2]=-1150833019;F[a+72>>2]=0;F[a+76>>2]=0;F[a+64>>2]=0;F[a+104>>2]=528734635;F[a+108>>2]=1541459225;F[a+96>>2]=1359893119;F[a+100>>2]=-1694144372;F[a+88>>2]=1013904242;F[a+92>>2]=-1521486534;b=f+288|0;pa(a,b,96);Ba(a,e);ia(a,112);ia(b,96);ia(f+112|0,64);ia(f,112);_=f+384|0}function Ha(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,G=0;e=F[b+44>>2];d=F[b+48>>2];g=F[b+52>>2];h=F[b+56>>2];i=F[b+60>>2];f=b- -64|0;j=F[f>>2];k=F[b+68>>2];l=F[b+72>>2];m=F[b+76>>2];n=F[b+4>>2];o=F[b+8>>2];p=F[b+12>>2];q=F[b+16>>2];r=F[b+20>>2];s=F[b+24>>2];t=F[b+28>>2];u=F[b+32>>2];v=F[b+36>>2];F[a>>2]=F[b>>2]+F[b+40>>2];F[a+36>>2]=m+v;F[a+32>>2]=l+u;F[a+28>>2]=k+t;F[a+24>>2]=j+s;F[a+20>>2]=i+r;F[a+16>>2]=h+q;F[a+12>>2]=g+p;F[a+8>>2]=d+o;F[a+4>>2]=e+n;d=F[b+44>>2];g=F[b+48>>2];h=F[b+52>>2];i=F[b+56>>2];j=F[b+60>>2];f=F[f>>2];e=F[b+68>>2];k=F[b+72>>2];l=F[b>>2];m=F[b+40>>2];n=F[b+4>>2];o=F[b+8>>2];p=F[b+12>>2];q=F[b+16>>2];r=F[b+20>>2];s=F[b+24>>2];t=F[b+28>>2];u=F[b+32>>2];F[a+76>>2]=F[b+76>>2]-F[b+36>>2];F[a+72>>2]=k-u;F[a+68>>2]=e-t;e=a- -64|0;F[e>>2]=f-s;F[a+60>>2]=j-r;F[a+56>>2]=i-q;F[a+52>>2]=h-p;F[a+48>>2]=g-o;F[a+44>>2]=d-n;F[a+40>>2]=m-l;ha(a+80|0,a,c);d=a+40|0;ha(d,d,c+40|0);ha(a+120|0,c+120|0,b+120|0);ha(a,b+80|0,c+80|0);b=F[a+44>>2];c=F[a+84>>2];d=F[a+48>>2];g=F[a+88>>2];h=F[a+52>>2];i=F[a+92>>2];f=F[a+56>>2];j=F[a+96>>2];k=F[a+60>>2];l=F[a+100>>2];m=F[e>>2];n=F[a+104>>2];o=F[a+68>>2];p=F[a+108>>2];q=F[a+72>>2];r=F[a+112>>2];u=F[a>>2];v=F[a+4>>2];y=F[a+8>>2];z=F[a+12>>2];A=F[a+16>>2];B=F[a+20>>2];C=F[a+24>>2];D=F[a+28>>2];E=F[a+32>>2];G=F[a+36>>2];s=F[a+40>>2];t=F[a+80>>2];w=F[a+76>>2];x=F[a+116>>2];F[a+76>>2]=w+x;F[a+72>>2]=q+r;F[a+68>>2]=o+p;F[e>>2]=m+n;F[a+60>>2]=k+l;F[a+56>>2]=f+j;F[a+52>>2]=h+i;F[a+48>>2]=d+g;F[a+44>>2]=b+c;F[a+40>>2]=s+t;F[a+36>>2]=x-w;F[a+32>>2]=r-q;F[a+28>>2]=p-o;F[a+24>>2]=n-m;F[a+20>>2]=l-k;F[a+16>>2]=j-f;F[a+12>>2]=i-h;F[a+8>>2]=g-d;F[a+4>>2]=c-b;F[a>>2]=t-s;b=G<<1;c=F[a+156>>2];F[a+156>>2]=b-c;e=E<<1;d=F[a+152>>2];F[a+152>>2]=e-d;g=D<<1;h=F[a+148>>2];F[a+148>>2]=g-h;i=C<<1;f=F[a+144>>2];F[a+144>>2]=i-f;j=B<<1;k=F[a+140>>2];F[a+140>>2]=j-k;l=A<<1;m=F[a+136>>2];F[a+136>>2]=l-m;n=z<<1;o=F[a+132>>2];F[a+132>>2]=n-o;p=y<<1;q=F[a+128>>2];F[a+128>>2]=p-q;r=v<<1;s=F[a+124>>2];F[a+124>>2]=r-s;t=u<<1;u=F[a+120>>2];F[a+120>>2]=t-u;F[a+112>>2]=d+e;F[a+108>>2]=g+h;F[a+104>>2]=i+f;F[a+100>>2]=j+k;F[a+96>>2]=l+m;F[a+92>>2]=n+o;F[a+88>>2]=p+q;F[a+84>>2]=r+s;F[a+80>>2]=t+u;F[a+116>>2]=b+c}function Tb(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;c=_-480|0;_=c;while(1){e=c+288|0;g=e+(d<<1)|0;f=G[b+d|0];D[g+1|0]=f>>>4;D[g|0]=f&15;g=d|1;e=e+(g<<1)|0;g=G[b+g|0];D[e+1|0]=g>>>4;D[e|0]=g&15;d=d+2|0;if((d|0)!=32){continue}break}b=0;while(1){d=b;b=(c+288|0)+h|0;e=d+G[b|0]|0;d=(e<<24)- -134217728|0;D[b|0]=e-(d>>24&240);e=G[b+1|0]+(d>>28)|0;d=(e<<24)- -134217728|0;D[b+1|0]=e-(d>>24&240);e=G[b+2|0]+(d>>28)|0;d=(e<<24)- -134217728|0;D[b+2|0]=e-(d>>24&240);b=d>>28;h=h+3|0;if((h|0)!=63){continue}break}D[c+351|0]=G[c+351|0]+b;b=a;F[b+32>>2]=0;F[b+36>>2]=0;F[b+24>>2]=0;F[b+28>>2]=0;F[b+16>>2]=0;F[b+20>>2]=0;F[b+8>>2]=0;F[b+12>>2]=0;F[b>>2]=0;F[b+4>>2]=0;F[b+44>>2]=0;F[b+48>>2]=0;F[b+40>>2]=1;F[b+52>>2]=0;F[b+56>>2]=0;F[b+60>>2]=0;F[b+64>>2]=0;F[b+68>>2]=0;F[b+72>>2]=0;F[b+76>>2]=0;F[b+80>>2]=1;ra(b+84|0,0,76);p=b+120|0;q=b+80|0;r=b+40|0;h=c+208|0;g=c+168|0;e=c+248|0;d=1;while(1){f=c+8|0;Rb(f,d>>>1|0,D[(c+288|0)+d|0]);b=c+128|0;nb(b,a,f);ha(a,b,e);ha(r,g,h);ha(q,h,e);ha(p,b,g);b=d>>>0<62;d=d+2|0;if(b){continue}break}b=a;d=F[b>>2];f=F[b+4>>2];i=F[b+8>>2];j=F[b+12>>2];k=F[b+16>>2];l=F[b+20>>2];m=F[b+24>>2];n=F[b+28>>2];o=F[b+36>>2];F[c+392>>2]=F[b+32>>2];F[c+396>>2]=o;F[c+384>>2]=m;F[c+388>>2]=n;F[c+376>>2]=k;F[c+380>>2]=l;F[c+368>>2]=i;F[c+372>>2]=j;F[c+360>>2]=d;F[c+364>>2]=f;d=F[b+48>>2];f=F[b+52>>2];i=F[b+56>>2];j=F[b+60>>2];k=b- -64|0;l=F[k>>2];k=F[k+4>>2];m=F[b+40>>2];n=F[b+44>>2];o=F[b+76>>2];F[c+432>>2]=F[b+72>>2];F[c+436>>2]=o;F[c+424>>2]=l;F[c+428>>2]=k;F[c+416>>2]=i;F[c+420>>2]=j;F[c+408>>2]=d;F[c+412>>2]=f;F[c+400>>2]=m;F[c+404>>2]=n;d=F[b+88>>2];f=F[b+92>>2];i=F[b+96>>2];j=F[b+100>>2];k=F[b+104>>2];l=F[b+108>>2];m=F[b+80>>2];n=F[b+84>>2];o=F[b+116>>2];F[c+472>>2]=F[b+112>>2];F[c+476>>2]=o;F[c+464>>2]=k;F[c+468>>2]=l;F[c+456>>2]=i;F[c+460>>2]=j;F[c+448>>2]=d;F[c+452>>2]=f;F[c+440>>2]=m;F[c+444>>2]=n;d=c+128|0;f=c+360|0;Oa(d,f);ha(f,d,e);i=c+400|0;ha(i,g,h);j=c+440|0;ha(j,h,e);Oa(d,f);ha(f,d,e);ha(i,g,h);ha(j,h,e);Oa(d,f);ha(f,d,e);ha(i,g,h);ha(j,h,e);Oa(d,f);ha(b,d,e);ha(r,g,h);ha(q,h,e);ha(p,d,g);d=0;while(1){f=c+8|0;Rb(f,d>>>1|0,D[(c+288|0)+d|0]);b=c+128|0;nb(b,a,f);ha(a,b,e);ha(r,g,h);ha(q,h,e);ha(p,b,g);b=d>>>0<62;d=d+2|0;if(b){continue}break}_=c+480|0}function nb(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0,v=0,w=0,x=0,y=0,z=0,A=0,B=0,C=0,D=0,E=0,G=0;e=F[b+44>>2];d=F[b+48>>2];g=F[b+52>>2];h=F[b+56>>2];i=F[b+60>>2];f=b- -64|0;j=F[f>>2];k=F[b+68>>2];l=F[b+72>>2];m=F[b+76>>2];n=F[b+4>>2];o=F[b+8>>2];p=F[b+12>>2];q=F[b+16>>2];r=F[b+20>>2];s=F[b+24>>2];t=F[b+28>>2];u=F[b+32>>2];v=F[b+36>>2];F[a>>2]=F[b>>2]+F[b+40>>2];F[a+36>>2]=m+v;F[a+32>>2]=l+u;F[a+28>>2]=k+t;F[a+24>>2]=j+s;F[a+20>>2]=i+r;F[a+16>>2]=h+q;F[a+12>>2]=g+p;F[a+8>>2]=d+o;F[a+4>>2]=e+n;d=F[b+44>>2];g=F[b+48>>2];h=F[b+52>>2];i=F[b+56>>2];j=F[b+60>>2];f=F[f>>2];e=F[b+68>>2];k=F[b+72>>2];l=F[b>>2];m=F[b+40>>2];n=F[b+4>>2];o=F[b+8>>2];p=F[b+12>>2];q=F[b+16>>2];r=F[b+20>>2];s=F[b+24>>2];t=F[b+28>>2];u=F[b+32>>2];F[a+76>>2]=F[b+76>>2]-F[b+36>>2];F[a+72>>2]=k-u;F[a+68>>2]=e-t;e=a- -64|0;F[e>>2]=f-s;F[a+60>>2]=j-r;F[a+56>>2]=i-q;F[a+52>>2]=h-p;F[a+48>>2]=g-o;F[a+44>>2]=d-n;F[a+40>>2]=m-l;ha(a+80|0,a,c);d=a+40|0;ha(d,d,c+40|0);ha(a+120|0,c+80|0,b+120|0);u=F[b+84>>2];v=F[b+88>>2];y=F[b+92>>2];z=F[b+96>>2];A=F[b+100>>2];B=F[b+104>>2];C=F[b+108>>2];D=F[b+112>>2];E=F[b+116>>2];c=F[a+44>>2];d=F[a+84>>2];g=F[a+48>>2];h=F[a+88>>2];i=F[a+52>>2];f=F[a+92>>2];j=F[a+56>>2];k=F[a+96>>2];l=F[a+60>>2];m=F[a+100>>2];n=F[e>>2];o=F[a+104>>2];p=F[a+68>>2];q=F[a+108>>2];r=F[a+72>>2];s=F[a+112>>2];G=F[b+80>>2];b=F[a+40>>2];t=F[a+80>>2];w=F[a+76>>2];x=F[a+116>>2];F[a+76>>2]=w+x;F[a+72>>2]=r+s;F[a+68>>2]=p+q;F[e>>2]=n+o;F[a+60>>2]=l+m;F[a+56>>2]=j+k;F[a+52>>2]=i+f;F[a+48>>2]=g+h;F[a+44>>2]=c+d;F[a+40>>2]=b+t;F[a+36>>2]=x-w;F[a+32>>2]=s-r;F[a+28>>2]=q-p;F[a+24>>2]=o-n;F[a+20>>2]=m-l;F[a+16>>2]=k-j;F[a+12>>2]=f-i;F[a+8>>2]=h-g;F[a+4>>2]=d-c;F[a>>2]=t-b;b=E<<1;c=F[a+156>>2];F[a+156>>2]=b-c;e=D<<1;d=F[a+152>>2];F[a+152>>2]=e-d;g=C<<1;h=F[a+148>>2];F[a+148>>2]=g-h;i=B<<1;f=F[a+144>>2];F[a+144>>2]=i-f;j=A<<1;k=F[a+140>>2];F[a+140>>2]=j-k;l=z<<1;m=F[a+136>>2];F[a+136>>2]=l-m;n=y<<1;o=F[a+132>>2];F[a+132>>2]=n-o;p=v<<1;q=F[a+128>>2];F[a+128>>2]=p-q;r=u<<1;s=F[a+124>>2];F[a+124>>2]=r-s;t=G<<1;u=F[a+120>>2];F[a+120>>2]=t-u;F[a+112>>2]=d+e;F[a+108>>2]=g+h;F[a+104>>2]=i+f;F[a+100>>2]=j+k;F[a+96>>2]=l+m;F[a+92>>2]=n+o;F[a+88>>2]=p+q;F[a+84>>2]=r+s;F[a+80>>2]=t+u;F[a+116>>2]=b+c}function Zc(a,b){a=a|0;b=b|0;var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0;c=b;b=F[b>>2]+7&-8;F[c>>2]=b+16;p=a;a=b;k=F[a>>2];b=F[a+4>>2];f=F[a+12>>2];n=f;h=_-32|0;_=h;c=f&2147483647;f=c;e=c-1006698496|0;d=c-1140785152|0;c=F[a+8>>2];j=c;a:{if((e|0)==(d|0)&c>>>0>>0|e>>>0>>0){f=c;c=n<<4|c>>>28;a=b;f=f<<4|a>>>28;a=a&268435455;b=a;if((a|0)==134217728&k>>>0>=1|a>>>0>134217728){a=c+1073741824|0;b=f+1|0;a=b>>>0<1?a+1|0:a;e=b;break a}e=f;a=c+1073741824|0;if(k|b^134217728){break a}c=a;b=f&1;f=b+e|0;e=f;a=b>>>0>e>>>0?c+1|0:c;break a}if(!(!j&(f|0)==2147418112?!(b|k):f>>>0<2147418112)){f=c;c=n<<4|c>>>28;e=f<<4|b>>>28;a=c&524287|2146959360;break a}e=0;a=2146435072;if(f>>>0>1140785151){break a}a=0;o=f>>>16|0;if(o>>>0<15249){break a}e=k;a=b;d=n&65535|65536;f=d;l=c;g=c;i=o-15233|0;b:{if(i&64){d=e;c=i+-64|0;e=c&31;if((c&63)>>>0>=32){a=d<>>32-e|a<>>0>=32){c=g<>>32-m|d<>>0>=32){c=0;g=g>>>i|0}else{c=g>>>i|0;g=((1<>>i}g=q|g;d=c|d;i=j&31;if((j&63)>>>0>=32){c=e<>>32-i|a<>2]=e;F[h+20>>2]=a;F[h+24>>2]=g;F[h+28>>2]=d;c=15361-o|0;c:{if(c&64){b=l;a=c+-64|0;d=a&31;if((a&63)>>>0>=32){c=0;k=f>>>d|0}else{c=f>>>d|0;k=((1<>>d}b=c;l=0;f=0;break c}if(!c){break c}a=f;e=l;d=64-c|0;j=d&31;if((d&63)>>>0>=32){a=e<>>32-j|a<>>0>=32){c=0;b=b>>>j|0}else{c=b>>>j|0;b=((1<>>j}k=g|b;b=c|d;c=l;d=a&31;if((a&63)>>>0>=32){a=0;l=f>>>d|0}else{a=f>>>d|0;l=((1<>>d}f=a}F[h>>2]=k;F[h+4>>2]=b;F[h+8>>2]=l;F[h+12>>2]=f;d=F[h+4>>2];b=F[h+8>>2];e=b<<4|d>>>28;a=F[h+12>>2]<<4|b>>>28;d=d&268435455;f=d;b=F[h>>2]|((F[h+16>>2]|F[h+24>>2])!=0|(F[h+20>>2]|F[h+28>>2])!=0);if((d|0)==134217728&b>>>0>=1|d>>>0>134217728){b=e+1|0;a=b>>>0<1?a+1|0:a;e=b;break a}if(b|f^134217728){break a}d=a;b=e+(e&1)|0;d=b>>>0>>0?d+1|0:d;e=b;a=d}_=h+32|0;x(0,e|0);x(1,n&-2147483648|a);K[p>>3]=z()}function _b(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0;o=a+3216|0;b=Xa(b,c,d,e,o);a:{b:{if((b|0)==-1){break b}g=a;n=_-16|0;_=n;q=b+d|0;f=q;b=ua(d,f,n+12|0);c:{if(!b){a=0;break c}a=0;d:{c=F[n+12>>2];if((c|0)!=1){if((c|0)!=-2147483647){break d}r=1}c=g+3220|0;if(!(!b|(b|0)==(f|0))){D[c|0]=G[b|0]!=0;l=b+1|0}if(!l){break c}b=Ra(l,f,g+3221|0);if(!b){break c}b=Ra(b,f,g+3253|0);if(!b){break c}b=Ra(b,f,g+3285|0);if(!b){break c}l=0;p=_-16|0;_=p;b=Sa(b,f,g+12|0,32);e:{if(!b){break e}h=g+44|0;j=_-16|0;_=j;c=ua(b,f,j+12|0);f:{if(!c){break f}m=h+4|0;k=h+104|0;while(1){b=F[j+12>>2];F[j+12>>2]=b-1;if(!b){a=c;break f}if((c|0)==(f|0)){a=c;break f}b=m;d=k;i=F[h>>2];if((d|0)!=(i|0)){d=i+100|0;F[h>>2]=d;b=i}d=d-100|0;if((d|0)!=(b|0)){while(1){i=d;d=d-100|0;ja(i,d,100);if((b|0)!=(d|0)){continue}break}}c=Ka(c,f,b);if(!c){break f}c=Sa(c,f,b+68|0,32);if(!c){break f}c=ua(c,f,b- -64|0);if(c){continue}break}}_=j+16|0;b=a;if(!b){break e}h=g+148|0;a=0;j=_-16|0;_=j;c=ua(b,f,j+12|0);g:{if(!c){break g}m=h+276|0;k=h+344|0;while(1){b=F[j+12>>2];F[j+12>>2]=b-1;if(!b){a=c;break g}if((c|0)==(f|0)){a=c;break g}b=m;d=k;i=F[h>>2];if((d|0)!=(i|0)){d=i+68|0;F[h>>2]=d;b=i}d=d-68|0;if((d|0)!=(b|0)){while(1){i=d;d=d-68|0;ja(i,d,68);if((b|0)!=(d|0)){continue}break}}c=Ra(c,f,b);if(!c){break g}c=Sa(c,f,b+36|0,32);if(!c){break g}c=ua(c,f,b+32|0);if(c){continue}break}}_=j+16|0;b=a;if(!b){break e}k=g+492|0;a=0;h=_-16|0;_=h;c=ua(b,f,h+12|0);h:{if(!c){break h}i=k+2656|0;m=k+2724|0;while(1){b=F[h+12>>2];F[h+12>>2]=b-1;if(!b){a=c;break h}if((c|0)==(f|0)){a=c;break h}b=i;d=m;g=F[k>>2];if((d|0)!=(g|0)){d=g+68|0;F[k>>2]=d;b=g}d=d-68|0;if((d|0)!=(b|0)){while(1){g=d;d=d-68|0;ja(g,d,68);if((b|0)!=(d|0)){continue}break}}c=Ra(c,f,b);if(!c){break h}c=Sa(c,f,b+36|0,32);if(!c){break h}c=ua(c,f,b+32|0);if(c){continue}break}}_=h+16|0;if(!a){break e}if(r){a=ua(a,f,p+12|0);if(!a){break e}}l=a}_=p+16|0;a=l;break c}F[g+3216>>2]=9}_=n+16|0;b=a;i:{if(!b){if(F[o>>2]){break b}a=10;break i}a=17;if((b|0)==(q|0)){break a}}F[o>>2]=a}e=-1}return e|0}function Ka(a,b,c){var d=0,e=0,f=0,g=0;a:{if(!a){break a}d=a+32|0;if(d>>>0>b>>>0){break a}f=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);g=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[c|0]=g;D[c+1|0]=g>>>8;D[c+2|0]=g>>>16;D[c+3|0]=g>>>24;D[c+4|0]=f;D[c+5|0]=f>>>8;D[c+6|0]=f>>>16;D[c+7|0]=f>>>24;f=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);g=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[c+24|0]=g;D[c+25|0]=g>>>8;D[c+26|0]=g>>>16;D[c+27|0]=g>>>24;D[c+28|0]=f;D[c+29|0]=f>>>8;D[c+30|0]=f>>>16;D[c+31|0]=f>>>24;f=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);g=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[c+16|0]=g;D[c+17|0]=g>>>8;D[c+18|0]=g>>>16;D[c+19|0]=g>>>24;D[c+20|0]=f;D[c+21|0]=f>>>8;D[c+22|0]=f>>>16;D[c+23|0]=f>>>24;f=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);g=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[c+8|0]=g;D[c+9|0]=g>>>8;D[c+10|0]=g>>>16;D[c+11|0]=g>>>24;D[c+12|0]=f;D[c+13|0]=f>>>8;D[c+14|0]=f>>>16;D[c+15|0]=f>>>24;a=a- -64|0;if(a>>>0>b>>>0){break a}e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);b=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);D[c+32|0]=b;D[c+33|0]=b>>>8;D[c+34|0]=b>>>16;D[c+35|0]=b>>>24;D[c+36|0]=e;D[c+37|0]=e>>>8;D[c+38|0]=e>>>16;D[c+39|0]=e>>>24;e=G[d+28|0]|G[d+29|0]<<8|(G[d+30|0]<<16|G[d+31|0]<<24);b=G[d+24|0]|G[d+25|0]<<8|(G[d+26|0]<<16|G[d+27|0]<<24);D[c+56|0]=b;D[c+57|0]=b>>>8;D[c+58|0]=b>>>16;D[c+59|0]=b>>>24;D[c+60|0]=e;D[c+61|0]=e>>>8;D[c+62|0]=e>>>16;D[c+63|0]=e>>>24;e=G[d+20|0]|G[d+21|0]<<8|(G[d+22|0]<<16|G[d+23|0]<<24);b=G[d+16|0]|G[d+17|0]<<8|(G[d+18|0]<<16|G[d+19|0]<<24);D[c+48|0]=b;D[c+49|0]=b>>>8;D[c+50|0]=b>>>16;D[c+51|0]=b>>>24;D[c+52|0]=e;D[c+53|0]=e>>>8;D[c+54|0]=e>>>16;D[c+55|0]=e>>>24;e=G[d+12|0]|G[d+13|0]<<8|(G[d+14|0]<<16|G[d+15|0]<<24);b=G[d+8|0]|G[d+9|0]<<8|(G[d+10|0]<<16|G[d+11|0]<<24);D[c+40|0]=b;D[c+41|0]=b>>>8;D[c+42|0]=b>>>16;D[c+43|0]=b>>>24;D[c+44|0]=e;D[c+45|0]=e>>>8;D[c+46|0]=e>>>16;D[c+47|0]=e>>>24;e=a}return e}function Cb(a,b,c,d){var e=0,f=0,g=0,h=0,i=0,j=0;F[d+4>>2]=0;F[d+8>>2]=0;D[d|0]=0;F[d+12>>2]=0;F[d+16>>2]=0;c=c- -64|0;if(c>>>0>>0){D[d|0]=G[a|0];b=b-c|0;a:{if((b|0)==1){break a}g=a+b|0;a=a+1|0;while(1){c=a;if(G[a|0]==8){f=c+1|0;b=f;while(1){b:{if((b|0)==(g|0)){a=g;break b}e=D[b|0];a=b+1|0;b=a;if((e|0)<0){continue}}break}c:{if((a|0)==(f|0)){h=0;break c}i=a-f|0;e=i&3;h=0;b=a;if(b+(f^-1)>>>0>=3){f=i&-4;while(1){j=(G[b-2|0]&127|(h<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;h=j|G[b|0]&127;f=f-4|0;if(f){continue}break}}if(!e){break c}while(1){b=b-1|0;h=G[b|0]&127|h<<7;e=e-1|0;if(e){continue}break}}F[d+4>>2]=h;i=1}if((a|0)==(g|0)){break a}if(G[a|0]==18){f=a+1|0;b=f;while(1){d:{if((b|0)==(g|0)){e=g;break d}a=D[b|0];e=b+1|0;b=e;if((a|0)<0){continue}}break}e:{if((e|0)==(f|0)){a=0;break e}j=e-f|0;h=j&3;a=0;b=e;if(b+(f^-1)>>>0>=3){f=j&-4;while(1){a=(G[b-2|0]&127|(a<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;a=a|G[b|0]&127;f=f-4|0;if(f){continue}break}}if(h){while(1){b=b-1|0;a=G[b|0]&127|a<<7;h=h-1|0;if(h){continue}break}}if(g-e>>>0>>0){break a}}F[d+16>>2]=a;F[d+12>>2]=e;a=a+e|0}f:{if((a|0)==(g|0)|(a|0)!=(c|0)){break f}g:{switch(G[c|0]&7){case 0:while(1){h:{if((c|0)==(g|0)){b=g;break h}a=D[c|0];b=c+1|0;c=b;if((a|0)<0){continue}}break};while(1){if((b|0)==(g|0)){a=g;break f}c=D[b|0];a=b+1|0;b=a;if((c|0)<=-1){continue}break};break f;case 2:break g;default:break a}}while(1){i:{if((c|0)==(g|0)){a=g;break i}b=D[c|0];a=c+1|0;c=a;if((b|0)<0){continue}}break}b=a;while(1){j:{if((b|0)==(g|0)){e=g;break j}c=D[b|0];e=b+1|0;b=e;if((c|0)<0){continue}}break}if((a|0)==(e|0)){break f}f=e-a|0;h=f&3;c=0;b=e;if(b+(a^-1)>>>0>=3){a=f&-4;while(1){c=(G[b-2|0]&127|(c<<14|(G[b-1|0]&127)<<7))<<14|(G[b-3|0]&127)<<7;b=b-4|0;c=c|G[b|0]&127;a=a-4|0;if(a){continue}break}}if(h){while(1){b=b-1|0;c=G[b|0]&127|c<<7;h=h-1|0;if(h){continue}break}}if(g-e>>>0>>0){break a}a=c+e|0}if((a|0)!=(g|0)){continue}break}}F[d+8>>2]=i}}function Pa(a,b){var c=0,d=0;c=G[b+4|0]|G[b+5|0]<<8|(G[b+6|0]<<16|G[b+7|0]<<24);d=G[b|0]|G[b+1|0]<<8|(G[b+2|0]<<16|G[b+3|0]<<24);D[a|0]=d;D[a+1|0]=d>>>8;D[a+2|0]=d>>>16;D[a+3|0]=d>>>24;D[a+4|0]=c;D[a+5|0]=c>>>8;D[a+6|0]=c>>>16;D[a+7|0]=c>>>24;c=G[b+28|0]|G[b+29|0]<<8|(G[b+30|0]<<16|G[b+31|0]<<24);d=G[b+24|0]|G[b+25|0]<<8|(G[b+26|0]<<16|G[b+27|0]<<24);D[a+24|0]=d;D[a+25|0]=d>>>8;D[a+26|0]=d>>>16;D[a+27|0]=d>>>24;D[a+28|0]=c;D[a+29|0]=c>>>8;D[a+30|0]=c>>>16;D[a+31|0]=c>>>24;c=G[b+20|0]|G[b+21|0]<<8|(G[b+22|0]<<16|G[b+23|0]<<24);d=G[b+16|0]|G[b+17|0]<<8|(G[b+18|0]<<16|G[b+19|0]<<24);D[a+16|0]=d;D[a+17|0]=d>>>8;D[a+18|0]=d>>>16;D[a+19|0]=d>>>24;D[a+20|0]=c;D[a+21|0]=c>>>8;D[a+22|0]=c>>>16;D[a+23|0]=c>>>24;c=G[b+12|0]|G[b+13|0]<<8|(G[b+14|0]<<16|G[b+15|0]<<24);d=G[b+8|0]|G[b+9|0]<<8|(G[b+10|0]<<16|G[b+11|0]<<24);D[a+8|0]=d;D[a+9|0]=d>>>8;D[a+10|0]=d>>>16;D[a+11|0]=d>>>24;D[a+12|0]=c;D[a+13|0]=c>>>8;D[a+14|0]=c>>>16;D[a+15|0]=c>>>24;c=G[b+36|0]|G[b+37|0]<<8|(G[b+38|0]<<16|G[b+39|0]<<24);d=G[b+32|0]|G[b+33|0]<<8|(G[b+34|0]<<16|G[b+35|0]<<24);D[a+32|0]=d;D[a+33|0]=d>>>8;D[a+34|0]=d>>>16;D[a+35|0]=d>>>24;D[a+36|0]=c;D[a+37|0]=c>>>8;D[a+38|0]=c>>>16;D[a+39|0]=c>>>24;c=G[b+44|0]|G[b+45|0]<<8|(G[b+46|0]<<16|G[b+47|0]<<24);d=G[b+40|0]|G[b+41|0]<<8|(G[b+42|0]<<16|G[b+43|0]<<24);D[a+40|0]=d;D[a+41|0]=d>>>8;D[a+42|0]=d>>>16;D[a+43|0]=d>>>24;D[a+44|0]=c;D[a+45|0]=c>>>8;D[a+46|0]=c>>>16;D[a+47|0]=c>>>24;c=G[b+52|0]|G[b+53|0]<<8|(G[b+54|0]<<16|G[b+55|0]<<24);d=G[b+48|0]|G[b+49|0]<<8|(G[b+50|0]<<16|G[b+51|0]<<24);D[a+48|0]=d;D[a+49|0]=d>>>8;D[a+50|0]=d>>>16;D[a+51|0]=d>>>24;D[a+52|0]=c;D[a+53|0]=c>>>8;D[a+54|0]=c>>>16;D[a+55|0]=c>>>24;c=G[b+60|0]|G[b+61|0]<<8|(G[b+62|0]<<16|G[b+63|0]<<24);b=G[b+56|0]|G[b+57|0]<<8|(G[b+58|0]<<16|G[b+59|0]<<24);D[a+56|0]=b;D[a+57|0]=b>>>8;D[a+58|0]=b>>>16;D[a+59|0]=b>>>24;D[a+60|0]=c;D[a+61|0]=c>>>8;D[a+62|0]=c>>>16;D[a+63|0]=c>>>24;return a- -64|0}function ae(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;if(c>>>0<43){F[a+3216>>2]=2;return-1}c=_-96|0;_=c;d=a+3245|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+24>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+28>>2]=e;d=a+3237|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+16>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+20>>2]=e;d=G[a+3225|0]|G[a+3226|0]<<8|(G[a+3227|0]<<16|G[a+3228|0]<<24);F[c>>2]=G[a+3221|0]|G[a+3222|0]<<8|(G[a+3223|0]<<16|G[a+3224|0]<<24);F[c+4>>2]=d;d=a+3229|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+8>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+12>>2]=e;d=a+3261|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+40>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+44>>2]=e;d=a+3269|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+48>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+52>>2]=e;d=a+3277|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+56>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+60>>2]=e;d=G[a+3257|0]|G[a+3258|0]<<8|(G[a+3259|0]<<16|G[a+3260|0]<<24);F[c+32>>2]=G[a+3253|0]|G[a+3254|0]<<8|(G[a+3255|0]<<16|G[a+3256|0]<<24);F[c+36>>2]=d;d=a+3293|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+72>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+76>>2]=e;d=a+3301|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+80>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+84>>2]=e;d=a+3309|0;e=G[d+4|0]|G[d+5|0]<<8|(G[d+6|0]<<16|G[d+7|0]<<24);F[c+88>>2]=G[d|0]|G[d+1|0]<<8|(G[d+2|0]<<16|G[d+3|0]<<24);F[c+92>>2]=e;d=G[a+3289|0]|G[a+3290|0]<<8|(G[a+3291|0]<<16|G[a+3292|0]<<24);F[c+64>>2]=G[a+3285|0]|G[a+3286|0]<<8|(G[a+3287|0]<<16|G[a+3288|0]<<24);F[c+68>>2]=d;vb(c,96,b+11|0);_=c+96|0;na(b+11|0,32,b);return 43}function $b(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0;l=a+7516|0;b=Xa(b,c,d,e,l);a:{b:{if((b|0)==-1){break b}f=a;h=_-16|0;_=h;m=b+d|0;g=m;a=ua(d,g,h+12|0);c:{if(!a){break c}d:{switch(F[h+12>>2]-1|0){case 0:F[f+7516>>2]=13;break c;default:F[f+7516>>2]=9;break c;case 1:case 2:case 3:break d}}a=Qb(a,g,f);if(!a){break c}b=Ka(a,g,f+96|0);if(!b){break c}k=f+160|0;a=0;i=_-16|0;_=i;c=ua(b,g,i+12|0);e:{if(!c){break e}o=k+7132|0;p=k+7204|0;while(1){b=F[i+12>>2];F[i+12>>2]=b-1;if(!b){a=c;break e}if((c|0)==(g|0)){a=c;break e}b=o;d=p;j=F[k>>2];if((d|0)!=(j|0)){d=j+72|0;F[k>>2]=d;b=j}d=d-72|0;if((d|0)!=(b|0)){while(1){j=d;d=d-72|0;ja(j,d,72);if((b|0)!=(d|0)){continue}break}}d=ua(c,g,b);if(!d){break e}c=0;if(!(!d|(d|0)==(g|0))){D[b+4|0]=G[d|0]!=0;c=d+1|0}if(!c){break e}c=Ka(c,g,b+5|0);if(c){continue}break}}_=i+16|0;if(!a){break c}b=F[h+12>>2];f:{if(b>>>0<=2){D[f+7364|0]=0;break f}g:{if((b|0)==3){b=ua(a,g,f+7368|0);if(!b){break c}c=f+7372|0;d=c;a=0;if(!(!b|(b|0)==(g|0))){D[d|0]=G[b|0]!=0;a=b+1|0}if(!a){break c}a=Ka(a,g,f+7373|0);if(!a){break c}a=ua(a,g,f+7440|0);if(!a){break c}d=f+7444|0;b=0;if(!(!a|(a|0)==(g|0))){D[d|0]=G[a|0]!=0;b=a+1|0}if(!b){break c}a=Ka(b,g,f+7445|0);if(!a){break c}if(G[c|0]){if(!G[f+7444|0]){break g}D[f+7364|0]=2;break f}D[f+7364|0]=0;break f}c=f+7364|0;d=c;b=0;if(!a|(a|0)==(g|0)){a=b}else{D[d|0]=G[a|0];a=a+1|0}if(!a){break c}if(!G[c|0]){break f}a=Nb(a,g,f+7368|0);if(!a){break c}if(G[c|0]<2){break f}a=Nb(a,g,f+7440|0);if(!a){break c}if(G[c|0]<3){break f}F[f+7516>>2]=10;break c}D[f+7364|0]=1}n=ua(a,g,f+7512|0)}_=h+16|0;h:{if(!n){if(F[l>>2]){break b}a=10;break h}a=17;if((n|0)==(m|0)){break a}}F[l>>2]=a}e=-1}return e|0}function pb(a,b){var c=0,d=0,e=0;c=_-192|0;_=c;e=c+144|0;fa(e,b);d=c+96|0;fa(d,e);fa(d,d);ha(d,b,d);ha(e,e,d);b=c+48|0;fa(b,e);ha(d,d,b);fa(b,d);fa(b,b);fa(b,b);fa(b,b);fa(b,b);ha(d,b,d);fa(b,d);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);ha(b,b,d);fa(c,b);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);fa(c,c);ha(b,c,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);ha(d,b,d);fa(b,d);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);ha(b,b,d);fa(c,b);b=1;while(1){fa(c,c);b=b+1|0;if((b|0)!=100){continue}break}b=c+48|0;ha(b,c,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);fa(b,b);d=c+96|0;ha(d,b,d);fa(d,d);fa(d,d);fa(d,d);fa(d,d);fa(d,d);ha(a,d,c+144|0);_=c+192|0}function Kd(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;d=_-240|0;_=d;e=oa(c);a:{if((e|0)!=229){c=-1;if((e|0)==-1){F[a+300>>2]=7;break a}F[a+300>>2]=11;break a}Ma(b,c,d);b:{if(G[d|0]==2){c=d|5;b=G[d+1|0]|G[d+2|0]<<8|(G[d+3|0]<<16|G[d+4|0]<<24);b=b<<24|b<<8&16711680|(b>>>8&65280|b>>>24);_a(a,c,b);_a(a+132|0,c,b);b=G[d+161|0]|G[d+162|0]<<8|(G[d+163|0]<<16|G[d+164|0]<<24);c=G[d+157|0]|G[d+158|0]<<8|(G[d+159|0]<<16|G[d+160|0]<<24);D[a+288|0]=c;D[a+289|0]=c>>>8;D[a+290|0]=c>>>16;D[a+291|0]=c>>>24;D[a+292|0]=b;D[a+293|0]=b>>>8;D[a+294|0]=b>>>16;D[a+295|0]=b>>>24;b=G[d+153|0]|G[d+154|0]<<8|(G[d+155|0]<<16|G[d+156|0]<<24);c=G[d+149|0]|G[d+150|0]<<8|(G[d+151|0]<<16|G[d+152|0]<<24);D[a+280|0]=c;D[a+281|0]=c>>>8;D[a+282|0]=c>>>16;D[a+283|0]=c>>>24;D[a+284|0]=b;D[a+285|0]=b>>>8;D[a+286|0]=b>>>16;D[a+287|0]=b>>>24;b=G[d+145|0]|G[d+146|0]<<8|(G[d+147|0]<<16|G[d+148|0]<<24);c=G[d+141|0]|G[d+142|0]<<8|(G[d+143|0]<<16|G[d+144|0]<<24);D[a+272|0]=c;D[a+273|0]=c>>>8;D[a+274|0]=c>>>16;D[a+275|0]=c>>>24;D[a+276|0]=b;D[a+277|0]=b>>>8;D[a+278|0]=b>>>16;D[a+279|0]=b>>>24;b=G[d+137|0]|G[d+138|0]<<8|(G[d+139|0]<<16|G[d+140|0]<<24);c=G[d+133|0]|G[d+134|0]<<8|(G[d+135|0]<<16|G[d+136|0]<<24);D[a+264|0]=c;D[a+265|0]=c>>>8;D[a+266|0]=c>>>16;D[a+267|0]=c>>>24;D[a+268|0]=b;D[a+269|0]=b>>>8;D[a+270|0]=b>>>16;D[a+271|0]=b>>>24;if(!fb(a+264|0,d,165,d+165|0)){F[a+300>>2]=14;c=-1;break b}F[a+296>>2]=1;c=0;break b}F[a+300>>2]=11;c=-1}ia(d,229)}_=d+240|0;return c|0}function gb(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0;g=_-336|0;_=g;i=b+32|0;m=i;h=32;c=_-208|0;_=c;e=c- -64|0;F[e>>2]=327033209;F[e+4>>2]=1541459225;F[c+56>>2]=-79577749;F[c+60>>2]=528734635;F[c+48>>2]=725511199;F[c+52>>2]=-1694144372;F[c+40>>2]=-1377402159;F[c+44>>2]=1359893119;F[c+32>>2]=1595750129;F[c+36>>2]=-1521486534;F[c+24>>2]=-23791573;F[c+28>>2]=1013904242;F[c+16>>2]=-2067093701;F[c+20>>2]=-1150833019;F[c+8>>2]=-205731576;F[c+12>>2]=1779033703;F[c>>2]=0;F[c+4>>2]=0;F[c+72>>2]=0;if(a){j=c+76|0;while(1){a:{if(!(h>>>0<128|d)){ta(c,a);d=F[c+4>>2];f=F[c>>2]+1024|0;d=f>>>0<1024?d+1|0:d;F[c>>2]=f;F[c+4>>2]=d;h=h-128|0;a=a+128|0;break a}e=128-d|0;f=e>>>0>h>>>0?h:e;b:{if(!f){break b}k=f&3;e=0;if(f-1>>>0>=3){l=f&-4;while(1){D[(e+d|0)+j|0]=G[a+e|0];d=e|1;D[(d+F[c+72>>2]|0)+j|0]=G[a+d|0];d=e|2;D[(d+F[c+72>>2]|0)+j|0]=G[a+d|0];d=e|3;D[(d+F[c+72>>2]|0)+j|0]=G[a+d|0];e=e+4|0;d=F[c+72>>2];l=l-4|0;if(l){continue}break}}if(!k){break b}while(1){D[(c+(e+d|0)|0)+76|0]=G[a+e|0];e=e+1|0;d=F[c+72>>2];k=k-1|0;if(k){continue}break}}h=h-f|0;a=a+f|0;e=d+f|0;F[c+72>>2]=e;if((e|0)!=128){break a}ta(c,j);F[c+72>>2]=0;d=F[c+4>>2];f=F[c>>2]+1024|0;d=f>>>0<1024?d+1|0:d;F[c>>2]=f;F[c+4>>2]=d}if(h){d=F[c+72>>2];continue}break}cb(c,m)}_=c+208|0;D[i|0]=G[i|0]&248;D[i+31|0]=G[i+31|0]&63|64;Tb(g,i);a=g+256|0;pb(a,g+80|0);c=g+208|0;ha(c,g,a);e=g+160|0;ha(e,g+40|0,a);Fa(b,e);Fa(g+304|0,c);D[b+31|0]=G[b+31|0]^G[g+304|0]<<7;_=g+336|0}function Ad(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;f=_-144|0;_=f;a:{if(c>>>0<220){F[a+300>>2]=2;a=-1;break a}b:{c:{if((d-F[a+260>>2]|0)>=0){c=a+132|0;bb(c,d);ja(f+8|0,c,132);break c}if((d-F[a+128>>2]|0)<0){break b}c=f+8|0;ja(c,a,132);bb(c,d)}c=b+55|0;D[c+1|0]=d>>>24;D[c|0]=1;D[c+4|0]=d;D[c+3|0]=d>>>8;D[c+2|0]=d>>>16;ja(c+5|0,f+8|0,128);d=G[a+292|0]|G[a+293|0]<<8|(G[a+294|0]<<16|G[a+295|0]<<24);e=G[a+288|0]|G[a+289|0]<<8|(G[a+290|0]<<16|G[a+291|0]<<24);D[c+157|0]=e;D[c+158|0]=e>>>8;D[c+159|0]=e>>>16;D[c+160|0]=e>>>24;D[c+161|0]=d;D[c+162|0]=d>>>8;D[c+163|0]=d>>>16;D[c+164|0]=d>>>24;d=G[a+284|0]|G[a+285|0]<<8|(G[a+286|0]<<16|G[a+287|0]<<24);e=G[a+280|0]|G[a+281|0]<<8|(G[a+282|0]<<16|G[a+283|0]<<24);D[c+149|0]=e;D[c+150|0]=e>>>8;D[c+151|0]=e>>>16;D[c+152|0]=e>>>24;D[c+153|0]=d;D[c+154|0]=d>>>8;D[c+155|0]=d>>>16;D[c+156|0]=d>>>24;d=G[a+276|0]|G[a+277|0]<<8|(G[a+278|0]<<16|G[a+279|0]<<24);e=G[a+272|0]|G[a+273|0]<<8|(G[a+274|0]<<16|G[a+275|0]<<24);D[c+141|0]=e;D[c+142|0]=e>>>8;D[c+143|0]=e>>>16;D[c+144|0]=e>>>24;D[c+145|0]=d;D[c+146|0]=d>>>8;D[c+147|0]=d>>>16;D[c+148|0]=d>>>24;d=G[a+268|0]|G[a+269|0]<<8|(G[a+270|0]<<16|G[a+271|0]<<24);a=G[a+264|0]|G[a+265|0]<<8|(G[a+266|0]<<16|G[a+267|0]<<24);D[c+133|0]=a;D[c+134|0]=a>>>8;D[c+135|0]=a>>>16;D[c+136|0]=a>>>24;D[c+137|0]=d;D[c+138|0]=d>>>8;D[c+139|0]=d>>>16;D[c+140|0]=d>>>24;a=Ca(c,165,b);break a}F[a+300>>2]=12;a=-1}_=f+144|0;return a|0}function Jd(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;d=_-176|0;_=d;e=oa(c);a:{if((e|0)!=165){c=-1;if((e|0)==-1){F[a+300>>2]=7;break a}F[a+300>>2]=11;break a}Ma(b,c,d);b:{if(G[d|0]==1){c=d|5;b=G[d+1|0]|G[d+2|0]<<8|(G[d+3|0]<<16|G[d+4|0]<<24);b=b<<24|b<<8&16711680|(b>>>8&65280|b>>>24);_a(a,c,b);_a(a+132|0,c,b);b=G[d+161|0]|G[d+162|0]<<8|(G[d+163|0]<<16|G[d+164|0]<<24);c=G[d+157|0]|G[d+158|0]<<8|(G[d+159|0]<<16|G[d+160|0]<<24);D[a+288|0]=c;D[a+289|0]=c>>>8;D[a+290|0]=c>>>16;D[a+291|0]=c>>>24;D[a+292|0]=b;D[a+293|0]=b>>>8;D[a+294|0]=b>>>16;D[a+295|0]=b>>>24;b=G[d+153|0]|G[d+154|0]<<8|(G[d+155|0]<<16|G[d+156|0]<<24);c=G[d+149|0]|G[d+150|0]<<8|(G[d+151|0]<<16|G[d+152|0]<<24);D[a+280|0]=c;D[a+281|0]=c>>>8;D[a+282|0]=c>>>16;D[a+283|0]=c>>>24;D[a+284|0]=b;D[a+285|0]=b>>>8;D[a+286|0]=b>>>16;D[a+287|0]=b>>>24;b=G[d+145|0]|G[d+146|0]<<8|(G[d+147|0]<<16|G[d+148|0]<<24);c=G[d+141|0]|G[d+142|0]<<8|(G[d+143|0]<<16|G[d+144|0]<<24);D[a+272|0]=c;D[a+273|0]=c>>>8;D[a+274|0]=c>>>16;D[a+275|0]=c>>>24;D[a+276|0]=b;D[a+277|0]=b>>>8;D[a+278|0]=b>>>16;D[a+279|0]=b>>>24;b=G[d+137|0]|G[d+138|0]<<8|(G[d+139|0]<<16|G[d+140|0]<<24);c=G[d+133|0]|G[d+134|0]<<8|(G[d+135|0]<<16|G[d+136|0]<<24);D[a+264|0]=c;D[a+265|0]=c>>>8;D[a+266|0]=c>>>16;D[a+267|0]=c>>>24;D[a+268|0]=b;D[a+269|0]=b>>>8;D[a+270|0]=b>>>16;D[a+271|0]=b>>>24;c=0;break b}F[a+300>>2]=11;c=-1}ia(d,165)}_=d+176|0;return c|0}function xa(a){var b=0,c=0,d=0,e=0;b=L(G[a+12|0],6);c=L(G[a+8|0],6);d=L(G[a+4|0],6);e=L(G[a|0],6);D[a+12|0]=G[b+34389|0]^(G[c+34386|0]^(G[d+34388|0]^G[e+34387|0]));D[a+8|0]=G[b+34387|0]^(G[c+34389|0]^(G[d+34386|0]^G[e+34388|0]));D[a+4|0]=G[b+34388|0]^(G[c+34387|0]^(G[d+34389|0]^G[e+34386|0]));D[a|0]=G[b+34386|0]^(G[c+34388|0]^(G[d+34387|0]^G[e+34389|0]));b=L(G[a+13|0],6);c=L(G[a+9|0],6);d=L(G[a+5|0],6);e=L(G[a+1|0],6);D[a+1|0]=G[b+34386|0]^(G[c+34388|0]^(G[d+34387|0]^G[e+34389|0]));D[a+5|0]=G[b+34388|0]^(G[c+34387|0]^(G[d+34389|0]^G[e+34386|0]));D[a+9|0]=G[b+34387|0]^(G[c+34389|0]^(G[d+34386|0]^G[e+34388|0]));D[a+13|0]=G[b+34389|0]^(G[c+34386|0]^(G[d+34388|0]^G[e+34387|0]));b=L(G[a+14|0],6);c=L(G[a+10|0],6);d=L(G[a+6|0],6);e=L(G[a+2|0],6);D[a+2|0]=G[b+34386|0]^(G[c+34388|0]^(G[d+34387|0]^G[e+34389|0]));D[a+14|0]=G[b+34389|0]^(G[c+34386|0]^(G[d+34388|0]^G[e+34387|0]));D[a+10|0]=G[b+34387|0]^(G[c+34389|0]^(G[d+34386|0]^G[e+34388|0]));D[a+6|0]=G[b+34388|0]^(G[c+34387|0]^(G[d+34389|0]^G[e+34386|0]));b=L(G[a+15|0],6);c=L(G[a+11|0],6);d=L(G[a+7|0],6);e=L(G[a+3|0],6);D[a+15|0]=G[b+34389|0]^(G[c+34386|0]^(G[d+34388|0]^G[e+34387|0]));D[a+11|0]=G[b+34387|0]^(G[c+34389|0]^(G[d+34386|0]^G[e+34388|0]));D[a+7|0]=G[b+34388|0]^(G[c+34387|0]^(G[d+34389|0]^G[e+34386|0]));D[a+3|0]=G[b+34386|0]^(G[c+34388|0]^(G[d+34387|0]^G[e+34389|0]))}function Ba(a,b){var c=0,d=0,e=0;d=F[a+64>>2];D[d+a|0]=128;c=d+1|0;a:{if(d>>>0<=55){if(c>>>0>55){break a}ra(a+c|0,0,55-d|0);break a}if(c>>>0<=63){ra(a+c|0,0,63-d|0)}jb(a,a);F[a+48>>2]=0;F[a+52>>2]=0;F[a+40>>2]=0;F[a+44>>2]=0;F[a+32>>2]=0;F[a+36>>2]=0;F[a+24>>2]=0;F[a+28>>2]=0;F[a+16>>2]=0;F[a+20>>2]=0;F[a+8>>2]=0;F[a+12>>2]=0;F[a>>2]=0;F[a+4>>2]=0}c=F[a+76>>2];e=F[a+64>>2]<<3;d=e+F[a+72>>2]|0;c=d>>>0>>0?c+1|0:c;F[a+72>>2]=d;F[a+76>>2]=c;D[a+63|0]=d;D[a+62|0]=(c&255)<<24|d>>>8;D[a+61|0]=(c&65535)<<16|d>>>16;D[a+60|0]=(c&16777215)<<8|d>>>24;D[a+59|0]=c;D[a+58|0]=c>>>8;D[a+57|0]=c>>>16;D[a+56|0]=c>>>24;jb(a,a);D[b|0]=G[a+83|0];D[b+4|0]=G[a+87|0];D[b+8|0]=G[a+91|0];D[b+12|0]=G[a+95|0];D[b+16|0]=G[a+99|0];D[b+20|0]=G[a+103|0];D[b+24|0]=G[a+107|0];D[b+28|0]=G[a+111|0];D[b+1|0]=H[a+82>>1];D[b+5|0]=H[a+86>>1];D[b+9|0]=H[a+90>>1];D[b+13|0]=H[a+94>>1];D[b+17|0]=H[a+98>>1];D[b+21|0]=H[a+102>>1];D[b+25|0]=H[a+106>>1];D[b+29|0]=H[a+110>>1];D[b+2|0]=F[a+80>>2]>>>8;D[b+6|0]=F[a+84>>2]>>>8;D[b+10|0]=F[a+88>>2]>>>8;D[b+14|0]=F[a+92>>2]>>>8;D[b+18|0]=F[a+96>>2]>>>8;D[b+22|0]=F[a+100>>2]>>>8;D[b+26|0]=F[a+104>>2]>>>8;D[b+30|0]=F[a+108>>2]>>>8;D[b+3|0]=F[a+80>>2];D[b+7|0]=F[a+84>>2];D[b+11|0]=F[a+88>>2];D[b+15|0]=F[a+92>>2];D[b+19|0]=F[a+96>>2];D[b+23|0]=F[a+100>>2];D[b+27|0]=F[a+104>>2];D[b+31|0]=F[a+108>>2]}function ad(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;if(c>>>0<306){F[a+228>>2]=2;return-1}c=b+77|0;D[c|0]=2;d=F[a+128>>2];d=d<<24|d<<8&16711680|(d>>>8&65280|d>>>24);D[c+1|0]=d;D[c+2|0]=d>>>8;D[c+3|0]=d>>>16;D[c+4|0]=d>>>24;ja(c+5|0,a,128);d=G[a+160|0]|G[a+161|0]<<8|(G[a+162|0]<<16|G[a+163|0]<<24);e=G[a+156|0]|G[a+157|0]<<8|(G[a+158|0]<<16|G[a+159|0]<<24);D[c+157|0]=e;D[c+158|0]=e>>>8;D[c+159|0]=e>>>16;D[c+160|0]=e>>>24;D[c+161|0]=d;D[c+162|0]=d>>>8;D[c+163|0]=d>>>16;D[c+164|0]=d>>>24;d=G[a+152|0]|G[a+153|0]<<8|(G[a+154|0]<<16|G[a+155|0]<<24);e=G[a+148|0]|G[a+149|0]<<8|(G[a+150|0]<<16|G[a+151|0]<<24);D[c+149|0]=e;D[c+150|0]=e>>>8;D[c+151|0]=e>>>16;D[c+152|0]=e>>>24;D[c+153|0]=d;D[c+154|0]=d>>>8;D[c+155|0]=d>>>16;D[c+156|0]=d>>>24;d=G[a+144|0]|G[a+145|0]<<8|(G[a+146|0]<<16|G[a+147|0]<<24);e=G[a+140|0]|G[a+141|0]<<8|(G[a+142|0]<<16|G[a+143|0]<<24);D[c+141|0]=e;D[c+142|0]=e>>>8;D[c+143|0]=e>>>16;D[c+144|0]=e>>>24;D[c+145|0]=d;D[c+146|0]=d>>>8;D[c+147|0]=d>>>16;D[c+148|0]=d>>>24;d=G[a+136|0]|G[a+137|0]<<8|(G[a+138|0]<<16|G[a+139|0]<<24);e=G[a+132|0]|G[a+133|0]<<8|(G[a+134|0]<<16|G[a+135|0]<<24);D[c+133|0]=e;D[c+134|0]=e>>>8;D[c+135|0]=e>>>16;D[c+136|0]=e>>>24;D[c+137|0]=d;D[c+138|0]=d>>>8;D[c+139|0]=d>>>16;D[c+140|0]=d>>>24;$a(a+132|0,c,165,c+165|0);return Ca(c,229,b)|0}function Kb(a,b){var c=0,d=0;c=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);F[b>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);c=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);F[b+4>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);c=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);F[b+8>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);c=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);F[b+12>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);c=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);F[b+16>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);c=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);F[b+20>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);c=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);F[b+24>>2]=c<<24|c<<8&16711680|(c>>>8&65280|c>>>24);a=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);F[b+28>>2]=a<<24|a<<8&16711680|(a>>>8&65280|a>>>24);c=F[b+28>>2];a=8;while(1){d=a&7;a:{if(!d){d=F[(a-1>>>3<<2)+34064>>2];c=se(c,8);c=d^(G[(c>>>8&255)+33808|0]<<8|G[(c&255)+33808|0]|G[(c>>>16&255)+33808|0]<<16|G[(c>>>24|0)+33808|0]<<24);break a}if((d|0)!=4){break a}c=G[(c&255)+33808|0]|G[(c>>>8&255)+33808|0]<<8|G[(c>>>16&255)+33808|0]<<16|G[(c>>>24|0)+33808|0]<<24}c=F[(a-8<<2)+b>>2]^c;F[(a<<2)+b>>2]=c;a=a+1|0;if((a|0)!=60){continue}break}}function Ga(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;d=F[b+44>>2];e=F[b+48>>2];f=F[b+52>>2];g=F[b+56>>2];h=F[b+60>>2];c=b- -64|0;i=F[c>>2];j=F[b+68>>2];k=F[b+72>>2];l=F[b+76>>2];m=F[b+4>>2];n=F[b+8>>2];o=F[b+12>>2];p=F[b+16>>2];q=F[b+20>>2];r=F[b+24>>2];s=F[b+28>>2];t=F[b+32>>2];u=F[b+36>>2];F[a>>2]=F[b>>2]+F[b+40>>2];F[a+36>>2]=l+u;F[a+32>>2]=k+t;F[a+28>>2]=j+s;F[a+24>>2]=i+r;F[a+20>>2]=h+q;F[a+16>>2]=g+p;F[a+12>>2]=f+o;F[a+8>>2]=e+n;F[a+4>>2]=d+m;d=F[b+44>>2];e=F[b+48>>2];f=F[b+52>>2];g=F[b+56>>2];h=F[b+60>>2];c=F[c>>2];i=F[b+68>>2];j=F[b+72>>2];k=F[b>>2];l=F[b+40>>2];m=F[b+4>>2];n=F[b+8>>2];o=F[b+12>>2];p=F[b+16>>2];q=F[b+20>>2];r=F[b+24>>2];s=F[b+28>>2];t=F[b+32>>2];F[a+76>>2]=F[b+76>>2]-F[b+36>>2];F[a+72>>2]=j-t;F[a+68>>2]=i-s;F[a- -64>>2]=c-r;F[a+60>>2]=h-q;F[a+56>>2]=g-p;F[a+52>>2]=f-o;F[a+48>>2]=e-n;F[a+44>>2]=d-m;F[a+40>>2]=l-k;d=F[b+88>>2];e=F[b+92>>2];f=F[b+96>>2];g=F[b+100>>2];h=F[b+104>>2];c=F[b+108>>2];i=F[b+80>>2];j=F[b+84>>2];k=F[b+116>>2];F[a+112>>2]=F[b+112>>2];F[a+116>>2]=k;F[a+104>>2]=h;F[a+108>>2]=c;F[a+96>>2]=f;F[a+100>>2]=g;F[a+88>>2]=d;F[a+92>>2]=e;F[a+80>>2]=i;F[a+84>>2]=j;ha(a+120|0,b+120|0,2032)}function oe(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0,f=0,g=0,h=0,i=0;g=_-16|0;_=g;a:{b:{e=a+164|0;h=F[a+160>>2];if((e|0)==(h|0)){break b}i=1;d=e;while(1){if(G[d+4|0]){d=d+72|0;if((h|0)!=(d|0)){continue}d=16;if(!i){break a}break b}f=f+55|0;i=0;d=d+72|0;if((h|0)!=(d|0)){continue}break}d=16;break a}d=17}c:{if(d+f>>>0>c>>>0){F[a+7516>>2]=2;a=-1;break c}f=123;D[b|0]=123;d=G[1687]|G[1688]<<8|(G[1689]<<16|G[1690]<<24);c=G[1683]|G[1684]<<8|(G[1685]<<16|G[1686]<<24);D[b+6|0]=c;D[b+7|0]=c>>>8;D[b+8|0]=c>>>16;D[b+9|0]=c>>>24;D[b+10|0]=d;D[b+11|0]=d>>>8;D[b+12|0]=d>>>16;D[b+13|0]=d>>>24;c=G[1682]|G[1683]<<8|(G[1684]<<16|G[1685]<<24);d=G[1678]|G[1679]<<8|(G[1680]<<16|G[1681]<<24);D[b+1|0]=d;D[b+2|0]=d>>>8;D[b+3|0]=d>>>16;D[b+4|0]=d>>>24;D[b+5|0]=c;D[b+6|0]=c>>>8;D[b+7|0]=c>>>16;D[b+8|0]=c>>>24;d=b+14|0;c=F[a+160>>2];d:{if((c|0)!=(e|0)){while(1){if(!G[e+4|0]){D[d+1|0]=34;D[d|0]=f;a=g+12|0;la(a,F[e>>2]);a=na(a,4,d+2|0);D[a+2|0]=34;D[a|0]=34;D[a+1|0]=58;a=na(e+5|0,32,a+3|0);D[a|0]=34;f=44;d=a+1|0}e=e+72|0;if((c|0)!=(e|0)){continue}break}if((f&255)==44){break d}}D[d|0]=f;d=d+1|0}D[d|0]=125;D[d+1|0]=125;a=(d-b|0)+2|0}_=g+16|0;return a|0}function dd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0;l=_-16|0;_=l;f=F[9380];g=aa[F[F[f>>2]+4>>2]](f,c)|0;f=F[9380];f=aa[F[F[f>>2]>>2]](f)|0;m=Db(F[a+128>>2],g,f);f=m+2|0;g=(f>>>0)/3|0;a:{if(((f-L(g,3)|0)+(g<<2)|0)-2>>>0>e>>>0){F[a+228>>2]=2;e=-1;break a}e=F[9380];k=aa[F[F[e>>2]+4>>2]](e,c)|0;e=F[9380];n=aa[F[F[e>>2]>>2]](e)|0;g=F[a+128>>2];e=k;f=m+2|0;i=(f>>>0)/3|0;j=((((f-L(i,3)|0)+(i<<2)|0)-2|0)+d|0)-m|0;o=j;D[j+1|0]=8;D[j|0]=3;h=j+2|0;b:{if(g>>>0<128){f=g;break b}while(1){D[h|0]=g|128;h=h+1|0;i=g>>>0>16383;f=g>>>7|0;g=f;if(i){continue}break}}D[h+1|0]=18;D[h|0]=f;h=h+2|0;c:{if(e>>>0<128){f=e;break c}g=e;while(1){D[h|0]=g|128;h=h+1|0;i=g>>>0>16383;f=g>>>7|0;g=f;if(i){continue}break}}D[h|0]=f;g=h+1|0;F[l+12>>2]=g;f=F[9380];i=k;k=((e+g|0)-o|0)+n|0;e=-1;if((aa[F[F[f>>2]+8>>2]](f,a,128,b,c,F[l+12>>2],i,j,k)|0)==-1){break a}g=0;c=F[a+128>>2]+1|0;F[a+128>>2]=c;d:{if(!(c&16777215)){c=a;b=3;break d}g=c&65535?c&255?3:2:1;c=(g<<5)+a|0;b=3}while(1){ka(c,32,b+37524|0,1,(b<<5)+a|0);e=b>>>0>g>>>0;b=b-1|0;if(e){continue}break}$a(a+132|0,j,k,j+k|0);e=Ca(j,m,d)}i=e;_=l+16|0;return i|0}function Hd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0;f=a+264|0;g=a+132|0;if(Da(301)>>>0>e>>>0){F[a+300>>2]=2;return-1}e=mb(g,mb(a,la(Za(d,301),2)));h=G[f+4|0]|G[f+5|0]<<8|(G[f+6|0]<<16|G[f+7|0]<<24);g=G[f|0]|G[f+1|0]<<8|(G[f+2|0]<<16|G[f+3|0]<<24);D[e|0]=g;D[e+1|0]=g>>>8;D[e+2|0]=g>>>16;D[e+3|0]=g>>>24;D[e+4|0]=h;D[e+5|0]=h>>>8;D[e+6|0]=h>>>16;D[e+7|0]=h>>>24;h=G[f+28|0]|G[f+29|0]<<8|(G[f+30|0]<<16|G[f+31|0]<<24);g=G[f+24|0]|G[f+25|0]<<8|(G[f+26|0]<<16|G[f+27|0]<<24);D[e+24|0]=g;D[e+25|0]=g>>>8;D[e+26|0]=g>>>16;D[e+27|0]=g>>>24;D[e+28|0]=h;D[e+29|0]=h>>>8;D[e+30|0]=h>>>16;D[e+31|0]=h>>>24;h=G[f+20|0]|G[f+21|0]<<8|(G[f+22|0]<<16|G[f+23|0]<<24);g=G[f+16|0]|G[f+17|0]<<8|(G[f+18|0]<<16|G[f+19|0]<<24);D[e+16|0]=g;D[e+17|0]=g>>>8;D[e+18|0]=g>>>16;D[e+19|0]=g>>>24;D[e+20|0]=h;D[e+21|0]=h>>>8;D[e+22|0]=h>>>16;D[e+23|0]=h>>>24;g=G[f+12|0]|G[f+13|0]<<8|(G[f+14|0]<<16|G[f+15|0]<<24);f=G[f+8|0]|G[f+9|0]<<8|(G[f+10|0]<<16|G[f+11|0]<<24);D[e+8|0]=f;D[e+9|0]=f>>>8;D[e+10|0]=f>>>16;D[e+11|0]=f>>>24;D[e+12|0]=g;D[e+13|0]=g>>>8;D[e+14|0]=g>>>16;D[e+15|0]=g>>>24;D[e+32|0]=F[a+296>>2]!=0;return Ya(b,c,d,301)|0}function ja(a,b,c){var d=0,e=0,f=0;if(c>>>0>=512){Y(a|0,b|0,c|0)|0;return a}e=a+c|0;a:{if(!((a^b)&3)){b:{if(!(a&3)){c=a;break b}if((c|0)<1){c=a;break b}c=a;while(1){D[c|0]=G[b|0];b=b+1|0;c=c+1|0;if(!(c&3)){break b}if(c>>>0>>0){continue}break}}d=e&-4;c:{if(d>>>0<64){break c}f=d+-64|0;if(f>>>0>>0){break c}while(1){F[c>>2]=F[b>>2];F[c+4>>2]=F[b+4>>2];F[c+8>>2]=F[b+8>>2];F[c+12>>2]=F[b+12>>2];F[c+16>>2]=F[b+16>>2];F[c+20>>2]=F[b+20>>2];F[c+24>>2]=F[b+24>>2];F[c+28>>2]=F[b+28>>2];F[c+32>>2]=F[b+32>>2];F[c+36>>2]=F[b+36>>2];F[c+40>>2]=F[b+40>>2];F[c+44>>2]=F[b+44>>2];F[c+48>>2]=F[b+48>>2];F[c+52>>2]=F[b+52>>2];F[c+56>>2]=F[b+56>>2];F[c+60>>2]=F[b+60>>2];b=b- -64|0;c=c- -64|0;if(f>>>0>=c>>>0){continue}break}}if(c>>>0>=d>>>0){break a}while(1){F[c>>2]=F[b>>2];b=b+4|0;c=c+4|0;if(d>>>0>c>>>0){continue}break}break a}if(e>>>0<4){c=a;break a}d=e-4|0;if(d>>>0>>0){c=a;break a}c=a;while(1){D[c|0]=G[b|0];D[c+1|0]=G[b+1|0];D[c+2|0]=G[b+2|0];D[c+3|0]=G[b+3|0];b=b+4|0;c=c+4|0;if(d>>>0>=c>>>0){continue}break}}if(c>>>0>>0){while(1){D[c|0]=G[b|0];b=b+1|0;c=c+1|0;if((e|0)!=(c|0)){continue}break}}return a}function bb(a,b){var c=0,d=0,e=0;a:{b:{c:{d:{e=F[a+128>>2];c=(b>>>24)-(e>>>24)&255;switch(c|0){case 1:break b;case 0:break d;default:break c}}c=256;if(b>>>0>=e>>>0){break a}}while(1){ka(a,32,37524,1,a);c=c-1|0;if(c>>>0>1){continue}break}}ka(a,32,37527,1,a+96|0);ka(a,32,37526,1,a- -64|0);ka(a,32,37525,1,a+32|0);ka(a,32,37524,1,a);e=b&-16777216;F[a+128>>2]=e}d=(b>>>16)-(e>>>16)&255;e:{f:{g:{if(!d){if(b>>>0>=e>>>0){break e}c=a+32|0;d=256;break g}c=a+32|0;if((d|0)==1){break f}}while(1){ka(c,32,37525,1,c);d=d-1|0;if(d>>>0>1){continue}break}}ka(c,32,37527,1,a+96|0);ka(c,32,37526,1,a- -64|0);ka(c,32,37525,1,c);e=b&-65536;F[a+128>>2]=e}d=(b>>>8)-(e>>>8)&255;h:{i:{j:{if(!d){if(b>>>0>=e>>>0){break h}c=a- -64|0;d=256;break j}c=a- -64|0;if((d|0)==1){break i}}while(1){ka(c,32,37526,1,c);d=d-1|0;if(d>>>0>1){continue}break}}ka(c,32,37527,1,a+96|0);ka(c,32,37526,1,c);e=b&-256;F[a+128>>2]=e}d=b-e&255;k:{l:{m:{if(!d){if(b>>>0>=e>>>0){break k}c=a+96|0;d=256;break m}c=a+96|0;if((d|0)==1){break l}}while(1){ka(c,32,37527,1,c);d=d-1|0;if(d>>>0>1){continue}break}}ka(c,32,37527,1,c);F[a+128>>2]=b}}function Fa(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0;c=F[b>>2];e=c;g=F[b+36>>2];h=F[b+32>>2];i=F[b+28>>2];j=F[b+24>>2];k=F[b+20>>2];l=F[b+16>>2];f=F[b+12>>2];d=F[b+8>>2];m=(L(g,19)+16777216>>25)+c>>26;c=F[b+4>>2];b=e+L(g+(h+(i+(j+(k+(l+(f+(d+(m+c>>25)>>26)>>25)>>26)>>25)>>26)>>25)>>26)>>25,19)|0;D[a|0]=b;D[a+2|0]=b>>>16;D[a+1|0]=b>>>8;c=c+(b>>26)|0;D[a+5|0]=c>>>14;D[a+4|0]=c>>>6;d=d+(c>>25)|0;D[a+8|0]=d>>>13;D[a+7|0]=d>>>5;e=b>>>24&3;b=c&33554431;D[a+3|0]=e|b<<2;c=(d>>26)+f|0;D[a+11|0]=c>>>11;D[a+10|0]=c>>>3;d=d&67108863;D[a+6|0]=d<<3|b>>>22;b=l+(c>>25)|0;D[a+15|0]=b>>>18;D[a+14|0]=b>>>10;D[a+13|0]=b>>>2;f=c&33554431;D[a+9|0]=f<<5|d>>>21;c=(b>>26)+k|0;D[a+16|0]=c;D[a+12|0]=b<<6|f>>>19;D[a+18|0]=c>>>16;D[a+17|0]=c>>>8;b=(c>>25)+j|0;D[a+21|0]=b>>>15;D[a+20|0]=b>>>7;d=(b>>26)+i|0;D[a+24|0]=d>>>13;D[a+23|0]=d>>>5;e=c>>>24&1;c=b&67108863;D[a+19|0]=e|c<<1;b=(d>>25)+h|0;D[a+27|0]=b>>>12;D[a+26|0]=b>>>4;d=d&33554431;D[a+22|0]=d<<3|c>>>23;c=(b>>26)+g|0;D[a+30|0]=c>>>10;D[a+29|0]=c>>>2;b=b&67108863;D[a+25|0]=b<<4|d>>>21;c=c&33554431;D[a+31|0]=c>>>18;D[a+28|0]=c<<6|b>>>20}function ya(a){var b=0,c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;e=G[a+12|0];c=L(e,6);g=G[a|0];f=L(g,6);d=G[a+8|0];b=G[a+4|0];D[a+12|0]=G[c+34384|0]^(G[f+34385|0]^(d^b));h=L(d,6);D[a+8|0]=G[c+34385|0]^(G[h+34384|0]^(b^g));i=L(b,6);D[a|0]=G[i+34385|0]^(G[f+34384|0]^(d^e));d=G[a+5|0];j=L(d,6);b=G[a+1|0];k=L(b,6);c=G[a+13|0];f=G[a+9|0];D[a+1|0]=G[j+34385|0]^(G[k+34384|0]^(c^f));l=L(c,6);D[a+13|0]=G[l+34384|0]^(G[k+34385|0]^(d^f));D[a+4|0]=G[h+34385|0]^(e^(g^G[i+34384|0]));e=L(f,6);D[a+9|0]=G[l+34385|0]^(G[e+34384|0]^(b^d));D[a+5|0]=G[e+34385|0]^(c^(b^G[j+34384|0]));e=G[a+6|0];c=L(e,6);g=G[a+2|0];f=L(g,6);d=G[a+14|0];b=G[a+10|0];D[a+2|0]=G[c+34385|0]^(G[f+34384|0]^(d^b));h=L(d,6);D[a+14|0]=G[h+34384|0]^(G[f+34385|0]^(b^e));b=L(b,6);D[a+10|0]=G[h+34385|0]^(G[b+34384|0]^(e^g));D[a+6|0]=G[b+34385|0]^(d^(g^G[c+34384|0]));e=G[a+15|0];c=L(e,6);g=G[a+3|0];f=L(g,6);d=G[a+11|0];b=G[a+7|0];D[a+15|0]=G[c+34384|0]^(G[f+34385|0]^(d^b));h=G[c+34385|0];c=L(d,6);D[a+11|0]=h^(G[c+34384|0]^(b^g));b=L(b,6);D[a+3|0]=G[b+34385|0]^(G[f+34384|0]^(d^e));D[a+7|0]=G[c+34385|0]^(e^(g^G[b+34384|0]))}function Ec(a,b,c){a=a|0;b=b|0;c=c|0;var d=0;if(c>>>0<=31){F[a>>2]=2;return-1}c=G[a+64|0]|G[a+65|0]<<8|(G[a+66|0]<<16|G[a+67|0]<<24);d=G[a+60|0]|G[a+61|0]<<8|(G[a+62|0]<<16|G[a+63|0]<<24);D[b+24|0]=d;D[b+25|0]=d>>>8;D[b+26|0]=d>>>16;D[b+27|0]=d>>>24;D[b+28|0]=c;D[b+29|0]=c>>>8;D[b+30|0]=c>>>16;D[b+31|0]=c>>>24;c=G[a+56|0]|G[a+57|0]<<8|(G[a+58|0]<<16|G[a+59|0]<<24);d=G[a+52|0]|G[a+53|0]<<8|(G[a+54|0]<<16|G[a+55|0]<<24);D[b+16|0]=d;D[b+17|0]=d>>>8;D[b+18|0]=d>>>16;D[b+19|0]=d>>>24;D[b+20|0]=c;D[b+21|0]=c>>>8;D[b+22|0]=c>>>16;D[b+23|0]=c>>>24;c=G[a+48|0]|G[a+49|0]<<8|(G[a+50|0]<<16|G[a+51|0]<<24);d=G[a+44|0]|G[a+45|0]<<8|(G[a+46|0]<<16|G[a+47|0]<<24);D[b+8|0]=d;D[b+9|0]=d>>>8;D[b+10|0]=d>>>16;D[b+11|0]=d>>>24;D[b+12|0]=c;D[b+13|0]=c>>>8;D[b+14|0]=c>>>16;D[b+15|0]=c>>>24;c=G[a+40|0]|G[a+41|0]<<8|(G[a+42|0]<<16|G[a+43|0]<<24);a=G[a+36|0]|G[a+37|0]<<8|(G[a+38|0]<<16|G[a+39|0]<<24);D[b|0]=a;D[b+1|0]=a>>>8;D[b+2|0]=a>>>16;D[b+3|0]=a>>>24;D[b+4|0]=c;D[b+5|0]=c>>>8;D[b+6|0]=c>>>16;D[b+7|0]=c>>>24;return 32}function Ra(a,b,c){var d=0,e=0;a:{if(!a){break a}e=b;b=a+32|0;if(e>>>0>>0){break a}d=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);e=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[c|0]=e;D[c+1|0]=e>>>8;D[c+2|0]=e>>>16;D[c+3|0]=e>>>24;D[c+4|0]=d;D[c+5|0]=d>>>8;D[c+6|0]=d>>>16;D[c+7|0]=d>>>24;d=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);e=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[c+24|0]=e;D[c+25|0]=e>>>8;D[c+26|0]=e>>>16;D[c+27|0]=e>>>24;D[c+28|0]=d;D[c+29|0]=d>>>8;D[c+30|0]=d>>>16;D[c+31|0]=d>>>24;d=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);e=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[c+16|0]=e;D[c+17|0]=e>>>8;D[c+18|0]=e>>>16;D[c+19|0]=e>>>24;D[c+20|0]=d;D[c+21|0]=d>>>8;D[c+22|0]=d>>>16;D[c+23|0]=d>>>24;d=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);a=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[c+8|0]=a;D[c+9|0]=a>>>8;D[c+10|0]=a>>>16;D[c+11|0]=a>>>24;D[c+12|0]=d;D[c+13|0]=d>>>8;D[c+14|0]=d>>>16;D[c+15|0]=d>>>24;d=b}return d}function Ea(a,b){var c=0,d=0;c=G[a+4|0]|G[a+5|0]<<8|(G[a+6|0]<<16|G[a+7|0]<<24);d=G[a|0]|G[a+1|0]<<8|(G[a+2|0]<<16|G[a+3|0]<<24);D[b+32|0]=d;D[b+33|0]=d>>>8;D[b+34|0]=d>>>16;D[b+35|0]=d>>>24;D[b+36|0]=c;D[b+37|0]=c>>>8;D[b+38|0]=c>>>16;D[b+39|0]=c>>>24;c=G[a+28|0]|G[a+29|0]<<8|(G[a+30|0]<<16|G[a+31|0]<<24);d=G[a+24|0]|G[a+25|0]<<8|(G[a+26|0]<<16|G[a+27|0]<<24);D[b+56|0]=d;D[b+57|0]=d>>>8;D[b+58|0]=d>>>16;D[b+59|0]=d>>>24;D[b+60|0]=c;D[b+61|0]=c>>>8;D[b+62|0]=c>>>16;D[b+63|0]=c>>>24;c=G[a+20|0]|G[a+21|0]<<8|(G[a+22|0]<<16|G[a+23|0]<<24);d=G[a+16|0]|G[a+17|0]<<8|(G[a+18|0]<<16|G[a+19|0]<<24);D[b+48|0]=d;D[b+49|0]=d>>>8;D[b+50|0]=d>>>16;D[b+51|0]=d>>>24;D[b+52|0]=c;D[b+53|0]=c>>>8;D[b+54|0]=c>>>16;D[b+55|0]=c>>>24;c=G[a+12|0]|G[a+13|0]<<8|(G[a+14|0]<<16|G[a+15|0]<<24);a=G[a+8|0]|G[a+9|0]<<8|(G[a+10|0]<<16|G[a+11|0]<<24);D[b+40|0]=a;D[b+41|0]=a>>>8;D[b+42|0]=a>>>16;D[b+43|0]=a>>>24;D[b+44|0]=c;D[b+45|0]=c>>>8;D[b+46|0]=c>>>16;D[b+47|0]=c>>>24;Jb(b,b+32|0,1856)}function jb(a,b){var c=0,d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0,m=0,n=0,o=0,p=0,q=0,r=0,s=0,t=0,u=0;f=_-256|0;_=f;while(1){F[(d<<2)+f>>2]=G[(c|3)+b|0]|(G[(c|1)+b|0]<<16|G[b+c|0]<<24|G[(c|2)+b|0]<<8);c=c+4|0;d=d+1|0;if((d|0)!=16){continue}break}b=16;c=F[f>>2];while(1){e=c;c=(b<<2)+f|0;d=F[c-8>>2];d=e+(F[c-28>>2]+(se(d,15)^se(d,13)^d>>>10)|0)|0;e=c;c=F[c-60>>2];F[e>>2]=(se(c,25)^se(c,14)^c>>>3)+d;b=b+1|0;if((b|0)!=64){continue}break}n=F[a+80>>2];i=n;o=F[a+84>>2];b=o;p=F[a+108>>2];g=p;q=F[a+104>>2];c=q;r=F[a+100>>2];e=r;s=F[a+96>>2];j=s;t=F[a+92>>2];k=t;u=F[a+88>>2];d=u;while(1){l=d;d=b;b=m<<2;h=j;g=(F[b+33552>>2]+((((se(h,26)^se(h,21)^se(h,7))+(h&e)|0)+g|0)+((h^-1)&c)|0)|0)+F[b+f>>2]|0;b=i;i=g+((se(b,30)^se(b,19)^se(b,10))+((d^l)&b^d&l)|0)|0;j=g+k|0;g=c;c=e;e=h;k=l;m=m+1|0;if((m|0)!=64){continue}break}F[a+108>>2]=g+p;F[a+104>>2]=c+q;F[a+100>>2]=e+r;F[a+96>>2]=j+s;F[a+92>>2]=k+t;F[a+88>>2]=d+u;F[a+84>>2]=b+o;F[a+80>>2]=i+n;_=f+256|0}function $d(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0,f=0,g=0,h=0;g=_-48|0;_=g;a:{if((c|0)<1){break a}D[b|0]=0;if((c|0)<23){break a}F[g+32>>2]=F[a+112>>2];d=Wa(b,c,1727,g+32|0);h=b+c|0;b:{if((d|0)>(c|0)){break b}if((d|0)<1){break a}f=b+d|0;e=c-d|0;d=Wa(f,e,1654,0);h=b+c|0;if((d|0)>(e|0)){break b}if((d|0)<1){break a}b=e-d|0;c=d+f|0;c:{e=a+152|0;if((e|0)!=F[a+148>>2]){d=0;while(1){F[g+16>>2]=F[(L(d,68)+a|0)+184>>2];f=Wa(c,b,1260,g+16|0);if((f|0)>(b|0)){break c}if((f|0)<1){break a}b=b-f|0;c=c+f|0;d=d+1|0;if(d>>>0<(F[a+148>>2]-e|0)/68>>>0){continue}break}}d=Wa(c,b,1631,0);if((d|0)>(b|0)){break c}if((d|0)<1){break a}f=a+496|0;if((f|0)==F[a+492>>2]){break a}c=c+d|0;b=b-d|0;d=0;while(1){F[g>>2]=F[(L(d,68)+a|0)+528>>2];e=Wa(c,b,1260,g);h=b+c|0;if((e|0)>(b|0)){break b}if((e|0)<1){break a}b=b-e|0;c=c+e|0;d=d+1|0;if(d>>>0<(F[a+492>>2]-f|0)/68>>>0){continue}break}break a}h=b+c|0}a=h-4|0;D[a|0]=46;D[a+1|0]=46;D[a+2|0]=46;D[a+3|0]=0}_=g+48|0}function Wa(a,b,c,d){var e=0,f=0,g=0,h=0,i=0,j=0;h=_-16|0;_=h;F[h+12>>2]=d;e=_-160|0;_=e;ja(e+8|0,35920,144);a:{b:{if((b|0)<=0){if(b){break b}b=1;a=e+159|0}F[e+52>>2]=a;F[e+28>>2]=a;f=-2-a|0;f=b>>>0>f>>>0?f:b;F[e+56>>2]=f;a=a+f|0;F[e+36>>2]=a;F[e+24>>2]=a;a=e+8|0;b=_-208|0;_=b;F[b+204>>2]=d;d=b+160|0;ra(d,0,40);F[b+200>>2]=F[b+204>>2];c:{if((hb(0,c,b+200|0,b+80|0,d)|0)<0){a=-1;break c}i=F[a+76>>2]>=0;d=F[a>>2];if(D[a+74|0]<=0){F[a>>2]=d&-33}j=d&32;d:{if(F[a+48>>2]){c=hb(a,c,b+200|0,b+80|0,b+160|0);break d}F[a+48>>2]=80;g=b+80|0;F[a+16>>2]=g;F[a+28>>2]=b;F[a+20>>2]=b;d=F[a+44>>2];F[a+44>>2]=b;g=hb(a,c,b+200|0,g,b+160|0);c=g;if(!d){break d}aa[F[a+36>>2]](a,0,0)|0;F[a+48>>2]=0;F[a+44>>2]=d;F[a+28>>2]=0;F[a+16>>2]=0;c=F[a+20>>2];F[a+20>>2]=0;c=c?g:-1}d=a;a=F[a>>2];F[d>>2]=a|j;a=a&32?-1:c;if(!i){break c}}_=b+208|0;if(!f){break a}b=F[e+28>>2];D[b-((b|0)==F[e+24>>2])|0]=0;break a}F[9439]=61;a=-1}_=e+160|0;_=h+16|0;return a}function Xb(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;a:{if(c>>>0<116){F[a+7516>>2]=2;a=-1;break a}D[b|0]=123;c=G[1682]|G[1683]<<8|(G[1684]<<16|G[1685]<<24);d=G[1678]|G[1679]<<8|(G[1680]<<16|G[1681]<<24);D[b+1|0]=d;D[b+2|0]=d>>>8;D[b+3|0]=d>>>16;D[b+4|0]=d>>>24;D[b+5|0]=c;D[b+6|0]=c>>>8;D[b+7|0]=c>>>16;D[b+8|0]=c>>>24;c=G[1687]|G[1688]<<8|(G[1689]<<16|G[1690]<<24);d=G[1683]|G[1684]<<8|(G[1685]<<16|G[1686]<<24);D[b+6|0]=d;D[b+7|0]=d>>>8;D[b+8|0]=d>>>16;D[b+9|0]=d>>>24;D[b+10|0]=c;D[b+11|0]=c>>>8;D[b+12|0]=c>>>16;D[b+13|0]=c>>>24;D[b+14|0]=34;c=na(a+96|0,32,b+15|0);D[c|0]=34;D[c+1|0]=44;D[c+12|0]=34;d=G[1696]|G[1697]<<8|(G[1698]<<16|G[1699]<<24);e=G[1692]|G[1693]<<8|(G[1694]<<16|G[1695]<<24);D[c+2|0]=e;D[c+3|0]=e>>>8;D[c+4|0]=e>>>16;D[c+5|0]=e>>>24;D[c+6|0]=d;D[c+7|0]=d>>>8;D[c+8|0]=d>>>16;D[c+9|0]=d>>>24;d=G[1700]|G[1701]<<8;D[c+10|0]=d;D[c+11|0]=d>>>8;a=na(a,32,c+13|0);D[a|0]=34;D[a+1|0]=125;a=(a-b|0)+2|0}return a|0}function re(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0,j=0,k=0,l=0;a:{b:{c:{d:{e:{f:{g:{h:{i:{j:{e=b;if(b){d=c;if(!d){break j}break i}a=(a>>>0)/(c>>>0)|0;$=0;break a}if(!a){break h}break g}if(!(d-1&d)){break f}h=(O(d)+33|0)-O(e)|0;i=0-h|0;break d}a=(e>>>0)/0|0;$=0;break a}d=32-O(e)|0;if(d>>>0<31){break e}break c}if((d|0)==1){break b}d=d?31-O(d-1^d)|0:32;c=d&31;if((d&63)>>>0>=32){e=0;a=b>>>c|0}else{e=b>>>c|0;a=((1<>>c}$=e;break a}h=d+1|0;i=63-d|0}d=b;e=h&63;f=e&31;if(e>>>0>=32){e=0;f=d>>>f|0}else{e=d>>>f|0;f=((1<>>f}i=i&63;d=i&31;if(i>>>0>=32){b=a<>>32-d|b<>>31;j=g;e=e<<1|f>>>31;g=i-(e+(d>>>0>>0)|0)>>31;k=c&g;f=j-k|0;e=e-(j>>>0>>0)|0;b=b<<1|a>>>31;a=l|a<<1;g=g&1;l=g;h=h-1|0;if(h){continue}break}}$=b<<1|a>>>31;a=g|a<<1;break a}a=0;b=0}$=b}return a}function fe(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;e=_-16|0;_=e;d=17;a:{if((G[a+7372|0]|!G[a+7364|0]?d:71)>>>0>c>>>0){F[a+7516>>2]=2;a=-1;break a}D[b|0]=123;c=G[1682]|G[1683]<<8|(G[1684]<<16|G[1685]<<24);d=G[1678]|G[1679]<<8|(G[1680]<<16|G[1681]<<24);D[b+1|0]=d;D[b+2|0]=d>>>8;D[b+3|0]=d>>>16;D[b+4|0]=d>>>24;D[b+5|0]=c;D[b+6|0]=c>>>8;D[b+7|0]=c>>>16;D[b+8|0]=c>>>24;c=G[1687]|G[1688]<<8|(G[1689]<<16|G[1690]<<24);d=G[1683]|G[1684]<<8|(G[1685]<<16|G[1686]<<24);D[b+6|0]=d;D[b+7|0]=d>>>8;D[b+8|0]=d>>>16;D[b+9|0]=d>>>24;D[b+10|0]=c;D[b+11|0]=c>>>8;D[b+12|0]=c>>>16;D[b+13|0]=c>>>24;D[b+14|0]=123;d=b+15|0;if(!(G[a+7372|0]|!G[a+7364|0])){D[b+15|0]=34;c=e+12|0;la(c,F[a+7368>>2]);c=na(c,4,b+16|0);D[c+2|0]=34;D[c|0]=34;D[c+1|0]=58;a=na(a+7373|0,32,c+3|0);D[a|0]=34;d=a+1|0}D[d|0]=125;D[d+1|0]=125;a=(d-b|0)+2|0}_=e+16|0;return a|0}function Ed(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;var g=0,h=0;g=_-160|0;_=g;h=-1;c=Ma(b,c,b);a:{if((c|0)==-1){F[a+300>>2]=7;break a}h=F[9380];Cb(b,c,aa[F[F[h>>2]>>2]](h)|0,g+136|0);if(G[g+136|0]!=3){F[a+300>>2]=3;h=-1;break a}if(!(F[g+148>>2]?F[g+144>>2]:0)){F[a+300>>2]=4;h=-1;break a}if(f){F[f>>2]=F[g+140>>2]}f=c+-64|0;if(!fb(a+264|0,b,f,b+f|0)){F[a+300>>2]=14;h=-1;break a}c=F[9380];if(aa[F[F[c>>2]+12>>2]](c,F[g+152>>2])>>>0>e>>>0){F[a+300>>2]=2;h=-1;break a}b:{c=F[g+140>>2];c:{if((c-F[a+260>>2]|0)>=0){h=a+132|0;bb(h,c);ja(g,h,132);break c}if((c-F[a+128>>2]|0)<0){break b}bb(ja(g,a,132),c)}c=F[9380];b=aa[F[F[c>>2]+16>>2]](c,g,128,b,f,F[g+148>>2],F[g+152>>2],d,e)|0;ia(g,132);h=-1;if((b|0)==-1){F[a+300>>2]=5;break a}F[a+296>>2]=1;h=b;break a}F[a+300>>2]=12;h=-1}_=g+160|0;return h|0}function he(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;e=_-16|0;_=e;a:{if((G[a+7364|0]?71:17)>>>0>c>>>0){F[a+7516>>2]=2;a=-1;break a}D[b|0]=123;c=G[1682]|G[1683]<<8|(G[1684]<<16|G[1685]<<24);d=G[1678]|G[1679]<<8|(G[1680]<<16|G[1681]<<24);D[b+1|0]=d;D[b+2|0]=d>>>8;D[b+3|0]=d>>>16;D[b+4|0]=d>>>24;D[b+5|0]=c;D[b+6|0]=c>>>8;D[b+7|0]=c>>>16;D[b+8|0]=c>>>24;c=G[1687]|G[1688]<<8|(G[1689]<<16|G[1690]<<24);d=G[1683]|G[1684]<<8|(G[1685]<<16|G[1686]<<24);D[b+6|0]=d;D[b+7|0]=d>>>8;D[b+8|0]=d>>>16;D[b+9|0]=d>>>24;D[b+10|0]=c;D[b+11|0]=c>>>8;D[b+12|0]=c>>>16;D[b+13|0]=c>>>24;D[b+14|0]=123;if(G[a+7364|0]){D[b+15|0]=34;c=e+12|0;la(c,F[a+7368>>2]);c=na(c,4,b+16|0);D[c+2|0]=34;D[c|0]=34;D[c+1|0]=58;a=na(a+7373|0,32,c+3|0);D[a|0]=34;a=a+1|0}else{a=b+15|0}D[a|0]=125;D[a+1|0]=125;a=(a-b|0)+2|0}_=e+16|0;return a|0}function ra(a,b,c){var d=0,e=0,f=0;a:{if(!c){break a}f=a+c|0;D[f-1|0]=b;D[a|0]=b;if(c>>>0<3){break a}D[f-2|0]=b;D[a+1|0]=b;D[f-3|0]=b;D[a+2|0]=b;if(c>>>0<7){break a}D[f-4|0]=b;D[a+3|0]=b;if(c>>>0<9){break a}f=0-a&3;e=f+a|0;d=L(b&255,16843009);F[e>>2]=d;b=c-f&-4;c=b+e|0;F[c-4>>2]=d;if(b>>>0<9){break a}F[e+8>>2]=d;F[e+4>>2]=d;F[c-8>>2]=d;F[c-12>>2]=d;if(b>>>0<25){break a}F[e+24>>2]=d;F[e+20>>2]=d;F[e+16>>2]=d;F[e+12>>2]=d;F[c-16>>2]=d;F[c-20>>2]=d;F[c-24>>2]=d;F[c-28>>2]=d;c=b;b=e&4|24;c=c-b|0;if(c>>>0<32){break a}d=qe(d,0,1,1);f=$;b=b+e|0;while(1){F[b+24>>2]=d;e=f;F[b+28>>2]=e;F[b+16>>2]=d;F[b+20>>2]=e;F[b+8>>2]=d;F[b+12>>2]=e;F[b>>2]=d;F[b+4>>2]=e;b=b+32|0;c=c-32|0;if(c>>>0>31){continue}break}}return a}function Gb(a,b,c){a:{if(b>>>0>20){break a}b:{switch(b-9|0){case 0:b=F[c>>2];F[c>>2]=b+4;F[a>>2]=F[b>>2];return;case 1:b=F[c>>2];F[c>>2]=b+4;b=F[b>>2];F[a>>2]=b;F[a+4>>2]=b>>31;return;case 2:b=F[c>>2];F[c>>2]=b+4;F[a>>2]=F[b>>2];F[a+4>>2]=0;return;case 3:b=F[c>>2]+7&-8;F[c>>2]=b+8;c=F[b+4>>2];F[a>>2]=F[b>>2];F[a+4>>2]=c;return;case 4:b=F[c>>2];F[c>>2]=b+4;b=E[b>>1];F[a>>2]=b;F[a+4>>2]=b>>31;return;case 5:b=F[c>>2];F[c>>2]=b+4;F[a>>2]=H[b>>1];F[a+4>>2]=0;return;case 6:b=F[c>>2];F[c>>2]=b+4;b=D[b|0];F[a>>2]=b;F[a+4>>2]=b>>31;return;case 7:b=F[c>>2];F[c>>2]=b+4;F[a>>2]=G[b|0];F[a+4>>2]=0;return;case 8:b=F[c>>2]+7&-8;F[c>>2]=b+8;K[a>>3]=K[b>>3];return;case 9:break b;default:break a}}aa[8](a,c)}}function sb(a,b,c,d,e){var f=0,g=0,h=0,i=0;f=_-80|0;_=f;g=-1;i=F[c+4>>2];h=F[b>>2];if(!(i>>>0>>0|i-h>>>0>2e3)){F[f+72>>2]=F[b+32>>2];h=F[b+28>>2];g=f- -64|0;F[g>>2]=F[b+24>>2];F[g+4>>2]=h;g=F[b+20>>2];F[f+56>>2]=F[b+16>>2];F[f+60>>2]=g;g=F[b+12>>2];F[f+48>>2]=F[b+8>>2];F[f+52>>2]=g;g=F[b+4>>2];h=F[b>>2];F[f+40>>2]=h;F[f+44>>2]=g;b=f+40|4;if(h>>>0>>0){while(1){ka(b,32,1921,1,b);g=F[f+40>>2]+1|0;F[f+40>>2]=g;if(g>>>0>2]){continue}break}}g=b;b=f|4;ka(g,32,1920,1,b);F[f>>2]=F[f+40>>2];a=F[a+4>>2];g=aa[F[F[a>>2]+16>>2]](a,b,32,F[c+8>>2],F[c+12>>2],F[c+24>>2],F[c+28>>2],d,e)|0;ia(f+40|0,36)}_=f+80|0;return g}function bc(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0;g=Ob(a);if(Da(g)>>>0>e>>>0){F[a+7516>>2]=2;return-1}e=a+164|0;f=la(Pa(Sb(la(Za(d,g),4),a),a+96|0),(F[a+160>>2]-e|0)/72|0);h=F[a+160>>2];if((h|0)!=(e|0)){while(1){f=la(f,F[e>>2]);D[f|0]=G[e+4|0];f=Pa(f+1|0,e+5|0);e=e+72|0;if((h|0)!=(e|0)){continue}break}}D[f|0]=G[a+7364|0];e=f+1|0;a:{if(!G[a+7364|0]){break a}e=la(e,F[a+7368>>2]);D[e|0]=G[a+7372|0];e=Pa(e+1|0,a+7373|0);if(G[a+7364|0]<2){break a}e=la(e,F[a+7440>>2]);D[e|0]=G[a+7444|0];e=Pa(e+1|0,a+7445|0)}la(e,F[a+7512>>2]);return Ya(b,c,d,g)|0}function Nc(a,b,c,d,e,f,g,h,i,j,k){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;j=j|0;k=k|0;var l=0,m=0,n=0;l=_-112|0;_=l;m=(aa[F[476]](F[9136],c)|0)+2|0;n=(m>>>0)/3|0;a:{b:{c:{if(((m-L(n,3)|0)+(n<<2)|0)-2>>>0>e>>>0){break c}if(aa[F[475]](F[9136])>>>0>g>>>0){break c}if(i>>>0>=43){break b}}F[a>>2]=2;c=-1;break a}if(k>>>0<=31){F[a>>2]=1;c=-1;break a}g=l+48|0;Ea(j,g);na(g,32,h);h=g;g=l+16|0;za(h,a+4|0,g);a=aa[F[476]](F[9136],c)|0;e=(d+e|0)-a|0;c=aa[F[477]](F[9136],g,32,b,c,e,a,l+8|0,8)|0;if((c|0)==-1){break a}na(l+8|0,8,f);na(e,a,d)}_=l+112|0;return c|0}function qa(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0;d=-1;a:{if((b&3)==1){break a}d=b+2|0;g=((d&3)+L(d>>>2|0,3)|0)-2|0;d=-1;if((g|0)==-1){break a}e=b&-4;b:{if(!e){e=a;break b}e=a+e|0;d=a;while(1){i=G[d|0];f=G[d+1|0];h=G[(G[d+2|0]&127)+1088|0];D[c+2|0]=G[(G[d+3|0]&127)+1088|0]|h<<6;f=G[(f&127)+1088|0]<<6;D[c+1|0]=(f|h)>>>2;D[c|0]=(f|G[(i&127)+1088|0]<<12)>>>10;c=c+3|0;d=d+4|0;if((d|0)!=(e|0)){continue}break}}b=(a+b|0)-e|0;if(b){a=G[(G[e+1|0]&127)+1088|0]|G[(G[e|0]&127)+1088|0]<<6;if((b|0)==3){D[c+1|0]=(G[(G[e+2|0]&127)+1088|0]|a<<6)>>>2}D[c|0]=a>>>4}d=g}return d}function ma(a,b,c){var d=0,e=0,f=0;if(!(G[a|0]&32)){a:{e=b;d=c;b=a;a=F[b+16>>2];b:{if(!a){a=G[b+74|0];D[b+74|0]=a-1|a;a=F[b>>2];c:{if(a&8){F[b>>2]=a|32;a=-1;break c}F[b+4>>2]=0;F[b+8>>2]=0;a=F[b+44>>2];F[b+28>>2]=a;F[b+20>>2]=a;F[b+16>>2]=a+F[b+48>>2];a=0}if(a){break b}a=F[b+16>>2]}f=F[b+20>>2];if(a-f>>>0>>0){aa[F[b+36>>2]](b,e,c)|0;break a}d:{if(D[b+75|0]<0){break d}a=c;while(1){d=a;if(!a){break d}a=d-1|0;if(G[e+a|0]!=10){continue}break}if(aa[F[b+36>>2]](b,e,d)>>>0>>0){break b}e=d+e|0;c=c-d|0;f=F[b+20>>2]}ja(f,e,c);F[b+20>>2]=F[b+20>>2]+c}}}}function na(a,b,c){var d=0,e=0,f=0,g=0,h=0;d=b-((b>>>0)%3|0)|0;a:{if(!d){e=a;break a}e=a+d|0;d=a;while(1){f=G[d+1|0];g=G[d|0];h=G[d+2|0];D[c+3|0]=G[(h&63)+1024|0];D[c|0]=G[(g>>>2|0)+1024|0];f=f<<8;D[c+2|0]=G[((f|h)>>>6&63)+1024|0];D[c+1|0]=G[((f|g<<16)>>>12&63)+1024|0];c=c+4|0;d=d+3|0;if((e|0)!=(d|0)){continue}break}}d=(a+b|0)-e|0;if(d){a=2;b=G[e|0];b:{if((d|0)==2){a=G[e+1|0]<<2;D[c+2|0]=G[(a&60)+1024|0];d=(a|b<<10)>>>6|0;a=3;break b}d=b<<4}D[c|0]=G[(d>>>6|0)+1024|0];D[c+1|0]=G[(d&63)+1024|0];c=a+c|0}return c}function Ca(a,b,c){var d=0,e=0,f=0,g=0,h=0,i=0;f=a;e=c;d=b-((b>>>0)%3|0)|0;if(d){f=a+d|0;d=a;while(1){g=G[d+1|0];h=G[d|0];i=G[d+2|0];D[e+3|0]=G[(i&63)+1024|0];D[e|0]=G[(h>>>2|0)+1024|0];g=g<<8;D[e+2|0]=G[((g|i)>>>6&63)+1024|0];D[e+1|0]=G[((g|h<<16)>>>12&63)+1024|0];e=e+4|0;d=d+3|0;if((f|0)!=(d|0)){continue}break}}d=(a+b|0)-f|0;if(d){a=2;b=G[f|0];a:{if((d|0)==2){a=G[f+1|0]<<2;D[e+2|0]=G[(a&60)+1024|0];d=(a|b<<10)>>>6|0;a=3;break a}d=b<<4}D[e|0]=G[(d>>>6|0)+1024|0];D[e+1|0]=G[(d&63)+1024|0];e=a+e|0}return e-c|0}function Gd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0,g=0,h=0;f=_-16|0;_=f;b=Xa(b,c,d,e,a+300|0);a:{if((b|0)!=-1){b=b+d|0;c=kb(d,b,f+12|0);b:{if(!c){d=10;break b}d=9;if(F[f+12>>2]-1>>>0>1){break b}c=lb(a,c,b);if(!c){d=10;break b}c=lb(a+132|0,c,b);if(!c){d=10;break b}c=Ra(c,b,a+264|0);if(!c){d=10;break b}g=a+296|0;c:{if(F[f+12>>2]==1){F[g>>2]=1;break c}d=10;if(!c|(b|0)==(c|0)){c=h}else{D[g|0]=G[c|0]!=0;c=c+1|0}if(!c){break b}}d=17;if((b|0)==(c|0)){break a}}F[a+300>>2]=d}e=-1}_=f+16|0;return e|0}function Yd(a,b){a=a|0;b=b|0;var c=0,d=0;c=b+3285|0;b=a+164|0;a:{b:{if((b|0)!=F[a+160>>2]){while(1){if(La(b+5|0,c,32)){d=F[b>>2];c=F[a+160>>2]-72|0;F[a+160>>2]=c;if((b|0)==(c|0)){break b}while(1){c=b;b=b+72|0;ja(c,b,72);if(F[a+160>>2]!=(b|0)){continue}break}break b}b=b+72|0;if((b|0)!=F[a+160>>2]){continue}break}}d=-1;if(!G[a+7364|0]){break b}if(La(a+7373|0,c,32)){b=F[a+7368>>2];break a}if(G[a+7364|0]<2){break b}if(!La(a+7445|0,c,32)){break b}d=F[a+7440>>2]}b=d}if((b|0)==-1){F[a+7516>>2]=6}return b|0}function ke(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0,g=0,h=0,i=0,j=0,k=0;g=c;e=b;a:{b:{if(b<<5>>>0<=d>>>0){if(e){break b}e=0;break a}F[a+7516>>2]=1;e=-1;break a}j=a+7364|0;h=a+164|0;k=a+169|0;while(1){b=j;f=F[a+160>>2];if((b|0)!=(f|0)){b=f+72|0;F[a+160>>2]=b}b=b-72|0;if((h|0)!=(b|0)){while(1){f=b;b=b-72|0;ja(f,b,72);if((b|0)!=(h|0)){continue}break}}D[a+168|0]=0;b=F[a+7512>>2]+1|0;F[h>>2]=b;F[a+7512>>2]=b;Ea(g,k);g=g+32|0;i=i+1|0;if((i|0)!=(e|0)){continue}break}}ia(c,d);return e|0}function Eb(a,b){if(!a){return 0}a:{b:{if(a){if(b>>>0<=127){break b}c:{if(!F[F[9424]>>2]){if((b&-128)==57216){break b}break c}if(b>>>0<=2047){D[a+1|0]=b&63|128;D[a|0]=b>>>6|192;a=2;break a}if(!((b&-8192)!=57344?b>>>0>=55296:0)){D[a+2|0]=b&63|128;D[a|0]=b>>>12|224;D[a+1|0]=b>>>6&63|128;a=3;break a}if(b-65536>>>0<=1048575){D[a+3|0]=b&63|128;D[a|0]=b>>>18|240;D[a+2|0]=b>>>6&63|128;D[a+1|0]=b>>>12&63|128;a=4;break a}}F[9439]=25;a=-1}else{a=1}break a}D[a|0]=b;a=1}return a}function zb(a,b,c,d){var e=0,f=0,g=0;e=_-48|0;_=e;ab(e+8|0,c,d);d=0;c=F[e+12>>2];f=(c|b)!=0;a:{b:{if(c){if(!f){break a}if(F[e+16>>2]==32){break b}break a}if(!f){break a}}if(!F[e+36>>2]){break a}f=F[e+20>>2];if(!f|F[e+24>>2]!=32){break a}g=F[e+28>>2];if(!g|F[e+32>>2]!=32){break a}c:{d:{if(c){c=Ja(c,a+3221|0);if(b){if(c){break a}break d}if(!c){break c}break a}if(!b){break c}}if(Ja(b,a+3221|0)){break a}}if(Ja(f,a+3253|0)){break a}d=!Ja(g,a+3285|0)}_=e+48|0;return d}function Ud(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0,f=0;e=oa(d);if((e|0)==-1){F[a+3216>>2]=7;return-1}qa(c,d,c);d=_-48|0;_=d;a:{b:{if((b|0)!=1){ab(d+8|0,c,e);c=F[d+36>>2];if(!c){F[a+3216>>2]=4;break b}e=F[d+40>>2]}b=_-32|0;_=b;f=c;c=F[a+4>>2];ib(b,f,e,aa[F[F[c>>2]>>2]](c)|0);c:{if(!F[b+24>>2]){F[a+8>>2]=4;c=-1;break c}c=F[a+4>>2];c=aa[F[F[c>>2]+12>>2]](c,F[b+28>>2])|0}_=b+32|0;if((c|0)!=-1){break a}F[a+3216>>2]=F[a+8>>2];F[a+8>>2]=0}c=-1}_=d+48|0;return c|0}function La(a,b,c){var d=0,e=0,f=0;d=_-16|0;D[d+15|0]=0;a:{if(!c){break a}f=c-1|0;e=c&3;if(e){while(1){D[d+15|0]=G[d+15|0]|G[b|0]^G[a|0];b=b+1|0;a=a+1|0;c=c-1|0;e=e-1|0;if(e){continue}break}}if(f>>>0<3){break a}while(1){D[d+15|0]=G[d+15|0]|G[a|0]^G[b|0];D[d+15|0]=G[d+15|0]|G[a+1|0]^G[b+1|0];D[d+15|0]=G[d+15|0]|G[a+2|0]^G[b+2|0];D[d+15|0]=G[d+15|0]|G[a+3|0]^G[b+3|0];b=b+4|0;a=a+4|0;c=c-4|0;if(c){continue}break}}return!G[d+15|0]}function Fc(a,b,c,d,e,f,g,h,i){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;h=h|0;i=i|0;var j=0,k=0;j=_-80|0;_=j;k=F[478];a:{if(aa[k|0](F[9136],oa(g))>>>0>i>>>0){F[a>>2]=2;g=-1;break a}k=oa(g);if((k|0)!=-1?(c|0)!=43|(e|0)!=11:1){F[a>>2]=7;g=-1;break a}c=b;b=j+48|0;qa(c,43,b);c=b;b=j+16|0;za(a+4|0,c,b);c=j+8|0;qa(d,11,c);qa(f,g,f);g=aa[F[479]](F[9136],b,32,c,8,f,k,h,i)|0;if((g|0)!=-1){break a}F[a>>2]=5}_=j+80|0;return g|0}function Hc(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0;h=_-16|0;_=h;a:{if(!(!f|g>>>0>=43)){F[a>>2]=2;g=-1;break a}g=-1;b=Xa(b,c,d,e,a);if((b|0)==-1){break a}b:{b=b+d|0;c=ua(d,b,h+12|0);c:{if(!c){break c}if(F[h+12>>2]!=1){F[a>>2]=9;break c}c=Ka(c,b,a+4|0);if(c){break b}}if(F[a>>2]){break a}F[a>>2]=10;break a}if((b|0)!=(c|0)){F[a>>2]=17;break a}if(f){na(a+4|0,32,f)}g=e}_=h+16|0;return g|0}function wb(a){var b=0,c=0,d=0,e=0,f=0;b=a+48|0;d=F[a+44>>2];if((b|0)==(d|0)){d=36}else{c=4;while(1){c=c+100|0;b=b+100|0;if((d|0)!=(b|0)){continue}break}d=c+32|0}e=4;c=4;b=a+152|0;f=F[a+148>>2];if((b|0)!=(f|0)){while(1){c=c+68|0;b=b+68|0;if((f|0)!=(b|0)){continue}break}}b=a+496|0;a=F[a+492>>2];if((b|0)!=(a|0)){while(1){e=e+68|0;b=b+68|0;if((a|0)!=(b|0)){continue}break}}return((c+d|0)+e|0)+101|0}function te(a,b,c){var d=0,e=0,f=0,g=0;g=c&63;f=g;e=f&31;if(f>>>0>=32){f=-1>>>e|0}else{f=-1>>>e|0;d=f;f=d|(1<>>0>=32){d=f<>>32-e|d<>>0>=32){d=-1<>>32-d}a=c&a;b=b&d;d=e&31;if(e>>>0>=32){c=0;a=b>>>d|0}else{c=b>>>d|0;a=((1<>>d}a=a|g;$=c|f;return a} +function hd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0;f=_-16|0;_=f;b=Xa(b,c,d,e,a+228|0);a:{if((b|0)!=-1){b=b+d|0;c=kb(d,b,f+12|0);b:{if(!c){d=10;break b}d=9;if(F[f+12>>2]!=1){break b}c=lb(a,c,b);if(!c){d=10;break b}d=10;c=Qb(c,b,a+132|0);if(!c){break b}d=17;if((b|0)==(c|0)){break a}}F[a+228>>2]=d}e=-1}_=f+16|0;return e|0}function Fd(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0,f=0;d=_-32|0;_=d;e=-1;c=Ma(b,c,b);a:{if((c|0)==-1){F[a+300>>2]=7;break a}f=b;b=F[9380];Cb(f,c,aa[F[F[b>>2]>>2]](b)|0,d+8|0);if(G[d+8|0]!=3){F[a+300>>2]=3;break a}if(!F[d+20>>2]){F[a+300>>2]=4;break a}a=F[9380];e=aa[F[F[a>>2]+12>>2]](a,F[d+24>>2])|0}_=d+32|0;return e|0}function vb(a,b,c){var d=0;d=_-112|0;_=d;F[d+80>>2]=1779033703;F[d+84>>2]=-1150833019;F[d+72>>2]=0;F[d+76>>2]=0;F[d+64>>2]=0;F[d+104>>2]=528734635;F[d+108>>2]=1541459225;F[d+96>>2]=1359893119;F[d+100>>2]=-1694144372;F[d+88>>2]=1013904242;F[d+92>>2]=-1521486534;pa(d,a,b);Ba(d,c);ia(d,112);_=d+112|0}function Ja(a,b){var c=0,d=0,e=0;c=32;a:{b:{if((a|b)&3){break b}while(1){if(F[a>>2]!=F[b>>2]){break b}b=b+4|0;a=a+4|0;c=c-4|0;if(c>>>0>3){continue}break}if(!c){break a}}while(1){d=G[a|0];e=G[b|0];if((d|0)==(e|0)){b=b+1|0;a=a+1|0;c=c-1|0;if(c){continue}break a}break}return d-e|0}return 0}function ia(a,b){var c=0,d=0;a:{if(!b){break a}c=a;d=b&7;if(d){while(1){D[c|0]=0;c=c+1|0;d=d-1|0;if(d){continue}break}}if(b-1>>>0<7){break a}a=a+b|0;while(1){D[c|0]=0;D[c+1|0]=0;D[c+2|0]=0;D[c+3|0]=0;D[c+4|0]=0;D[c+5|0]=0;D[c+6|0]=0;D[c+7|0]=0;c=c+8|0;if((a|0)!=(c|0)){continue}break}}}function Rd(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0;h=_-32|0;_=h;a:{if((oa(c)|0)!=32){F[a>>2]=7;c=-1;break a}qa(b,c,h);c=-1;b=oa(g);if((b|0)==-1){F[a>>2]=7;break a}qa(f,g,f);b:{if(b>>>0>=64){c=0;if(fb(h,d,e,f)){break b}}F[a>>2]=5;c=-1}}_=h+32|0;return c|0}function Na(a,b,c){var d=0,e=0,f=0;a:{if(b>>>0<1){d=a;break a}while(1){d=re(a,b,10);e=$;f=e;e=qe(d,e,10,0);c=c-1|0;D[c|0]=a-e|48;e=b>>>0>9;a=d;b=f;if(e){continue}break}}if(d){while(1){c=c-1|0;a=(d>>>0)/10|0;D[c|0]=d-L(a,10)|48;b=d>>>0>9;d=a;if(b){continue}break}}return c}function pa(a,b,c){var d=0,e=0,f=0;if(c){d=F[a+64>>2];while(1){D[a+d|0]=G[b+e|0];d=F[a+64>>2]+1|0;F[a+64>>2]=d;if((d|0)==64){jb(a,a);F[a+64>>2]=0;d=F[a+76>>2];f=F[a+72>>2]+512|0;d=f>>>0<512?d+1|0:d;F[a+72>>2]=f;F[a+76>>2]=d;d=0}e=e+1|0;if((e|0)!=(c|0)){continue}break}}}function rd(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0;h=_+-64|0;_=h;a:{if(g>>>0<43){F[a>>2]=2;a=-1;break a}if(!F[a+100>>2]){F[a>>2]=16;a=-1;break a}g=a+68|0;a=h+32|0;Aa(g,32,0,0,d,e,a,32);ka(a,32,b,c,h);Ca(h,32,f);a=0}_=h- -64|0;return a|0}function je(a,b,c){a=a|0;b=b|0;c=c|0;var d=0;a:{if(c>>>0<=31){F[a+7516>>2]=1;a=-1;break a}d=G[a+7364|0];if(d>>>0<=1){D[a+7364|0]=d+1}ja(a+7440|0,a+7368|0,72);D[a+7372|0]=0;d=F[a+7512>>2]+1|0;F[a+7368>>2]=d;F[a+7512>>2]=d;Ea(b,a+7373|0);a=1}ia(b,c);return a|0}function Fb(a,b){var c=0,d=0,e=0;A(+a);c=v(1)|0;d=v(0)|0;e=c;c=c>>>20&2047;if((c|0)!=2047){if(!c){c=b;if(a==0){b=0}else{a=Fb(a*0x10000000000000000,b);b=F[b>>2]+-64|0}F[c>>2]=b;return a}F[b>>2]=c-1022;x(0,d|0);x(1,e&-2146435073|1071644672);a=+z()}return a}function pd(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0;h=_-256|0;_=h;a:{if(g>>>0<43){F[a>>2]=2;a=-1;break a}if(!F[a+100>>2]){F[a>>2]=16;a=-1;break a}Aa(a+68|0,32,0,0,d,e,h,256);ka(h,256,b,c,f);Ca(f,32,f);a=0}_=h+256|0;return a|0}function qd(a,b,c,d,e,f,g){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;g=g|0;var h=0;h=_-32|0;_=h;a:{if(g>>>0<43){F[a>>2]=2;a=-1;break a}if(!F[a+100>>2]){F[a>>2]=16;a=-1;break a}Aa(a+68|0,32,0,0,d,e,h,32);ka(h,32,b,c,f);Ca(f,32,f);a=0}_=h+32|0;return a|0}function Xa(a,b,c,d,e){var f=0,g=0;f=-1;g=oa(d);a:{b:{if((g|0)==-1){c=7;if(e){break b}break a}Ma(c,d,c);d=a;a=g-(aa[F[475]](33528)|0)|0;f=aa[F[479]](33528,d,b,c,g,c,a,c,a)|0;if((f|0)!=-1){return f}c=8;if(!e){break a}}F[e>>2]=c;f=-1}return f}function Ob(a){var b=0,c=0,d=0;d=4;b=a+164|0;c=F[a+160>>2];if((b|0)!=(c|0)){while(1){d=d+69|0;b=b+72|0;if((c|0)!=(b|0)){continue}break}}b=d+165|0;c=b;a:{if(!G[a+7364|0]){break a}b=b+69|0;c=b;if(G[a+7364|0]<2){break a}c=b+69|0}return c+4|0}function be(a,b,c,d,e,f){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;f=f|0;var g=0;g=_-32|0;_=g;a:{if((oa(d)|0)!=32){F[a+3216>>2]=7;d=-1;break a}qa(c,d,g);d=-1;c=oa(f);if((c|0)==-1){F[a+3216>>2]=7;break a}qa(e,f,e);d=Ab(a,b,g,e,c)}_=g+32|0;return d|0}function Mb(a,b,c){var d=0,e=0,f=0;e=1;if(a>>>0>=128){while(1){e=e+1|0;d=a>>>0>16383;a=a>>>7|0;if(d){continue}break}}d=1;if(b>>>0>=128){a=b;while(1){d=d+1|0;f=a>>>0>16383;a=a>>>7|0;if(f){continue}break}}return(((b+c|0)+e|0)+d|0)+37|0}function Db(a,b,c){var d=0,e=0,f=0;d=1;e=1;if(a>>>0>=128){while(1){e=e+1|0;f=a>>>0>16383;a=a>>>7|0;if(f){continue}break}}if(b>>>0>=128){a=b;while(1){d=d+1|0;f=a>>>0>16383;a=a>>>7|0;if(f){continue}break}}return(((b+c|0)+e|0)+d|0)+67|0}function Ya(a,b,c,d){var e=0,f=0,g=0,h=0,i=0,j=0;f=aa[F[476]](33528,d)|0;e=f+(aa[F[475]](33528)|0)|0;g=e+2|0;h=(g>>>0)/3|0;i=a;j=b;b=((g-L(h,3)|0)+(h<<2)|0)-2|0;a=(b+c|0)-e|0;aa[F[477]](33528,i,j,a,d,a,f,a,e)|0;Ca(a,e,c);return b}function Zd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0;f=_-32|0;_=f;a:{if((oa(c)|0)!=32){F[a+3216>>2]=7;c=-1;break a}qa(b,c,f);c=-1;b=oa(e);if((b|0)==-1){F[a+3216>>2]=7;break a}qa(d,e,d);c=zb(a,f,d,b)}_=f+32|0;return c|0}function qe(a,b,c,d){var e=0,f=0,g=0,h=0,i=0,j=0;e=c>>>16|0;f=a>>>16|0;j=L(e,f);g=c&65535;h=a&65535;i=L(g,h);f=(i>>>16|0)+L(f,g)|0;e=(f&65535)+L(e,h)|0;$=(L(b,c)+j|0)+L(a,d)+(f>>>16)+(e>>>16)|0;return i&65535|e<<16}function kb(a,b,c){var d=0,e=0;F[c>>2]=0;a:{if(!a){break a}e=b;b=a+4|0;if(e>>>0>>0){break a}F[c>>2]=0;d=G[a|0]<<8;F[c>>2]=d;d=(d|G[a+1|0])<<8;F[c>>2]=d;d=(d|G[a+2|0])<<8;F[c>>2]=d;F[c>>2]=d|G[a+3|0];d=b}return d}function va(a,b,c,d,e){var f=0;f=_-256|0;_=f;if(!(e&73728|(c|0)<=(d|0))){c=c-d|0;d=c>>>0<256;ra(f,b&255,d?c:256);if(!d){while(1){ma(a,f,256);c=c-256|0;if(c>>>0>255){continue}break}}ma(a,f,c)}_=f+256|0}function pe(a){a=a|0;var b=0,c=0,d=0;b=a+164|0;c=F[a+160>>2];a:{if((b|0)!=(c|0)){a=1;while(1){if(!G[b+4|0]){d=d+55|0;a=0}b=b+72|0;if((c|0)!=(b|0)){continue}break}b=16;if(!a){break a}}b=17}return b+d|0}function ne(a){a=a|0;var b=0,c=0,d=0;b=a+164|0;c=F[a+160>>2];if((b|0)!=(c|0)){while(1){if(!G[b+4|0]){D[b+4|0]=1;d=d+1|0}b=b+72|0;if((c|0)!=(b|0)){continue}break}}D[a+7372|0]=1;return d|0}function ua(a,b,c){var d=0;F[c>>2]=0;if(!(!a|a+4>>>0>b>>>0)){F[c>>2]=0;b=G[a|0]<<8;F[c>>2]=b;b=(b|G[a+1|0])<<8;F[c>>2]=b;b=(b|G[a+2|0])<<8;F[c>>2]=b;F[c>>2]=b|G[a+3|0];d=a+4|0}return d}function ed(a,b){a=a|0;b=b|0;var c=0;c=F[9380];b=aa[F[F[c>>2]+4>>2]](c,b)|0;c=F[9380];c=aa[F[F[c>>2]>>2]](c)|0;b=Db(F[a+128>>2],b,c)+2|0;a=(b>>>0)/3|0;return((b-L(a,3)|0)+(a<<2)|0)-2|0}function Ia(a){var b=0,c=0;b=F[9438];c=a+3&-4;a=b+c|0;a:{if(a>>>0<=b>>>0?c:0){break a}if(a>>>0>ba()<<16>>>0){if(!(Z(a|0)|0)){break a}}F[9438]=a;return b}F[9439]=48;return-1}function id(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0;f=a+132|0;if(Da(232)>>>0>e>>>0){F[a+228>>2]=2;return-1}Sb(mb(a,la(Za(d,232),1)),f);return Ya(b,c,d,232)|0}function Hb(a){var b=0,c=0,d=0;if(D[F[a>>2]]-48>>>0<10){while(1){b=F[a>>2];d=D[b|0];F[a>>2]=b+1;c=(L(c,10)+d|0)-48|0;if(D[b+1|0]-48>>>0<10){continue}break}}return c}function db(a,b){var c=0,d=0;d=F[a+44>>2]==(a+48|0)?0:F[a+112>>2];c=F[a+4>>2];b=aa[F[F[c>>2]+4>>2]](c,b)|0;a=F[a+4>>2];return Mb(d,b,aa[F[F[a>>2]>>2]](a)|0)}function tb(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;if(c>>>0<43){F[a>>2]=2;return-1}if(e>>>0<=31){F[a>>2]=15;return-1}a=a+4|0;Ea(d,a);na(a,32,b);return 0}function Ac(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;if(c>>>0<43){F[a>>2]=2;return-1}if(e>>>0<=31){F[a>>2]=15;return-1}a=a+4|0;gb(d,a);na(a,32,b);return 0}function ud(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<43){F[a>>2]=15;return-1}if((Ma(b,c,b)|0)==-1){F[a>>2]=7;return-1}za(a+4|0,b,a+68|0);F[a+100>>2]=1;return 0}function Rc(a){a=a|0;ia(a,36);F[a+32>>2]=0;F[a+24>>2]=0;F[a+28>>2]=0;F[a+16>>2]=0;F[a+20>>2]=0;F[a+8>>2]=0;F[a+12>>2]=0;F[a>>2]=0;F[a+4>>2]=0;return 36}function Ic(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;var f=0;f=a+4|0;if(Da(68)>>>0>e>>>0){F[a>>2]=2;return-1}Pa(la(Za(d,68),1),f);return Ya(b,c,d,68)|0}function Nb(a,b,c){var d=0,e=0;a=ua(a,b,c);a:{if(!a){break a}if(!(!a|(a|0)==(b|0))){D[c+4|0]=G[a|0]!=0;d=a+1|0}if(!d){break a}e=Ka(d,b,c+5|0)}return e}function $c(a,b,c){a=a|0;b=b|0;c=c|0;var d=0,e=0;e=F[a+20>>2];d=F[a+16>>2]-e|0;d=c>>>0>>0?c:d;ja(e,b,d);F[a+20>>2]=d+F[a+20>>2];return c|0}function Za(a,b){var c=0,d=0;c=aa[F[476]](33528,b)+aa[F[475]](33528)|0;d=c+2|0;b=(d>>>0)/3|0;return((((d-L(b,3)|0)+(b<<2)|0)-2|0)+a|0)-c|0}function Ib(a){var b=0,c=0,d=0;b=1;if(a>>>0>=128){c=a;while(1){b=b+1|0;d=c>>>0>16383;c=c>>>7|0;if(d){continue}break}}return(a+b|0)+104|0} +function Vb(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;if(e>>>0<86){F[a+7516>>2]=2;return-1}e=a;a=d+22|0;$a(e,b,c,a);na(a,64,d);return 86}function Bb(a){F[a+8>>2]=0;F[a+4>>2]=1768;F[a>>2]=1752;F[a+492>>2]=a+496;F[a+148>>2]=a+152;F[a+44>>2]=a+48;D[a+3220|0]=0;F[a+3216>>2]=0}function yc(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;if(e>>>0<86){F[a>>2]=2;return-1}e=a+4|0;a=d+22|0;$a(e,b,c,a);na(a,64,d);return 86}function ce(a,b,c,d){a=a|0;b=b|0;c=c|0;d=d|0;var e=0;e=oa(d);if((e|0)==-1){F[a+3216>>2]=7;return-1}qa(c,d,c);return Ab(a,b,0,c,e)|0}function Zb(a,b,c){a=a|0;b=b|0;c=c|0;a:{if(c>>>0<=63){F[a+7516>>2]=1;a=-1;break a}gb(b,a);Ea(b+32|0,a+96|0);a=0}ia(b,c);return a|0}function la(a,b){b=b<<8&16711680|b<<24|(b>>>8&65280|b>>>24);D[a|0]=b;D[a+1|0]=b>>>8;D[a+2|0]=b>>>16;D[a+3|0]=b>>>24;return a+4|0}function Sd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;if(e>>>0<43){F[a>>2]=2;return-1}vb(b,c,d+11|0);na(d+11|0,32,d);return 43}function sd(a,b,c,d,e){a=a|0;b=b|0;c=c|0;d=d|0;e=e|0;if(!F[a+100>>2]){F[a>>2]=16;return-1}Aa(a+68|0,32,0,0,b,c,d,e);return 0}function fd(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<=159){F[a+228>>2]=1;return-1}_a(a,b,0);gb(b+128|0,a+132|0);ia(b,c);return 0}function _d(a,b,c){a=a|0;b=b|0;c=c|0;var d=0;d=oa(c);if((d|0)==-1){F[a+3216>>2]=7;return-1}qa(b,c,b);return zb(a,0,b,d)|0}function Da(a){var b=0;b=(aa[F[476]](33528,a)+aa[F[475]](33528)|0)+2|0;a=(b>>>0)/3|0;return((b-L(a,3)|0)+(a<<2)|0)-2|0}function Sa(a,b,c,d){var e=0,f=0;a:{if(!a){break a}e=b;b=a+d|0;if(e>>>0>>0){break a}ja(c,a,d);f=b}return f}function Pc(a,b){a=a|0;b=b|0;b=(aa[F[476]](F[9136],b)|0)+2|0;a=(b>>>0)/3|0;return((b-L(a,3)|0)+(a<<2)|0)-2|0}function Oc(a){a=a|0;var b=0;b=(aa[F[475]](F[9136])|0)+2|0;a=(b>>>0)/3|0;return((b-L(a,3)|0)+(a<<2)|0)-2|0}function gc(a){a=a|0;ia(a,7520);F[a+7512>>2]=0;F[a+7516>>2]=0;D[a+7364|0]=0;F[a+160>>2]=a+164;return 7520}function wd(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<=31){F[a>>2]=1;return-1}Ea(b,a+4|0);F[a+100>>2]=0;return 0}function jc(a){a=a|0;ia(a,7520);F[a+7512>>2]=0;F[a+7516>>2]=0;D[a+7364|0]=0;F[a+160>>2]=a+164;return a|0}function cd(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<43){F[a+228>>2]=2;return-1}return Ca(a+132|0,32,b)|0}function Dd(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<43){F[a+300>>2]=2;return-1}return Ca(a+264|0,32,b)|0}function qc(a){a=a|0;a=F[a+7516>>2];if(a>>>0<=17){a=F[(a<<2)+33456>>2]}else{a=1383}return a|0}function oc(a){a=a|0;a=F[a+3216>>2];if(a>>>0<=17){a=F[(a<<2)+33456>>2]}else{a=1383}return a|0}function Qc(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<43){F[a>>2]=15;return-1}qa(b,43,a+4|0);return 0}function vd(a,b,c){a=a|0;b=b|0;c=c|0;if(c>>>0<43){F[a>>2]=2;return-1}Ca(a+4|0,32,b);return 0}function ld(a){a=a|0;a=F[a+228>>2];if(a>>>0<=17){a=F[(a<<2)+33456>>2]}else{a=1383}return a|0}function Md(a){a=a|0;a=F[a+300>>2];if(a>>>0<=17){a=F[(a<<2)+33456>>2]}else{a=1383}return a|0}function Wd(a,b){a=a|0;b=b|0;b=xb(a,b)+2|0;a=(b>>>0)/3|0;return((b-L(a,3)|0)+(a<<2)|0)-2|0}function Va(a){a=a|0;a=F[a>>2];if(a>>>0<=17){a=F[(a<<2)+33456>>2]}else{a=1383}return a|0}function se(a,b){var c=0,d=0;c=b&31;d=(-1>>>c&a)<>>a}function oa(a){if((a&3)!=1){a=a+2|0;a=((a&3)+L(a>>>2|0,3)|0)-2|0}else{a=-1}return a}function sc(a,b,c){a=a|0;b=b|0;c=c|0;if(a){D[a|0]=3}if(b){D[b|0]=2}if(c){D[c|0]=8}}function lb(a,b,c){b=Sa(b,c,a,128);if(!b){return 0}return kb(b,c,a+128|0)}function ee(a){a=a|0;if(G[a+7364|0]>=2){D[a+7364|0]=1;ia(a+7440|0,72)}}function Gc(a,b){a=a|0;b=b|0;a=F[478];return aa[a|0](F[9136],oa(b))|0}function Qd(a){a=a|0;return(a>>>0<=17?F[(a<<2)+33456>>2]:1383)|0}function ge(a){a=a|0;return(G[a+7372|0]|!G[a+7364|0]?17:71)|0}function xb(a,b){b=db(a,b);if(!G[a+3220|0]){b=Ib(b)}return b}function Bc(a){a=a|0;ia(a,100);ra(a,0,100);return 100}function Xd(a){a=a|0;return(F[a+44>>2]==(a+48|0))<<5}function mb(a,b){return la(Ta(b,a,128),F[a+128>>2])}function Kc(a){a=a|0;ia(a,68);ra(a,0,68);return 68}function hc(a){a=a|0;ia(a,4);F[a>>2]=0;return a|0}function fc(a){a=a|0;ia(a,3320);Bb(a);return 3320}function ie(a){a=a|0;return(G[a+7364|0]?71:17)|0}function ic(a){a=a|0;ia(a,3320);Bb(a);return a|0}function ec(a){a=a|0;ia(a,4);F[a>>2]=0;return 4}function Uc(a){a=a|0;a=_-a&-16;_=a;return a|0}function wc(a,b){a=a|0;b=b|0;return b+16&-16}function _a(a,b,c){F[a+128>>2]=c;ja(a,b,128)}function yd(a){a=a|0;ia(a,104);return a|0}function xd(a){a=a|0;ia(a,104);return 104}function nd(a){a=a|0;ia(a,232);return a|0}function md(a){a=a|0;ia(a,232);return 232}function Od(a){a=a|0;ia(a,304);return a|0}function Nd(a){a=a|0;ia(a,304);return 304}function Cc(a){a=a|0;ia(a,100);return a|0}function pc(a){a=a|0;return F[a+7516>>2]}function nc(a){a=a|0;return F[a+3216>>2]}function le(a,b){a=a|0;b=b|0;return b<<5}function Sc(a){a=a|0;ia(a,36);return a|0}function Lc(a){a=a|0;ia(a,68);return a|0}function yb(a){a=a|0;return G[a+3220|0]}function uc(a,b){a=a|0;b=b|0;return b|0}function td(a){a=a|0;return F[a+100>>2]}function kd(a){a=a|0;return F[a+228>>2]}function dc(a){a=a|0;return Da(Ob(a))|0}function cc(a){a=a|0;return Da(wb(a))|0}function Ta(a,b,c){return ja(a,b,c)+c|0}function Pb(a){a=a|0;return F[a+128>>2]}function Ld(a){a=a|0;return F[a+300>>2]}function Cd(a){a=a|0;return F[a+296>>2]}function jd(a){a=a|0;return Da(232)|0}function Id(a){a=a|0;return Da(301)|0}function Jc(a){a=a|0;return Da(68)|0}function Ua(a){a=a|0;return F[a>>2]}function Ma(a,b,c){return qa(a,b,c)}function za(a,b,c){Jb(c,a+32|0,b)}function me(a){a=a|0;return 100}function gd(a){a=a|0;return 160}function bd(a){a=a|0;return 306}function Yb(a){a=a|0;return 116}function Bd(a){a=a|0;return 220}function rb(a){a=a|0;return 64}function qb(a){a=a|0;return 32}function Wb(a){a=a|0;return 86}function Qa(a){a=a|0;return 43}function xc(a){a=a|0;return 8}function mc(){return 7520}function lc(){return 3320}function zd(){return 104}function od(){return 232}function Wc(){return _|0}function Vc(a){a=a|0;_=a}function Pd(){return 304}function Dc(){return 100}function zc(){return 86}function ub(){return 43}function eb(){return 32}function Tc(){return 36}function Mc(){return 68}function rc(){return-1}function kc(){return 4}function Ub(){} +// EMSCRIPTEN_END_FUNCS +e=G;p(da);var aa=c([null,xc,wc,vc,uc,tc,$c,_c,Zc]);function ba(){return C.byteLength/65536|0}return{"d":Ub,"e":aa,"f":Va,"g":Qd,"h":Ua,"i":Tc,"j":Sc,"k":Rc,"l":Qc,"m":ub,"n":Pc,"o":Oc,"p":qb,"q":Nc,"r":Va,"s":Ua,"t":Mc,"u":Lc,"v":Kc,"w":eb,"x":eb,"y":tb,"z":tb,"A":Jc,"B":Ic,"C":Hc,"D":Gc,"E":Fc,"F":Ec,"G":Dc,"H":Cc,"I":Va,"J":Ua,"K":Bc,"L":eb,"M":ub,"N":Ac,"O":zc,"P":yc,"Q":sc,"R":rc,"S":qc,"T":pc,"U":oc,"V":nc,"W":Va,"X":Ua,"Y":mc,"Z":lc,"_":kc,"$":jc,"aa":ic,"ba":hc,"ca":gc,"da":fc,"ea":ec,"fa":dc,"ga":cc,"ha":bc,"ia":ac,"ja":$b,"ka":_b,"la":rb,"ma":Zb,"na":Yb,"oa":Xb,"pa":Wb,"qa":Vb,"ra":pe,"sa":oe,"ta":ne,"ua":me,"va":le,"wa":ke,"xa":qb,"ya":je,"za":ie,"Aa":he,"Ba":ge,"Ca":fe,"Da":ee,"Ea":rb,"Fa":de,"Ga":ce,"Ha":be,"Ia":Qa,"Ja":ae,"Ka":yb,"La":$d,"Ma":_d,"Na":Zd,"Oa":Yd,"Pa":yb,"Qa":Xd,"Ra":Wd,"Sa":Vd,"Ta":Ud,"Ua":Td,"Va":Qa,"Wa":Sd,"Xa":Rd,"Ya":Pd,"Za":Od,"_a":Nd,"$a":Md,"ab":Ld,"bb":Kd,"cb":Jd,"db":Id,"eb":Hd,"fb":Gd,"gb":Fd,"hb":Ed,"ib":Qa,"jb":Dd,"kb":Pb,"lb":Cd,"mb":Bd,"nb":Ad,"ob":Va,"pb":Ua,"qb":zd,"rb":yd,"sb":xd,"tb":qb,"ub":wd,"vb":Qa,"wb":vd,"xb":ud,"yb":td,"zb":sd,"Ab":Qa,"Bb":rd,"Cb":qd,"Db":pd,"Eb":od,"Fb":nd,"Gb":md,"Hb":ld,"Ib":kd,"Jb":jd,"Kb":id,"Lb":hd,"Mb":gd,"Nb":fd,"Ob":ed,"Pb":dd,"Qb":Qa,"Rb":cd,"Sb":Pb,"Tb":bd,"Ub":ad,"Vb":Yc,"Wb":Xc,"Xb":Wc,"Yb":Vc,"Zb":Uc}}return ca(ea)} +// EMSCRIPTEN_END_ASM + + + + +)(sa)} +function ta(){return{then:function(b){b({instance:new ra})}}}var ua=Error,WebAssembly={};u=[];"object"!==typeof WebAssembly&&t("no native wasm support detected"); +function w(b){var c="i8";"*"===c.charAt(c.length-1)&&(c="i32");switch(c){case "i1":x[b>>0]=0;break;case "i8":x[b>>0]=0;break;case "i16":va[b>>1]=0;break;case "i32":y[b>>2]=0;break;case "i64":wa=[0,(xa=0,1<=+Math.abs(xa)?0>>0:~~+Math.ceil((xa-+(~~xa>>>0))/4294967296)>>>0:0)];y[b>>2]=wa[0];y[b+4>>2]=wa[1];break;case "float":ya[b>>2]=0;break;case "double":za[b>>3]=0;break;default:t("invalid type for setValue: "+c)}} +function Aa(b,c){c=c||"i8";"*"===c.charAt(c.length-1)&&(c="i32");switch(c){case "i1":return x[b>>0];case "i8":return x[b>>0];case "i16":return va[b>>1];case "i32":return y[b>>2];case "i64":return y[b>>2];case "float":return ya[b>>2];case "double":return za[b>>3];default:t("invalid type for getValue: "+c)}return null}var Ba,Ca=!1,Da="undefined"!==typeof TextDecoder?new TextDecoder("utf8"):void 0; +function z(b,c){if(b){var d=A,e=b+c;for(c=b;d[c]&&!(c>=e);)++c;if(16f?e+=String.fromCharCode(f):(f-=65536,e+=String.fromCharCode(55296|f>>10,56320|f&1023))}}else e+=String.fromCharCode(f)}b=e}}else b="";return b} +function Ea(b,c,d,e){if(!(0=p){var v=b.charCodeAt(++k);p=65536+((p&1023)<<10)|v&1023}if(127>=p){if(d>=e)break;c[d++]=p}else{if(2047>=p){if(d+1>=e)break;c[d++]=192|p>>6}else{if(65535>=p){if(d+2>=e)break;c[d++]=224|p>>12}else{if(d+3>=e)break;c[d++]=240|p>>18;c[d++]=128|p>>12&63}c[d++]=128|p>>6&63}c[d++]=128|p&63}}c[d]=0;return d-f} +function Fa(b){for(var c=0,d=0;d=e&&(e=65536+((e&1023)<<10)|b.charCodeAt(++d)&1023);127>=e?++c:c=2047>=e?c+2:65535>=e?c+3:c+4}return c}function Ga(b,c){for(var d=0;d>0]=b.charCodeAt(d)}var Ia,x,A,va,y,ya,za,qa=a.INITIAL_MEMORY||16777216;a.wasmMemory?Ba=a.wasmMemory:Ba=new pa;Ba&&(Ia=Ba.buffer);qa=Ia.byteLength;var B=Ia;Ia=B;a.HEAP8=x=new Int8Array(B);a.HEAP16=va=new Int16Array(B);a.HEAP32=y=new Int32Array(B);a.HEAPU8=A=new Uint8Array(B); +a.HEAPU16=new Uint16Array(B);a.HEAPU32=new Uint32Array(B);a.HEAPF32=ya=new Float32Array(B);a.HEAPF64=za=new Float64Array(B);var Ja,Ka=[],La=[],Ma=[];function Na(){var b=a.preRun.shift();Ka.unshift(b)}var C=0,Oa=null,Pa=null;a.preloadedImages={};a.preloadedAudios={};function t(b){if(a.onAbort)a.onAbort(b);oa(b);Ca=!0;b=new ua("abort("+b+"). Build with -s ASSERTIONS=1 for more info.");ba(b);throw b;}var Qa="data:application/octet-stream;base64,",D;D="olm_legacy.wasm"; +if(!D.startsWith(Qa)){var Ra=D;D=a.locateFile?a.locateFile(Ra,m):m+Ra}function Sa(){var b=D;try{if(b==D&&u)return new Uint8Array(u);var c=r(b);if(c)return c;if(ma)return ma(b);throw"both async and sync fetching of the wasm failed";}catch(d){t(d)}} +function Ta(){if(!u&&(fa||ha)){if("function"===typeof fetch&&!D.startsWith("file://"))return fetch(D,{credentials:"same-origin"}).then(function(b){if(!b.ok)throw"failed to load wasm binary file at '"+D+"'";return b.arrayBuffer()}).catch(function(){return Sa()});if(la)return new Promise(function(b,c){la(D,function(d){b(new Uint8Array(d))},c)})}return Promise.resolve().then(function(){return Sa()})}var xa,wa; +function Ua(b){for(;0>4;f=(f&15)<<4|k>>2;var v=(k&3)<<6|p;c+=String.fromCharCode(e);64!==k&&(c+=String.fromCharCode(f));64!==p&&(c+=String.fromCharCode(v))}while(d + + diff --git a/assets/paperclip-3961996319.da562307.svg b/assets/paperclip-3961996319.da562307.svg new file mode 100644 index 00000000..5538dd7a --- /dev/null +++ b/assets/paperclip-3961996319.da562307.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/paperclip.ec29fd9d.svg b/assets/paperclip.ec29fd9d.svg new file mode 100644 index 00000000..c18661ec --- /dev/null +++ b/assets/paperclip.ec29fd9d.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/plus-3937109722.5c243914.svg b/assets/plus-3937109722.5c243914.svg new file mode 100644 index 00000000..6f60a21d --- /dev/null +++ b/assets/plus-3937109722.5c243914.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/plus-4190356069.084c5e3d.svg b/assets/plus-4190356069.084c5e3d.svg new file mode 100644 index 00000000..04b67dea --- /dev/null +++ b/assets/plus-4190356069.084c5e3d.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/plus.49560f96.svg b/assets/plus.49560f96.svg new file mode 100644 index 00000000..54e5d066 --- /dev/null +++ b/assets/plus.49560f96.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/room-members-3084360280.6f64aaef.svg b/assets/room-members-3084360280.6f64aaef.svg new file mode 100644 index 00000000..c2e87efb --- /dev/null +++ b/assets/room-members-3084360280.6f64aaef.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/room-members-3847743605.9fcf4567.svg b/assets/room-members-3847743605.9fcf4567.svg new file mode 100644 index 00000000..85c244c6 --- /dev/null +++ b/assets/room-members-3847743605.9fcf4567.svg @@ -0,0 +1,7 @@ + + + + + + + diff --git a/assets/room-members.35ed0bf9.svg b/assets/room-members.35ed0bf9.svg new file mode 100644 index 00000000..61cdf29c --- /dev/null +++ b/assets/room-members.35ed0bf9.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/search-261439583.1bffaca1.svg b/assets/search-261439583.1bffaca1.svg new file mode 100644 index 00000000..3700c3ed --- /dev/null +++ b/assets/search-261439583.1bffaca1.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/search-3263540198.1511780c.svg b/assets/search-3263540198.1511780c.svg new file mode 100644 index 00000000..b923e680 --- /dev/null +++ b/assets/search-3263540198.1511780c.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/search.21e0fd39.svg b/assets/search.21e0fd39.svg new file mode 100644 index 00000000..584b8651 --- /dev/null +++ b/assets/search.21e0fd39.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/send-1171052351.caa5c494.svg b/assets/send-1171052351.caa5c494.svg new file mode 100644 index 00000000..a21a5787 --- /dev/null +++ b/assets/send-1171052351.caa5c494.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/send-3413346515.b0fb8626.svg b/assets/send-3413346515.b0fb8626.svg new file mode 100644 index 00000000..1742eefe --- /dev/null +++ b/assets/send-3413346515.b0fb8626.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/send.7a090949.svg b/assets/send.7a090949.svg new file mode 100644 index 00000000..b64d0741 --- /dev/null +++ b/assets/send.7a090949.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/settings-2175246113.00804666.svg b/assets/settings-2175246113.00804666.svg new file mode 100644 index 00000000..85d1de17 --- /dev/null +++ b/assets/settings-2175246113.00804666.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/settings-878939771.57cf3680.svg b/assets/settings-878939771.57cf3680.svg new file mode 100644 index 00000000..4e3aee30 --- /dev/null +++ b/assets/settings-878939771.57cf3680.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/settings.45b8e09f.svg b/assets/settings.45b8e09f.svg new file mode 100644 index 00000000..fb8809ae --- /dev/null +++ b/assets/settings.45b8e09f.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/assets/theme-element-dark.4718033a.css b/assets/theme-element-dark.4718033a.css new file mode 100644 index 00000000..b55d7804 --- /dev/null +++ b/assets/theme-element-dark.4718033a.css @@ -0,0 +1 @@ +@font-face{font-family:"emoji";src:local("Apple Color Emoji"),local("Segoe UI Emoji"),local("Segoe UI Symbol"),local("Noto Color Emoji"),local("Twemoji"),local("Twemoji Mozilla"),local("Android Emoji"),local("EmojiSymbols"),local("Symbola");unicode-range:U+1F300-1F5FF,U+1F600-1F64F,U+1F680-1F6FF,U+2600-26FF}html{height:100%}main{display:block}@media screen and (min-width: 600px){.PreSessionScreen{width:600px;box-sizing:border-box;margin:50px auto 0}}.room-placeholder{display:flex;flex-direction:row}.SessionView{position:fixed;height:100%;width:100%;display:grid;grid-template:"status status" auto "left middle" 1fr / 320px 1fr;min-height:0;min-width:0}.right-shown{grid-template:"status status status" auto "left middle right" 1fr / 320px 1fr 300px}.hydrogen.ios .SessionView{height:var(--ios-viewport-height, 100%);top:var(--ios-viewport-top, 0)}.middle .close-middle{display:none}@media screen and (max-width: 800px){.SessionView:not(.middle-shown):not(.right-shown){grid-template:"status" auto "left" 1fr / 1fr}.SessionView.middle-shown{grid-template:"status" auto "middle" 1fr / 1fr}.SessionView.right-shown{grid-template:"status" auto "right" 1fr / 1fr}.SessionView:not(.middle-shown):not(.right-shown) .room-placeholder{display:none}.SessionView.middle-shown .LeftPanel,.SessionView.right-shown .middle,.SessionView.right-shown .LeftPanel{display:none}.middle .close-middle{display:block!important}.LeftPanel .grid{display:none!important}}.LeftPanel{grid-area:left;min-width:0;min-height:0}.room-placeholder,.middle{min-width:0;grid-area:middle;width:100%;min-height:0}.middle{display:flex;flex-direction:column}.SessionStatusView{grid-area:status}.lightbox{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1;box-sizing:border-box;height:100%}.RoomView_body{flex:1 1;min-height:0;min-width:0;display:flex;flex-direction:column;height:100%}.RoomView_body .Timeline,.RoomView_body .TimelineLoadingView{flex:1 0}.middle-header{display:flex}.RoomGridView{display:grid}.RoomGridView.layout3x2{grid-template:"t0 t1 t2" 1fr "t3 t4 t5" 1fr / 1fr 1fr 1fr}.RoomGridView>.tile0{grid-area:t0}.RoomGridView>.tile1{grid-area:t1}.RoomGridView>.tile2{grid-area:t2}.RoomGridView>.tile3{grid-area:t3}.RoomGridView>.tile4{grid-area:t4}.RoomGridView>.tile5{grid-area:t5}.RoomGridView>div{display:flex;min-width:0;min-height:0}.RoomGridView>div.focus-ring{z-index:1;pointer-events:none}.menu{position:absolute;z-index:2}.menu .menu-item{box-sizing:border-box;width:100%}.Settings{display:flex;flex-direction:column}.SettingsBody{min-height:0;overflow-y:auto}.LazyListParent{flex:1 1}.LoadingView{display:flex;justify-content:center;align-items:center}.vertical-layout{display:flex;flex-direction:row;align-items:center;gap:12px}.vertical-layout>.stretch{flex:1 0}.popupContainer{position:absolute;white-space:nowrap}.SessionPickerView{padding:.4em}.SessionPickerView ul{list-style:none;padding:0}.SessionPickerView li{margin:.4em 0}.SessionPickerView .session-info{cursor:pointer;display:flex;align-items:center}.SessionPickerView .session-info>:not(:first-child){margin-left:8px}.SessionPickerView li .user-id{flex:1 1;overflow:hidden;text-overflow:ellipsis}.SessionPickerView li .error{margin:0 20px}.PasswordLoginView{padding:0 .4em .4em}.SessionLoadStatusView>.status,.LoginView_query-spinner{display:flex;gap:12px}.SessionLoadStatusView>.status p,.LoginView_query-spinner p{flex:1 1;margin:0}.SessionLoadStatusView .spinner{--size: 20px}.StartSSOLoginView{display:flex;flex-direction:column;padding:0 .4em}.StartSSOLoginView_button{flex:1 1;margin-top:12px}.LoginView_separator{justify-content:center;display:flex;margin:8px}.CompleteSSOView_title{display:flex;justify-content:center}.LoginView_sso{padding:.4em .4em 0}.LeftPanel{display:flex;flex-direction:column}.LeftPanel .utilities{display:flex}.LeftPanel .utilities .FilterField{flex:1 1;min-width:0}.LeftPanel ul{list-style:none;padding:0;margin:0}.RoomList{flex:1 0;overflow-y:auto;overscroll-behavior:contain}.RoomList>li>a{display:flex;align-items:center}.RoomList .description{margin:0;flex:1 1;min-width:0;display:flex}.RoomList .description>.name{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1 1}.RightPanelView{grid-area:right;min-height:0;min-width:0;display:flex;flex-direction:column}.RoomDetailsView,.MemberDetailsView{flex-direction:column;flex:1 1}.RoomDetailsView_avatar{display:flex}.RoomDetailsView_name h2,.MemberDetailsView_name h2{text-align:center}.RoomDetailsView_label,.RoomDetailsView_row,.RoomDetailsView,.MemberDetailsView,.EncryptionIconView{display:flex;align-items:center;color:var(--text-color)}.RoomDetailsView_value{display:flex;justify-content:flex-end}.EncryptionIconView{justify-content:center}.RightPanelView_buttons{display:flex;justify-content:space-between;width:100%;box-sizing:border-box;padding:16px}.RightPanelView_buttons .hide{visibility:hidden}.MemberTileView a{display:flex;align-items:center}.middle-header{align-items:center}.middle-header h2{flex:1 1}.middle-header button{display:block}.middle-header .room-description{flex:1 1;min-width:0}.RoomHeader .topic{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.RoomHeader .description{flex:1 1 auto;min-width:0}.middle-header h2{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;margin:0}.MessageComposer_replyPreview{display:grid;grid-template-columns:1fr auto}.MessageComposer_replyPreview .Timeline_message{grid-column:1/-1}.MessageComposer_input{display:flex;align-items:center}.MessageComposer_input>input{display:block;flex:1 1;min-width:0;box-sizing:border-box}.TimelineLoadingView{display:flex;align-items:center;justify-content:center}.TimelineLoadingView>:not(:first-child){margin-left:12px}.Timeline{display:flex;flex-direction:column;position:relative;min-height:0}.Timeline_jumpDown{position:absolute}.Timeline_scroller{overflow-y:scroll;overscroll-behavior-y:contain;overflow-anchor:none;padding:0;margin:0;position:relative;min-height:0;flex:1 0}.Timeline_scroller>ul{list-style:none;padding:1px 0;margin:0}.AnnouncementView{display:flex;align-items:center}.GapView{display:flex}.GapView>:nth-child(2){flex:1 1}.Timeline_messageBody img{max-width:400px;max-height:300px}.hydrogen{--avatar-size: 32px}.hydrogen .avatar{width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6);overflow:hidden;flex-shrink:0;user-select:none;text-align:center;speak:none}.hydrogen .avatar img{width:100%;height:100%;object-fit:cover}.hydrogen .avatar.size-128{--avatar-size: 128px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-64{--avatar-size: 64px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-52{--avatar-size: 52px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-30{--avatar-size: 30px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-24{--avatar-size: 24px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-12{--avatar-size: 12px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}@keyframes spinner{0%{transform:rotate(0);stroke-dasharray:0 0 10 90}45%{stroke-dasharray:0 0 90 10}75%{stroke-dasharray:0 50 50 0}to{transform:rotate(360deg);stroke-dasharray:10 90 0 0}}.hydrogen:not(.legacy) .spinner circle{transform-origin:50% 50%;animation-name:spinner;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear;stroke-dasharray:0 0 85 85;fill:none;stroke:currentcolor;stroke-width:12;stroke-linecap:butt}.hydrogen.legacy .spinner{display:inline-block;position:relative}.hydrogen.legacy .spinner div{box-sizing:border-box;display:block;position:absolute;padding:2px;border:2px solid currentcolor;border-radius:50%;animation:legacy-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:currentcolor transparent transparent transparent;width:var(--size);height:var(--size)}.hydrogen.legacy .spinner div:nth-child(1){animation-delay:-.45s}.hydrogen.legacy .spinner div:nth-child(2){animation-delay:-.3s}.hydrogen.legacy .spinner div:nth-child(3){animation-delay:-.15s}@keyframes legacy-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.spinner{--size: 20px;width:var(--size);height:var(--size)}.form-row.text>input,.form-row.text>textarea{display:block;width:100%;min-width:0;box-sizing:border-box}.FilterField{display:flex}.FilterField input{display:block;flex:1 1;min-width:0}.SessionStatusView{display:flex}.SessionStatusView p{margin:0 10px;word-break:break-all;word-break:break-word}body.hydrogen{overscroll-behavior:none;overflow:hidden}.hydrogen{margin:0}.hiddenWithLayout{visibility:hidden}.hidden{display:none!important}input::-ms-clear{display:none}@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(./Inter-Thin.5d8e2ac4.woff2?v=3.13) format("woff2"),url(./Inter-Thin.5565b01e.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(./Inter-ThinItalic.6b3ded18.woff2?v=3.13) format("woff2"),url(./Inter-ThinItalic.c413497b.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(./Inter-ExtraLight.da47c335.woff2?v=3.13) format("woff2"),url(./Inter-ExtraLight.d7be68a4.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(./Inter-ExtraLightItalic.b3f94cfe.woff2?v=3.13) format("woff2"),url(./Inter-ExtraLightItalic.762fa4d2.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(./Inter-Light.0f7dfe72.woff2?v=3.13) format("woff2"),url(./Inter-Light.38326098.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(./Inter-LightItalic.125c7e6a.woff2?v=3.13) format("woff2"),url(./Inter-LightItalic.ec6c76a8.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(./Inter-Regular.89d406b0.woff2?v=3.13) format("woff2"),url(./Inter-Regular.5b3a854b.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(./Inter-Italic.bab4e808.woff2?v=3.13) format("woff2"),url(./Inter-Italic.7b187d57.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(./Inter-Medium.5d308f3d.woff2?v=3.13) format("woff2"),url(./Inter-Medium.0fc5d904.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(./Inter-MediumItalic.76551c20.woff2?v=3.13) format("woff2"),url(./Inter-MediumItalic.1458af9d.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(./Inter-SemiBold.c7c3befe.woff2?v=3.13) format("woff2"),url(./Inter-SemiBold.04cd699f.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(./Inter-SemiBoldItalic.d376ade4.woff2?v=3.13) format("woff2"),url(./Inter-SemiBoldItalic.420db54a.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(./Inter-Bold.6f5e9a23.woff2?v=3.13) format("woff2"),url(./Inter-Bold.20d46cff.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(./Inter-BoldItalic.e09dcbe1.woff2?v=3.13) format("woff2"),url(./Inter-BoldItalic.31a185fa.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(./Inter-ExtraBold.0ef4267e.woff2?v=3.13) format("woff2"),url(./Inter-ExtraBold.45bae435.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(./Inter-ExtraBoldItalic.d1e1f6a0.woff2?v=3.13) format("woff2"),url(./Inter-ExtraBoldItalic.30a1af87.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(./Inter-Black.7f1f5616.woff2?v=3.13) format("woff2"),url(./Inter-Black.067c82f7.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(./Inter-BlackItalic.72d5983b.woff2?v=3.13) format("woff2"),url(./Inter-BlackItalic.c628a2cf.woff?v=3.13) format("woff")}.Timeline_jumpDown{width:40px;height:40px;bottom:16px;right:32px;border-radius:100%;border:1px solid var(--background-color-secondary--darker-7);background-image:var(--icon-url-0);background-position:center;background-color:var(--background-color-primary--darker-10);background-repeat:no-repeat;cursor:pointer}.Timeline_message{display:grid;grid-template:"avatar sender" auto "avatar body" auto "time body" 1fr "time reactions" auto / 30px 1fr;column-gap:8px;padding:4px;margin:0 12px;box-sizing:border-box}.Timeline_message:not(.continuation){margin-top:4px}.ReplyPreviewView .Timeline_message{display:grid;grid-template:"body" auto;margin-left:0;padding:0}.ReplyPreviewView .Timeline_message:not(.continuation){margin-top:0}@media screen and (max-width: 800px){.Timeline_message{grid-template:"avatar sender" auto "body body" 1fr "time time" auto "reactions reactions" auto / 30px 1fr}.Timeline_messageSender{margin-top:0!important;align-self:center}}.Timeline_message:hover:not(.disabled),.Timeline_message.selected,.Timeline_message.menuOpen{background-color:#8d97a51a;border-radius:4px}.Timeline_message:hover>.Timeline_messageOptions,.Timeline_message.menuOpen>.Timeline_messageOptions{display:block;user-select:none}.Timeline_messageAvatar{grid-area:avatar;text-decoration:none}.Timeline_messageSender{grid-area:sender;font-weight:700;line-height:1.7rem}.Timeline_messageSender,.Timeline_messageBody{margin:0;word-break:break-all;word-break:break-word}.Timeline_message:not(.continuation) .Timeline_messageSender,.Timeline_message:not(.continuation) .Timeline_messageBody{margin-top:4px}.Timeline_messageOptions{display:none;grid-area:body;align-self:start;justify-self:end;margin-top:-12px;margin-right:4px;border:var(--background-color-primary--darker-10) 1px solid;height:24px;width:24px;background-color:var(--background-color-primary);color:inherit;border-radius:4px;padding:0;text-align:center;line-height:22px;cursor:pointer}.Timeline_messageTime{grid-area:time}.Timeline_messageBody time{padding:2px 0 0 10px;user-select:none}.Timeline_messageBody time,.Timeline_messageTime{font-size:.8em;line-height:normal;color:var(--timeline-time-text-color)}.Timeline_messageBody.statusMessage{font-style:italic;color:var(--light-text-color)}.Timeline_messageBody{grid-area:body;line-height:2.2rem;width:100%;min-width:0}.hydrogen .Timeline_messageSender.usercolor1{color:var(--usercolor1)}.hydrogen .Timeline_messageSender.usercolor2{color:var(--usercolor2)}.hydrogen .Timeline_messageSender.usercolor3{color:var(--usercolor3)}.hydrogen .Timeline_messageSender.usercolor4{color:var(--usercolor4)}.hydrogen .Timeline_messageSender.usercolor5{color:var(--usercolor5)}.hydrogen .Timeline_messageSender.usercolor6{color:var(--usercolor6)}.hydrogen .Timeline_messageSender.usercolor7{color:var(--usercolor7)}.hydrogen .Timeline_messageSender.usercolor8{color:var(--usercolor8)}.Timeline_messageBody h1,.Timeline_messageBody h2,.Timeline_messageBody h3,.Timeline_messageBody h4,.Timeline_messageBody h5,.Timeline_messageBody h6{font-weight:700;margin:.7em 0}.Timeline_messageBody h1{font-size:1.6em}.Timeline_messageBody h2{font-size:1.5em}.Timeline_messageBody h3{font-size:1.4em}.Timeline_messageBody h4{font-size:1.3em}.Timeline_messageBody h5{font-size:1.2em}.Timeline_messageBody h6{font-size:1.1em}.Timeline_messageBody a{word-break:break-all}.Timeline_messageBody a.link{color:var(--link-color);text-decoration:none}.Timeline_messageBody .media{display:grid;margin-top:4px;width:100%}.Timeline_messageBody .media>a{text-decoration:none;width:100%;display:block}.Timeline_messageBody .media>*{grid-row:1;grid-column:1}.Timeline_messageBody .media img,.Timeline_messageBody .media video{width:100%;height:auto;align-self:start;border-radius:4px;display:block}.hydrogen:not(.legacy) .Timeline_messageBody .media img,.hydrogen:not(.legacy) .Timeline_messageBody .media video{align-self:stretch}.Timeline_messageBody .media>.status{align-self:end;justify-self:start;font-size:.8em}.Timeline_messageBody .media>progress{align-self:center;justify-self:center;width:75%}.Timeline_messageBody .media>time{align-self:end;justify-self:end}.Timeline_messageBody .media>time,.Timeline_messageBody .media>.status{color:var(--text-color);display:block;padding:2px;margin:4px;background-color:#ffffffbf;border-radius:4px}.Timeline_messageBody .media>.spacer{width:100%;align-self:start}.Timeline_messageBody code,.Timeline_messageBody pre{background-color:var(--background-color-secondary);font-family:monospace;font-size:.9em}.Timeline_messageBody code{border-radius:3px;padding:.2em .3em;margin:0}.Timeline_messageBody pre{border:1px solid var(--light-border);padding:.5em;max-height:30em;overflow:auto}.Timeline_messageBody pre>code{background-color:unset;border-radius:unset;display:block;font-size:unset}.Timeline_messageBody blockquote{margin-left:0;padding-left:20px;border-left:4px solid var(--light-border)}.Timeline_messageBody table{border:1px solid var(--background-color-secondary--darker-15);border-radius:2px;border-spacing:0}.Timeline_messageBody thead th{border-bottom:1px solid var(--background-color-secondary--darker-15)}.Timeline_messageBody td,.Timeline_messageBody th{padding:2px 5px}.Timeline_messageBody tbody tr:nth-child(2n){background-color:var(--background-color-secondary)}.Timeline_messageBody .pill{padding:0 5px;border-radius:15px;background-color:var(--background-color-secondary);border:1px solid var(--background-color-secondary--darker-10);text-decoration:none;display:inline-flex;align-items:center;line-height:2rem;vertical-align:top;margin:1px}.Timeline_messageBody .pill div.avatar{display:inline-block;margin-right:3px}.Timeline_message.unsent .Timeline_messageBody{color:var(--light-text-color)}.Timeline_message.unverified .Timeline_messageBody{color:var(--error-color)}.Timeline_messageReactions{grid-area:reactions;margin-top:6px}.Timeline_messageReactions button{display:inline-flex;line-height:2rem;margin-right:6px;padding:1px 6px;border:1px solid var(--light-border);border-radius:10px;background-color:var(--background-color-secondary);color:inherit;cursor:pointer;user-select:none;vertical-align:middle}.Timeline_messageReactions button.active{background-color:var(--background-color-secondary);border-color:var(--accent-color)}@keyframes glow-reaction-border{0%{border-color:var(--background-color-secondary)}to{border-color:var(--accent-color)}}.Timeline_messageReactions button.active.pending{animation-name:glow-reaction-border;animation-duration:.5s;animation-direction:alternate;animation-iteration-count:infinite;animation-timing-function:linear}.Timeline_locationLink{padding:0 8px;border-radius:16px;border:1px solid var(--light-border);background-color:var(--background-color-secondary);text-decoration:none;display:inline-block;line-height:2rem;vertical-align:top;margin:1px 4px}.AnnouncementView{margin:5px 0;padding:5px 10%}.AnnouncementView>div{margin:0 auto;padding:10px 20px;background-color:var(--background-color-secondary);text-align:center;border-radius:10px}.GapView>:not(:first-child){margin-left:12px}.GapView{padding:52px 20px}.GapView.isAtTop{padding:52px 20px 12px}:root{font-size:10px;--icon-color: var(--background-color-secondary--darker-40);--light-border: var(--background-color-secondary--darker-5);--light-text-color: var(--background-color-secondary--darker-55);--timeline-time-text-color: var(--background-color-secondary--darker-35);--icon-background: var(--background-color-secondary--darker-7);--right-panel-text-color: var(--background-color-secondary--darker-35)}.hydrogen{font-family:Inter,sans-serif,"emoji";background-color:var(--background-color-primary);color:var(--text-color);font-size:1.4rem;--usercolor1: #368BD6;--usercolor2: #AC3BA8;--usercolor3: #03B381;--usercolor4: #E64F7A;--usercolor5: #FF812D;--usercolor6: #2DC2C5;--usercolor7: #5C56F5;--usercolor8: #74D12C}.hydrogen button{font-family:inherit}.avatar{border-radius:100%;background:var(--background-color-primary);color:var(--fixed-white)}.hydrogen .avatar.usercolor1{background-color:var(--usercolor1)}.hydrogen .avatar.usercolor2{background-color:var(--usercolor2)}.hydrogen .avatar.usercolor3{background-color:var(--usercolor3)}.hydrogen .avatar.usercolor4{background-color:var(--usercolor4)}.hydrogen .avatar.usercolor5{background-color:var(--usercolor5)}.hydrogen .avatar.usercolor6{background-color:var(--usercolor6)}.hydrogen .avatar.usercolor7{background-color:var(--usercolor7)}.hydrogen .avatar.usercolor8{background-color:var(--usercolor8)}.logo{height:48px;min-width:48px;background-image:var(--icon-url-1);background-repeat:no-repeat;background-position:center}.button-row{display:flex}.button-row>*{margin-right:10px}.button-row>*:last-child{margin-right:0}.button-row .button-action{margin:10px 0;flex:1 0 auto}.form-row.text textarea{font-family:Inter,sans-serif;background-color:var(--background-color-secondary);color:inherit}.form-group{margin:24px 0}.form-row{margin:12px 0}.form-row.text>input,.form-row.text>textarea{padding:12px;border:1px solid var(--light-border);border-radius:8px;margin-top:5px;font-size:1em;resize:vertical;background-color:var(--background-color-secondary);color:inherit}.form-row.check{display:flex;align-items:baseline;gap:4px}.form-row.text>label,.form-row.text>input{display:block}.form-row .form-row-description{font-size:1rem;color:var(--light-text-color);margin:8px 0 0}.button-action{cursor:pointer}a.button-action{text-decoration:none;text-align:center;display:block}.button-action.secondary{color:var(--accent-color)}.button-action.primary{background-color:var(--accent-color);border-radius:8px;color:var(--fixed-white);font-weight:700}.button-action.primary:disabled{color:var(--fixed-white--darker-10)}.button-action.primary.destructive{background-color:var(--error-color)}.button-action.secondary.destructive{color:var(--error-color)}.button-action{border:none;padding:10px;background:none;font-weight:500}.button-utility{cursor:pointer;width:32px;height:32px;background-position:center;background-color:var(--icon-background);background-repeat:no-repeat;border:none;border-radius:100%;display:block}.button-utility.grid{background-image:var(--icon-url-2)}.button-utility.settings{background-image:var(--icon-url-3)}.button-utility.create{background-image:var(--icon-url-4)}.button-utility.grid.on{background-image:var(--icon-url-5)}.FilterField{background-image:var(--icon-url-6);background-repeat:no-repeat;background-position:8px center;background-color:var(--icon-background);border:1px solid transparent;border-radius:16px;height:32px;align-items:center;padding-left:30px;box-sizing:border-box}.FilterField:focus-within{border:1px var(--icon-background) solid;background-color:var(--background-color-primary)}.FilterField:focus-within button{border-color:var(--background-color-primary)}.FilterField input{font-family:Inter;font-size:1.3rem;font-weight:500;line-height:1.573rem;outline:none;border:none;background-color:transparent;height:100%;color:var(--text-color)}.FilterField button{width:30px;height:30px;background-position:center;background-color:var(--icon-background);background-repeat:no-repeat;background-image:var(--icon-url-7);border:7px solid transparent;border-radius:100%;box-sizing:border-box}.PreSessionScreen{padding:30px}.PreSessionScreen h1{font-size:16px;text-align:center}.SessionLoadView{padding-top:16px}.StartSSOLoginView_button{border:1px solid var(--accent-color);border-radius:8px}.LoginView_back{background-image:var(--icon-url-8);background-color:transparent}.LoginView_separator{font-weight:500;font-size:1.5rem}.LoginView_forwardInfo{font-size:.9em;margin-left:1em;color:var(--light-text-color)}.CompleteSSOView_title{font-weight:500}@media screen and (min-width: 600px){.PreSessionScreen{box-shadow:0 6px 32px #0000001a;border-radius:8px}}.PreSessionScreen .logo{height:48px;min-width:48px}.LeftPanel{background:var(--background-color-secondary);font-size:1.5rem;padding:12px 8px 0}.LeftPanel>:not(:first-child){margin-top:12px}.LeftPanel .utilities>:not(:first-child){margin-left:8px}.LeftPanel .filter{border-bottom:1px solid var(--background-color-secondary)}.LeftPanel .filter input{padding:.8em;border:none}.LeftPanel .RoomList{padding:0 8px 0 0;margin-right:-8px}.RoomList>li{margin:0;padding:4px 8px 4px 0;align-items:center}.RoomList>li>a{text-decoration:none;align-items:center}.RoomList li:not(:first-child){margin-top:4px}.RoomList li.active{background:var(--background-color-secondary--darker-7);border-radius:5px}.RoomList li>a>*{margin-right:8px}.RoomList .description{align-items:center}.RoomList .name.unread{font-weight:600}.RoomList .badge{min-width:1.6rem;height:1.6rem;border-radius:1.6rem;box-sizing:border-box;padding:.1rem .3rem;background-color:var(--room-badge);color:var(--fixed-white);font-weight:700;font-size:1rem;line-height:1.4rem;text-align:center}.RoomList .badge.highlighted{background-color:var(--error-color)}a{color:inherit}.SessionStatusView{padding:4px;min-height:22px;background-color:var(--accent-color);color:var(--fixed-white);align-items:center}.SessionStatusView button.link{color:currentcolor;text-align:left}.SessionStatusView>.end{flex:1 1;display:flex;justify-content:flex-end;align-self:stretch;align-items:stretch}.SessionStatusView .dismiss{border:none;background:none;background-image:var(--icon-url-9);background-position:center;background-repeat:no-repeat;width:32px;cursor:pointer}.room-placeholder{align-items:center;justify-content:center;text-align:center;padding:20px}.SessionPickerView li{font-size:1.2em}.SessionPickerView .session-info{text-decoration:none;padding:12px;border:1px solid var(--light-border);border-radius:8px;background-image:var(--icon-url-10);background-position:center right 30px;background-repeat:no-repeat;font-weight:500}.SessionPickerView .session-actions{margin:10px 0 20px;display:flex}.SessionPickerView .session-actions>*{margin-right:10px}.SessionPickerView .session-actions>*:last-child{margin-right:0}.SessionPickerView .session-actions button{border:none;background:none;color:inherit}.SessionPickerView button.destructive{color:var(--error-color)}.RoomGridView>div.container{border-right:1px solid var(--background-color-secondary);border-bottom:1px solid var(--background-color-secondary)}.RoomGridView>.focused>.room-placeholder .unfocused{display:none}.RoomGridView>:not(.focused)>.room-placeholder .focused{display:none}.room-placeholder .unfocused{color:var(--right-panel-text-color)}.RoomGridView>div.focus-ring{border:2px solid var(--accent-color--darker-5);border-radius:12px}.middle-header{box-sizing:border-box;flex:0 0 56px;background:var(--background-color-primary);padding:0 16px;border-bottom:1px solid var(--background-color-secondary)}.middle-header h2{font-size:1.8rem;font-weight:600}.middle-header>:not(:last-child){margin-right:8px}.close-middle,.close-session{background-image:var(--icon-url-11);background-position-x:10px}.RoomHeader .topic{font-size:14rem}.RoomHeader .room-options{background-image:var(--icon-url-12)}.RoomView_error{color:var(--error-color);background:#efefef;height:0px;font-weight:700;transition:.25s all ease-out;padding-right:20px;padding-left:20px}.RoomView_error div{overflow:hidden;height:100%;width:100%;position:relative;display:flex;align-items:center}.RoomView_error:not(:empty){height:auto;padding-top:20px;padding-bottom:20px}.RoomView_error p{position:relative;display:block;width:100%;height:auto;margin:0}.RoomView_error button{width:40px;padding-top:20px;padding-bottom:20px;background:none;border:none;position:relative;border-radius:5px;transition:.1s all ease-out;cursor:pointer}.RoomView_error button:hover{background:#cfcfcf}.RoomView_error button:before{content:"\274c";position:absolute;top:15px;left:9px;width:20px;height:10px;font-size:10px;align-self:middle}.MessageComposer_replyPreview .Timeline_message{margin:5px 0 0;max-height:30vh;overflow:auto}.MessageComposer_replyPreview{background:var(--background-color-secondary);margin:0 10px 10px;box-shadow:0 0 5px var(--background-color-secondary--darker-15);border-radius:5px}.MessageComposer_input,.MessageComposer_replyPreview{padding:8px}.MessageComposer_replyPreview>.replying{display:inline-flex;flex-direction:row;align-items:center;font-weight:700}.MessageComposer_replyPreview>button.cancel{width:32px;height:32px;display:block;border:none;text-indent:200%;white-space:nowrap;overflow:hidden;background-color:transparent;background-image:var(--icon-url-13);background-repeat:no-repeat;background-position:center;background-size:18px;cursor:pointer}.MessageComposer_input:first-child{border-top:1px solid var(--background-color-secondary)}.MessageComposer_input>:not(:first-child){margin-left:12px}.MessageComposer_input>textarea{border:none;border-radius:24px;background:var(--background-color-secondary);color:inherit;font-size:14px;font-family:Inter,sans-serif;resize:none;flex:1 1;padding:14px;box-sizing:border-box;overflow:hidden;max-height:113px;overflow-y:auto;overflow-y:overlay}.MessageComposer_input>button.send{width:32px;height:32px;display:block;border-radius:100%;border:none;text-indent:200%;overflow:hidden;background-color:var(--accent-color);background-image:var(--icon-url-14);background-repeat:no-repeat;background-position:center;align-self:end;margin-bottom:8px}.MessageComposer_input>button.sendFile{width:32px;height:32px;display:block;border:none;text-indent:200%;white-space:nowrap;overflow:hidden;background-color:transparent;background-image:var(--icon-url-15);background-repeat:no-repeat;background-position:center}.MessageComposer.MessageComposer_canSend button.sendFile{display:none}.MessageComposer:not(.MessageComposer_canSend) button.send{display:none}.SettingsBody{padding:0 16px}.Settings h3{margin:16px 0 8px}.Settings p{max-width:700px}.Settings .row .label{font-weight:600}.Settings .row .label,.Settings .row .content{margin-top:4px;margin-bottom:4px}.Settings .row .content{margin-left:4px;flex:1 1}.Settings .row.code .content{font-family:monospace}.Settings .row .content button{display:inline-block;margin:0 8px}.Settings .row .content input[type=range]{width:100%;max-width:300px;min-width:160px}.Settings .row{margin:4px 0;display:flex;flex-wrap:wrap;align-items:center}.Settings .row .label{flex:0 0 200px;align-self:flex-start}.Settings .row .content p{margin:8px 0}.Settings .row .content p:first-child{margin-top:0}.Settings .row .content p:last-child{margin-bottom:0}.error{color:var(--error-color);font-weight:600}button.link{font-size:1em;border:none;text-decoration:underline;background:none;cursor:pointer;margin:-12px;padding:12px;color:inherit}.Settings a,.Settings .link{color:var(--accent-color);font-weight:600}.lightbox{background-color:#000000bf;display:grid;grid-template:"content close" auto "content details" 1fr / 1fr auto;color:var(--background-color-primary);padding:4px}@media (max-aspect-ratio: 1/1){.lightbox{grid-template:"close" auto "content" 1fr "details" auto / 1fr}.lightbox .details{width:100%!important}}.lightbox .picture{grid-area:content;background-size:contain;background-position:center;background-repeat:no-repeat;width:100%;height:100%;align-self:center;justify-self:center}.lightbox .loading{grid-area:content;align-self:center;justify-self:center;display:flex}.lightbox .loading>:not(:first-child){margin-left:8px}.lightbox .close{display:block;grid-area:close;justify-self:end;background-image:var(--icon-url-16);background-position:center;background-size:16px;background-repeat:no-repeat;width:16px;height:16px;padding:12px}.lightbox .details{grid-area:details;padding:12px;font-size:1.5rem;width:200px}.menu{border-radius:8px;box-shadow:2px 2px 10px #00000080;padding:4px;background-color:var(--background-color-primary);list-style:none;margin:0}.menu li{margin-bottom:10px}.menu .menu-item{color:var(--text-color)}.menu button{border-radius:4px;border:none;background-color:transparent;text-align:left;padding:8px 32px 8px 8px;font-size:1.5rem;height:24px;cursor:pointer}.menu .destructive button{color:var(--error-color)}.menu .quick-reactions{display:flex;padding:8px 32px 8px 8px}.menu .quick-reactions button{padding:2px 4px;text-align:center}.InviteView_body{display:flex;justify-content:space-around;align-items:center;flex:1 1;overflow:auto}.InviteView_invite{display:flex;width:100%;max-width:400px;flex-direction:column;padding:0 24px}.InviteView_roomProfile{display:grid;gap:4px;grid-template:"avatar name" auto "avatar description" 1fr / 72px 1fr;align-self:center;margin-bottom:24px}.InviteView_roomProfile h3{grid-area:name;margin:0}.InviteView_roomDescription{grid-area:description;font-size:1.2rem;margin:0;color:var(--light-text-color)}.InviteView_roomAvatar{grid-area:avatar}.InviteView_dmAvatar{align-self:center}.InviteView_inviter{text-align:center;margin:24px 0}.InviteView_inviter .avatar{display:inline-block;vertical-align:middle;margin-right:4px}.InviteView_buttonRow{margin:10px auto;max-width:200px;width:100%}.InviteView_buttonRow button{display:block;width:100%}.DisabledComposerView{padding:12px;background-color:var(--background-color-secondary)}.DisabledComposerView h3{margin:0}.UnknownRoomView{align-items:center;justify-content:center;text-align:center;padding:16px;box-sizing:border-box}.UnknownRoomView h2{word-break:break-all;word-break:break-word}.UnknownRoomView button{max-width:200px;width:100%}.LoadingView{height:100%;width:100%}.LoadingView .spinner{margin-right:5px}.RightPanelView{background:var(--background-color-secondary)}.RoomDetailsView{padding:0 16px 16px}.RoomDetailsView_id,.MemberDetailsView_id{color:var(--right-panel-text-color);font-size:12px}.RoomDetailsView_rows{margin-top:36px;width:100%}.RoomDetailsView_name h2,.MemberDetailsView_name h2{margin-bottom:4px;font-size:1.8rem}.RoomDetailsView_row{margin-bottom:20px;font-weight:500;font-size:15px;width:100%;background:none;border:none;padding:0}button.RoomDetailsView_row{cursor:pointer}button.RoomDetailsView_row:after{content:var(--icon-url-17);margin-left:12px}.RoomDetailsView_row:not(button):after{content:" ";width:19px}.RoomDetailsView_label:before{padding-right:16px;height:24px;width:20px}.RoomDetailsView_label{width:200px}.RoomDetailsView_value{color:var(--right-panel-text-color);flex:1 1}.MemberCount:before{content:var(--icon-url-18)}.EncryptionStatus:before{content:var(--icon-url-19)}.EncryptionIconView{width:52px;height:52px;border-radius:100%;background:var(--right-panel-text-color);border:3px solid var(--background-color-secondary);margin-left:-16px}.EncryptionIconView_encrypted,.EncryptionIconView_unencrypted{height:24px;width:24px}.EncryptionIconView_encrypted{content:var(--icon-url-20)}.EncryptionIconView_unencrypted{content:var(--icon-url-21)}.RightPanelView_buttons .button-utility{width:24px;height:24px}.RightPanelView_buttons .close{background-image:var(--icon-url-22)}.RightPanelView_buttons .back{background-image:var(--icon-url-23)}.MemberListView{padding-left:16px;padding-right:16px;margin:0}.MemberTileView{margin-bottom:8px;list-style:none}.MemberTileView a{text-decoration:none}.MemberTileView .avatar{margin-right:8px}.MemberTileView_name{text-overflow:ellipsis;overflow:hidden;white-space:nowrap;flex:1 1}.MemberDetailsView_section{box-sizing:border-box;padding:16px;width:100%}.MemberDetailsView_label{font-size:12px;font-weight:600;color:var(--right-panel-text-color);text-transform:uppercase}.MemberDetailsView_value,.MemberDetailsView_options{margin-left:8px;margin-top:5px;font-size:12px}.MemberDetailsView_options{display:inline-flex;flex-direction:column}.MemberDetailsView_options a,.MemberDetailsView_options button{color:var(--accent-color);text-decoration:none;margin:0 0 3px;padding:0;border:none;background:none;cursor:pointer}.LazyListParent{overflow-y:auto}.LogoutScreen{height:100vh}.LogoutScreen .content{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center}.LogoutScreen .status{display:flex;gap:12px}.CreateRoomView,.RoomBeingCreated_error{max-width:400px}.RoomBeingCreated_error{margin-top:48px}.centered-column{padding:0 12px;align-self:center;width:100%;box-sizing:border-box}.CreateRoomView_selectAvatar{border:none;background:none;cursor:pointer}.CreateRoomView_selectAvatarPlaceholder{width:64px;height:64px;border-radius:100%;background-color:var(--icon-background);background-image:var(--icon-url-24);background-repeat:no-repeat;background-position:center;background-size:36px}:root{--background-color-primary: #21262b;--background-color-secondary: #2D3239;--text-color: #fff;--accent-color: #03B381;--error-color: #FF4B55;--fixed-white: #fff;--room-badge: #61708b;--link-color: #238cf5}:root{--background-color-secondary--darker-7: #3d444d;--background-color-primary--darker-10: #374048;--background-color-secondary--darker-15: #4f5764;--background-color-secondary--darker-10: #444b56;--background-color-secondary--darker-40: #8d97a5;--background-color-secondary--darker-5: #383f47;--background-color-secondary--darker-55: #b8bec7;--background-color-secondary--darker-35: #7f8a9a;--fixed-white--darker-10: #ffffff;--accent-color--darker-5: #03cc93}:root{--icon-url-0: url(./chevron-down-1956489915.3389f17f.svg);--icon-url-1: url(./element-logo-1551909733.1d59f06a.svg);--icon-url-2: url(./enable-grid-2288309723.f83895c8.svg);--icon-url-3: url(./settings-878939771.57cf3680.svg);--icon-url-4: url(./plus-3937109722.5c243914.svg);--icon-url-5: url(./disable-grid-4240599831.c8dc25a1.svg);--icon-url-6: url(./search-261439583.1bffaca1.svg);--icon-url-7: url(./clear-4137897294.7b90e8df.svg);--icon-url-8: url(./chevron-left-2611498805.b5555a61.svg);--icon-url-9: url(./dismiss-2476348673.d0f98560.svg);--icon-url-10: url(./chevron-right-2390431650.ec9bf561.svg);--icon-url-11: url(./chevron-left-2611498805.b5555a61.svg);--icon-url-12: url(./vertical-ellipsis-487061581.e7709afd.svg);--icon-url-13: url(./clear-4137897294.7b90e8df.svg);--icon-url-14: url(./send-3413346515.b0fb8626.svg);--icon-url-15: url(./paperclip-3961996319.da562307.svg);--icon-url-16: url(./dismiss-2743697487.2f1a17f1.svg);--icon-url-17: url(./chevron-small-4098047679.489e66cc.svg);--icon-url-18: url(./room-members-3084360280.6f64aaef.svg);--icon-url-19: url(./encryption-status-3449529405.c200a9bb.svg);--icon-url-20: url(./e2ee-normal-1448349558.af8f5484.svg);--icon-url-21: url(./e2ee-disabled-1470792300.6863c16d.svg);--icon-url-22: url(./clear-4137897294.7b90e8df.svg);--icon-url-23: url(./chevron-thin-left-3078630092.d0d143e3.svg);--icon-url-24: url(./plus-3937109722.5c243914.svg)} diff --git a/assets/theme-element-light.0779c91e.css b/assets/theme-element-light.0779c91e.css new file mode 100644 index 00000000..19ad9ca1 --- /dev/null +++ b/assets/theme-element-light.0779c91e.css @@ -0,0 +1 @@ +@font-face{font-family:"emoji";src:local("Apple Color Emoji"),local("Segoe UI Emoji"),local("Segoe UI Symbol"),local("Noto Color Emoji"),local("Twemoji"),local("Twemoji Mozilla"),local("Android Emoji"),local("EmojiSymbols"),local("Symbola");unicode-range:U+1F300-1F5FF,U+1F600-1F64F,U+1F680-1F6FF,U+2600-26FF}html{height:100%}main{display:block}@media screen and (min-width: 600px){.PreSessionScreen{width:600px;box-sizing:border-box;margin:50px auto 0}}.room-placeholder{display:flex;flex-direction:row}.SessionView{position:fixed;height:100%;width:100%;display:grid;grid-template:"status status" auto "left middle" 1fr / 320px 1fr;min-height:0;min-width:0}.right-shown{grid-template:"status status status" auto "left middle right" 1fr / 320px 1fr 300px}.hydrogen.ios .SessionView{height:var(--ios-viewport-height, 100%);top:var(--ios-viewport-top, 0)}.middle .close-middle{display:none}@media screen and (max-width: 800px){.SessionView:not(.middle-shown):not(.right-shown){grid-template:"status" auto "left" 1fr / 1fr}.SessionView.middle-shown{grid-template:"status" auto "middle" 1fr / 1fr}.SessionView.right-shown{grid-template:"status" auto "right" 1fr / 1fr}.SessionView:not(.middle-shown):not(.right-shown) .room-placeholder{display:none}.SessionView.middle-shown .LeftPanel,.SessionView.right-shown .middle,.SessionView.right-shown .LeftPanel{display:none}.middle .close-middle{display:block!important}.LeftPanel .grid{display:none!important}}.LeftPanel{grid-area:left;min-width:0;min-height:0}.room-placeholder,.middle{min-width:0;grid-area:middle;width:100%;min-height:0}.middle{display:flex;flex-direction:column}.SessionStatusView{grid-area:status}.lightbox{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1;box-sizing:border-box;height:100%}.RoomView_body{flex:1 1;min-height:0;min-width:0;display:flex;flex-direction:column;height:100%}.RoomView_body .Timeline,.RoomView_body .TimelineLoadingView{flex:1 0}.middle-header{display:flex}.RoomGridView{display:grid}.RoomGridView.layout3x2{grid-template:"t0 t1 t2" 1fr "t3 t4 t5" 1fr / 1fr 1fr 1fr}.RoomGridView>.tile0{grid-area:t0}.RoomGridView>.tile1{grid-area:t1}.RoomGridView>.tile2{grid-area:t2}.RoomGridView>.tile3{grid-area:t3}.RoomGridView>.tile4{grid-area:t4}.RoomGridView>.tile5{grid-area:t5}.RoomGridView>div{display:flex;min-width:0;min-height:0}.RoomGridView>div.focus-ring{z-index:1;pointer-events:none}.menu{position:absolute;z-index:2}.menu .menu-item{box-sizing:border-box;width:100%}.Settings{display:flex;flex-direction:column}.SettingsBody{min-height:0;overflow-y:auto}.LazyListParent{flex:1 1}.LoadingView{display:flex;justify-content:center;align-items:center}.vertical-layout{display:flex;flex-direction:row;align-items:center;gap:12px}.vertical-layout>.stretch{flex:1 0}.popupContainer{position:absolute;white-space:nowrap}.SessionPickerView{padding:.4em}.SessionPickerView ul{list-style:none;padding:0}.SessionPickerView li{margin:.4em 0}.SessionPickerView .session-info{cursor:pointer;display:flex;align-items:center}.SessionPickerView .session-info>:not(:first-child){margin-left:8px}.SessionPickerView li .user-id{flex:1 1;overflow:hidden;text-overflow:ellipsis}.SessionPickerView li .error{margin:0 20px}.PasswordLoginView{padding:0 .4em .4em}.SessionLoadStatusView>.status,.LoginView_query-spinner{display:flex;gap:12px}.SessionLoadStatusView>.status p,.LoginView_query-spinner p{flex:1 1;margin:0}.SessionLoadStatusView .spinner{--size: 20px}.StartSSOLoginView{display:flex;flex-direction:column;padding:0 .4em}.StartSSOLoginView_button{flex:1 1;margin-top:12px}.LoginView_separator{justify-content:center;display:flex;margin:8px}.CompleteSSOView_title{display:flex;justify-content:center}.LoginView_sso{padding:.4em .4em 0}.LeftPanel{display:flex;flex-direction:column}.LeftPanel .utilities{display:flex}.LeftPanel .utilities .FilterField{flex:1 1;min-width:0}.LeftPanel ul{list-style:none;padding:0;margin:0}.RoomList{flex:1 0;overflow-y:auto;overscroll-behavior:contain}.RoomList>li>a{display:flex;align-items:center}.RoomList .description{margin:0;flex:1 1;min-width:0;display:flex}.RoomList .description>.name{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1 1}.RightPanelView{grid-area:right;min-height:0;min-width:0;display:flex;flex-direction:column}.RoomDetailsView,.MemberDetailsView{flex-direction:column;flex:1 1}.RoomDetailsView_avatar{display:flex}.RoomDetailsView_name h2,.MemberDetailsView_name h2{text-align:center}.RoomDetailsView_label,.RoomDetailsView_row,.RoomDetailsView,.MemberDetailsView,.EncryptionIconView{display:flex;align-items:center;color:var(--text-color)}.RoomDetailsView_value{display:flex;justify-content:flex-end}.EncryptionIconView{justify-content:center}.RightPanelView_buttons{display:flex;justify-content:space-between;width:100%;box-sizing:border-box;padding:16px}.RightPanelView_buttons .hide{visibility:hidden}.MemberTileView a{display:flex;align-items:center}.middle-header{align-items:center}.middle-header h2{flex:1 1}.middle-header button{display:block}.middle-header .room-description{flex:1 1;min-width:0}.RoomHeader .topic{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.RoomHeader .description{flex:1 1 auto;min-width:0}.middle-header h2{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;margin:0}.MessageComposer_replyPreview{display:grid;grid-template-columns:1fr auto}.MessageComposer_replyPreview .Timeline_message{grid-column:1/-1}.MessageComposer_input{display:flex;align-items:center}.MessageComposer_input>input{display:block;flex:1 1;min-width:0;box-sizing:border-box}.TimelineLoadingView{display:flex;align-items:center;justify-content:center}.TimelineLoadingView>:not(:first-child){margin-left:12px}.Timeline{display:flex;flex-direction:column;position:relative;min-height:0}.Timeline_jumpDown{position:absolute}.Timeline_scroller{overflow-y:scroll;overscroll-behavior-y:contain;overflow-anchor:none;padding:0;margin:0;position:relative;min-height:0;flex:1 0}.Timeline_scroller>ul{list-style:none;padding:1px 0;margin:0}.AnnouncementView{display:flex;align-items:center}.GapView{display:flex}.GapView>:nth-child(2){flex:1 1}.Timeline_messageBody img{max-width:400px;max-height:300px}.hydrogen{--avatar-size: 32px}.hydrogen .avatar{width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6);overflow:hidden;flex-shrink:0;user-select:none;text-align:center;speak:none}.hydrogen .avatar img{width:100%;height:100%;object-fit:cover}.hydrogen .avatar.size-128{--avatar-size: 128px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-64{--avatar-size: 64px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-52{--avatar-size: 52px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-30{--avatar-size: 30px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-24{--avatar-size: 24px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-12{--avatar-size: 12px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}@keyframes spinner{0%{transform:rotate(0);stroke-dasharray:0 0 10 90}45%{stroke-dasharray:0 0 90 10}75%{stroke-dasharray:0 50 50 0}to{transform:rotate(360deg);stroke-dasharray:10 90 0 0}}.hydrogen:not(.legacy) .spinner circle{transform-origin:50% 50%;animation-name:spinner;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear;stroke-dasharray:0 0 85 85;fill:none;stroke:currentcolor;stroke-width:12;stroke-linecap:butt}.hydrogen.legacy .spinner{display:inline-block;position:relative}.hydrogen.legacy .spinner div{box-sizing:border-box;display:block;position:absolute;padding:2px;border:2px solid currentcolor;border-radius:50%;animation:legacy-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:currentcolor transparent transparent transparent;width:var(--size);height:var(--size)}.hydrogen.legacy .spinner div:nth-child(1){animation-delay:-.45s}.hydrogen.legacy .spinner div:nth-child(2){animation-delay:-.3s}.hydrogen.legacy .spinner div:nth-child(3){animation-delay:-.15s}@keyframes legacy-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.spinner{--size: 20px;width:var(--size);height:var(--size)}.form-row.text>input,.form-row.text>textarea{display:block;width:100%;min-width:0;box-sizing:border-box}.FilterField{display:flex}.FilterField input{display:block;flex:1 1;min-width:0}.SessionStatusView{display:flex}.SessionStatusView p{margin:0 10px;word-break:break-all;word-break:break-word}body.hydrogen{overscroll-behavior:none;overflow:hidden}.hydrogen{margin:0}.hiddenWithLayout{visibility:hidden}.hidden{display:none!important}input::-ms-clear{display:none}@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(./Inter-Thin.5d8e2ac4.woff2?v=3.13) format("woff2"),url(./Inter-Thin.5565b01e.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(./Inter-ThinItalic.6b3ded18.woff2?v=3.13) format("woff2"),url(./Inter-ThinItalic.c413497b.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(./Inter-ExtraLight.da47c335.woff2?v=3.13) format("woff2"),url(./Inter-ExtraLight.d7be68a4.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(./Inter-ExtraLightItalic.b3f94cfe.woff2?v=3.13) format("woff2"),url(./Inter-ExtraLightItalic.762fa4d2.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(./Inter-Light.0f7dfe72.woff2?v=3.13) format("woff2"),url(./Inter-Light.38326098.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(./Inter-LightItalic.125c7e6a.woff2?v=3.13) format("woff2"),url(./Inter-LightItalic.ec6c76a8.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(./Inter-Regular.89d406b0.woff2?v=3.13) format("woff2"),url(./Inter-Regular.5b3a854b.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(./Inter-Italic.bab4e808.woff2?v=3.13) format("woff2"),url(./Inter-Italic.7b187d57.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(./Inter-Medium.5d308f3d.woff2?v=3.13) format("woff2"),url(./Inter-Medium.0fc5d904.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(./Inter-MediumItalic.76551c20.woff2?v=3.13) format("woff2"),url(./Inter-MediumItalic.1458af9d.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(./Inter-SemiBold.c7c3befe.woff2?v=3.13) format("woff2"),url(./Inter-SemiBold.04cd699f.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(./Inter-SemiBoldItalic.d376ade4.woff2?v=3.13) format("woff2"),url(./Inter-SemiBoldItalic.420db54a.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(./Inter-Bold.6f5e9a23.woff2?v=3.13) format("woff2"),url(./Inter-Bold.20d46cff.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(./Inter-BoldItalic.e09dcbe1.woff2?v=3.13) format("woff2"),url(./Inter-BoldItalic.31a185fa.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(./Inter-ExtraBold.0ef4267e.woff2?v=3.13) format("woff2"),url(./Inter-ExtraBold.45bae435.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(./Inter-ExtraBoldItalic.d1e1f6a0.woff2?v=3.13) format("woff2"),url(./Inter-ExtraBoldItalic.30a1af87.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(./Inter-Black.7f1f5616.woff2?v=3.13) format("woff2"),url(./Inter-Black.067c82f7.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(./Inter-BlackItalic.72d5983b.woff2?v=3.13) format("woff2"),url(./Inter-BlackItalic.c628a2cf.woff?v=3.13) format("woff")}.Timeline_jumpDown{width:40px;height:40px;bottom:16px;right:32px;border-radius:100%;border:1px solid var(--background-color-secondary--darker-7);background-image:var(--icon-url-0);background-position:center;background-color:var(--background-color-primary--darker-10);background-repeat:no-repeat;cursor:pointer}.Timeline_message{display:grid;grid-template:"avatar sender" auto "avatar body" auto "time body" 1fr "time reactions" auto / 30px 1fr;column-gap:8px;padding:4px;margin:0 12px;box-sizing:border-box}.Timeline_message:not(.continuation){margin-top:4px}.ReplyPreviewView .Timeline_message{display:grid;grid-template:"body" auto;margin-left:0;padding:0}.ReplyPreviewView .Timeline_message:not(.continuation){margin-top:0}@media screen and (max-width: 800px){.Timeline_message{grid-template:"avatar sender" auto "body body" 1fr "time time" auto "reactions reactions" auto / 30px 1fr}.Timeline_messageSender{margin-top:0!important;align-self:center}}.Timeline_message:hover:not(.disabled),.Timeline_message.selected,.Timeline_message.menuOpen{background-color:#8d97a51a;border-radius:4px}.Timeline_message:hover>.Timeline_messageOptions,.Timeline_message.menuOpen>.Timeline_messageOptions{display:block;user-select:none}.Timeline_messageAvatar{grid-area:avatar;text-decoration:none}.Timeline_messageSender{grid-area:sender;font-weight:700;line-height:1.7rem}.Timeline_messageSender,.Timeline_messageBody{margin:0;word-break:break-all;word-break:break-word}.Timeline_message:not(.continuation) .Timeline_messageSender,.Timeline_message:not(.continuation) .Timeline_messageBody{margin-top:4px}.Timeline_messageOptions{display:none;grid-area:body;align-self:start;justify-self:end;margin-top:-12px;margin-right:4px;border:var(--background-color-primary--darker-10) 1px solid;height:24px;width:24px;background-color:var(--background-color-primary);color:inherit;border-radius:4px;padding:0;text-align:center;line-height:22px;cursor:pointer}.Timeline_messageTime{grid-area:time}.Timeline_messageBody time{padding:2px 0 0 10px;user-select:none}.Timeline_messageBody time,.Timeline_messageTime{font-size:.8em;line-height:normal;color:var(--timeline-time-text-color)}.Timeline_messageBody.statusMessage{font-style:italic;color:var(--light-text-color)}.Timeline_messageBody{grid-area:body;line-height:2.2rem;width:100%;min-width:0}.hydrogen .Timeline_messageSender.usercolor1{color:var(--usercolor1)}.hydrogen .Timeline_messageSender.usercolor2{color:var(--usercolor2)}.hydrogen .Timeline_messageSender.usercolor3{color:var(--usercolor3)}.hydrogen .Timeline_messageSender.usercolor4{color:var(--usercolor4)}.hydrogen .Timeline_messageSender.usercolor5{color:var(--usercolor5)}.hydrogen .Timeline_messageSender.usercolor6{color:var(--usercolor6)}.hydrogen .Timeline_messageSender.usercolor7{color:var(--usercolor7)}.hydrogen .Timeline_messageSender.usercolor8{color:var(--usercolor8)}.Timeline_messageBody h1,.Timeline_messageBody h2,.Timeline_messageBody h3,.Timeline_messageBody h4,.Timeline_messageBody h5,.Timeline_messageBody h6{font-weight:700;margin:.7em 0}.Timeline_messageBody h1{font-size:1.6em}.Timeline_messageBody h2{font-size:1.5em}.Timeline_messageBody h3{font-size:1.4em}.Timeline_messageBody h4{font-size:1.3em}.Timeline_messageBody h5{font-size:1.2em}.Timeline_messageBody h6{font-size:1.1em}.Timeline_messageBody a{word-break:break-all}.Timeline_messageBody a.link{color:var(--link-color);text-decoration:none}.Timeline_messageBody .media{display:grid;margin-top:4px;width:100%}.Timeline_messageBody .media>a{text-decoration:none;width:100%;display:block}.Timeline_messageBody .media>*{grid-row:1;grid-column:1}.Timeline_messageBody .media img,.Timeline_messageBody .media video{width:100%;height:auto;align-self:start;border-radius:4px;display:block}.hydrogen:not(.legacy) .Timeline_messageBody .media img,.hydrogen:not(.legacy) .Timeline_messageBody .media video{align-self:stretch}.Timeline_messageBody .media>.status{align-self:end;justify-self:start;font-size:.8em}.Timeline_messageBody .media>progress{align-self:center;justify-self:center;width:75%}.Timeline_messageBody .media>time{align-self:end;justify-self:end}.Timeline_messageBody .media>time,.Timeline_messageBody .media>.status{color:var(--text-color);display:block;padding:2px;margin:4px;background-color:#ffffffbf;border-radius:4px}.Timeline_messageBody .media>.spacer{width:100%;align-self:start}.Timeline_messageBody code,.Timeline_messageBody pre{background-color:var(--background-color-secondary);font-family:monospace;font-size:.9em}.Timeline_messageBody code{border-radius:3px;padding:.2em .3em;margin:0}.Timeline_messageBody pre{border:1px solid var(--light-border);padding:.5em;max-height:30em;overflow:auto}.Timeline_messageBody pre>code{background-color:unset;border-radius:unset;display:block;font-size:unset}.Timeline_messageBody blockquote{margin-left:0;padding-left:20px;border-left:4px solid var(--light-border)}.Timeline_messageBody table{border:1px solid var(--background-color-secondary--darker-15);border-radius:2px;border-spacing:0}.Timeline_messageBody thead th{border-bottom:1px solid var(--background-color-secondary--darker-15)}.Timeline_messageBody td,.Timeline_messageBody th{padding:2px 5px}.Timeline_messageBody tbody tr:nth-child(2n){background-color:var(--background-color-secondary)}.Timeline_messageBody .pill{padding:0 5px;border-radius:15px;background-color:var(--background-color-secondary);border:1px solid var(--background-color-secondary--darker-10);text-decoration:none;display:inline-flex;align-items:center;line-height:2rem;vertical-align:top;margin:1px}.Timeline_messageBody .pill div.avatar{display:inline-block;margin-right:3px}.Timeline_message.unsent .Timeline_messageBody{color:var(--light-text-color)}.Timeline_message.unverified .Timeline_messageBody{color:var(--error-color)}.Timeline_messageReactions{grid-area:reactions;margin-top:6px}.Timeline_messageReactions button{display:inline-flex;line-height:2rem;margin-right:6px;padding:1px 6px;border:1px solid var(--light-border);border-radius:10px;background-color:var(--background-color-secondary);color:inherit;cursor:pointer;user-select:none;vertical-align:middle}.Timeline_messageReactions button.active{background-color:var(--background-color-secondary);border-color:var(--accent-color)}@keyframes glow-reaction-border{0%{border-color:var(--background-color-secondary)}to{border-color:var(--accent-color)}}.Timeline_messageReactions button.active.pending{animation-name:glow-reaction-border;animation-duration:.5s;animation-direction:alternate;animation-iteration-count:infinite;animation-timing-function:linear}.Timeline_locationLink{padding:0 8px;border-radius:16px;border:1px solid var(--light-border);background-color:var(--background-color-secondary);text-decoration:none;display:inline-block;line-height:2rem;vertical-align:top;margin:1px 4px}.AnnouncementView{margin:5px 0;padding:5px 10%}.AnnouncementView>div{margin:0 auto;padding:10px 20px;background-color:var(--background-color-secondary);text-align:center;border-radius:10px}.GapView>:not(:first-child){margin-left:12px}.GapView{padding:52px 20px}.GapView.isAtTop{padding:52px 20px 12px}:root{font-size:10px;--icon-color: var(--background-color-secondary--darker-40);--light-border: var(--background-color-secondary--darker-5);--light-text-color: var(--background-color-secondary--darker-55);--timeline-time-text-color: var(--background-color-secondary--darker-35);--icon-background: var(--background-color-secondary--darker-7);--right-panel-text-color: var(--background-color-secondary--darker-35)}.hydrogen{font-family:Inter,sans-serif,"emoji";background-color:var(--background-color-primary);color:var(--text-color);font-size:1.4rem;--usercolor1: #368BD6;--usercolor2: #AC3BA8;--usercolor3: #03B381;--usercolor4: #E64F7A;--usercolor5: #FF812D;--usercolor6: #2DC2C5;--usercolor7: #5C56F5;--usercolor8: #74D12C}.hydrogen button{font-family:inherit}.avatar{border-radius:100%;background:var(--background-color-primary);color:var(--fixed-white)}.hydrogen .avatar.usercolor1{background-color:var(--usercolor1)}.hydrogen .avatar.usercolor2{background-color:var(--usercolor2)}.hydrogen .avatar.usercolor3{background-color:var(--usercolor3)}.hydrogen .avatar.usercolor4{background-color:var(--usercolor4)}.hydrogen .avatar.usercolor5{background-color:var(--usercolor5)}.hydrogen .avatar.usercolor6{background-color:var(--usercolor6)}.hydrogen .avatar.usercolor7{background-color:var(--usercolor7)}.hydrogen .avatar.usercolor8{background-color:var(--usercolor8)}.logo{height:48px;min-width:48px;background-image:var(--icon-url-1);background-repeat:no-repeat;background-position:center}.button-row{display:flex}.button-row>*{margin-right:10px}.button-row>*:last-child{margin-right:0}.button-row .button-action{margin:10px 0;flex:1 0 auto}.form-row.text textarea{font-family:Inter,sans-serif;background-color:var(--background-color-secondary);color:inherit}.form-group{margin:24px 0}.form-row{margin:12px 0}.form-row.text>input,.form-row.text>textarea{padding:12px;border:1px solid var(--light-border);border-radius:8px;margin-top:5px;font-size:1em;resize:vertical;background-color:var(--background-color-secondary);color:inherit}.form-row.check{display:flex;align-items:baseline;gap:4px}.form-row.text>label,.form-row.text>input{display:block}.form-row .form-row-description{font-size:1rem;color:var(--light-text-color);margin:8px 0 0}.button-action{cursor:pointer}a.button-action{text-decoration:none;text-align:center;display:block}.button-action.secondary{color:var(--accent-color)}.button-action.primary{background-color:var(--accent-color);border-radius:8px;color:var(--fixed-white);font-weight:700}.button-action.primary:disabled{color:var(--fixed-white--darker-10)}.button-action.primary.destructive{background-color:var(--error-color)}.button-action.secondary.destructive{color:var(--error-color)}.button-action{border:none;padding:10px;background:none;font-weight:500}.button-utility{cursor:pointer;width:32px;height:32px;background-position:center;background-color:var(--icon-background);background-repeat:no-repeat;border:none;border-radius:100%;display:block}.button-utility.grid{background-image:var(--icon-url-2)}.button-utility.settings{background-image:var(--icon-url-3)}.button-utility.create{background-image:var(--icon-url-4)}.button-utility.grid.on{background-image:var(--icon-url-5)}.FilterField{background-image:var(--icon-url-6);background-repeat:no-repeat;background-position:8px center;background-color:var(--icon-background);border:1px solid transparent;border-radius:16px;height:32px;align-items:center;padding-left:30px;box-sizing:border-box}.FilterField:focus-within{border:1px var(--icon-background) solid;background-color:var(--background-color-primary)}.FilterField:focus-within button{border-color:var(--background-color-primary)}.FilterField input{font-family:Inter;font-size:1.3rem;font-weight:500;line-height:1.573rem;outline:none;border:none;background-color:transparent;height:100%;color:var(--text-color)}.FilterField button{width:30px;height:30px;background-position:center;background-color:var(--icon-background);background-repeat:no-repeat;background-image:var(--icon-url-7);border:7px solid transparent;border-radius:100%;box-sizing:border-box}.PreSessionScreen{padding:30px}.PreSessionScreen h1{font-size:16px;text-align:center}.SessionLoadView{padding-top:16px}.StartSSOLoginView_button{border:1px solid var(--accent-color);border-radius:8px}.LoginView_back{background-image:var(--icon-url-8);background-color:transparent}.LoginView_separator{font-weight:500;font-size:1.5rem}.LoginView_forwardInfo{font-size:.9em;margin-left:1em;color:var(--light-text-color)}.CompleteSSOView_title{font-weight:500}@media screen and (min-width: 600px){.PreSessionScreen{box-shadow:0 6px 32px #0000001a;border-radius:8px}}.PreSessionScreen .logo{height:48px;min-width:48px}.LeftPanel{background:var(--background-color-secondary);font-size:1.5rem;padding:12px 8px 0}.LeftPanel>:not(:first-child){margin-top:12px}.LeftPanel .utilities>:not(:first-child){margin-left:8px}.LeftPanel .filter{border-bottom:1px solid var(--background-color-secondary)}.LeftPanel .filter input{padding:.8em;border:none}.LeftPanel .RoomList{padding:0 8px 0 0;margin-right:-8px}.RoomList>li{margin:0;padding:4px 8px 4px 0;align-items:center}.RoomList>li>a{text-decoration:none;align-items:center}.RoomList li:not(:first-child){margin-top:4px}.RoomList li.active{background:var(--background-color-secondary--darker-7);border-radius:5px}.RoomList li>a>*{margin-right:8px}.RoomList .description{align-items:center}.RoomList .name.unread{font-weight:600}.RoomList .badge{min-width:1.6rem;height:1.6rem;border-radius:1.6rem;box-sizing:border-box;padding:.1rem .3rem;background-color:var(--room-badge);color:var(--fixed-white);font-weight:700;font-size:1rem;line-height:1.4rem;text-align:center}.RoomList .badge.highlighted{background-color:var(--error-color)}a{color:inherit}.SessionStatusView{padding:4px;min-height:22px;background-color:var(--accent-color);color:var(--fixed-white);align-items:center}.SessionStatusView button.link{color:currentcolor;text-align:left}.SessionStatusView>.end{flex:1 1;display:flex;justify-content:flex-end;align-self:stretch;align-items:stretch}.SessionStatusView .dismiss{border:none;background:none;background-image:var(--icon-url-9);background-position:center;background-repeat:no-repeat;width:32px;cursor:pointer}.room-placeholder{align-items:center;justify-content:center;text-align:center;padding:20px}.SessionPickerView li{font-size:1.2em}.SessionPickerView .session-info{text-decoration:none;padding:12px;border:1px solid var(--light-border);border-radius:8px;background-image:var(--icon-url-10);background-position:center right 30px;background-repeat:no-repeat;font-weight:500}.SessionPickerView .session-actions{margin:10px 0 20px;display:flex}.SessionPickerView .session-actions>*{margin-right:10px}.SessionPickerView .session-actions>*:last-child{margin-right:0}.SessionPickerView .session-actions button{border:none;background:none;color:inherit}.SessionPickerView button.destructive{color:var(--error-color)}.RoomGridView>div.container{border-right:1px solid var(--background-color-secondary);border-bottom:1px solid var(--background-color-secondary)}.RoomGridView>.focused>.room-placeholder .unfocused{display:none}.RoomGridView>:not(.focused)>.room-placeholder .focused{display:none}.room-placeholder .unfocused{color:var(--right-panel-text-color)}.RoomGridView>div.focus-ring{border:2px solid var(--accent-color--darker-5);border-radius:12px}.middle-header{box-sizing:border-box;flex:0 0 56px;background:var(--background-color-primary);padding:0 16px;border-bottom:1px solid var(--background-color-secondary)}.middle-header h2{font-size:1.8rem;font-weight:600}.middle-header>:not(:last-child){margin-right:8px}.close-middle,.close-session{background-image:var(--icon-url-11);background-position-x:10px}.RoomHeader .topic{font-size:14rem}.RoomHeader .room-options{background-image:var(--icon-url-12)}.RoomView_error{color:var(--error-color);background:#efefef;height:0px;font-weight:700;transition:.25s all ease-out;padding-right:20px;padding-left:20px}.RoomView_error div{overflow:hidden;height:100%;width:100%;position:relative;display:flex;align-items:center}.RoomView_error:not(:empty){height:auto;padding-top:20px;padding-bottom:20px}.RoomView_error p{position:relative;display:block;width:100%;height:auto;margin:0}.RoomView_error button{width:40px;padding-top:20px;padding-bottom:20px;background:none;border:none;position:relative;border-radius:5px;transition:.1s all ease-out;cursor:pointer}.RoomView_error button:hover{background:#cfcfcf}.RoomView_error button:before{content:"\274c";position:absolute;top:15px;left:9px;width:20px;height:10px;font-size:10px;align-self:middle}.MessageComposer_replyPreview .Timeline_message{margin:5px 0 0;max-height:30vh;overflow:auto}.MessageComposer_replyPreview{background:var(--background-color-secondary);margin:0 10px 10px;box-shadow:0 0 5px var(--background-color-secondary--darker-15);border-radius:5px}.MessageComposer_input,.MessageComposer_replyPreview{padding:8px}.MessageComposer_replyPreview>.replying{display:inline-flex;flex-direction:row;align-items:center;font-weight:700}.MessageComposer_replyPreview>button.cancel{width:32px;height:32px;display:block;border:none;text-indent:200%;white-space:nowrap;overflow:hidden;background-color:transparent;background-image:var(--icon-url-13);background-repeat:no-repeat;background-position:center;background-size:18px;cursor:pointer}.MessageComposer_input:first-child{border-top:1px solid var(--background-color-secondary)}.MessageComposer_input>:not(:first-child){margin-left:12px}.MessageComposer_input>textarea{border:none;border-radius:24px;background:var(--background-color-secondary);color:inherit;font-size:14px;font-family:Inter,sans-serif;resize:none;flex:1 1;padding:14px;box-sizing:border-box;overflow:hidden;max-height:113px;overflow-y:auto;overflow-y:overlay}.MessageComposer_input>button.send{width:32px;height:32px;display:block;border-radius:100%;border:none;text-indent:200%;overflow:hidden;background-color:var(--accent-color);background-image:var(--icon-url-14);background-repeat:no-repeat;background-position:center;align-self:end;margin-bottom:8px}.MessageComposer_input>button.sendFile{width:32px;height:32px;display:block;border:none;text-indent:200%;white-space:nowrap;overflow:hidden;background-color:transparent;background-image:var(--icon-url-15);background-repeat:no-repeat;background-position:center}.MessageComposer.MessageComposer_canSend button.sendFile{display:none}.MessageComposer:not(.MessageComposer_canSend) button.send{display:none}.SettingsBody{padding:0 16px}.Settings h3{margin:16px 0 8px}.Settings p{max-width:700px}.Settings .row .label{font-weight:600}.Settings .row .label,.Settings .row .content{margin-top:4px;margin-bottom:4px}.Settings .row .content{margin-left:4px;flex:1 1}.Settings .row.code .content{font-family:monospace}.Settings .row .content button{display:inline-block;margin:0 8px}.Settings .row .content input[type=range]{width:100%;max-width:300px;min-width:160px}.Settings .row{margin:4px 0;display:flex;flex-wrap:wrap;align-items:center}.Settings .row .label{flex:0 0 200px;align-self:flex-start}.Settings .row .content p{margin:8px 0}.Settings .row .content p:first-child{margin-top:0}.Settings .row .content p:last-child{margin-bottom:0}.error{color:var(--error-color);font-weight:600}button.link{font-size:1em;border:none;text-decoration:underline;background:none;cursor:pointer;margin:-12px;padding:12px;color:inherit}.Settings a,.Settings .link{color:var(--accent-color);font-weight:600}.lightbox{background-color:#000000bf;display:grid;grid-template:"content close" auto "content details" 1fr / 1fr auto;color:var(--background-color-primary);padding:4px}@media (max-aspect-ratio: 1/1){.lightbox{grid-template:"close" auto "content" 1fr "details" auto / 1fr}.lightbox .details{width:100%!important}}.lightbox .picture{grid-area:content;background-size:contain;background-position:center;background-repeat:no-repeat;width:100%;height:100%;align-self:center;justify-self:center}.lightbox .loading{grid-area:content;align-self:center;justify-self:center;display:flex}.lightbox .loading>:not(:first-child){margin-left:8px}.lightbox .close{display:block;grid-area:close;justify-self:end;background-image:var(--icon-url-16);background-position:center;background-size:16px;background-repeat:no-repeat;width:16px;height:16px;padding:12px}.lightbox .details{grid-area:details;padding:12px;font-size:1.5rem;width:200px}.menu{border-radius:8px;box-shadow:2px 2px 10px #00000080;padding:4px;background-color:var(--background-color-primary);list-style:none;margin:0}.menu li{margin-bottom:10px}.menu .menu-item{color:var(--text-color)}.menu button{border-radius:4px;border:none;background-color:transparent;text-align:left;padding:8px 32px 8px 8px;font-size:1.5rem;height:24px;cursor:pointer}.menu .destructive button{color:var(--error-color)}.menu .quick-reactions{display:flex;padding:8px 32px 8px 8px}.menu .quick-reactions button{padding:2px 4px;text-align:center}.InviteView_body{display:flex;justify-content:space-around;align-items:center;flex:1 1;overflow:auto}.InviteView_invite{display:flex;width:100%;max-width:400px;flex-direction:column;padding:0 24px}.InviteView_roomProfile{display:grid;gap:4px;grid-template:"avatar name" auto "avatar description" 1fr / 72px 1fr;align-self:center;margin-bottom:24px}.InviteView_roomProfile h3{grid-area:name;margin:0}.InviteView_roomDescription{grid-area:description;font-size:1.2rem;margin:0;color:var(--light-text-color)}.InviteView_roomAvatar{grid-area:avatar}.InviteView_dmAvatar{align-self:center}.InviteView_inviter{text-align:center;margin:24px 0}.InviteView_inviter .avatar{display:inline-block;vertical-align:middle;margin-right:4px}.InviteView_buttonRow{margin:10px auto;max-width:200px;width:100%}.InviteView_buttonRow button{display:block;width:100%}.DisabledComposerView{padding:12px;background-color:var(--background-color-secondary)}.DisabledComposerView h3{margin:0}.UnknownRoomView{align-items:center;justify-content:center;text-align:center;padding:16px;box-sizing:border-box}.UnknownRoomView h2{word-break:break-all;word-break:break-word}.UnknownRoomView button{max-width:200px;width:100%}.LoadingView{height:100%;width:100%}.LoadingView .spinner{margin-right:5px}.RightPanelView{background:var(--background-color-secondary)}.RoomDetailsView{padding:0 16px 16px}.RoomDetailsView_id,.MemberDetailsView_id{color:var(--right-panel-text-color);font-size:12px}.RoomDetailsView_rows{margin-top:36px;width:100%}.RoomDetailsView_name h2,.MemberDetailsView_name h2{margin-bottom:4px;font-size:1.8rem}.RoomDetailsView_row{margin-bottom:20px;font-weight:500;font-size:15px;width:100%;background:none;border:none;padding:0}button.RoomDetailsView_row{cursor:pointer}button.RoomDetailsView_row:after{content:var(--icon-url-17);margin-left:12px}.RoomDetailsView_row:not(button):after{content:" ";width:19px}.RoomDetailsView_label:before{padding-right:16px;height:24px;width:20px}.RoomDetailsView_label{width:200px}.RoomDetailsView_value{color:var(--right-panel-text-color);flex:1 1}.MemberCount:before{content:var(--icon-url-18)}.EncryptionStatus:before{content:var(--icon-url-19)}.EncryptionIconView{width:52px;height:52px;border-radius:100%;background:var(--right-panel-text-color);border:3px solid var(--background-color-secondary);margin-left:-16px}.EncryptionIconView_encrypted,.EncryptionIconView_unencrypted{height:24px;width:24px}.EncryptionIconView_encrypted{content:var(--icon-url-20)}.EncryptionIconView_unencrypted{content:var(--icon-url-21)}.RightPanelView_buttons .button-utility{width:24px;height:24px}.RightPanelView_buttons .close{background-image:var(--icon-url-22)}.RightPanelView_buttons .back{background-image:var(--icon-url-23)}.MemberListView{padding-left:16px;padding-right:16px;margin:0}.MemberTileView{margin-bottom:8px;list-style:none}.MemberTileView a{text-decoration:none}.MemberTileView .avatar{margin-right:8px}.MemberTileView_name{text-overflow:ellipsis;overflow:hidden;white-space:nowrap;flex:1 1}.MemberDetailsView_section{box-sizing:border-box;padding:16px;width:100%}.MemberDetailsView_label{font-size:12px;font-weight:600;color:var(--right-panel-text-color);text-transform:uppercase}.MemberDetailsView_value,.MemberDetailsView_options{margin-left:8px;margin-top:5px;font-size:12px}.MemberDetailsView_options{display:inline-flex;flex-direction:column}.MemberDetailsView_options a,.MemberDetailsView_options button{color:var(--accent-color);text-decoration:none;margin:0 0 3px;padding:0;border:none;background:none;cursor:pointer}.LazyListParent{overflow-y:auto}.LogoutScreen{height:100vh}.LogoutScreen .content{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center}.LogoutScreen .status{display:flex;gap:12px}.CreateRoomView,.RoomBeingCreated_error{max-width:400px}.RoomBeingCreated_error{margin-top:48px}.centered-column{padding:0 12px;align-self:center;width:100%;box-sizing:border-box}.CreateRoomView_selectAvatar{border:none;background:none;cursor:pointer}.CreateRoomView_selectAvatarPlaceholder{width:64px;height:64px;border-radius:100%;background-color:var(--icon-background);background-image:var(--icon-url-24);background-repeat:no-repeat;background-position:center;background-size:36px}:root{--background-color-primary: #fff;--background-color-secondary: #f6f6f6;--text-color: #2E2F32;--accent-color: #03b381;--error-color: #FF4B55;--fixed-white: #fff;--room-badge: #61708b;--link-color: #238cf5}:root{--background-color-secondary--darker-7: #e4e4e4;--background-color-primary--darker-10: #e6e6e6;--background-color-secondary--darker-15: #d0d0d0;--background-color-secondary--darker-10: #dddddd;--background-color-secondary--darker-40: #909090;--background-color-secondary--darker-5: #e9e9e9;--background-color-secondary--darker-55: #6a6a6a;--background-color-secondary--darker-35: #9d9d9d;--fixed-white--darker-10: #e6e6e6;--accent-color--darker-5: #039a6f}:root{--icon-url-0: url(./chevron-down-3300400168.d1a083a1.svg);--icon-url-1: url(./element-logo-703176763.fc54fc8d.svg);--icon-url-2: url(./enable-grid-2071838379.ab4f40c5.svg);--icon-url-3: url(./settings-2175246113.00804666.svg);--icon-url-4: url(./plus-4190356069.084c5e3d.svg);--icon-url-5: url(./disable-grid-3304422220.8a79cfcb.svg);--icon-url-6: url(./search-3263540198.1511780c.svg);--icon-url-7: url(./clear-426756705.361f7a30.svg);--icon-url-8: url(./chevron-left-3506338632.4e437777.svg);--icon-url-9: url(./dismiss-2743697487.2f1a17f1.svg);--icon-url-10: url(./chevron-right-847198822.23380c56.svg);--icon-url-11: url(./chevron-left-3506338632.4e437777.svg);--icon-url-12: url(./vertical-ellipsis-3416547705.f619a721.svg);--icon-url-13: url(./clear-426756705.361f7a30.svg);--icon-url-14: url(./send-1171052351.caa5c494.svg);--icon-url-15: url(./paperclip-2441131778.1f5e29f3.svg);--icon-url-16: url(./dismiss-2743697487.2f1a17f1.svg);--icon-url-17: url(./chevron-small-781914114.936b4943.svg);--icon-url-18: url(./room-members-3847743605.9fcf4567.svg);--icon-url-19: url(./encryption-status-475927392.2fedc0bd.svg);--icon-url-20: url(./e2ee-normal-1448349558.af8f5484.svg);--icon-url-21: url(./e2ee-disabled-1470792300.6863c16d.svg);--icon-url-22: url(./clear-426756705.361f7a30.svg);--icon-url-23: url(./chevron-thin-left-3831175135.13f60c05.svg);--icon-url-24: url(./plus-4190356069.084c5e3d.svg)} diff --git a/assets/theme-element-runtime.8f0a458e.css b/assets/theme-element-runtime.8f0a458e.css new file mode 100644 index 00000000..b1009dcc --- /dev/null +++ b/assets/theme-element-runtime.8f0a458e.css @@ -0,0 +1 @@ +@font-face{font-family:"emoji";src:local("Apple Color Emoji"),local("Segoe UI Emoji"),local("Segoe UI Symbol"),local("Noto Color Emoji"),local("Twemoji"),local("Twemoji Mozilla"),local("Android Emoji"),local("EmojiSymbols"),local("Symbola");unicode-range:U+1F300-1F5FF,U+1F600-1F64F,U+1F680-1F6FF,U+2600-26FF}html{height:100%}main{display:block}@media screen and (min-width: 600px){.PreSessionScreen{width:600px;box-sizing:border-box;margin:50px auto 0}}.room-placeholder{display:flex;flex-direction:row}.SessionView{position:fixed;height:100%;width:100%;display:grid;grid-template:"status status" auto "left middle" 1fr / 320px 1fr;min-height:0;min-width:0}.right-shown{grid-template:"status status status" auto "left middle right" 1fr / 320px 1fr 300px}.hydrogen.ios .SessionView{height:var(--ios-viewport-height, 100%);top:var(--ios-viewport-top, 0)}.middle .close-middle{display:none}@media screen and (max-width: 800px){.SessionView:not(.middle-shown):not(.right-shown){grid-template:"status" auto "left" 1fr / 1fr}.SessionView.middle-shown{grid-template:"status" auto "middle" 1fr / 1fr}.SessionView.right-shown{grid-template:"status" auto "right" 1fr / 1fr}.SessionView:not(.middle-shown):not(.right-shown) .room-placeholder{display:none}.SessionView.middle-shown .LeftPanel,.SessionView.right-shown .middle,.SessionView.right-shown .LeftPanel{display:none}.middle .close-middle{display:block!important}.LeftPanel .grid{display:none!important}}.LeftPanel{grid-area:left;min-width:0;min-height:0}.room-placeholder,.middle{min-width:0;grid-area:middle;width:100%;min-height:0}.middle{display:flex;flex-direction:column}.SessionStatusView{grid-area:status}.lightbox{position:absolute;top:0;bottom:0;left:0;right:0;z-index:1;box-sizing:border-box;height:100%}.RoomView_body{flex:1 1;min-height:0;min-width:0;display:flex;flex-direction:column;height:100%}.RoomView_body .Timeline,.RoomView_body .TimelineLoadingView{flex:1 0}.middle-header{display:flex}.RoomGridView{display:grid}.RoomGridView.layout3x2{grid-template:"t0 t1 t2" 1fr "t3 t4 t5" 1fr / 1fr 1fr 1fr}.RoomGridView>.tile0{grid-area:t0}.RoomGridView>.tile1{grid-area:t1}.RoomGridView>.tile2{grid-area:t2}.RoomGridView>.tile3{grid-area:t3}.RoomGridView>.tile4{grid-area:t4}.RoomGridView>.tile5{grid-area:t5}.RoomGridView>div{display:flex;min-width:0;min-height:0}.RoomGridView>div.focus-ring{z-index:1;pointer-events:none}.menu{position:absolute;z-index:2}.menu .menu-item{box-sizing:border-box;width:100%}.Settings{display:flex;flex-direction:column}.SettingsBody{min-height:0;overflow-y:auto}.LazyListParent{flex:1 1}.LoadingView{display:flex;justify-content:center;align-items:center}.vertical-layout{display:flex;flex-direction:row;align-items:center;gap:12px}.vertical-layout>.stretch{flex:1 0}.popupContainer{position:absolute;white-space:nowrap}.SessionPickerView{padding:.4em}.SessionPickerView ul{list-style:none;padding:0}.SessionPickerView li{margin:.4em 0}.SessionPickerView .session-info{cursor:pointer;display:flex;align-items:center}.SessionPickerView .session-info>:not(:first-child){margin-left:8px}.SessionPickerView li .user-id{flex:1 1;overflow:hidden;text-overflow:ellipsis}.SessionPickerView li .error{margin:0 20px}.PasswordLoginView{padding:0 .4em .4em}.SessionLoadStatusView>.status,.LoginView_query-spinner{display:flex;gap:12px}.SessionLoadStatusView>.status p,.LoginView_query-spinner p{flex:1 1;margin:0}.SessionLoadStatusView .spinner{--size: 20px}.StartSSOLoginView{display:flex;flex-direction:column;padding:0 .4em}.StartSSOLoginView_button{flex:1 1;margin-top:12px}.LoginView_separator{justify-content:center;display:flex;margin:8px}.CompleteSSOView_title{display:flex;justify-content:center}.LoginView_sso{padding:.4em .4em 0}.LeftPanel{display:flex;flex-direction:column}.LeftPanel .utilities{display:flex}.LeftPanel .utilities .FilterField{flex:1 1;min-width:0}.LeftPanel ul{list-style:none;padding:0;margin:0}.RoomList{flex:1 0;overflow-y:auto;overscroll-behavior:contain}.RoomList>li>a{display:flex;align-items:center}.RoomList .description{margin:0;flex:1 1;min-width:0;display:flex}.RoomList .description>.name{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;flex:1 1}.RightPanelView{grid-area:right;min-height:0;min-width:0;display:flex;flex-direction:column}.RoomDetailsView,.MemberDetailsView{flex-direction:column;flex:1 1}.RoomDetailsView_avatar{display:flex}.RoomDetailsView_name h2,.MemberDetailsView_name h2{text-align:center}.RoomDetailsView_label,.RoomDetailsView_row,.RoomDetailsView,.MemberDetailsView,.EncryptionIconView{display:flex;align-items:center;color:var(--text-color)}.RoomDetailsView_value{display:flex;justify-content:flex-end}.EncryptionIconView{justify-content:center}.RightPanelView_buttons{display:flex;justify-content:space-between;width:100%;box-sizing:border-box;padding:16px}.RightPanelView_buttons .hide{visibility:hidden}.MemberTileView a{display:flex;align-items:center}.middle-header{align-items:center}.middle-header h2{flex:1 1}.middle-header button{display:block}.middle-header .room-description{flex:1 1;min-width:0}.RoomHeader .topic{overflow:hidden;white-space:nowrap;text-overflow:ellipsis}.RoomHeader .description{flex:1 1 auto;min-width:0}.middle-header h2{overflow:hidden;white-space:nowrap;text-overflow:ellipsis;margin:0}.MessageComposer_replyPreview{display:grid;grid-template-columns:1fr auto}.MessageComposer_replyPreview .Timeline_message{grid-column:1/-1}.MessageComposer_input{display:flex;align-items:center}.MessageComposer_input>input{display:block;flex:1 1;min-width:0;box-sizing:border-box}.TimelineLoadingView{display:flex;align-items:center;justify-content:center}.TimelineLoadingView>:not(:first-child){margin-left:12px}.Timeline{display:flex;flex-direction:column;position:relative;min-height:0}.Timeline_jumpDown{position:absolute}.Timeline_scroller{overflow-y:scroll;overscroll-behavior-y:contain;overflow-anchor:none;padding:0;margin:0;position:relative;min-height:0;flex:1 0}.Timeline_scroller>ul{list-style:none;padding:1px 0;margin:0}.AnnouncementView{display:flex;align-items:center}.GapView{display:flex}.GapView>:nth-child(2){flex:1 1}.Timeline_messageBody img{max-width:400px;max-height:300px}.hydrogen{--avatar-size: 32px}.hydrogen .avatar{width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6);overflow:hidden;flex-shrink:0;user-select:none;text-align:center;speak:none}.hydrogen .avatar img{width:100%;height:100%;object-fit:cover}.hydrogen .avatar.size-128{--avatar-size: 128px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-64{--avatar-size: 64px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-52{--avatar-size: 52px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-30{--avatar-size: 30px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-24{--avatar-size: 24px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}.hydrogen .avatar.size-12{--avatar-size: 12px;width:var(--avatar-size);height:var(--avatar-size);line-height:var(--avatar-size);font-size:calc(var(--avatar-size) * .6)}@keyframes spinner{0%{transform:rotate(0);stroke-dasharray:0 0 10 90}45%{stroke-dasharray:0 0 90 10}75%{stroke-dasharray:0 50 50 0}to{transform:rotate(360deg);stroke-dasharray:10 90 0 0}}.hydrogen:not(.legacy) .spinner circle{transform-origin:50% 50%;animation-name:spinner;animation-duration:2s;animation-iteration-count:infinite;animation-timing-function:linear;stroke-dasharray:0 0 85 85;fill:none;stroke:currentcolor;stroke-width:12;stroke-linecap:butt}.hydrogen.legacy .spinner{display:inline-block;position:relative}.hydrogen.legacy .spinner div{box-sizing:border-box;display:block;position:absolute;padding:2px;border:2px solid currentcolor;border-radius:50%;animation:legacy-spinner 1.2s cubic-bezier(.5,0,.5,1) infinite;border-color:currentcolor transparent transparent transparent;width:var(--size);height:var(--size)}.hydrogen.legacy .spinner div:nth-child(1){animation-delay:-.45s}.hydrogen.legacy .spinner div:nth-child(2){animation-delay:-.3s}.hydrogen.legacy .spinner div:nth-child(3){animation-delay:-.15s}@keyframes legacy-spinner{0%{transform:rotate(0)}to{transform:rotate(360deg)}}.spinner{--size: 20px;width:var(--size);height:var(--size)}.form-row.text>input,.form-row.text>textarea{display:block;width:100%;min-width:0;box-sizing:border-box}.FilterField{display:flex}.FilterField input{display:block;flex:1 1;min-width:0}.SessionStatusView{display:flex}.SessionStatusView p{margin:0 10px;word-break:break-all;word-break:break-word}body.hydrogen{overscroll-behavior:none;overflow:hidden}.hydrogen{margin:0}.hiddenWithLayout{visibility:hidden}.hidden{display:none!important}input::-ms-clear{display:none}@font-face{font-family:Inter;font-style:normal;font-weight:100;font-display:swap;src:url(./Inter-Thin.5d8e2ac4.woff2?v=3.13) format("woff2"),url(./Inter-Thin.5565b01e.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:100;font-display:swap;src:url(./Inter-ThinItalic.6b3ded18.woff2?v=3.13) format("woff2"),url(./Inter-ThinItalic.c413497b.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:200;font-display:swap;src:url(./Inter-ExtraLight.da47c335.woff2?v=3.13) format("woff2"),url(./Inter-ExtraLight.d7be68a4.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:200;font-display:swap;src:url(./Inter-ExtraLightItalic.b3f94cfe.woff2?v=3.13) format("woff2"),url(./Inter-ExtraLightItalic.762fa4d2.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:300;font-display:swap;src:url(./Inter-Light.0f7dfe72.woff2?v=3.13) format("woff2"),url(./Inter-Light.38326098.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:300;font-display:swap;src:url(./Inter-LightItalic.125c7e6a.woff2?v=3.13) format("woff2"),url(./Inter-LightItalic.ec6c76a8.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:400;font-display:swap;src:url(./Inter-Regular.89d406b0.woff2?v=3.13) format("woff2"),url(./Inter-Regular.5b3a854b.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:400;font-display:swap;src:url(./Inter-Italic.bab4e808.woff2?v=3.13) format("woff2"),url(./Inter-Italic.7b187d57.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:500;font-display:swap;src:url(./Inter-Medium.5d308f3d.woff2?v=3.13) format("woff2"),url(./Inter-Medium.0fc5d904.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:500;font-display:swap;src:url(./Inter-MediumItalic.76551c20.woff2?v=3.13) format("woff2"),url(./Inter-MediumItalic.1458af9d.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:600;font-display:swap;src:url(./Inter-SemiBold.c7c3befe.woff2?v=3.13) format("woff2"),url(./Inter-SemiBold.04cd699f.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:600;font-display:swap;src:url(./Inter-SemiBoldItalic.d376ade4.woff2?v=3.13) format("woff2"),url(./Inter-SemiBoldItalic.420db54a.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:700;font-display:swap;src:url(./Inter-Bold.6f5e9a23.woff2?v=3.13) format("woff2"),url(./Inter-Bold.20d46cff.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:700;font-display:swap;src:url(./Inter-BoldItalic.e09dcbe1.woff2?v=3.13) format("woff2"),url(./Inter-BoldItalic.31a185fa.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:800;font-display:swap;src:url(./Inter-ExtraBold.0ef4267e.woff2?v=3.13) format("woff2"),url(./Inter-ExtraBold.45bae435.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:800;font-display:swap;src:url(./Inter-ExtraBoldItalic.d1e1f6a0.woff2?v=3.13) format("woff2"),url(./Inter-ExtraBoldItalic.30a1af87.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:normal;font-weight:900;font-display:swap;src:url(./Inter-Black.7f1f5616.woff2?v=3.13) format("woff2"),url(./Inter-Black.067c82f7.woff?v=3.13) format("woff")}@font-face{font-family:Inter;font-style:italic;font-weight:900;font-display:swap;src:url(./Inter-BlackItalic.72d5983b.woff2?v=3.13) format("woff2"),url(./Inter-BlackItalic.c628a2cf.woff?v=3.13) format("woff")}.Timeline_jumpDown{width:40px;height:40px;bottom:16px;right:32px;border-radius:100%;border:1px solid var(--background-color-secondary--darker-7);background-image:var(--icon-url-0);background-position:center;background-color:var(--background-color-primary--darker-10);background-repeat:no-repeat;cursor:pointer}.Timeline_message{display:grid;grid-template:"avatar sender" auto "avatar body" auto "time body" 1fr "time reactions" auto / 30px 1fr;column-gap:8px;padding:4px;margin:0 12px;box-sizing:border-box}.Timeline_message:not(.continuation){margin-top:4px}.ReplyPreviewView .Timeline_message{display:grid;grid-template:"body" auto;margin-left:0;padding:0}.ReplyPreviewView .Timeline_message:not(.continuation){margin-top:0}@media screen and (max-width: 800px){.Timeline_message{grid-template:"avatar sender" auto "body body" 1fr "time time" auto "reactions reactions" auto / 30px 1fr}.Timeline_messageSender{margin-top:0!important;align-self:center}}.Timeline_message:hover:not(.disabled),.Timeline_message.selected,.Timeline_message.menuOpen{background-color:#8d97a51a;border-radius:4px}.Timeline_message:hover>.Timeline_messageOptions,.Timeline_message.menuOpen>.Timeline_messageOptions{display:block;user-select:none}.Timeline_messageAvatar{grid-area:avatar;text-decoration:none}.Timeline_messageSender{grid-area:sender;font-weight:700;line-height:1.7rem}.Timeline_messageSender,.Timeline_messageBody{margin:0;word-break:break-all;word-break:break-word}.Timeline_message:not(.continuation) .Timeline_messageSender,.Timeline_message:not(.continuation) .Timeline_messageBody{margin-top:4px}.Timeline_messageOptions{display:none;grid-area:body;align-self:start;justify-self:end;margin-top:-12px;margin-right:4px;border:var(--background-color-primary--darker-10) 1px solid;height:24px;width:24px;background-color:var(--background-color-primary);color:inherit;border-radius:4px;padding:0;text-align:center;line-height:22px;cursor:pointer}.Timeline_messageTime{grid-area:time}.Timeline_messageBody time{padding:2px 0 0 10px;user-select:none}.Timeline_messageBody time,.Timeline_messageTime{font-size:.8em;line-height:normal;color:var(--timeline-time-text-color)}.Timeline_messageBody.statusMessage{font-style:italic;color:var(--light-text-color)}.Timeline_messageBody{grid-area:body;line-height:2.2rem;width:100%;min-width:0}.hydrogen .Timeline_messageSender.usercolor1{color:var(--usercolor1)}.hydrogen .Timeline_messageSender.usercolor2{color:var(--usercolor2)}.hydrogen .Timeline_messageSender.usercolor3{color:var(--usercolor3)}.hydrogen .Timeline_messageSender.usercolor4{color:var(--usercolor4)}.hydrogen .Timeline_messageSender.usercolor5{color:var(--usercolor5)}.hydrogen .Timeline_messageSender.usercolor6{color:var(--usercolor6)}.hydrogen .Timeline_messageSender.usercolor7{color:var(--usercolor7)}.hydrogen .Timeline_messageSender.usercolor8{color:var(--usercolor8)}.Timeline_messageBody h1,.Timeline_messageBody h2,.Timeline_messageBody h3,.Timeline_messageBody h4,.Timeline_messageBody h5,.Timeline_messageBody h6{font-weight:700;margin:.7em 0}.Timeline_messageBody h1{font-size:1.6em}.Timeline_messageBody h2{font-size:1.5em}.Timeline_messageBody h3{font-size:1.4em}.Timeline_messageBody h4{font-size:1.3em}.Timeline_messageBody h5{font-size:1.2em}.Timeline_messageBody h6{font-size:1.1em}.Timeline_messageBody a{word-break:break-all}.Timeline_messageBody a.link{color:var(--link-color);text-decoration:none}.Timeline_messageBody .media{display:grid;margin-top:4px;width:100%}.Timeline_messageBody .media>a{text-decoration:none;width:100%;display:block}.Timeline_messageBody .media>*{grid-row:1;grid-column:1}.Timeline_messageBody .media img,.Timeline_messageBody .media video{width:100%;height:auto;align-self:start;border-radius:4px;display:block}.hydrogen:not(.legacy) .Timeline_messageBody .media img,.hydrogen:not(.legacy) .Timeline_messageBody .media video{align-self:stretch}.Timeline_messageBody .media>.status{align-self:end;justify-self:start;font-size:.8em}.Timeline_messageBody .media>progress{align-self:center;justify-self:center;width:75%}.Timeline_messageBody .media>time{align-self:end;justify-self:end}.Timeline_messageBody .media>time,.Timeline_messageBody .media>.status{color:var(--text-color);display:block;padding:2px;margin:4px;background-color:#ffffffbf;border-radius:4px}.Timeline_messageBody .media>.spacer{width:100%;align-self:start}.Timeline_messageBody code,.Timeline_messageBody pre{background-color:var(--background-color-secondary);font-family:monospace;font-size:.9em}.Timeline_messageBody code{border-radius:3px;padding:.2em .3em;margin:0}.Timeline_messageBody pre{border:1px solid var(--light-border);padding:.5em;max-height:30em;overflow:auto}.Timeline_messageBody pre>code{background-color:unset;border-radius:unset;display:block;font-size:unset}.Timeline_messageBody blockquote{margin-left:0;padding-left:20px;border-left:4px solid var(--light-border)}.Timeline_messageBody table{border:1px solid var(--background-color-secondary--darker-15);border-radius:2px;border-spacing:0}.Timeline_messageBody thead th{border-bottom:1px solid var(--background-color-secondary--darker-15)}.Timeline_messageBody td,.Timeline_messageBody th{padding:2px 5px}.Timeline_messageBody tbody tr:nth-child(2n){background-color:var(--background-color-secondary)}.Timeline_messageBody .pill{padding:0 5px;border-radius:15px;background-color:var(--background-color-secondary);border:1px solid var(--background-color-secondary--darker-10);text-decoration:none;display:inline-flex;align-items:center;line-height:2rem;vertical-align:top;margin:1px}.Timeline_messageBody .pill div.avatar{display:inline-block;margin-right:3px}.Timeline_message.unsent .Timeline_messageBody{color:var(--light-text-color)}.Timeline_message.unverified .Timeline_messageBody{color:var(--error-color)}.Timeline_messageReactions{grid-area:reactions;margin-top:6px}.Timeline_messageReactions button{display:inline-flex;line-height:2rem;margin-right:6px;padding:1px 6px;border:1px solid var(--light-border);border-radius:10px;background-color:var(--background-color-secondary);color:inherit;cursor:pointer;user-select:none;vertical-align:middle}.Timeline_messageReactions button.active{background-color:var(--background-color-secondary);border-color:var(--accent-color)}@keyframes glow-reaction-border{0%{border-color:var(--background-color-secondary)}to{border-color:var(--accent-color)}}.Timeline_messageReactions button.active.pending{animation-name:glow-reaction-border;animation-duration:.5s;animation-direction:alternate;animation-iteration-count:infinite;animation-timing-function:linear}.Timeline_locationLink{padding:0 8px;border-radius:16px;border:1px solid var(--light-border);background-color:var(--background-color-secondary);text-decoration:none;display:inline-block;line-height:2rem;vertical-align:top;margin:1px 4px}.AnnouncementView{margin:5px 0;padding:5px 10%}.AnnouncementView>div{margin:0 auto;padding:10px 20px;background-color:var(--background-color-secondary);text-align:center;border-radius:10px}.GapView>:not(:first-child){margin-left:12px}.GapView{padding:52px 20px}.GapView.isAtTop{padding:52px 20px 12px}:root{font-size:10px;--icon-color: var(--background-color-secondary--darker-40);--light-border: var(--background-color-secondary--darker-5);--light-text-color: var(--background-color-secondary--darker-55);--timeline-time-text-color: var(--background-color-secondary--darker-35);--icon-background: var(--background-color-secondary--darker-7);--right-panel-text-color: var(--background-color-secondary--darker-35)}.hydrogen{font-family:Inter,sans-serif,"emoji";background-color:var(--background-color-primary);color:var(--text-color);font-size:1.4rem;--usercolor1: #368BD6;--usercolor2: #AC3BA8;--usercolor3: #03B381;--usercolor4: #E64F7A;--usercolor5: #FF812D;--usercolor6: #2DC2C5;--usercolor7: #5C56F5;--usercolor8: #74D12C}.hydrogen button{font-family:inherit}.avatar{border-radius:100%;background:var(--background-color-primary);color:var(--fixed-white)}.hydrogen .avatar.usercolor1{background-color:var(--usercolor1)}.hydrogen .avatar.usercolor2{background-color:var(--usercolor2)}.hydrogen .avatar.usercolor3{background-color:var(--usercolor3)}.hydrogen .avatar.usercolor4{background-color:var(--usercolor4)}.hydrogen .avatar.usercolor5{background-color:var(--usercolor5)}.hydrogen .avatar.usercolor6{background-color:var(--usercolor6)}.hydrogen .avatar.usercolor7{background-color:var(--usercolor7)}.hydrogen .avatar.usercolor8{background-color:var(--usercolor8)}.logo{height:48px;min-width:48px;background-image:var(--icon-url-1);background-repeat:no-repeat;background-position:center}.button-row{display:flex}.button-row>*{margin-right:10px}.button-row>*:last-child{margin-right:0}.button-row .button-action{margin:10px 0;flex:1 0 auto}.form-row.text textarea{font-family:Inter,sans-serif;background-color:var(--background-color-secondary);color:inherit}.form-group{margin:24px 0}.form-row{margin:12px 0}.form-row.text>input,.form-row.text>textarea{padding:12px;border:1px solid var(--light-border);border-radius:8px;margin-top:5px;font-size:1em;resize:vertical;background-color:var(--background-color-secondary);color:inherit}.form-row.check{display:flex;align-items:baseline;gap:4px}.form-row.text>label,.form-row.text>input{display:block}.form-row .form-row-description{font-size:1rem;color:var(--light-text-color);margin:8px 0 0}.button-action{cursor:pointer}a.button-action{text-decoration:none;text-align:center;display:block}.button-action.secondary{color:var(--accent-color)}.button-action.primary{background-color:var(--accent-color);border-radius:8px;color:var(--fixed-white);font-weight:700}.button-action.primary:disabled{color:var(--fixed-white--darker-10)}.button-action.primary.destructive{background-color:var(--error-color)}.button-action.secondary.destructive{color:var(--error-color)}.button-action{border:none;padding:10px;background:none;font-weight:500}.button-utility{cursor:pointer;width:32px;height:32px;background-position:center;background-color:var(--icon-background);background-repeat:no-repeat;border:none;border-radius:100%;display:block}.button-utility.grid{background-image:var(--icon-url-2)}.button-utility.settings{background-image:var(--icon-url-3)}.button-utility.create{background-image:var(--icon-url-4)}.button-utility.grid.on{background-image:var(--icon-url-5)}.FilterField{background-image:var(--icon-url-6);background-repeat:no-repeat;background-position:8px center;background-color:var(--icon-background);border:1px solid transparent;border-radius:16px;height:32px;align-items:center;padding-left:30px;box-sizing:border-box}.FilterField:focus-within{border:1px var(--icon-background) solid;background-color:var(--background-color-primary)}.FilterField:focus-within button{border-color:var(--background-color-primary)}.FilterField input{font-family:Inter;font-size:1.3rem;font-weight:500;line-height:1.573rem;outline:none;border:none;background-color:transparent;height:100%;color:var(--text-color)}.FilterField button{width:30px;height:30px;background-position:center;background-color:var(--icon-background);background-repeat:no-repeat;background-image:var(--icon-url-7);border:7px solid transparent;border-radius:100%;box-sizing:border-box}.PreSessionScreen{padding:30px}.PreSessionScreen h1{font-size:16px;text-align:center}.SessionLoadView{padding-top:16px}.StartSSOLoginView_button{border:1px solid var(--accent-color);border-radius:8px}.LoginView_back{background-image:var(--icon-url-8);background-color:transparent}.LoginView_separator{font-weight:500;font-size:1.5rem}.LoginView_forwardInfo{font-size:.9em;margin-left:1em;color:var(--light-text-color)}.CompleteSSOView_title{font-weight:500}@media screen and (min-width: 600px){.PreSessionScreen{box-shadow:0 6px 32px #0000001a;border-radius:8px}}.PreSessionScreen .logo{height:48px;min-width:48px}.LeftPanel{background:var(--background-color-secondary);font-size:1.5rem;padding:12px 8px 0}.LeftPanel>:not(:first-child){margin-top:12px}.LeftPanel .utilities>:not(:first-child){margin-left:8px}.LeftPanel .filter{border-bottom:1px solid var(--background-color-secondary)}.LeftPanel .filter input{padding:.8em;border:none}.LeftPanel .RoomList{padding:0 8px 0 0;margin-right:-8px}.RoomList>li{margin:0;padding:4px 8px 4px 0;align-items:center}.RoomList>li>a{text-decoration:none;align-items:center}.RoomList li:not(:first-child){margin-top:4px}.RoomList li.active{background:var(--background-color-secondary--darker-7);border-radius:5px}.RoomList li>a>*{margin-right:8px}.RoomList .description{align-items:center}.RoomList .name.unread{font-weight:600}.RoomList .badge{min-width:1.6rem;height:1.6rem;border-radius:1.6rem;box-sizing:border-box;padding:.1rem .3rem;background-color:var(--room-badge);color:var(--fixed-white);font-weight:700;font-size:1rem;line-height:1.4rem;text-align:center}.RoomList .badge.highlighted{background-color:var(--error-color)}a{color:inherit}.SessionStatusView{padding:4px;min-height:22px;background-color:var(--accent-color);color:var(--fixed-white);align-items:center}.SessionStatusView button.link{color:currentcolor;text-align:left}.SessionStatusView>.end{flex:1 1;display:flex;justify-content:flex-end;align-self:stretch;align-items:stretch}.SessionStatusView .dismiss{border:none;background:none;background-image:var(--icon-url-9);background-position:center;background-repeat:no-repeat;width:32px;cursor:pointer}.room-placeholder{align-items:center;justify-content:center;text-align:center;padding:20px}.SessionPickerView li{font-size:1.2em}.SessionPickerView .session-info{text-decoration:none;padding:12px;border:1px solid var(--light-border);border-radius:8px;background-image:var(--icon-url-10);background-position:center right 30px;background-repeat:no-repeat;font-weight:500}.SessionPickerView .session-actions{margin:10px 0 20px;display:flex}.SessionPickerView .session-actions>*{margin-right:10px}.SessionPickerView .session-actions>*:last-child{margin-right:0}.SessionPickerView .session-actions button{border:none;background:none;color:inherit}.SessionPickerView button.destructive{color:var(--error-color)}.RoomGridView>div.container{border-right:1px solid var(--background-color-secondary);border-bottom:1px solid var(--background-color-secondary)}.RoomGridView>.focused>.room-placeholder .unfocused{display:none}.RoomGridView>:not(.focused)>.room-placeholder .focused{display:none}.room-placeholder .unfocused{color:var(--right-panel-text-color)}.RoomGridView>div.focus-ring{border:2px solid var(--accent-color--darker-5);border-radius:12px}.middle-header{box-sizing:border-box;flex:0 0 56px;background:var(--background-color-primary);padding:0 16px;border-bottom:1px solid var(--background-color-secondary)}.middle-header h2{font-size:1.8rem;font-weight:600}.middle-header>:not(:last-child){margin-right:8px}.close-middle,.close-session{background-image:var(--icon-url-11);background-position-x:10px}.RoomHeader .topic{font-size:14rem}.RoomHeader .room-options{background-image:var(--icon-url-12)}.RoomView_error{color:var(--error-color);background:#efefef;height:0px;font-weight:700;transition:.25s all ease-out;padding-right:20px;padding-left:20px}.RoomView_error div{overflow:hidden;height:100%;width:100%;position:relative;display:flex;align-items:center}.RoomView_error:not(:empty){height:auto;padding-top:20px;padding-bottom:20px}.RoomView_error p{position:relative;display:block;width:100%;height:auto;margin:0}.RoomView_error button{width:40px;padding-top:20px;padding-bottom:20px;background:none;border:none;position:relative;border-radius:5px;transition:.1s all ease-out;cursor:pointer}.RoomView_error button:hover{background:#cfcfcf}.RoomView_error button:before{content:"\274c";position:absolute;top:15px;left:9px;width:20px;height:10px;font-size:10px;align-self:middle}.MessageComposer_replyPreview .Timeline_message{margin:5px 0 0;max-height:30vh;overflow:auto}.MessageComposer_replyPreview{background:var(--background-color-secondary);margin:0 10px 10px;box-shadow:0 0 5px var(--background-color-secondary--darker-15);border-radius:5px}.MessageComposer_input,.MessageComposer_replyPreview{padding:8px}.MessageComposer_replyPreview>.replying{display:inline-flex;flex-direction:row;align-items:center;font-weight:700}.MessageComposer_replyPreview>button.cancel{width:32px;height:32px;display:block;border:none;text-indent:200%;white-space:nowrap;overflow:hidden;background-color:transparent;background-image:var(--icon-url-13);background-repeat:no-repeat;background-position:center;background-size:18px;cursor:pointer}.MessageComposer_input:first-child{border-top:1px solid var(--background-color-secondary)}.MessageComposer_input>:not(:first-child){margin-left:12px}.MessageComposer_input>textarea{border:none;border-radius:24px;background:var(--background-color-secondary);color:inherit;font-size:14px;font-family:Inter,sans-serif;resize:none;flex:1 1;padding:14px;box-sizing:border-box;overflow:hidden;max-height:113px;overflow-y:auto;overflow-y:overlay}.MessageComposer_input>button.send{width:32px;height:32px;display:block;border-radius:100%;border:none;text-indent:200%;overflow:hidden;background-color:var(--accent-color);background-image:var(--icon-url-14);background-repeat:no-repeat;background-position:center;align-self:end;margin-bottom:8px}.MessageComposer_input>button.sendFile{width:32px;height:32px;display:block;border:none;text-indent:200%;white-space:nowrap;overflow:hidden;background-color:transparent;background-image:var(--icon-url-15);background-repeat:no-repeat;background-position:center}.MessageComposer.MessageComposer_canSend button.sendFile{display:none}.MessageComposer:not(.MessageComposer_canSend) button.send{display:none}.SettingsBody{padding:0 16px}.Settings h3{margin:16px 0 8px}.Settings p{max-width:700px}.Settings .row .label{font-weight:600}.Settings .row .label,.Settings .row .content{margin-top:4px;margin-bottom:4px}.Settings .row .content{margin-left:4px;flex:1 1}.Settings .row.code .content{font-family:monospace}.Settings .row .content button{display:inline-block;margin:0 8px}.Settings .row .content input[type=range]{width:100%;max-width:300px;min-width:160px}.Settings .row{margin:4px 0;display:flex;flex-wrap:wrap;align-items:center}.Settings .row .label{flex:0 0 200px;align-self:flex-start}.Settings .row .content p{margin:8px 0}.Settings .row .content p:first-child{margin-top:0}.Settings .row .content p:last-child{margin-bottom:0}.error{color:var(--error-color);font-weight:600}button.link{font-size:1em;border:none;text-decoration:underline;background:none;cursor:pointer;margin:-12px;padding:12px;color:inherit}.Settings a,.Settings .link{color:var(--accent-color);font-weight:600}.lightbox{background-color:#000000bf;display:grid;grid-template:"content close" auto "content details" 1fr / 1fr auto;color:var(--background-color-primary);padding:4px}@media (max-aspect-ratio: 1/1){.lightbox{grid-template:"close" auto "content" 1fr "details" auto / 1fr}.lightbox .details{width:100%!important}}.lightbox .picture{grid-area:content;background-size:contain;background-position:center;background-repeat:no-repeat;width:100%;height:100%;align-self:center;justify-self:center}.lightbox .loading{grid-area:content;align-self:center;justify-self:center;display:flex}.lightbox .loading>:not(:first-child){margin-left:8px}.lightbox .close{display:block;grid-area:close;justify-self:end;background-image:var(--icon-url-16);background-position:center;background-size:16px;background-repeat:no-repeat;width:16px;height:16px;padding:12px}.lightbox .details{grid-area:details;padding:12px;font-size:1.5rem;width:200px}.menu{border-radius:8px;box-shadow:2px 2px 10px #00000080;padding:4px;background-color:var(--background-color-primary);list-style:none;margin:0}.menu li{margin-bottom:10px}.menu .menu-item{color:var(--text-color)}.menu button{border-radius:4px;border:none;background-color:transparent;text-align:left;padding:8px 32px 8px 8px;font-size:1.5rem;height:24px;cursor:pointer}.menu .destructive button{color:var(--error-color)}.menu .quick-reactions{display:flex;padding:8px 32px 8px 8px}.menu .quick-reactions button{padding:2px 4px;text-align:center}.InviteView_body{display:flex;justify-content:space-around;align-items:center;flex:1 1;overflow:auto}.InviteView_invite{display:flex;width:100%;max-width:400px;flex-direction:column;padding:0 24px}.InviteView_roomProfile{display:grid;gap:4px;grid-template:"avatar name" auto "avatar description" 1fr / 72px 1fr;align-self:center;margin-bottom:24px}.InviteView_roomProfile h3{grid-area:name;margin:0}.InviteView_roomDescription{grid-area:description;font-size:1.2rem;margin:0;color:var(--light-text-color)}.InviteView_roomAvatar{grid-area:avatar}.InviteView_dmAvatar{align-self:center}.InviteView_inviter{text-align:center;margin:24px 0}.InviteView_inviter .avatar{display:inline-block;vertical-align:middle;margin-right:4px}.InviteView_buttonRow{margin:10px auto;max-width:200px;width:100%}.InviteView_buttonRow button{display:block;width:100%}.DisabledComposerView{padding:12px;background-color:var(--background-color-secondary)}.DisabledComposerView h3{margin:0}.UnknownRoomView{align-items:center;justify-content:center;text-align:center;padding:16px;box-sizing:border-box}.UnknownRoomView h2{word-break:break-all;word-break:break-word}.UnknownRoomView button{max-width:200px;width:100%}.LoadingView{height:100%;width:100%}.LoadingView .spinner{margin-right:5px}.RightPanelView{background:var(--background-color-secondary)}.RoomDetailsView{padding:0 16px 16px}.RoomDetailsView_id,.MemberDetailsView_id{color:var(--right-panel-text-color);font-size:12px}.RoomDetailsView_rows{margin-top:36px;width:100%}.RoomDetailsView_name h2,.MemberDetailsView_name h2{margin-bottom:4px;font-size:1.8rem}.RoomDetailsView_row{margin-bottom:20px;font-weight:500;font-size:15px;width:100%;background:none;border:none;padding:0}button.RoomDetailsView_row{cursor:pointer}button.RoomDetailsView_row:after{content:var(--icon-url-17);margin-left:12px}.RoomDetailsView_row:not(button):after{content:" ";width:19px}.RoomDetailsView_label:before{padding-right:16px;height:24px;width:20px}.RoomDetailsView_label{width:200px}.RoomDetailsView_value{color:var(--right-panel-text-color);flex:1 1}.MemberCount:before{content:var(--icon-url-18)}.EncryptionStatus:before{content:var(--icon-url-19)}.EncryptionIconView{width:52px;height:52px;border-radius:100%;background:var(--right-panel-text-color);border:3px solid var(--background-color-secondary);margin-left:-16px}.EncryptionIconView_encrypted,.EncryptionIconView_unencrypted{height:24px;width:24px}.EncryptionIconView_encrypted{content:var(--icon-url-20)}.EncryptionIconView_unencrypted{content:var(--icon-url-21)}.RightPanelView_buttons .button-utility{width:24px;height:24px}.RightPanelView_buttons .close{background-image:var(--icon-url-22)}.RightPanelView_buttons .back{background-image:var(--icon-url-23)}.MemberListView{padding-left:16px;padding-right:16px;margin:0}.MemberTileView{margin-bottom:8px;list-style:none}.MemberTileView a{text-decoration:none}.MemberTileView .avatar{margin-right:8px}.MemberTileView_name{text-overflow:ellipsis;overflow:hidden;white-space:nowrap;flex:1 1}.MemberDetailsView_section{box-sizing:border-box;padding:16px;width:100%}.MemberDetailsView_label{font-size:12px;font-weight:600;color:var(--right-panel-text-color);text-transform:uppercase}.MemberDetailsView_value,.MemberDetailsView_options{margin-left:8px;margin-top:5px;font-size:12px}.MemberDetailsView_options{display:inline-flex;flex-direction:column}.MemberDetailsView_options a,.MemberDetailsView_options button{color:var(--accent-color);text-decoration:none;margin:0 0 3px;padding:0;border:none;background:none;cursor:pointer}.LazyListParent{overflow-y:auto}.LogoutScreen{height:100vh}.LogoutScreen .content{height:100%;display:flex;flex-direction:column;align-items:center;justify-content:center}.LogoutScreen .status{display:flex;gap:12px}.CreateRoomView,.RoomBeingCreated_error{max-width:400px}.RoomBeingCreated_error{margin-top:48px}.centered-column{padding:0 12px;align-self:center;width:100%;box-sizing:border-box}.CreateRoomView_selectAvatar{border:none;background:none;cursor:pointer}.CreateRoomView_selectAvatarPlaceholder{width:64px;height:64px;border-radius:100%;background-color:var(--icon-background);background-image:var(--icon-url-24);background-repeat:no-repeat;background-position:center;background-size:36px} diff --git a/assets/theme-element.json b/assets/theme-element.json new file mode 100644 index 00000000..24c0d793 --- /dev/null +++ b/assets/theme-element.json @@ -0,0 +1 @@ +{"version":1,"name":"Element","id":"element","values":{"variants":{"light":{"base":true,"default":true,"name":"Light","variables":{"background-color-primary":"#fff","background-color-secondary":"#f6f6f6","text-color":"#2E2F32","accent-color":"#03b381","error-color":"#FF4B55","fixed-white":"#fff","room-badge":"#61708b","link-color":"#238cf5"}},"dark":{"dark":true,"default":true,"name":"Dark","variables":{"background-color-primary":"#21262b","background-color-secondary":"#2D3239","text-color":"#fff","accent-color":"#03B381","error-color":"#FF4B55","fixed-white":"#fff","room-badge":"#61708b","link-color":"#238cf5"}}}},"source":{"built-assets":{"element-light":"theme-element-light.0779c91e.css","element-dark":"theme-element-dark.4718033a.css"},"runtime-asset":"theme-element-runtime.8f0a458e.css","derived-variables":["background-color-secondary--darker-7","background-color-primary--darker-10","background-color-secondary--darker-15","background-color-secondary--darker-10","background-color-secondary--darker-40","background-color-secondary--darker-5","background-color-secondary--darker-55","background-color-secondary--darker-35","fixed-white--darker-10","accent-color--darker-5","icon-color=background-color-secondary--darker-40","light-border=background-color-secondary--darker-5","light-text-color=background-color-secondary--darker-55","timeline-time-text-color=background-color-secondary--darker-35","icon-background=background-color-secondary--darker-7","right-panel-text-color=background-color-secondary--darker-35"],"icon":{"icon-url-0":"chevron-down.9a7440b9.svg?primary=icon-color","icon-url-1":"element-logo.86bc8565.svg?primary=accent-color","icon-url-2":"enable-grid.eef43c65.svg?primary=icon-color","icon-url-3":"settings.45b8e09f.svg?primary=icon-color","icon-url-4":"plus.49560f96.svg?primary=icon-color","icon-url-5":"disable-grid.371ceaaa.svg?primary=icon-color","icon-url-6":"search.21e0fd39.svg?primary=icon-color","icon-url-7":"clear.0d180c33.svg?primary=icon-color","icon-url-8":"chevron-left.b8b2c5fc.svg?primary=icon-color","icon-url-9":"clear.0d180c33.svg?primary=background-color-primary","icon-url-10":"chevron-right.885731d1.svg?primary=icon-color","icon-url-11":"chevron-left.b8b2c5fc.svg?primary=icon-color","icon-url-12":"vertical-ellipsis.70ab5d25.svg?primary=icon-color","icon-url-13":"clear.0d180c33.svg?primary=icon-color","icon-url-14":"send.7a090949.svg?primary=background-color-primary","icon-url-15":"paperclip.ec29fd9d.svg?primary=icon-color","icon-url-16":"clear.0d180c33.svg?primary=fixed-white","icon-url-17":"chevron-small.dfd7e618.svg?primary=icon-color","icon-url-18":"room-members.35ed0bf9.svg?primary=icon-color","icon-url-19":"encryption-status.8054183e.svg?primary=icon-color","icon-url-20":"e2ee-normal.bef76bd4.svg?primary=fixed-white","icon-url-21":"e2ee-disabled.8507165d.svg?primary=fixed-white","icon-url-22":"clear.0d180c33.svg?primary=icon-color","icon-url-23":"chevron-thin-left.d111869b.svg?primary=icon-color","icon-url-24":"plus.49560f96.svg?primary=icon-color"}}} \ No newline at end of file diff --git a/assets/vertical-ellipsis-3416547705.f619a721.svg b/assets/vertical-ellipsis-3416547705.f619a721.svg new file mode 100644 index 00000000..44c362b1 --- /dev/null +++ b/assets/vertical-ellipsis-3416547705.f619a721.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/vertical-ellipsis-487061581.e7709afd.svg b/assets/vertical-ellipsis-487061581.e7709afd.svg new file mode 100644 index 00000000..eb1641d9 --- /dev/null +++ b/assets/vertical-ellipsis-487061581.e7709afd.svg @@ -0,0 +1,3 @@ + + + diff --git a/assets/vertical-ellipsis.70ab5d25.svg b/assets/vertical-ellipsis.70ab5d25.svg new file mode 100644 index 00000000..1d5dd9ea --- /dev/null +++ b/assets/vertical-ellipsis.70ab5d25.svg @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/config.json b/config.json new file mode 100644 index 00000000..c4ef1ccc --- /dev/null +++ b/config.json @@ -0,0 +1,16 @@ +{ + "push": { + "appId": "io.element.hydrogen.web", + "gatewayUrl": "https://matrix.org", + "applicationServerKey": "BC-gpSdVHEXhvHSHS0AzzWrQoukv2BE7KzpoPO_FfPacqOo3l1pdqz7rSgmB04pZCWaHPz7XRe6fjLaC-WPDopM" + }, + "defaultHomeServer": "matrix.org", + "bugReportEndpointUrl": "https://element.io/bugreports/submit", + "themeManifests": [ + "assets/theme-element.json" + ], + "defaultTheme": { + "light": "element-light", + "dark": "element-dark" + } +} \ No newline at end of file diff --git a/index.html b/index.html new file mode 100644 index 00000000..bed565dd --- /dev/null +++ b/index.html @@ -0,0 +1,24 @@ + + + + + + + + Hydrogen Chat + + + + + + + + + + + + + + + + diff --git a/sw.js b/sw.js new file mode 100644 index 00000000..f644828d --- /dev/null +++ b/sw.js @@ -0,0 +1,2 @@ +var T="./assets/icon.2a39c64c.png";const A=["config.json","assets/theme-element.json","index.html"],R=["assets/icon.2a39c64c.png","assets/icon-maskable.965d12c4.png","assets/download-sandbox.48a866e9.html","assets/olm.92f1ccd0.js","assets/olm.b3e0f9b4.wasm","assets/chevron-down-1956489915.3389f17f.svg","assets/element-logo-1551909733.1d59f06a.svg","assets/settings-878939771.57cf3680.svg","assets/plus-3937109722.5c243914.svg","assets/disable-grid-4240599831.c8dc25a1.svg","assets/enable-grid-2288309723.f83895c8.svg","assets/clear-4137897294.7b90e8df.svg","assets/search-261439583.1bffaca1.svg","assets/chevron-right-2390431650.ec9bf561.svg","assets/chevron-left-2611498805.b5555a61.svg","assets/send-3413346515.b0fb8626.svg","assets/dismiss-2743697487.2f1a17f1.svg","assets/chevron-small-4098047679.489e66cc.svg","assets/paperclip-3961996319.da562307.svg","assets/encryption-status-3449529405.c200a9bb.svg","assets/room-members-3084360280.6f64aaef.svg","assets/e2ee-normal-1448349558.af8f5484.svg","assets/vertical-ellipsis-487061581.e7709afd.svg","assets/e2ee-disabled-1470792300.6863c16d.svg","assets/chevron-thin-left-3078630092.d0d143e3.svg","assets/dismiss-2476348673.d0f98560.svg","assets/chevron-down-3300400168.d1a083a1.svg","assets/element-logo-703176763.fc54fc8d.svg","assets/enable-grid-2071838379.ab4f40c5.svg","assets/settings-2175246113.00804666.svg","assets/plus-4190356069.084c5e3d.svg","assets/disable-grid-3304422220.8a79cfcb.svg","assets/search-3263540198.1511780c.svg","assets/clear-426756705.361f7a30.svg","assets/chevron-left-3506338632.4e437777.svg","assets/chevron-right-847198822.23380c56.svg","assets/vertical-ellipsis-3416547705.f619a721.svg","assets/send-1171052351.caa5c494.svg","assets/paperclip-2441131778.1f5e29f3.svg","assets/chevron-small-781914114.936b4943.svg","assets/room-members-3847743605.9fcf4567.svg","assets/encryption-status-475927392.2fedc0bd.svg","assets/chevron-thin-left-3831175135.13f60c05.svg","assets/index.ca5690cf.js","assets/theme-element-light.0779c91e.css","assets/theme-element-runtime.8f0a458e.css","assets/theme-element-dark.4718033a.css","assets/chevron-down.9a7440b9.svg","assets/element-logo.86bc8565.svg","assets/enable-grid.eef43c65.svg","assets/settings.45b8e09f.svg","assets/plus.49560f96.svg","assets/disable-grid.371ceaaa.svg","assets/search.21e0fd39.svg","assets/clear.0d180c33.svg","assets/chevron-left.b8b2c5fc.svg","assets/chevron-right.885731d1.svg","assets/vertical-ellipsis.70ab5d25.svg","assets/send.7a090949.svg","assets/paperclip.ec29fd9d.svg","assets/chevron-small.dfd7e618.svg","assets/room-members.35ed0bf9.svg","assets/encryption-status.8054183e.svg","assets/e2ee-normal.bef76bd4.svg","assets/e2ee-disabled.8507165d.svg","assets/chevron-thin-left.d111869b.svg"],_=["assets/main.bdb9a925.js","assets/olm_legacy.9dc48f49.js","assets/Inter-Thin.5d8e2ac4.woff2","assets/Inter-ExtraLight.da47c335.woff2","assets/Inter-ThinItalic.6b3ded18.woff2","assets/Inter-ExtraLightItalic.b3f94cfe.woff2","assets/Inter-LightItalic.125c7e6a.woff2","assets/Inter-Light.0f7dfe72.woff2","assets/Inter-Italic.bab4e808.woff2","assets/Inter-Medium.5d308f3d.woff2","assets/Inter-Regular.89d406b0.woff2","assets/Inter-MediumItalic.76551c20.woff2","assets/Inter-SemiBold.c7c3befe.woff2","assets/Inter-SemiBoldItalic.d376ade4.woff2","assets/Inter-ExtraBold.0ef4267e.woff2","assets/Inter-Bold.6f5e9a23.woff2","assets/Inter-BoldItalic.e09dcbe1.woff2","assets/Inter-Black.7f1f5616.woff2","assets/Inter-ExtraBoldItalic.d1e1f6a0.woff2","assets/Inter-BlackItalic.72d5983b.woff2","assets/Inter-Thin.5565b01e.woff","assets/Inter-ExtraLight.d7be68a4.woff","assets/Inter-ThinItalic.c413497b.woff","assets/Inter-Light.38326098.woff","assets/Inter-LightItalic.ec6c76a8.woff","assets/Inter-ExtraLightItalic.762fa4d2.woff","assets/Inter-Medium.0fc5d904.woff","assets/Inter-Italic.7b187d57.woff","assets/Inter-Regular.5b3a854b.woff","assets/Inter-MediumItalic.1458af9d.woff","assets/Inter-ExtraBold.45bae435.woff","assets/Inter-SemiBoldItalic.420db54a.woff","assets/Inter-SemiBold.04cd699f.woff","assets/Inter-Bold.20d46cff.woff","assets/Inter-Black.067c82f7.woff","assets/Inter-ExtraBoldItalic.30a1af87.woff","assets/Inter-BlackItalic.c628a2cf.woff","assets/Inter-BoldItalic.31a185fa.woff","assets/manifest.56e72e88.json"],m=`hydrogen-assets-${"2832467534"}`,l="hydrogen-assets",y="hydrogen-media-thumbnails-v2";self.addEventListener("install",function(e){e.waitUntil((async()=>{await(await caches.open(m)).addAll(A);const a=await caches.open(l);await Promise.all(R.map(async n=>{await a.match(n)||await a.add(n)}))})())});self.addEventListener("activate",e=>{self.clients.claim(),e.waitUntil(k())});async function k(){const e=await caches.keys();for(const s of e)s!==m&&s!==l&&s!==y&&await caches.delete(s);const t=await caches.open(l),a=await t.keys(),n=R.concat(_).map(s=>new URL(s,self.registration.scope).href);for(const s of a)n.some(o=>o===s.url)||t.delete(s)}self.addEventListener("fetch",e=>{e.request.method==="GET"&&e.respondWith(I(e.request))});function E(e){if(e.pathname.startsWith("/_matrix/media/r0/thumbnail/")){const t=parseInt(e.searchParams.get("width"),10),a=parseInt(e.searchParams.get("height"),10);if(t<=50&&a<=50)return!0}return!1}const f=new URL(self.registration.scope);let d=new AbortController;async function I(e){try{if(e.url.includes("config.json")||/theme-.+\.json/.test(e.url))return D(e);const t=new URL(e.url);t.origin===f.origin&&t.pathname===f.pathname&&(e=new Request(new URL("index.html",f.href)));let a=await N(e);return a||(E(t)?a=await fetch(e,{signal:d.signal,mode:"cors",credentials:"omit"}):a=await fetch(e,{signal:d.signal}),await H(e,a)),a}catch(t){throw t.name!=="TypeError"&&t.name!=="AbortError"&&console.error("error in service worker",t),t}}async function D(e){let t=await N(e);const a=O(e);return t||await a}async function O(e){const t=await fetch(e,{signal:d.signal,headers:{"Cache-Control":"no-cache"}});return H(e,t.clone()),t}async function H(e,t){if(t.status>=400)return;const a=new URL(e.url),n=self.registration.scope;if(E(a))(await caches.open(y)).put(e,t.clone());else if(e.url.startsWith(n)){let s=e.url.substr(n.length),o;_.includes(s)?o=l:A.includes(s)&&(o=m),o&&await(await caches.open(o)).put(e,t.clone())}}async function N(e){let a=await(await caches.open(m)).match(e);if(a||(a=await(await caches.open(l)).match(e),a))return a;const s=new URL(e.url);if(E(s)){const o=await caches.open(y);a=await o.match(e),(a==null?void 0:a.status)>=400&&(await o.delete(e),a=null)}return a}self.addEventListener("message",e=>{var n;const t=s=>e.source.postMessage({replyTo:e.data.id,payload:s}),{replyTo:a}=e.data;if(a){const s=g.get(a);s&&(g.delete(a),s(e.data.payload))}else switch((n=e.data)==null?void 0:n.type){case"version":t({version:"0.3.1",buildHash:"2832467534"});break;case"skipWaiting":self.skipWaiting();break;case"haltRequests":e.waitUntil(M().finally(()=>t()));break;case"closeSession":e.waitUntil(W(e.data.payload.sessionId,e.source.id).finally(()=>t()));break}});const p="new_message";async function F(e){if(e.notification.tag!==p){console.log("clicked notif with tag",e.notification.tag);return}const{sessionId:t,roomId:a}=e.notification.data,s=`${`#/session/${t}`}/room/${a}`,o=await b(async i=>await w(i,"hasSessionOpen",{sessionId:t}));if(o){if(console.log("notificationclick: client has session open, showing room there"),o.postMessage({type:"openRoom",payload:{roomId:a}}),"focus"in o)try{await o.focus()}catch(i){console.error(i)}}else if(self.clients.openWindow){console.log("notificationclick: no client found with session open, opening new window");const i=new URL(`./${s}`,f).href;await self.clients.openWindow(i)}}self.addEventListener("notificationclick",e=>{e.notification.close(),e.waitUntil(F(e))});async function P(e){var n;console.log("got a push message",e);const t=e.session_id;let a=e.sender_display_name||e.sender;if(a&&e.event_id){const s=e.room_id;if(!!await b(async c=>{if(c.visibilityState==="visible"&&c.focused)return await w(c,"hasRoomOpen",{sessionId:t,roomId:s})})){console.log("client is focused, room is open, don't show notif");return}const i=Array.from(await self.registration.getNotifications({tag:p})),L=i.filter(c=>c.data.roomId===s).some(c=>c.data.multi),U=i.some(c=>!c.data.multi),r=e.room_name||e.room_alias;let C=!1,h,u;if(L){console.log("already have a multi message, don't do anything");return}else U?(console.log("showing multi message notification"),C=!0,h=r||a,u="New messages"):(console.log("showing new message notification"),r&&r!==a?h=`${a} in ${r}`:h=a,u=((n=e.content)==null?void 0:n.body)||"New message");await self.registration.showNotification(h,{body:u,data:{sessionId:t,roomId:s,multi:C},tag:p,badge:T})}}self.addEventListener("push",e=>{e.waitUntil(P(e.data.json()))});async function W(e,t){const a=await self.clients.matchAll();await Promise.all(a.map(async n=>{n.id!==t&&await w(n,"closeSession",{sessionId:e})}))}async function M(){const e=await self.clients.matchAll({type:"window"});await Promise.all(e.map(t=>w(t,"haltRequests"))),d.abort()}const g=new Map;let S=0;function w(e,t,a){S+=1;const n=S,s=new Promise(o=>{g.set(n,o)});return e.postMessage({type:t,id:n,payload:a}),s}async function b(e){const t=await self.clients.matchAll({type:"window"});for(const a of t)if(await e(a))return a} +//# sourceMappingURL=sw.js.map diff --git a/sw.js.map b/sw.js.map new file mode 100644 index 00000000..26916db8 --- /dev/null +++ b/sw.js.map @@ -0,0 +1 @@ +{"version":3,"file":"sw.js","sources":["../src/platform/web/assets/icon.png?url","../src/platform/web/sw.js"],"sourcesContent":["export default \"__VITE_ASSET__2a39c64c__\"","/*\nCopyright 2020 Bruno Windels \nCopyright 2020 The Matrix.org Foundation C.I.C.\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n*/\n\nimport NOTIFICATION_BADGE_ICON from \"./assets/icon.png?url\";\n// replaced by the service worker build plugin\nconst UNHASHED_PRECACHED_ASSETS = DEFINE_UNHASHED_PRECACHED_ASSETS;\nconst HASHED_PRECACHED_ASSETS = DEFINE_HASHED_PRECACHED_ASSETS;\nconst HASHED_CACHED_ON_REQUEST_ASSETS = DEFINE_HASHED_CACHED_ON_REQUEST_ASSETS;\n\nconst unhashedCacheName = `hydrogen-assets-${DEFINE_GLOBAL_HASH}`;\nconst hashedCacheName = `hydrogen-assets`;\nconst mediaThumbnailCacheName = `hydrogen-media-thumbnails-v2`;\n\nself.addEventListener('install', function(e) {\n e.waitUntil((async () => {\n const unhashedCache = await caches.open(unhashedCacheName);\n await unhashedCache.addAll(UNHASHED_PRECACHED_ASSETS);\n const hashedCache = await caches.open(hashedCacheName);\n await Promise.all(HASHED_PRECACHED_ASSETS.map(async asset => {\n if (!await hashedCache.match(asset)) {\n await hashedCache.add(asset);\n }\n }));\n })());\n});\n\nself.addEventListener('activate', (event) => {\n // on a first page load/sw install,\n // start using the service worker on all pages straight away\n self.clients.claim();\n event.waitUntil(purgeOldCaches());\n});\n\nasync function purgeOldCaches() {\n // remove any caches we don't know about\n const keyList = await caches.keys();\n for (const key of keyList) {\n if (key !== unhashedCacheName && key !== hashedCacheName && key !== mediaThumbnailCacheName) {\n await caches.delete(key);\n }\n }\n // remove the cache for any old hashed resource\n const hashedCache = await caches.open(hashedCacheName);\n const keys = await hashedCache.keys();\n const hashedAssetURLs =\n HASHED_PRECACHED_ASSETS\n .concat(HASHED_CACHED_ON_REQUEST_ASSETS)\n .map(a => new URL(a, self.registration.scope).href);\n\n for (const request of keys) {\n if (!hashedAssetURLs.some(url => url === request.url)) {\n hashedCache.delete(request);\n }\n }\n}\n\nself.addEventListener('fetch', (event) => {\n /*\n service worker shouldn't handle xhr uploads because otherwise\n the progress events won't fire.\n This has to do with xhr not being supported in service workers.\n */\n if (event.request.method === \"GET\") {\n event.respondWith(handleRequest(event.request));\n }\n});\n\nfunction isCacheableThumbnail(url) {\n if (url.pathname.startsWith(\"/_matrix/media/r0/thumbnail/\")) {\n const width = parseInt(url.searchParams.get(\"width\"), 10);\n const height = parseInt(url.searchParams.get(\"height\"), 10);\n if (width <= 50 && height <= 50) {\n return true;\n }\n }\n return false;\n}\n\nconst baseURL = new URL(self.registration.scope);\nlet pendingFetchAbortController = new AbortController();\n\nasync function handleRequest(request) {\n try {\n if (request.url.includes(\"config.json\") || /theme-.+\\.json/.test(request.url)) {\n return handleStaleWhileRevalidateRequest(request);\n }\n const url = new URL(request.url);\n // rewrite / to /index.html so it hits the cache\n if (url.origin === baseURL.origin && url.pathname === baseURL.pathname) {\n request = new Request(new URL(\"index.html\", baseURL.href));\n }\n let response = await readCache(request);\n if (!response) {\n // use cors so the resource in the cache isn't opaque and uses up to 7mb\n // https://developers.google.com/web/tools/chrome-devtools/progressive-web-apps?utm_source=devtools#opaque-responses\n if (isCacheableThumbnail(url)) {\n response = await fetch(request, {signal: pendingFetchAbortController.signal, mode: \"cors\", credentials: \"omit\"});\n } else {\n response = await fetch(request, {signal: pendingFetchAbortController.signal});\n }\n await updateCache(request, response);\n }\n return response;\n } catch (err) {\n if (err.name !== \"TypeError\" && err.name !== \"AbortError\") {\n console.error(\"error in service worker\", err);\n }\n throw err;\n }\n}\n\n/**\n * Stale-while-revalidate caching for certain files\n * see https://developer.chrome.com/docs/workbox/caching-strategies-overview/#stale-while-revalidate\n */\nasync function handleStaleWhileRevalidateRequest(request) {\n let response = await readCache(request);\n const networkResponsePromise = fetchAndUpdateCache(request);\n if (response) {\n return response;\n } else {\n return await networkResponsePromise;\n }\n}\n\nasync function fetchAndUpdateCache(request) {\n const response = await fetch(request, {\n signal: pendingFetchAbortController.signal,\n headers: {\n \"Cache-Control\": \"no-cache\",\n },\n });\n updateCache(request, response.clone());\n return response;\n}\n\nasync function updateCache(request, response) {\n // don't write error responses to the cache\n if (response.status >= 400) {\n return;\n }\n const url = new URL(request.url);\n const baseURL = self.registration.scope;\n if (isCacheableThumbnail(url)) {\n const cache = await caches.open(mediaThumbnailCacheName);\n cache.put(request, response.clone());\n } else if (request.url.startsWith(baseURL)) {\n let assetName = request.url.substr(baseURL.length);\n let cacheName;\n if (HASHED_CACHED_ON_REQUEST_ASSETS.includes(assetName)) {\n cacheName = hashedCacheName;\n } else if (UNHASHED_PRECACHED_ASSETS.includes(assetName)) {\n cacheName = unhashedCacheName;\n }\n if (cacheName) {\n const cache = await caches.open(cacheName);\n await cache.put(request, response.clone());\n }\n }\n}\n\nasync function readCache(request) {\n const unhashedCache = await caches.open(unhashedCacheName);\n let response = await unhashedCache.match(request);\n if (response) {\n return response;\n }\n const hashedCache = await caches.open(hashedCacheName);\n response = await hashedCache.match(request);\n if (response) {\n return response;\n }\n \n const url = new URL(request.url);\n if (isCacheableThumbnail(url)) {\n const mediaThumbnailCache = await caches.open(mediaThumbnailCacheName);\n response = await mediaThumbnailCache.match(request);\n // added in 0.1.26, remove previously cached error responses, remove this in some time\n if (response?.status >= 400) {\n await mediaThumbnailCache.delete(request);\n response = null;\n }\n }\n return response;\n}\n\nself.addEventListener('message', (event) => {\n const reply = payload => event.source.postMessage({replyTo: event.data.id, payload});\n const {replyTo} = event.data;\n if (replyTo) {\n const resolve = pendingReplies.get(replyTo);\n if (resolve) {\n pendingReplies.delete(replyTo);\n resolve(event.data.payload);\n }\n } else {\n switch (event.data?.type) {\n case \"version\":\n reply({version: DEFINE_VERSION, buildHash: DEFINE_GLOBAL_HASH});\n break;\n case \"skipWaiting\":\n self.skipWaiting();\n break;\n case \"haltRequests\":\n event.waitUntil(haltRequests().finally(() => reply()));\n break;\n case \"closeSession\":\n event.waitUntil(\n closeSession(event.data.payload.sessionId, event.source.id)\n .finally(() => reply())\n );\n break;\n }\n }\n});\n\nconst NOTIF_TAG_NEW_MESSAGE = \"new_message\";\n\nasync function openClientFromNotif(event) {\n if (event.notification.tag !== NOTIF_TAG_NEW_MESSAGE) {\n console.log(\"clicked notif with tag\", event.notification.tag);\n return;\n }\n const {sessionId, roomId} = event.notification.data;\n const sessionHash = `#/session/${sessionId}`;\n const roomHash = `${sessionHash}/room/${roomId}`;\n const clientWithSession = await findClient(async client => {\n return await sendAndWaitForReply(client, \"hasSessionOpen\", {sessionId});\n });\n if (clientWithSession) {\n console.log(\"notificationclick: client has session open, showing room there\");\n // use a message rather than clientWithSession.navigate here as this refreshes the page on chrome\n clientWithSession.postMessage({type: \"openRoom\", payload: {roomId}});\n if ('focus' in clientWithSession) {\n try {\n await clientWithSession.focus();\n } catch (err) { console.error(err); } // I've had this throw on me on Android\n }\n } else if (self.clients.openWindow) {\n console.log(\"notificationclick: no client found with session open, opening new window\");\n const roomURL = new URL(`./${roomHash}`, baseURL).href;\n await self.clients.openWindow(roomURL);\n }\n}\n\nself.addEventListener('notificationclick', event => {\n event.notification.close();\n event.waitUntil(openClientFromNotif(event));\n});\n\nasync function handlePushNotification(n) {\n console.log(\"got a push message\", n);\n const sessionId = n.session_id;\n let sender = n.sender_display_name || n.sender;\n if (sender && n.event_id) {\n const roomId = n.room_id;\n const hasFocusedClientOnRoom = !!await findClient(async client => {\n if (client.visibilityState === \"visible\" && client.focused) {\n return await sendAndWaitForReply(client, \"hasRoomOpen\", {sessionId, roomId});\n }\n });\n if (hasFocusedClientOnRoom) {\n console.log(\"client is focused, room is open, don't show notif\");\n return;\n }\n const newMessageNotifs = Array.from(await self.registration.getNotifications({tag: NOTIF_TAG_NEW_MESSAGE}));\n const notifsForRoom = newMessageNotifs.filter(n => n.data.roomId === roomId);\n const hasMultiNotification = notifsForRoom.some(n => n.data.multi);\n const hasSingleNotifsForRoom = newMessageNotifs.some(n => !n.data.multi);\n const roomName = n.room_name || n.room_alias;\n let multi = false;\n let label;\n let body;\n if (hasMultiNotification) {\n console.log(\"already have a multi message, don't do anything\");\n return;\n } else if (hasSingleNotifsForRoom) {\n console.log(\"showing multi message notification\");\n multi = true;\n label = roomName || sender;\n body = \"New messages\";\n } else {\n console.log(\"showing new message notification\");\n if (roomName && roomName !== sender) {\n label = `${sender} in ${roomName}`;\n } else {\n label = sender;\n }\n body = n.content?.body || \"New message\";\n }\n await self.registration.showNotification(label, {\n body,\n data: {sessionId, roomId, multi},\n tag: NOTIF_TAG_NEW_MESSAGE,\n badge: NOTIFICATION_BADGE_ICON\n });\n }\n // we could consider hiding previous notifications here based on the unread count\n // (although we can't really figure out which notifications to hide) and also hiding\n // notifications makes it hard to ensure we always show a notification after a push message\n // when no client is visible, see https://goo.gl/yqv4Q4\n}\n\nself.addEventListener('push', event => {\n event.waitUntil(handlePushNotification(event.data.json()));\n});\n\nasync function closeSession(sessionId, requestingClientId) {\n const clients = await self.clients.matchAll();\n await Promise.all(clients.map(async client => {\n if (client.id !== requestingClientId) {\n await sendAndWaitForReply(client, \"closeSession\", {sessionId});\n }\n }));\n}\n\nasync function haltRequests() {\n // first ask all clients to block sending any more requests\n const clients = await self.clients.matchAll({type: \"window\"});\n await Promise.all(clients.map(client => {\n return sendAndWaitForReply(client, \"haltRequests\");\n }));\n // and only then abort the current requests\n pendingFetchAbortController.abort();\n}\n\nconst pendingReplies = new Map();\nlet messageIdCounter = 0;\nfunction sendAndWaitForReply(client, type, payload) {\n messageIdCounter += 1;\n const id = messageIdCounter;\n const promise = new Promise(resolve => {\n pendingReplies.set(id, resolve);\n });\n client.postMessage({type, id, payload});\n return promise;\n}\n\nasync function findClient(predicate) {\n const clientList = await self.clients.matchAll({type: \"window\"});\n for (const client of clientList) {\n if (await predicate(client)) {\n return client;\n }\n }\n}\n"],"names":[],"mappings":"AAAA,GAAe,GAAA,6BCmBf,KAAM,GAA4B,oCAC5B,EAA0B,kCAC1B,EAAkC,0CAElC,EAAoB,mBAAmB,OAAA,oBAAA,IACvC,EAAkB,kBAClB,EAA0B,+BAEhC,KAAK,iBAAiB,UAAW,SAAS,EAAG,CACzC,EAAE,UAAW,UAAY,CAErB,KAAM,AADgB,MAAM,QAAO,KAAK,CAAiB,GACrC,OAAO,CAAyB,EACpD,KAAM,GAAc,KAAM,QAAO,KAAK,CAAe,EACrD,KAAM,SAAQ,IAAI,EAAwB,IAAI,KAAM,IAAS,CACzD,AAAK,KAAM,GAAY,MAAM,CAAK,GAC9B,KAAM,GAAY,IAAI,CAAK,CAElC,CAAA,CAAC,CACL,GAAA,CAAG,CACR,CAAC,EAED,KAAK,iBAAiB,WAAY,AAAC,GAAU,CAGzC,KAAK,QAAQ,QACb,EAAM,UAAU,EAAc,CAAE,CACpC,CAAC,EAED,kBAAgC,CAE5B,KAAM,GAAU,KAAM,QAAO,OAC7B,SAAW,KAAO,GACd,AAAI,IAAQ,GAAqB,IAAQ,GAAmB,IAAQ,GAChE,KAAM,QAAO,OAAO,CAAG,EAI/B,KAAM,GAAc,KAAM,QAAO,KAAK,CAAe,EAC/C,EAAO,KAAM,GAAY,OACzB,EACF,EACC,OAAO,CAA+B,EACtC,IAAI,GAAK,GAAI,KAAI,EAAG,KAAK,aAAa,KAAK,EAAE,IAAI,EAEtD,SAAW,KAAW,GAClB,AAAK,EAAgB,KAAK,GAAO,IAAQ,EAAQ,GAAG,GAChD,EAAY,OAAO,CAAO,CAGtC,CAEA,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