344 lines
1.1 MiB
344 lines
1.1 MiB
/*
|
||
* v0.5.1 generated at Thu Aug 1 04:21:30 PM CEST 2024
|
||
* https://xrfragment.org
|
||
* SPDX-License-Identifier: AGPL-3.0-or-later
|
||
*/
|
||
(function(){
|
||
/*! For license information please see matrix-crdt.js.LICENSE.txt */
|
||
!function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t():"function"==typeof define&&define.amd?define([],t):"object"==typeof exports?exports.Matrix=t():e.Matrix=t()}(self,(()=>(()=>{var e={9141:e=>{"use strict";for(var t=/[\\\"\x00-\x1F]/g,n={},r=0;r<32;++r)n[String.fromCharCode(r)]="\\U"+("0000"+r.toString(16)).slice(-4).toUpperCase();function i(e){return t.lastIndex=0,e.replace(t,(function(e){return n[e]}))}n["\b"]="\\b",n["\t"]="\\t",n["\n"]="\\n",n["\f"]="\\f",n["\r"]="\\r",n['"']='\\"',n["\\"]="\\\\",e.exports={stringify:function e(t){switch(typeof t){case"string":return'"'+i(t)+'"';case"number":return isFinite(t)?t:"null";case"boolean":return t;case"object":return null===t?"null":Array.isArray(t)?function(t){for(var n="[",r="",i=0;i<t.length;++i)r+=n,n=",",r+=e(t[i]);return","!=n?"[]":r+"]"}(t):function(t){var n="{",r="",s=Object.keys(t);s.sort();for(var o=0;o<s.length;++o){var a=s[o];r+=n+'"'+i(a)+'":',n=",",r+=e(t[a])}return","!=n?"{}":r+"}"}(t);default:throw new Error("Cannot stringify: "+typeof t)}}}},8162:e=>{"use strict";e.exports=function(e){if(e.length>=255)throw new TypeError("Alphabet too long");for(var t=new Uint8Array(256),n=0;n<t.length;n++)t[n]=255;for(var r=0;r<e.length;r++){var i=e.charAt(r),s=i.charCodeAt(0);if(255!==t[s])throw new TypeError(i+" is ambiguous");t[s]=r}var o=e.length,a=e.charAt(0),c=Math.log(o)/Math.log(256),l=Math.log(256)/Math.log(o);function d(e){if("string"!=typeof e)throw new TypeError("Expected String");if(0===e.length)return new Uint8Array;for(var n=0,r=0,i=0;e[n]===a;)r++,n++;for(var s=(e.length-n)*c+1>>>0,l=new Uint8Array(s);e[n];){var d=t[e.charCodeAt(n)];if(255===d)return;for(var u=0,h=s-1;(0!==d||u<i)&&-1!==h;h--,u++)d+=o*l[h]>>>0,l[h]=d%256>>>0,d=d/256>>>0;if(0!==d)throw new Error("Non-zero carry");i=u,n++}for(var f=s-i;f!==s&&0===l[f];)f++;for(var g=new Uint8Array(r+(s-f)),p=r;f!==s;)g[p++]=l[f++];return g}return{encode:function(t){if(t instanceof Uint8Array||(ArrayBuffer.isView(t)?t=new Uint8Array(t.buffer,t.byteOffset,t.byteLength):Array.isArray(t)&&(t=Uint8Array.from(t))),!(t instanceof Uint8Array))throw new TypeError("Expected Uint8Array");if(0===t.length)return"";for(var n=0,r=0,i=0,s=t.length;i!==s&&0===t[i];)i++,n++;for(var c=(s-i)*l+1>>>0,d=new Uint8Array(c);i!==s;){for(var u=t[i],h=0,f=c-1;(0!==u||h<r)&&-1!==f;f--,h++)u+=256*d[f]>>>0,d[f]=u%o>>>0,u=u/o>>>0;if(0!==u)throw new Error("Non-zero carry");r=h,i++}for(var g=c-r;g!==c&&0===d[g];)g++;for(var p=a.repeat(n);g<c;++g)p+=e.charAt(d[g]);return p},decodeUnsafe:d,decode:function(e){var t=d(e);if(t)return t;throw new Error("Non-base"+o+" character")}}}},9742:(e,t)=>{"use strict";t.byteLength=function(e){var t=a(e),n=t[0],r=t[1];return 3*(n+r)/4-r},t.toByteArray=function(e){var t,n,s=a(e),o=s[0],c=s[1],l=new i(function(e,t,n){return 3*(t+n)/4-n}(0,o,c)),d=0,u=c>0?o-4:o;for(n=0;n<u;n+=4)t=r[e.charCodeAt(n)]<<18|r[e.charCodeAt(n+1)]<<12|r[e.charCodeAt(n+2)]<<6|r[e.charCodeAt(n+3)],l[d++]=t>>16&255,l[d++]=t>>8&255,l[d++]=255&t;return 2===c&&(t=r[e.charCodeAt(n)]<<2|r[e.charCodeAt(n+1)]>>4,l[d++]=255&t),1===c&&(t=r[e.charCodeAt(n)]<<10|r[e.charCodeAt(n+1)]<<4|r[e.charCodeAt(n+2)]>>2,l[d++]=t>>8&255,l[d++]=255&t),l},t.fromByteArray=function(e){for(var t,r=e.length,i=r%3,s=[],o=16383,a=0,l=r-i;a<l;a+=o)s.push(c(e,a,a+o>l?l:a+o));return 1===i?(t=e[r-1],s.push(n[t>>2]+n[t<<4&63]+"==")):2===i&&(t=(e[r-2]<<8)+e[r-1],s.push(n[t>>10]+n[t>>4&63]+n[t<<2&63]+"=")),s.join("")};for(var n=[],r=[],i="undefined"!=typeof Uint8Array?Uint8Array:Array,s="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",o=0;o<64;++o)n[o]=s[o],r[s.charCodeAt(o)]=o;function a(e){var t=e.length;if(t%4>0)throw new Error("Invalid string. Length must be a multiple of 4");var n=e.indexOf("=");return-1===n&&(n=t),[n,n===t?0:4-n%4]}function c(e,t,r){for(var i,s,o=[],a=t;a<r;a+=3)i=(e[a]<<16&16711680)+(e[a+1]<<8&65280)+(255&e[a+2]),o.push(n[(s=i)>>18&63]+n[s>>12&63]+n[s>>6&63]+n[63&s]);return o.join("")}r["-".charCodeAt(0)]=62,r["_".charCodeAt(0)]=63},4770:function(e,t){var n,r;n=function(){var e=XMLHttpRequest;if(!e)throw new Error("missing XMLHttpRequest");t.log={trace:r,debug:r,info:r,warn:r,error:r};function t(s,o){if("function"!=typeof o)throw new Error("Bad callback given: "+o);if(!s)throw new Error("No options given");var a=s.onResponse;if((s="string"==typeof s?{uri:s}:JSON.parse(JSON.stringify(s))).onResponse=a,s.verbose&&(t.log=function(){var e,t,n={},s=["trace","debug","info","warn","error"];for(t=0;t<s.length;t++)n[e=s[t]]=r,"undefined"!=typeof console&&console&&console[e]&&(n[e]=i(console,e));return n}()),s.url&&(s.uri=s.url,delete s.url),!s.uri&&""!==s.uri)throw new Error("options.uri is a required argument");if("string"!=typeof s.uri)throw new Error("options.uri must be a string");for(var c=["proxy","_redirectsFollowed","maxRedirects","followRedirect"],l=0;l<c.length;l++)if(s[c[l]])throw new Error("options."+c[l]+" is not supported");if(s.callback=o,s.method=s.method||"GET",s.headers=s.headers||{},s.body=s.body||null,s.timeout=s.timeout||t.DEFAULT_TIMEOUT,s.headers.host)throw new Error("Options.headers.host is not supported");s.json&&(s.headers.accept=s.headers.accept||"application/json","GET"!==s.method&&(s.headers["content-type"]="application/json"),"boolean"!=typeof s.json?s.body=JSON.stringify(s.json):"string"!=typeof s.body&&(s.body=JSON.stringify(s.body)));var d=function(e){var t=[];for(var n in e)e.hasOwnProperty(n)&&t.push(encodeURIComponent(n)+"="+encodeURIComponent(e[n]));return t.join("&")};if(s.qs){var u="string"==typeof s.qs?s.qs:d(s.qs);-1!==s.uri.indexOf("?")?s.uri=s.uri+"&"+u:s.uri=s.uri+"?"+u}if(s.form){if("string"==typeof s.form)throw"form name unsupported";if("POST"===s.method){var h=(s.encoding||"application/x-www-form-urlencoded").toLowerCase();switch(s.headers["content-type"]=h,h){case"application/x-www-form-urlencoded":s.body=d(s.form).replace(/%20/g,"+");break;case"multipart/form-data":var f=function(e){var t={};t.boundry="-------------------------------"+Math.floor(1e9*Math.random());var n=[];for(var r in e)e.hasOwnProperty(r)&&n.push("--"+t.boundry+'\nContent-Disposition: form-data; name="'+r+'"\n\n'+e[r]+"\n");return n.push("--"+t.boundry+"--"),t.body=n.join(""),t.length=t.body.length,t.type="multipart/form-data; boundary="+t.boundry,t}(s.form);s.body=f.body,s.headers["content-type"]=f.type;break;default:throw new Error("unsupported encoding:"+h)}}}return s.onResponse=s.onResponse||r,!0===s.onResponse&&(s.onResponse=o,s.callback=r),!s.headers.authorization&&s.auth&&(s.headers.authorization="Basic "+function(e){var t,n,r,i,s,o="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",a=0,c=0,l="",d=[];if(!e)return e;do{t=(s=e.charCodeAt(a++)<<16|e.charCodeAt(a++)<<8|e.charCodeAt(a++))>>18&63,n=s>>12&63,r=s>>6&63,i=63&s,d[c++]=o.charAt(t)+o.charAt(n)+o.charAt(r)+o.charAt(i)}while(a<e.length);switch(l=d.join(""),e.length%3){case 1:l=l.slice(0,-2)+"==";break;case 2:l=l.slice(0,-1)+"="}return l}(s.auth.username+":"+s.auth.password)),function(r){var i=new e,s=!1,o=function(e){var t,n=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/;try{t=location.href}catch(e){(t=document.createElement("a")).href="",t=t.href}var r=n.exec(t.toLowerCase())||[],i=n.exec(e.toLowerCase());return!(!i||i[1]==r[1]&&i[2]==r[2]&&(i[3]||("http:"===i[1]?80:443))==(r[3]||("http:"===r[1]?80:443)))}(r.uri),a="withCredentials"in i;if(n+=1,i.seq_id=n,i.id=n+": "+r.method+" "+r.uri,i._id=i.id,o&&!a){var c=new Error("Browser does not support cross-origin request: "+r.uri);return c.cors="unsupported",r.callback(c,i)}function l(){s=!0;var e=new Error("ETIMEDOUT");return e.code="ETIMEDOUT",e.duration=r.timeout,t.log.error("Timeout",{id:i._id,milliseconds:r.timeout}),r.callback(e,i)}i.timeoutTimer=setTimeout(l,r.timeout);var d={response:!1,loading:!1,end:!1};return i.onreadystatechange=u,i.open(r.method,r.uri,!0),o&&(i.withCredentials=!!r.withCredentials),i.send(r.body),i;function u(n){if(s)return t.log.debug("Ignoring timed out state change",{state:i.readyState,id:i.id});if(t.log.debug("State change",{state:i.readyState,id:i.id,timed_out:s}),i.readyState===e.OPENED)for(var o in t.log.debug("Request started",{id:i.id}),r.headers)i.setRequestHeader(o,r.headers[o]);else i.readyState===e.HEADERS_RECEIVED?h():i.readyState===e.LOADING?(h(),f()):i.readyState===e.DONE&&(h(),f(),g())}function h(){if(!d.response){if(d.response=!0,t.log.debug("Got response",{id:i.id,status:i.status}),clearTimeout(i.timeoutTimer),i.statusCode=i.status,o&&0==i.statusCode){var e=new Error("CORS request rejected: "+r.uri);return e.cors="rejected",d.loading=!0,d.end=!0,r.callback(e,i)}r.onResponse(null,i)}}function f(){d.loading||(d.loading=!0,t.log.debug("Response body loading",{id:i.id}))}function g(){if(!d.end){if(d.end=!0,t.log.debug("Request done",{id:i.id}),i.body=i.responseText,r.json)try{i.body=JSON.parse(i.responseText)}catch(e){return r.callback(e,i)}r.callback(null,i,i.body)}}}(s)}var n=0;function r(){}function i(e,t){return function(n,r){return"object"==typeof r&&(n+=" "+JSON.stringify(r)),e[t].call(e,n)}}return t.withCredentials=!1,t.DEFAULT_TIMEOUT=18e4,t.defaults=function(e,n){var r=function(t){return function(n,r){for(var i in n="string"==typeof n?{uri:n}:JSON.parse(JSON.stringify(n)),e)void 0===n[i]&&(n[i]=e[i]);return t(n,r)}},i=r(t);return i.get=r(t.get),i.post=r(t.post),i.put=r(t.put),i.head=r(t.head),i},["get","put","post","head"].forEach((function(e){var n=e.toUpperCase();t[e.toLowerCase()]=function(e){"string"==typeof e?e={method:n,uri:e}:(e=JSON.parse(JSON.stringify(e))).method=n;var r=[e].concat(Array.prototype.slice.apply(arguments,[1]));return t.apply(this,r)}})),t.couch=function(e,n){return"string"==typeof e&&(e={uri:e}),e.json=!0,e.body&&(e.json=e.body),delete e.body,n=n||r,t(e,(function(e,t,r){if(e)return n(e,t,r);if((t.statusCode<200||t.statusCode>299)&&r.error){for(var i in e=new Error("CouchDB error: "+(r.error.reason||r.error.error)),r)e[i]=r[i];return n(e,t,r)}return n(e,t,r)}))},t},void 0===(r=n.apply(t,[]))||(e.exports=r)},7191:(e,t,n)=>{const r=n(8162);e.exports=r("123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz")},8764:(e,t,n)=>{"use strict";const r=n(9742),i=n(645),s="function"==typeof Symbol&&"function"==typeof Symbol.for?Symbol.for("nodejs.util.inspect.custom"):null;t.Buffer=c,t.SlowBuffer=function(e){return+e!=e&&(e=0),c.alloc(+e)},t.INSPECT_MAX_BYTES=50;const o=2147483647;function a(e){if(e>o)throw new RangeError('The value "'+e+'" is invalid for option "size"');const t=new Uint8Array(e);return Object.setPrototypeOf(t,c.prototype),t}function c(e,t,n){if("number"==typeof e){if("string"==typeof t)throw new TypeError('The "string" argument must be of type string. Received type number');return u(e)}return l(e,t,n)}function l(e,t,n){if("string"==typeof e)return function(e,t){if("string"==typeof t&&""!==t||(t="utf8"),!c.isEncoding(t))throw new TypeError("Unknown encoding: "+t);const n=0|p(e,t);let r=a(n);const i=r.write(e,t);return i!==n&&(r=r.slice(0,i)),r}(e,t);if(ArrayBuffer.isView(e))return function(e){if(z(e,Uint8Array)){const t=new Uint8Array(e);return f(t.buffer,t.byteOffset,t.byteLength)}return h(e)}(e);if(null==e)throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e);if(z(e,ArrayBuffer)||e&&z(e.buffer,ArrayBuffer))return f(e,t,n);if("undefined"!=typeof SharedArrayBuffer&&(z(e,SharedArrayBuffer)||e&&z(e.buffer,SharedArrayBuffer)))return f(e,t,n);if("number"==typeof e)throw new TypeError('The "value" argument must not be of type number. Received type number');const r=e.valueOf&&e.valueOf();if(null!=r&&r!==e)return c.from(r,t,n);const i=function(e){if(c.isBuffer(e)){const t=0|g(e.length),n=a(t);return 0===n.length||e.copy(n,0,0,t),n}return void 0!==e.length?"number"!=typeof e.length||J(e.length)?a(0):h(e):"Buffer"===e.type&&Array.isArray(e.data)?h(e.data):void 0}(e);if(i)return i;if("undefined"!=typeof Symbol&&null!=Symbol.toPrimitive&&"function"==typeof e[Symbol.toPrimitive])return c.from(e[Symbol.toPrimitive]("string"),t,n);throw new TypeError("The first argument must be one of type string, Buffer, ArrayBuffer, Array, or Array-like Object. Received type "+typeof e)}function d(e){if("number"!=typeof e)throw new TypeError('"size" argument must be of type number');if(e<0)throw new RangeError('The value "'+e+'" is invalid for option "size"')}function u(e){return d(e),a(e<0?0:0|g(e))}function h(e){const t=e.length<0?0:0|g(e.length),n=a(t);for(let r=0;r<t;r+=1)n[r]=255&e[r];return n}function f(e,t,n){if(t<0||e.byteLength<t)throw new RangeError('"offset" is outside of buffer bounds');if(e.byteLength<t+(n||0))throw new RangeError('"length" is outside of buffer bounds');let r;return r=void 0===t&&void 0===n?new Uint8Array(e):void 0===n?new Uint8Array(e,t):new Uint8Array(e,t,n),Object.setPrototypeOf(r,c.prototype),r}function g(e){if(e>=o)throw new RangeError("Attempt to allocate Buffer larger than maximum size: 0x"+o.toString(16)+" bytes");return 0|e}function p(e,t){if(c.isBuffer(e))return e.length;if(ArrayBuffer.isView(e)||z(e,ArrayBuffer))return e.byteLength;if("string"!=typeof e)throw new TypeError('The "string" argument must be one of type string, Buffer, or ArrayBuffer. Received type '+typeof e);const n=e.length,r=arguments.length>2&&!0===arguments[2];if(!r&&0===n)return 0;let i=!1;for(;;)switch(t){case"ascii":case"latin1":case"binary":return n;case"utf8":case"utf-8":return W(e).length;case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return 2*n;case"hex":return n>>>1;case"base64":return H(e).length;default:if(i)return r?-1:W(e).length;t=(""+t).toLowerCase(),i=!0}}function m(e,t,n){let r=!1;if((void 0===t||t<0)&&(t=0),t>this.length)return"";if((void 0===n||n>this.length)&&(n=this.length),n<=0)return"";if((n>>>=0)<=(t>>>=0))return"";for(e||(e="utf8");;)switch(e){case"hex":return A(this,t,n);case"utf8":case"utf-8":return R(this,t,n);case"ascii":return k(this,t,n);case"latin1":case"binary":return O(this,t,n);case"base64":return T(this,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return D(this,t,n);default:if(r)throw new TypeError("Unknown encoding: "+e);e=(e+"").toLowerCase(),r=!0}}function y(e,t,n){const r=e[t];e[t]=e[n],e[n]=r}function v(e,t,n,r,i){if(0===e.length)return-1;if("string"==typeof n?(r=n,n=0):n>2147483647?n=2147483647:n<-2147483648&&(n=-2147483648),J(n=+n)&&(n=i?0:e.length-1),n<0&&(n=e.length+n),n>=e.length){if(i)return-1;n=e.length-1}else if(n<0){if(!i)return-1;n=0}if("string"==typeof t&&(t=c.from(t,r)),c.isBuffer(t))return 0===t.length?-1:b(e,t,n,r,i);if("number"==typeof t)return t&=255,"function"==typeof Uint8Array.prototype.indexOf?i?Uint8Array.prototype.indexOf.call(e,t,n):Uint8Array.prototype.lastIndexOf.call(e,t,n):b(e,[t],n,r,i);throw new TypeError("val must be string, number or Buffer")}function b(e,t,n,r,i){let s,o=1,a=e.length,c=t.length;if(void 0!==r&&("ucs2"===(r=String(r).toLowerCase())||"ucs-2"===r||"utf16le"===r||"utf-16le"===r)){if(e.length<2||t.length<2)return-1;o=2,a/=2,c/=2,n/=2}function l(e,t){return 1===o?e[t]:e.readUInt16BE(t*o)}if(i){let r=-1;for(s=n;s<a;s++)if(l(e,s)===l(t,-1===r?0:s-r)){if(-1===r&&(r=s),s-r+1===c)return r*o}else-1!==r&&(s-=s-r),r=-1}else for(n+c>a&&(n=a-c),s=n;s>=0;s--){let n=!0;for(let r=0;r<c;r++)if(l(e,s+r)!==l(t,r)){n=!1;break}if(n)return s}return-1}function _(e,t,n,r){n=Number(n)||0;const i=e.length-n;r?(r=Number(r))>i&&(r=i):r=i;const s=t.length;let o;for(r>s/2&&(r=s/2),o=0;o<r;++o){const r=parseInt(t.substr(2*o,2),16);if(J(r))return o;e[n+o]=r}return o}function E(e,t,n,r){return Y(W(t,e.length-n),e,n,r)}function w(e,t,n,r){return Y(function(e){const t=[];for(let n=0;n<e.length;++n)t.push(255&e.charCodeAt(n));return t}(t),e,n,r)}function S(e,t,n,r){return Y(H(t),e,n,r)}function C(e,t,n,r){return Y(function(e,t){let n,r,i;const s=[];for(let o=0;o<e.length&&!((t-=2)<0);++o)n=e.charCodeAt(o),r=n>>8,i=n%256,s.push(i),s.push(r);return s}(t,e.length-n),e,n,r)}function T(e,t,n){return 0===t&&n===e.length?r.fromByteArray(e):r.fromByteArray(e.slice(t,n))}function R(e,t,n){n=Math.min(e.length,n);const r=[];let i=t;for(;i<n;){const t=e[i];let s=null,o=t>239?4:t>223?3:t>191?2:1;if(i+o<=n){let n,r,a,c;switch(o){case 1:t<128&&(s=t);break;case 2:n=e[i+1],128==(192&n)&&(c=(31&t)<<6|63&n,c>127&&(s=c));break;case 3:n=e[i+1],r=e[i+2],128==(192&n)&&128==(192&r)&&(c=(15&t)<<12|(63&n)<<6|63&r,c>2047&&(c<55296||c>57343)&&(s=c));break;case 4:n=e[i+1],r=e[i+2],a=e[i+3],128==(192&n)&&128==(192&r)&&128==(192&a)&&(c=(15&t)<<18|(63&n)<<12|(63&r)<<6|63&a,c>65535&&c<1114112&&(s=c))}}null===s?(s=65533,o=1):s>65535&&(s-=65536,r.push(s>>>10&1023|55296),s=56320|1023&s),r.push(s),i+=o}return function(e){const t=e.length;if(t<=I)return String.fromCharCode.apply(String,e);let n="",r=0;for(;r<t;)n+=String.fromCharCode.apply(String,e.slice(r,r+=I));return n}(r)}t.kMaxLength=o,c.TYPED_ARRAY_SUPPORT=function(){try{const e=new Uint8Array(1),t={foo:function(){return 42}};return Object.setPrototypeOf(t,Uint8Array.prototype),Object.setPrototypeOf(e,t),42===e.foo()}catch(e){return!1}}(),c.TYPED_ARRAY_SUPPORT||"undefined"==typeof console||"function"!=typeof console.error||console.error("This browser lacks typed array (Uint8Array) support which is required by `buffer` v5.x. Use `buffer` v4.x if you require old browser support."),Object.defineProperty(c.prototype,"parent",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.buffer}}),Object.defineProperty(c.prototype,"offset",{enumerable:!0,get:function(){if(c.isBuffer(this))return this.byteOffset}}),c.poolSize=8192,c.from=function(e,t,n){return l(e,t,n)},Object.setPrototypeOf(c.prototype,Uint8Array.prototype),Object.setPrototypeOf(c,Uint8Array),c.alloc=function(e,t,n){return function(e,t,n){return d(e),e<=0?a(e):void 0!==t?"string"==typeof n?a(e).fill(t,n):a(e).fill(t):a(e)}(e,t,n)},c.allocUnsafe=function(e){return u(e)},c.allocUnsafeSlow=function(e){return u(e)},c.isBuffer=function(e){return null!=e&&!0===e._isBuffer&&e!==c.prototype},c.compare=function(e,t){if(z(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),z(t,Uint8Array)&&(t=c.from(t,t.offset,t.byteLength)),!c.isBuffer(e)||!c.isBuffer(t))throw new TypeError('The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array');if(e===t)return 0;let n=e.length,r=t.length;for(let i=0,s=Math.min(n,r);i<s;++i)if(e[i]!==t[i]){n=e[i],r=t[i];break}return n<r?-1:r<n?1:0},c.isEncoding=function(e){switch(String(e).toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"latin1":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return!0;default:return!1}},c.concat=function(e,t){if(!Array.isArray(e))throw new TypeError('"list" argument must be an Array of Buffers');if(0===e.length)return c.alloc(0);let n;if(void 0===t)for(t=0,n=0;n<e.length;++n)t+=e[n].length;const r=c.allocUnsafe(t);let i=0;for(n=0;n<e.length;++n){let t=e[n];if(z(t,Uint8Array))i+t.length>r.length?(c.isBuffer(t)||(t=c.from(t)),t.copy(r,i)):Uint8Array.prototype.set.call(r,t,i);else{if(!c.isBuffer(t))throw new TypeError('"list" argument must be an Array of Buffers');t.copy(r,i)}i+=t.length}return r},c.byteLength=p,c.prototype._isBuffer=!0,c.prototype.swap16=function(){const e=this.length;if(e%2!=0)throw new RangeError("Buffer size must be a multiple of 16-bits");for(let t=0;t<e;t+=2)y(this,t,t+1);return this},c.prototype.swap32=function(){const e=this.length;if(e%4!=0)throw new RangeError("Buffer size must be a multiple of 32-bits");for(let t=0;t<e;t+=4)y(this,t,t+3),y(this,t+1,t+2);return this},c.prototype.swap64=function(){const e=this.length;if(e%8!=0)throw new RangeError("Buffer size must be a multiple of 64-bits");for(let t=0;t<e;t+=8)y(this,t,t+7),y(this,t+1,t+6),y(this,t+2,t+5),y(this,t+3,t+4);return this},c.prototype.toString=function(){const e=this.length;return 0===e?"":0===arguments.length?R(this,0,e):m.apply(this,arguments)},c.prototype.toLocaleString=c.prototype.toString,c.prototype.equals=function(e){if(!c.isBuffer(e))throw new TypeError("Argument must be a Buffer");return this===e||0===c.compare(this,e)},c.prototype.inspect=function(){let e="";const n=t.INSPECT_MAX_BYTES;return e=this.toString("hex",0,n).replace(/(.{2})/g,"$1 ").trim(),this.length>n&&(e+=" ... "),"<Buffer "+e+">"},s&&(c.prototype[s]=c.prototype.inspect),c.prototype.compare=function(e,t,n,r,i){if(z(e,Uint8Array)&&(e=c.from(e,e.offset,e.byteLength)),!c.isBuffer(e))throw new TypeError('The "target" argument must be one of type Buffer or Uint8Array. Received type '+typeof e);if(void 0===t&&(t=0),void 0===n&&(n=e?e.length:0),void 0===r&&(r=0),void 0===i&&(i=this.length),t<0||n>e.length||r<0||i>this.length)throw new RangeError("out of range index");if(r>=i&&t>=n)return 0;if(r>=i)return-1;if(t>=n)return 1;if(this===e)return 0;let s=(i>>>=0)-(r>>>=0),o=(n>>>=0)-(t>>>=0);const a=Math.min(s,o),l=this.slice(r,i),d=e.slice(t,n);for(let e=0;e<a;++e)if(l[e]!==d[e]){s=l[e],o=d[e];break}return s<o?-1:o<s?1:0},c.prototype.includes=function(e,t,n){return-1!==this.indexOf(e,t,n)},c.prototype.indexOf=function(e,t,n){return v(this,e,t,n,!0)},c.prototype.lastIndexOf=function(e,t,n){return v(this,e,t,n,!1)},c.prototype.write=function(e,t,n,r){if(void 0===t)r="utf8",n=this.length,t=0;else if(void 0===n&&"string"==typeof t)r=t,n=this.length,t=0;else{if(!isFinite(t))throw new Error("Buffer.write(string, encoding, offset[, length]) is no longer supported");t>>>=0,isFinite(n)?(n>>>=0,void 0===r&&(r="utf8")):(r=n,n=void 0)}const i=this.length-t;if((void 0===n||n>i)&&(n=i),e.length>0&&(n<0||t<0)||t>this.length)throw new RangeError("Attempt to write outside buffer bounds");r||(r="utf8");let s=!1;for(;;)switch(r){case"hex":return _(this,e,t,n);case"utf8":case"utf-8":return E(this,e,t,n);case"ascii":case"latin1":case"binary":return w(this,e,t,n);case"base64":return S(this,e,t,n);case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return C(this,e,t,n);default:if(s)throw new TypeError("Unknown encoding: "+r);r=(""+r).toLowerCase(),s=!0}},c.prototype.toJSON=function(){return{type:"Buffer",data:Array.prototype.slice.call(this._arr||this,0)}};const I=4096;function k(e,t,n){let r="";n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(127&e[i]);return r}function O(e,t,n){let r="";n=Math.min(e.length,n);for(let i=t;i<n;++i)r+=String.fromCharCode(e[i]);return r}function A(e,t,n){const r=e.length;(!t||t<0)&&(t=0),(!n||n<0||n>r)&&(n=r);let i="";for(let r=t;r<n;++r)i+=Q[e[r]];return i}function D(e,t,n){const r=e.slice(t,n);let i="";for(let e=0;e<r.length-1;e+=2)i+=String.fromCharCode(r[e]+256*r[e+1]);return i}function M(e,t,n){if(e%1!=0||e<0)throw new RangeError("offset is not uint");if(e+t>n)throw new RangeError("Trying to access beyond buffer length")}function P(e,t,n,r,i,s){if(!c.isBuffer(e))throw new TypeError('"buffer" argument must be a Buffer instance');if(t>i||t<s)throw new RangeError('"value" argument is out of bounds');if(n+r>e.length)throw new RangeError("Index out of range")}function U(e,t,n,r,i){q(t,r,i,e,n,7);let s=Number(t&BigInt(4294967295));e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s,s>>=8,e[n++]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,o>>=8,e[n++]=o,n}function L(e,t,n,r,i){q(t,r,i,e,n,7);let s=Number(t&BigInt(4294967295));e[n+7]=s,s>>=8,e[n+6]=s,s>>=8,e[n+5]=s,s>>=8,e[n+4]=s;let o=Number(t>>BigInt(32)&BigInt(4294967295));return e[n+3]=o,o>>=8,e[n+2]=o,o>>=8,e[n+1]=o,o>>=8,e[n]=o,n+8}function N(e,t,n,r,i,s){if(n+r>e.length)throw new RangeError("Index out of range");if(n<0)throw new RangeError("Index out of range")}function x(e,t,n,r,s){return t=+t,n>>>=0,s||N(e,0,n,4),i.write(e,t,n,r,23,4),n+4}function B(e,t,n,r,s){return t=+t,n>>>=0,s||N(e,0,n,8),i.write(e,t,n,r,52,8),n+8}c.prototype.slice=function(e,t){const n=this.length;(e=~~e)<0?(e+=n)<0&&(e=0):e>n&&(e=n),(t=void 0===t?n:~~t)<0?(t+=n)<0&&(t=0):t>n&&(t=n),t<e&&(t=e);const r=this.subarray(e,t);return Object.setPrototypeOf(r,c.prototype),r},c.prototype.readUintLE=c.prototype.readUIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,s=0;for(;++s<t&&(i*=256);)r+=this[e+s]*i;return r},c.prototype.readUintBE=c.prototype.readUIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e+--t],i=1;for(;t>0&&(i*=256);)r+=this[e+--t]*i;return r},c.prototype.readUint8=c.prototype.readUInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),this[e]},c.prototype.readUint16LE=c.prototype.readUInt16LE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]|this[e+1]<<8},c.prototype.readUint16BE=c.prototype.readUInt16BE=function(e,t){return e>>>=0,t||M(e,2,this.length),this[e]<<8|this[e+1]},c.prototype.readUint32LE=c.prototype.readUInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),(this[e]|this[e+1]<<8|this[e+2]<<16)+16777216*this[e+3]},c.prototype.readUint32BE=c.prototype.readUInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),16777216*this[e]+(this[e+1]<<16|this[e+2]<<8|this[e+3])},c.prototype.readBigUInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||V(e,this.length-8);const r=t+256*this[++e]+65536*this[++e]+this[++e]*2**24,i=this[++e]+256*this[++e]+65536*this[++e]+n*2**24;return BigInt(r)+(BigInt(i)<<BigInt(32))})),c.prototype.readBigUInt64BE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||V(e,this.length-8);const r=t*2**24+65536*this[++e]+256*this[++e]+this[++e],i=this[++e]*2**24+65536*this[++e]+256*this[++e]+n;return(BigInt(r)<<BigInt(32))+BigInt(i)})),c.prototype.readIntLE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=this[e],i=1,s=0;for(;++s<t&&(i*=256);)r+=this[e+s]*i;return i*=128,r>=i&&(r-=Math.pow(2,8*t)),r},c.prototype.readIntBE=function(e,t,n){e>>>=0,t>>>=0,n||M(e,t,this.length);let r=t,i=1,s=this[e+--r];for(;r>0&&(i*=256);)s+=this[e+--r]*i;return i*=128,s>=i&&(s-=Math.pow(2,8*t)),s},c.prototype.readInt8=function(e,t){return e>>>=0,t||M(e,1,this.length),128&this[e]?-1*(255-this[e]+1):this[e]},c.prototype.readInt16LE=function(e,t){e>>>=0,t||M(e,2,this.length);const n=this[e]|this[e+1]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt16BE=function(e,t){e>>>=0,t||M(e,2,this.length);const n=this[e+1]|this[e]<<8;return 32768&n?4294901760|n:n},c.prototype.readInt32LE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]|this[e+1]<<8|this[e+2]<<16|this[e+3]<<24},c.prototype.readInt32BE=function(e,t){return e>>>=0,t||M(e,4,this.length),this[e]<<24|this[e+1]<<16|this[e+2]<<8|this[e+3]},c.prototype.readBigInt64LE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||V(e,this.length-8);const r=this[e+4]+256*this[e+5]+65536*this[e+6]+(n<<24);return(BigInt(r)<<BigInt(32))+BigInt(t+256*this[++e]+65536*this[++e]+this[++e]*2**24)})),c.prototype.readBigInt64BE=X((function(e){$(e>>>=0,"offset");const t=this[e],n=this[e+7];void 0!==t&&void 0!==n||V(e,this.length-8);const r=(t<<24)+65536*this[++e]+256*this[++e]+this[++e];return(BigInt(r)<<BigInt(32))+BigInt(this[++e]*2**24+65536*this[++e]+256*this[++e]+n)})),c.prototype.readFloatLE=function(e,t){return e>>>=0,t||M(e,4,this.length),i.read(this,e,!0,23,4)},c.prototype.readFloatBE=function(e,t){return e>>>=0,t||M(e,4,this.length),i.read(this,e,!1,23,4)},c.prototype.readDoubleLE=function(e,t){return e>>>=0,t||M(e,8,this.length),i.read(this,e,!0,52,8)},c.prototype.readDoubleBE=function(e,t){return e>>>=0,t||M(e,8,this.length),i.read(this,e,!1,52,8)},c.prototype.writeUintLE=c.prototype.writeUIntLE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||P(this,e,t,n,Math.pow(2,8*n)-1,0);let i=1,s=0;for(this[t]=255&e;++s<n&&(i*=256);)this[t+s]=e/i&255;return t+n},c.prototype.writeUintBE=c.prototype.writeUIntBE=function(e,t,n,r){e=+e,t>>>=0,n>>>=0,r||P(this,e,t,n,Math.pow(2,8*n)-1,0);let i=n-1,s=1;for(this[t+i]=255&e;--i>=0&&(s*=256);)this[t+i]=e/s&255;return t+n},c.prototype.writeUint8=c.prototype.writeUInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,255,0),this[t]=255&e,t+1},c.prototype.writeUint16LE=c.prototype.writeUInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeUint16BE=c.prototype.writeUInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,65535,0),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeUint32LE=c.prototype.writeUInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t+3]=e>>>24,this[t+2]=e>>>16,this[t+1]=e>>>8,this[t]=255&e,t+4},c.prototype.writeUint32BE=c.prototype.writeUInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,4294967295,0),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigUInt64LE=X((function(e,t=0){return U(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeBigUInt64BE=X((function(e,t=0){return L(this,e,t,BigInt(0),BigInt("0xffffffffffffffff"))})),c.prototype.writeIntLE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);P(this,e,t,n,r-1,-r)}let i=0,s=1,o=0;for(this[t]=255&e;++i<n&&(s*=256);)e<0&&0===o&&0!==this[t+i-1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+n},c.prototype.writeIntBE=function(e,t,n,r){if(e=+e,t>>>=0,!r){const r=Math.pow(2,8*n-1);P(this,e,t,n,r-1,-r)}let i=n-1,s=1,o=0;for(this[t+i]=255&e;--i>=0&&(s*=256);)e<0&&0===o&&0!==this[t+i+1]&&(o=1),this[t+i]=(e/s>>0)-o&255;return t+n},c.prototype.writeInt8=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,1,127,-128),e<0&&(e=255+e+1),this[t]=255&e,t+1},c.prototype.writeInt16LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=255&e,this[t+1]=e>>>8,t+2},c.prototype.writeInt16BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,2,32767,-32768),this[t]=e>>>8,this[t+1]=255&e,t+2},c.prototype.writeInt32LE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),this[t]=255&e,this[t+1]=e>>>8,this[t+2]=e>>>16,this[t+3]=e>>>24,t+4},c.prototype.writeInt32BE=function(e,t,n){return e=+e,t>>>=0,n||P(this,e,t,4,2147483647,-2147483648),e<0&&(e=4294967295+e+1),this[t]=e>>>24,this[t+1]=e>>>16,this[t+2]=e>>>8,this[t+3]=255&e,t+4},c.prototype.writeBigInt64LE=X((function(e,t=0){return U(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeBigInt64BE=X((function(e,t=0){return L(this,e,t,-BigInt("0x8000000000000000"),BigInt("0x7fffffffffffffff"))})),c.prototype.writeFloatLE=function(e,t,n){return x(this,e,t,!0,n)},c.prototype.writeFloatBE=function(e,t,n){return x(this,e,t,!1,n)},c.prototype.writeDoubleLE=function(e,t,n){return B(this,e,t,!0,n)},c.prototype.writeDoubleBE=function(e,t,n){return B(this,e,t,!1,n)},c.prototype.copy=function(e,t,n,r){if(!c.isBuffer(e))throw new TypeError("argument should be a Buffer");if(n||(n=0),r||0===r||(r=this.length),t>=e.length&&(t=e.length),t||(t=0),r>0&&r<n&&(r=n),r===n)return 0;if(0===e.length||0===this.length)return 0;if(t<0)throw new RangeError("targetStart out of bounds");if(n<0||n>=this.length)throw new RangeError("Index out of range");if(r<0)throw new RangeError("sourceEnd out of bounds");r>this.length&&(r=this.length),e.length-t<r-n&&(r=e.length-t+n);const i=r-n;return this===e&&"function"==typeof Uint8Array.prototype.copyWithin?this.copyWithin(t,n,r):Uint8Array.prototype.set.call(e,this.subarray(n,r),t),i},c.prototype.fill=function(e,t,n,r){if("string"==typeof e){if("string"==typeof t?(r=t,t=0,n=this.length):"string"==typeof n&&(r=n,n=this.length),void 0!==r&&"string"!=typeof r)throw new TypeError("encoding must be a string");if("string"==typeof r&&!c.isEncoding(r))throw new TypeError("Unknown encoding: "+r);if(1===e.length){const t=e.charCodeAt(0);("utf8"===r&&t<128||"latin1"===r)&&(e=t)}}else"number"==typeof e?e&=255:"boolean"==typeof e&&(e=Number(e));if(t<0||this.length<t||this.length<n)throw new RangeError("Out of range index");if(n<=t)return this;let i;if(t>>>=0,n=void 0===n?this.length:n>>>0,e||(e=0),"number"==typeof e)for(i=t;i<n;++i)this[i]=e;else{const s=c.isBuffer(e)?e:c.from(e,r),o=s.length;if(0===o)throw new TypeError('The value "'+e+'" is invalid for argument "value"');for(i=0;i<n-t;++i)this[i+t]=s[i%o]}return this};const j={};function F(e,t,n){j[e]=class extends n{constructor(){super(),Object.defineProperty(this,"message",{value:t.apply(this,arguments),writable:!0,configurable:!0}),this.name=`${this.name} [${e}]`,this.stack,delete this.name}get code(){return e}set code(e){Object.defineProperty(this,"code",{configurable:!0,enumerable:!0,value:e,writable:!0})}toString(){return`${this.name} [${e}]: ${this.message}`}}}function K(e){let t="",n=e.length;const r="-"===e[0]?1:0;for(;n>=r+4;n-=3)t=`_${e.slice(n-3,n)}${t}`;return`${e.slice(0,n)}${t}`}function q(e,t,n,r,i,s){if(e>n||e<t){const r="bigint"==typeof t?"n":"";let i;throw i=s>3?0===t||t===BigInt(0)?`>= 0${r} and < 2${r} ** ${8*(s+1)}${r}`:`>= -(2${r} ** ${8*(s+1)-1}${r}) and < 2 ** ${8*(s+1)-1}${r}`:`>= ${t}${r} and <= ${n}${r}`,new j.ERR_OUT_OF_RANGE("value",i,e)}!function(e,t,n){$(t,"offset"),void 0!==e[t]&&void 0!==e[t+n]||V(t,e.length-(n+1))}(r,i,s)}function $(e,t){if("number"!=typeof e)throw new j.ERR_INVALID_ARG_TYPE(t,"number",e)}function V(e,t,n){if(Math.floor(e)!==e)throw $(e,n),new j.ERR_OUT_OF_RANGE(n||"offset","an integer",e);if(t<0)throw new j.ERR_BUFFER_OUT_OF_BOUNDS;throw new j.ERR_OUT_OF_RANGE(n||"offset",`>= ${n?1:0} and <= ${t}`,e)}F("ERR_BUFFER_OUT_OF_BOUNDS",(function(e){return e?`${e} is outside of buffer bounds`:"Attempt to access memory outside buffer bounds"}),RangeError),F("ERR_INVALID_ARG_TYPE",(function(e,t){return`The "${e}" argument must be of type number. Received type ${typeof t}`}),TypeError),F("ERR_OUT_OF_RANGE",(function(e,t,n){let r=`The value of "${e}" is out of range.`,i=n;return Number.isInteger(n)&&Math.abs(n)>2**32?i=K(String(n)):"bigint"==typeof n&&(i=String(n),(n>BigInt(2)**BigInt(32)||n<-(BigInt(2)**BigInt(32)))&&(i=K(i)),i+="n"),r+=` It must be ${t}. Received ${i}`,r}),RangeError);const G=/[^+/0-9A-Za-z-_]/g;function W(e,t){let n;t=t||1/0;const r=e.length;let i=null;const s=[];for(let o=0;o<r;++o){if(n=e.charCodeAt(o),n>55295&&n<57344){if(!i){if(n>56319){(t-=3)>-1&&s.push(239,191,189);continue}if(o+1===r){(t-=3)>-1&&s.push(239,191,189);continue}i=n;continue}if(n<56320){(t-=3)>-1&&s.push(239,191,189),i=n;continue}n=65536+(i-55296<<10|n-56320)}else i&&(t-=3)>-1&&s.push(239,191,189);if(i=null,n<128){if((t-=1)<0)break;s.push(n)}else if(n<2048){if((t-=2)<0)break;s.push(n>>6|192,63&n|128)}else if(n<65536){if((t-=3)<0)break;s.push(n>>12|224,n>>6&63|128,63&n|128)}else{if(!(n<1114112))throw new Error("Invalid code point");if((t-=4)<0)break;s.push(n>>18|240,n>>12&63|128,n>>6&63|128,63&n|128)}}return s}function H(e){return r.toByteArray(function(e){if((e=(e=e.split("=")[0]).trim().replace(G,"")).length<2)return"";for(;e.length%4!=0;)e+="=";return e}(e))}function Y(e,t,n,r){let i;for(i=0;i<r&&!(i+n>=t.length||i>=e.length);++i)t[i+n]=e[i];return i}function z(e,t){return e instanceof t||null!=e&&null!=e.constructor&&null!=e.constructor.name&&e.constructor.name===t.name}function J(e){return e!=e}const Q=function(){const e="0123456789abcdef",t=new Array(256);for(let n=0;n<16;++n){const r=16*n;for(let i=0;i<16;++i)t[r+i]=e[n]+e[i]}return t}();function X(e){return"undefined"==typeof BigInt?Z:e}function Z(){throw new Error("BigInt not supported")}},1924:(e,t,n)=>{"use strict";var r=n(210),i=n(5559),s=i(r("String.prototype.indexOf"));e.exports=function(e,t){var n=r(e,!!t);return"function"==typeof n&&s(e,".prototype.")>-1?i(n):n}},5559:(e,t,n)=>{"use strict";var r=n(8612),i=n(210),s=n(7771),o=i("%TypeError%"),a=i("%Function.prototype.apply%"),c=i("%Function.prototype.call%"),l=i("%Reflect.apply%",!0)||r.call(c,a),d=i("%Object.defineProperty%",!0),u=i("%Math.max%");if(d)try{d({},"a",{value:1})}catch(e){d=null}e.exports=function(e){if("function"!=typeof e)throw new o("a function is required");var t=l(r,c,arguments);return s(t,1+u(0,e.length-(arguments.length-1)),!0)};var h=function(){return l(r,a,arguments)};d?d(e.exports,"apply",{value:h}):e.exports.apply=h},7811:(e,t)=>{"use strict";var n=/; *([!#$%&'*+.^_`|~0-9A-Za-z-]+) *= *("(?:[\u000b\u0020\u0021\u0023-\u005b\u005d-\u007e\u0080-\u00ff]|\\[\u000b\u0020-\u00ff])*"|[!#$%&'*+.^_`|~0-9A-Za-z-]+) */g,r=/^[\u000b\u0020-\u007e\u0080-\u00ff]+$/,i=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+$/,s=/\\([\u000b\u0020-\u00ff])/g,o=/([\\"])/g,a=/^[!#$%&'*+.^_`|~0-9A-Za-z-]+\/[!#$%&'*+.^_`|~0-9A-Za-z-]+$/;function c(e){var t=String(e);if(i.test(t))return t;if(t.length>0&&!r.test(t))throw new TypeError("invalid parameter value");return'"'+t.replace(o,"\\$1")+'"'}function l(e){this.parameters=Object.create(null),this.type=e}t.format=function(e){if(!e||"object"!=typeof e)throw new TypeError("argument obj is required");var t=e.parameters,n=e.type;if(!n||!a.test(n))throw new TypeError("invalid type");var r=n;if(t&&"object"==typeof t)for(var s,o=Object.keys(t).sort(),l=0;l<o.length;l++){if(s=o[l],!i.test(s))throw new TypeError("invalid parameter name");r+="; "+s+"="+c(t[s])}return r},t.parse=function(e){if(!e)throw new TypeError("argument string is required");var t="object"==typeof e?function(e){var t;if("function"==typeof e.getHeader?t=e.getHeader("content-type"):"object"==typeof e.headers&&(t=e.headers&&e.headers["content-type"]),"string"!=typeof t)throw new TypeError("content-type header is missing from object");return t}(e):e;if("string"!=typeof t)throw new TypeError("argument string is required to be a string");var r=t.indexOf(";"),i=-1!==r?t.slice(0,r).trim():t.trim();if(!a.test(i))throw new TypeError("invalid media type");var o=new l(i.toLowerCase());if(-1!==r){var c,d,u;for(n.lastIndex=r;d=n.exec(t);){if(d.index!==r)throw new TypeError("invalid parameter format");r+=d[0].length,c=d[1].toLowerCase(),34===(u=d[2]).charCodeAt(0)&&-1!==(u=u.slice(1,-1)).indexOf("\\")&&(u=u.replace(s,"$1")),o.parameters[c]=u}if(r!==t.length)throw new TypeError("invalid parameter format")}return o}},1227:(e,t,n)=>{t.formatArgs=function(t){if(t[0]=(this.useColors?"%c":"")+this.namespace+(this.useColors?" %c":" ")+t[0]+(this.useColors?"%c ":" ")+"+"+e.exports.humanize(this.diff),!this.useColors)return;const n="color: "+this.color;t.splice(1,0,n,"color: inherit");let r=0,i=0;t[0].replace(/%[a-zA-Z%]/g,(e=>{"%%"!==e&&(r++,"%c"===e&&(i=r))})),t.splice(i,0,n)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")}catch(e){}return!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG),e},t.useColors=function(){return!("undefined"==typeof window||!window.process||"renderer"!==window.process.type&&!window.process.__nwjs)||("undefined"==typeof navigator||!navigator.userAgent||!navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))&&("undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)&&parseInt(RegExp.$1,10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/))},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=n(2447)(t);const{formatters:r}=e.exports;r.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},2447:(e,t,n)=>{e.exports=function(e){function t(e){let n,i,s,o=null;function a(...e){if(!a.enabled)return;const r=a,i=Number(new Date),s=i-(n||i);r.diff=s,r.prev=n,r.curr=i,n=i,e[0]=t.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let o=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,((n,i)=>{if("%%"===n)return"%";o++;const s=t.formatters[i];if("function"==typeof s){const t=e[o];n=s.call(r,t),e.splice(o,1),o--}return n})),t.formatArgs.call(r,e),(r.log||t.log).apply(r,e)}return a.namespace=e,a.useColors=t.useColors(),a.color=t.selectColor(e),a.extend=r,a.destroy=t.destroy,Object.defineProperty(a,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==o?o:(i!==t.namespaces&&(i=t.namespaces,s=t.enabled(e)),s),set:e=>{o=e}}),"function"==typeof t.init&&t.init(a),a}function r(e,n){const r=t(this.namespace+(void 0===n?":":n)+e);return r.log=this.log,r}function i(e){return e.toString().substring(2,e.toString().length-2).replace(/\.\*\?$/,"*")}return t.debug=t,t.default=t,t.coerce=function(e){return e instanceof Error?e.stack||e.message:e},t.disable=function(){const e=[...t.names.map(i),...t.skips.map(i).map((e=>"-"+e))].join(",");return t.enable(""),e},t.enable=function(e){let n;t.save(e),t.namespaces=e,t.names=[],t.skips=[];const r=("string"==typeof e?e:"").split(/[\s,]+/),i=r.length;for(n=0;n<i;n++)r[n]&&("-"===(e=r[n].replace(/\*/g,".*?"))[0]?t.skips.push(new RegExp("^"+e.slice(1)+"$")):t.names.push(new RegExp("^"+e+"$")))},t.enabled=function(e){if("*"===e[e.length-1])return!0;let n,r;for(n=0,r=t.skips.length;n<r;n++)if(t.skips[n].test(e))return!1;for(n=0,r=t.names.length;n<r;n++)if(t.names[n].test(e))return!0;return!1},t.humanize=n(7824),t.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach((n=>{t[n]=e[n]})),t.names=[],t.skips=[],t.formatters={},t.selectColor=function(e){let n=0;for(let t=0;t<e.length;t++)n=(n<<5)-n+e.charCodeAt(t),n|=0;return t.colors[Math.abs(n)%t.colors.length]},t.enable(t.load()),t}},2296:(e,t,n)=>{"use strict";var r=n(1044)(),i=n(210),s=r&&i("%Object.defineProperty%",!0);if(s)try{s({},"a",{value:1})}catch(e){s=!1}var o=i("%SyntaxError%"),a=i("%TypeError%"),c=n(7296);e.exports=function(e,t,n){if(!e||"object"!=typeof e&&"function"!=typeof e)throw new a("`obj` must be an object or a function`");if("string"!=typeof t&&"symbol"!=typeof t)throw new a("`property` must be a string or a symbol`");if(arguments.length>3&&"boolean"!=typeof arguments[3]&&null!==arguments[3])throw new a("`nonEnumerable`, if provided, must be a boolean or null");if(arguments.length>4&&"boolean"!=typeof arguments[4]&&null!==arguments[4])throw new a("`nonWritable`, if provided, must be a boolean or null");if(arguments.length>5&&"boolean"!=typeof arguments[5]&&null!==arguments[5])throw new a("`nonConfigurable`, if provided, must be a boolean or null");if(arguments.length>6&&"boolean"!=typeof arguments[6])throw new a("`loose`, if provided, must be a boolean");var r=arguments.length>3?arguments[3]:null,i=arguments.length>4?arguments[4]:null,l=arguments.length>5?arguments[5]:null,d=arguments.length>6&&arguments[6],u=!!c&&c(e,t);if(s)s(e,t,{configurable:null===l&&u?u.configurable:!l,enumerable:null===r&&u?u.enumerable:!r,value:n,writable:null===i&&u?u.writable:!i});else{if(!d&&(r||i||l))throw new o("This environment does not support defining a property as non-configurable, non-writable, or non-enumerable.");e[t]=n}}},2114:e=>{"use strict";function t(e,t){for(const n in t)Object.defineProperty(e,n,{value:t[n],enumerable:!0,configurable:!0});return e}e.exports=function(e,n,r){if(!e||"string"==typeof e)throw new TypeError("Please pass an Error to err-code");r||(r={}),"object"==typeof n&&(r=n,n=""),n&&(r.code=n);try{return t(e,r)}catch(n){r.message=e.message,r.stack=e.stack;const i=function(){};return i.prototype=Object.create(Object.getPrototypeOf(e)),t(new i,r)}}},7187:e=>{"use strict";var t,n="object"==typeof Reflect?Reflect:null,r=n&&"function"==typeof n.apply?n.apply:function(e,t,n){return Function.prototype.apply.call(e,t,n)};t=n&&"function"==typeof n.ownKeys?n.ownKeys:Object.getOwnPropertySymbols?function(e){return Object.getOwnPropertyNames(e).concat(Object.getOwnPropertySymbols(e))}:function(e){return Object.getOwnPropertyNames(e)};var i=Number.isNaN||function(e){return e!=e};function s(){s.init.call(this)}e.exports=s,e.exports.once=function(e,t){return new Promise((function(n,r){function i(n){e.removeListener(t,s),r(n)}function s(){"function"==typeof e.removeListener&&e.removeListener("error",i),n([].slice.call(arguments))}p(e,t,s,{once:!0}),"error"!==t&&function(e,t,n){"function"==typeof e.on&&p(e,"error",t,{once:!0})}(e,i)}))},s.EventEmitter=s,s.prototype._events=void 0,s.prototype._eventsCount=0,s.prototype._maxListeners=void 0;var o=10;function a(e){if("function"!=typeof e)throw new TypeError('The "listener" argument must be of type Function. Received type '+typeof e)}function c(e){return void 0===e._maxListeners?s.defaultMaxListeners:e._maxListeners}function l(e,t,n,r){var i,s,o,l;if(a(n),void 0===(s=e._events)?(s=e._events=Object.create(null),e._eventsCount=0):(void 0!==s.newListener&&(e.emit("newListener",t,n.listener?n.listener:n),s=e._events),o=s[t]),void 0===o)o=s[t]=n,++e._eventsCount;else if("function"==typeof o?o=s[t]=r?[n,o]:[o,n]:r?o.unshift(n):o.push(n),(i=c(e))>0&&o.length>i&&!o.warned){o.warned=!0;var d=new Error("Possible EventEmitter memory leak detected. "+o.length+" "+String(t)+" listeners added. Use emitter.setMaxListeners() to increase limit");d.name="MaxListenersExceededWarning",d.emitter=e,d.type=t,d.count=o.length,l=d,console&&console.warn&&console.warn(l)}return e}function d(){if(!this.fired)return this.target.removeListener(this.type,this.wrapFn),this.fired=!0,0===arguments.length?this.listener.call(this.target):this.listener.apply(this.target,arguments)}function u(e,t,n){var r={fired:!1,wrapFn:void 0,target:e,type:t,listener:n},i=d.bind(r);return i.listener=n,r.wrapFn=i,i}function h(e,t,n){var r=e._events;if(void 0===r)return[];var i=r[t];return void 0===i?[]:"function"==typeof i?n?[i.listener||i]:[i]:n?function(e){for(var t=new Array(e.length),n=0;n<t.length;++n)t[n]=e[n].listener||e[n];return t}(i):g(i,i.length)}function f(e){var t=this._events;if(void 0!==t){var n=t[e];if("function"==typeof n)return 1;if(void 0!==n)return n.length}return 0}function g(e,t){for(var n=new Array(t),r=0;r<t;++r)n[r]=e[r];return n}function p(e,t,n,r){if("function"==typeof e.on)r.once?e.once(t,n):e.on(t,n);else{if("function"!=typeof e.addEventListener)throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type '+typeof e);e.addEventListener(t,(function i(s){r.once&&e.removeEventListener(t,i),n(s)}))}}Object.defineProperty(s,"defaultMaxListeners",{enumerable:!0,get:function(){return o},set:function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received '+e+".");o=e}}),s.init=function(){void 0!==this._events&&this._events!==Object.getPrototypeOf(this)._events||(this._events=Object.create(null),this._eventsCount=0),this._maxListeners=this._maxListeners||void 0},s.prototype.setMaxListeners=function(e){if("number"!=typeof e||e<0||i(e))throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received '+e+".");return this._maxListeners=e,this},s.prototype.getMaxListeners=function(){return c(this)},s.prototype.emit=function(e){for(var t=[],n=1;n<arguments.length;n++)t.push(arguments[n]);var i="error"===e,s=this._events;if(void 0!==s)i=i&&void 0===s.error;else if(!i)return!1;if(i){var o;if(t.length>0&&(o=t[0]),o instanceof Error)throw o;var a=new Error("Unhandled error."+(o?" ("+o.message+")":""));throw a.context=o,a}var c=s[e];if(void 0===c)return!1;if("function"==typeof c)r(c,this,t);else{var l=c.length,d=g(c,l);for(n=0;n<l;++n)r(d[n],this,t)}return!0},s.prototype.addListener=function(e,t){return l(this,e,t,!1)},s.prototype.on=s.prototype.addListener,s.prototype.prependListener=function(e,t){return l(this,e,t,!0)},s.prototype.once=function(e,t){return a(t),this.on(e,u(this,e,t)),this},s.prototype.prependOnceListener=function(e,t){return a(t),this.prependListener(e,u(this,e,t)),this},s.prototype.removeListener=function(e,t){var n,r,i,s,o;if(a(t),void 0===(r=this._events))return this;if(void 0===(n=r[e]))return this;if(n===t||n.listener===t)0==--this._eventsCount?this._events=Object.create(null):(delete r[e],r.removeListener&&this.emit("removeListener",e,n.listener||t));else if("function"!=typeof n){for(i=-1,s=n.length-1;s>=0;s--)if(n[s]===t||n[s].listener===t){o=n[s].listener,i=s;break}if(i<0)return this;0===i?n.shift():function(e,t){for(;t+1<e.length;t++)e[t]=e[t+1];e.pop()}(n,i),1===n.length&&(r[e]=n[0]),void 0!==r.removeListener&&this.emit("removeListener",e,o||t)}return this},s.prototype.off=s.prototype.removeListener,s.prototype.removeAllListeners=function(e){var t,n,r;if(void 0===(n=this._events))return this;if(void 0===n.removeListener)return 0===arguments.length?(this._events=Object.create(null),this._eventsCount=0):void 0!==n[e]&&(0==--this._eventsCount?this._events=Object.create(null):delete n[e]),this;if(0===arguments.length){var i,s=Object.keys(n);for(r=0;r<s.length;++r)"removeListener"!==(i=s[r])&&this.removeAllListeners(i);return this.removeAllListeners("removeListener"),this._events=Object.create(null),this._eventsCount=0,this}if("function"==typeof(t=n[e]))this.removeListener(e,t);else if(void 0!==t)for(r=t.length-1;r>=0;r--)this.removeListener(e,t[r]);return this},s.prototype.listeners=function(e){return h(this,e,!0)},s.prototype.rawListeners=function(e){return h(this,e,!1)},s.listenerCount=function(e,t){return"function"==typeof e.listenerCount?e.listenerCount(t):f.call(e,t)},s.prototype.listenerCount=f,s.prototype.eventNames=function(){return this._eventsCount>0?t(this._events):[]}},7648:e=>{"use strict";var t=Object.prototype.toString,n=Math.max,r=function(e,t){for(var n=[],r=0;r<e.length;r+=1)n[r]=e[r];for(var i=0;i<t.length;i+=1)n[i+e.length]=t[i];return n};e.exports=function(e){var i=this;if("function"!=typeof i||"[object Function]"!==t.apply(i))throw new TypeError("Function.prototype.bind called on incompatible "+i);for(var s,o=function(e,t){for(var n=[],r=1,i=0;r<e.length;r+=1,i+=1)n[i]=e[r];return n}(arguments),a=n(0,i.length-o.length),c=[],l=0;l<a;l++)c[l]="$"+l;if(s=Function("binder","return function ("+function(e,t){for(var n="",r=0;r<e.length;r+=1)n+=e[r],r+1<e.length&&(n+=",");return n}(c)+"){ return binder.apply(this,arguments); }")((function(){if(this instanceof s){var t=i.apply(this,r(o,arguments));return Object(t)===t?t:this}return i.apply(e,r(o,arguments))})),i.prototype){var d=function(){};d.prototype=i.prototype,s.prototype=new d,d.prototype=null}return s}},8612:(e,t,n)=>{"use strict";var r=n(7648);e.exports=Function.prototype.bind||r},5177:e=>{e.exports=function(){if("undefined"==typeof globalThis)return null;var e={RTCPeerConnection:globalThis.RTCPeerConnection||globalThis.mozRTCPeerConnection||globalThis.webkitRTCPeerConnection,RTCSessionDescription:globalThis.RTCSessionDescription||globalThis.mozRTCSessionDescription||globalThis.webkitRTCSessionDescription,RTCIceCandidate:globalThis.RTCIceCandidate||globalThis.mozRTCIceCandidate||globalThis.webkitRTCIceCandidate};return e.RTCPeerConnection?e:null}},210:(e,t,n)=>{"use strict";var r,i=SyntaxError,s=Function,o=TypeError,a=function(e){try{return s('"use strict"; return ('+e+").constructor;")()}catch(e){}},c=Object.getOwnPropertyDescriptor;if(c)try{c({},"")}catch(e){c=null}var l=function(){throw new o},d=c?function(){try{return l}catch(e){try{return c(arguments,"callee").get}catch(e){return l}}}():l,u=n(1405)(),h=n(8185)(),f=Object.getPrototypeOf||(h?function(e){return e.__proto__}:null),g={},p="undefined"!=typeof Uint8Array&&f?f(Uint8Array):r,m={"%AggregateError%":"undefined"==typeof AggregateError?r:AggregateError,"%Array%":Array,"%ArrayBuffer%":"undefined"==typeof ArrayBuffer?r:ArrayBuffer,"%ArrayIteratorPrototype%":u&&f?f([][Symbol.iterator]()):r,"%AsyncFromSyncIteratorPrototype%":r,"%AsyncFunction%":g,"%AsyncGenerator%":g,"%AsyncGeneratorFunction%":g,"%AsyncIteratorPrototype%":g,"%Atomics%":"undefined"==typeof Atomics?r:Atomics,"%BigInt%":"undefined"==typeof BigInt?r:BigInt,"%BigInt64Array%":"undefined"==typeof BigInt64Array?r:BigInt64Array,"%BigUint64Array%":"undefined"==typeof BigUint64Array?r:BigUint64Array,"%Boolean%":Boolean,"%DataView%":"undefined"==typeof DataView?r:DataView,"%Date%":Date,"%decodeURI%":decodeURI,"%decodeURIComponent%":decodeURIComponent,"%encodeURI%":encodeURI,"%encodeURIComponent%":encodeURIComponent,"%Error%":Error,"%eval%":eval,"%EvalError%":EvalError,"%Float32Array%":"undefined"==typeof Float32Array?r:Float32Array,"%Float64Array%":"undefined"==typeof Float64Array?r:Float64Array,"%FinalizationRegistry%":"undefined"==typeof FinalizationRegistry?r:FinalizationRegistry,"%Function%":s,"%GeneratorFunction%":g,"%Int8Array%":"undefined"==typeof Int8Array?r:Int8Array,"%Int16Array%":"undefined"==typeof Int16Array?r:Int16Array,"%Int32Array%":"undefined"==typeof Int32Array?r:Int32Array,"%isFinite%":isFinite,"%isNaN%":isNaN,"%IteratorPrototype%":u&&f?f(f([][Symbol.iterator]())):r,"%JSON%":"object"==typeof JSON?JSON:r,"%Map%":"undefined"==typeof Map?r:Map,"%MapIteratorPrototype%":"undefined"!=typeof Map&&u&&f?f((new Map)[Symbol.iterator]()):r,"%Math%":Math,"%Number%":Number,"%Object%":Object,"%parseFloat%":parseFloat,"%parseInt%":parseInt,"%Promise%":"undefined"==typeof Promise?r:Promise,"%Proxy%":"undefined"==typeof Proxy?r:Proxy,"%RangeError%":RangeError,"%ReferenceError%":ReferenceError,"%Reflect%":"undefined"==typeof Reflect?r:Reflect,"%RegExp%":RegExp,"%Set%":"undefined"==typeof Set?r:Set,"%SetIteratorPrototype%":"undefined"!=typeof Set&&u&&f?f((new Set)[Symbol.iterator]()):r,"%SharedArrayBuffer%":"undefined"==typeof SharedArrayBuffer?r:SharedArrayBuffer,"%String%":String,"%StringIteratorPrototype%":u&&f?f(""[Symbol.iterator]()):r,"%Symbol%":u?Symbol:r,"%SyntaxError%":i,"%ThrowTypeError%":d,"%TypedArray%":p,"%TypeError%":o,"%Uint8Array%":"undefined"==typeof Uint8Array?r:Uint8Array,"%Uint8ClampedArray%":"undefined"==typeof Uint8ClampedArray?r:Uint8ClampedArray,"%Uint16Array%":"undefined"==typeof Uint16Array?r:Uint16Array,"%Uint32Array%":"undefined"==typeof Uint32Array?r:Uint32Array,"%URIError%":URIError,"%WeakMap%":"undefined"==typeof WeakMap?r:WeakMap,"%WeakRef%":"undefined"==typeof WeakRef?r:WeakRef,"%WeakSet%":"undefined"==typeof WeakSet?r:WeakSet};if(f)try{null.error}catch(e){var y=f(f(e));m["%Error.prototype%"]=y}var v=function e(t){var n;if("%AsyncFunction%"===t)n=a("async function () {}");else if("%GeneratorFunction%"===t)n=a("function* () {}");else if("%AsyncGeneratorFunction%"===t)n=a("async function* () {}");else if("%AsyncGenerator%"===t){var r=e("%AsyncGeneratorFunction%");r&&(n=r.prototype)}else if("%AsyncIteratorPrototype%"===t){var i=e("%AsyncGenerator%");i&&f&&(n=f(i.prototype))}return m[t]=n,n},b={"%ArrayBufferPrototype%":["ArrayBuffer","prototype"],"%ArrayPrototype%":["Array","prototype"],"%ArrayProto_entries%":["Array","prototype","entries"],"%ArrayProto_forEach%":["Array","prototype","forEach"],"%ArrayProto_keys%":["Array","prototype","keys"],"%ArrayProto_values%":["Array","prototype","values"],"%AsyncFunctionPrototype%":["AsyncFunction","prototype"],"%AsyncGenerator%":["AsyncGeneratorFunction","prototype"],"%AsyncGeneratorPrototype%":["AsyncGeneratorFunction","prototype","prototype"],"%BooleanPrototype%":["Boolean","prototype"],"%DataViewPrototype%":["DataView","prototype"],"%DatePrototype%":["Date","prototype"],"%ErrorPrototype%":["Error","prototype"],"%EvalErrorPrototype%":["EvalError","prototype"],"%Float32ArrayPrototype%":["Float32Array","prototype"],"%Float64ArrayPrototype%":["Float64Array","prototype"],"%FunctionPrototype%":["Function","prototype"],"%Generator%":["GeneratorFunction","prototype"],"%GeneratorPrototype%":["GeneratorFunction","prototype","prototype"],"%Int8ArrayPrototype%":["Int8Array","prototype"],"%Int16ArrayPrototype%":["Int16Array","prototype"],"%Int32ArrayPrototype%":["Int32Array","prototype"],"%JSONParse%":["JSON","parse"],"%JSONStringify%":["JSON","stringify"],"%MapPrototype%":["Map","prototype"],"%NumberPrototype%":["Number","prototype"],"%ObjectPrototype%":["Object","prototype"],"%ObjProto_toString%":["Object","prototype","toString"],"%ObjProto_valueOf%":["Object","prototype","valueOf"],"%PromisePrototype%":["Promise","prototype"],"%PromiseProto_then%":["Promise","prototype","then"],"%Promise_all%":["Promise","all"],"%Promise_reject%":["Promise","reject"],"%Promise_resolve%":["Promise","resolve"],"%RangeErrorPrototype%":["RangeError","prototype"],"%ReferenceErrorPrototype%":["ReferenceError","prototype"],"%RegExpPrototype%":["RegExp","prototype"],"%SetPrototype%":["Set","prototype"],"%SharedArrayBufferPrototype%":["SharedArrayBuffer","prototype"],"%StringPrototype%":["String","prototype"],"%SymbolPrototype%":["Symbol","prototype"],"%SyntaxErrorPrototype%":["SyntaxError","prototype"],"%TypedArrayPrototype%":["TypedArray","prototype"],"%TypeErrorPrototype%":["TypeError","prototype"],"%Uint8ArrayPrototype%":["Uint8Array","prototype"],"%Uint8ClampedArrayPrototype%":["Uint8ClampedArray","prototype"],"%Uint16ArrayPrototype%":["Uint16Array","prototype"],"%Uint32ArrayPrototype%":["Uint32Array","prototype"],"%URIErrorPrototype%":["URIError","prototype"],"%WeakMapPrototype%":["WeakMap","prototype"],"%WeakSetPrototype%":["WeakSet","prototype"]},_=n(8612),E=n(8824),w=_.call(Function.call,Array.prototype.concat),S=_.call(Function.apply,Array.prototype.splice),C=_.call(Function.call,String.prototype.replace),T=_.call(Function.call,String.prototype.slice),R=_.call(Function.call,RegExp.prototype.exec),I=/[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g,k=/\\(\\)?/g,O=function(e,t){var n,r=e;if(E(b,r)&&(r="%"+(n=b[r])[0]+"%"),E(m,r)){var s=m[r];if(s===g&&(s=v(r)),void 0===s&&!t)throw new o("intrinsic "+e+" exists, but is not available. Please file an issue!");return{alias:n,name:r,value:s}}throw new i("intrinsic "+e+" does not exist!")};e.exports=function(e,t){if("string"!=typeof e||0===e.length)throw new o("intrinsic name must be a non-empty string");if(arguments.length>1&&"boolean"!=typeof t)throw new o('"allowMissing" argument must be a boolean');if(null===R(/^%?[^%]*%?$/,e))throw new i("`%` may not be present anywhere but at the beginning and end of the intrinsic name");var n=function(e){var t=T(e,0,1),n=T(e,-1);if("%"===t&&"%"!==n)throw new i("invalid intrinsic syntax, expected closing `%`");if("%"===n&&"%"!==t)throw new i("invalid intrinsic syntax, expected opening `%`");var r=[];return C(e,I,(function(e,t,n,i){r[r.length]=n?C(i,k,"$1"):t||e})),r}(e),r=n.length>0?n[0]:"",s=O("%"+r+"%",t),a=s.name,l=s.value,d=!1,u=s.alias;u&&(r=u[0],S(n,w([0,1],u)));for(var h=1,f=!0;h<n.length;h+=1){var g=n[h],p=T(g,0,1),y=T(g,-1);if(('"'===p||"'"===p||"`"===p||'"'===y||"'"===y||"`"===y)&&p!==y)throw new i("property names with quotes must have matching quotes");if("constructor"!==g&&f||(d=!0),E(m,a="%"+(r+="."+g)+"%"))l=m[a];else if(null!=l){if(!(g in l)){if(!t)throw new o("base intrinsic for "+e+" exists, but the property is not available.");return}if(c&&h+1>=n.length){var v=c(l,g);l=(f=!!v)&&"get"in v&&!("originalValue"in v.get)?v.get:l[g]}else f=E(l,g),l=l[g];f&&!d&&(m[a]=l)}}return l}},7296:(e,t,n)=>{"use strict";var r=n(210)("%Object.getOwnPropertyDescriptor%",!0);if(r)try{r([],"length")}catch(e){r=null}e.exports=r},1044:(e,t,n)=>{"use strict";var r=n(210)("%Object.defineProperty%",!0),i=function(){if(r)try{return r({},"a",{value:1}),!0}catch(e){return!1}return!1};i.hasArrayLengthDefineBug=function(){if(!i())return null;try{return 1!==r([],"length",{value:1}).length}catch(e){return!0}},e.exports=i},8185:e=>{"use strict";var t={foo:{}},n=Object;e.exports=function(){return{__proto__:t}.foo===t.foo&&!({__proto__:null}instanceof n)}},1405:(e,t,n)=>{"use strict";var r="undefined"!=typeof Symbol&&Symbol,i=n(5419);e.exports=function(){return"function"==typeof r&&"function"==typeof Symbol&&"symbol"==typeof r("foo")&&"symbol"==typeof Symbol("bar")&&i()}},5419:e=>{"use strict";e.exports=function(){if("function"!=typeof Symbol||"function"!=typeof Object.getOwnPropertySymbols)return!1;if("symbol"==typeof Symbol.iterator)return!0;var e={},t=Symbol("test"),n=Object(t);if("string"==typeof t)return!1;if("[object Symbol]"!==Object.prototype.toString.call(t))return!1;if("[object Symbol]"!==Object.prototype.toString.call(n))return!1;for(t in e[t]=42,e)return!1;if("function"==typeof Object.keys&&0!==Object.keys(e).length)return!1;if("function"==typeof Object.getOwnPropertyNames&&0!==Object.getOwnPropertyNames(e).length)return!1;var r=Object.getOwnPropertySymbols(e);if(1!==r.length||r[0]!==t)return!1;if(!Object.prototype.propertyIsEnumerable.call(e,t))return!1;if("function"==typeof Object.getOwnPropertyDescriptor){var i=Object.getOwnPropertyDescriptor(e,t);if(42!==i.value||!0!==i.enumerable)return!1}return!0}},8824:(e,t,n)=>{"use strict";var r=Function.prototype.call,i=Object.prototype.hasOwnProperty,s=n(8612);e.exports=s.call(r,i)},645:(e,t)=>{t.read=function(e,t,n,r,i){var s,o,a=8*i-r-1,c=(1<<a)-1,l=c>>1,d=-7,u=n?i-1:0,h=n?-1:1,f=e[t+u];for(u+=h,s=f&(1<<-d)-1,f>>=-d,d+=a;d>0;s=256*s+e[t+u],u+=h,d-=8);for(o=s&(1<<-d)-1,s>>=-d,d+=r;d>0;o=256*o+e[t+u],u+=h,d-=8);if(0===s)s=1-l;else{if(s===c)return o?NaN:1/0*(f?-1:1);o+=Math.pow(2,r),s-=l}return(f?-1:1)*o*Math.pow(2,s-r)},t.write=function(e,t,n,r,i,s){var o,a,c,l=8*s-i-1,d=(1<<l)-1,u=d>>1,h=23===i?Math.pow(2,-24)-Math.pow(2,-77):0,f=r?0:s-1,g=r?1:-1,p=t<0||0===t&&1/t<0?1:0;for(t=Math.abs(t),isNaN(t)||t===1/0?(a=isNaN(t)?1:0,o=d):(o=Math.floor(Math.log(t)/Math.LN2),t*(c=Math.pow(2,-o))<1&&(o--,c*=2),(t+=o+u>=1?h/c:h*Math.pow(2,1-u))*c>=2&&(o++,c/=2),o+u>=d?(a=0,o=d):o+u>=1?(a=(t*c-1)*Math.pow(2,i),o+=u):(a=t*Math.pow(2,u-1)*Math.pow(2,i),o=0));i>=8;e[n+f]=255&a,f+=g,a/=256,i-=8);for(o=o<<i|a,l+=i;l>0;e[n+f]=255&o,f+=g,o/=256,l-=8);e[n+f-g]|=128*p}},5717:e=>{"function"==typeof Object.create?e.exports=function(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}))}:e.exports=function(e,t){if(t){e.super_=t;var n=function(){};n.prototype=t.prototype,e.prototype=new n,e.prototype.constructor=e}}},2043:function(e,t,n){var r,i;!function(s,o){"use strict";r=function(){var e=function(){},t="undefined",n=typeof window!==t&&typeof window.navigator!==t&&/Trident\/|MSIE /.test(window.navigator.userAgent),r=["trace","debug","info","warn","error"];function i(e,t){var n=e[t];if("function"==typeof n.bind)return n.bind(e);try{return Function.prototype.bind.call(n,e)}catch(t){return function(){return Function.prototype.apply.apply(n,[e,arguments])}}}function s(){console.log&&(console.log.apply?console.log.apply(console,arguments):Function.prototype.apply.apply(console.log,[console,arguments])),console.trace&&console.trace()}function o(t,n){for(var i=0;i<r.length;i++){var s=r[i];this[s]=i<t?e:this.methodFactory(s,t,n)}this.log=this.debug}function a(e,n,r){return function(){typeof console!==t&&(o.call(this,n,r),this[e].apply(this,arguments))}}function c(r,o,c){return function(r){return"debug"===r&&(r="log"),typeof console!==t&&("trace"===r&&n?s:void 0!==console[r]?i(console,r):void 0!==console.log?i(console,"log"):e)}(r)||a.apply(this,arguments)}function l(e,n,i){var s,a=this;n=null==n?"WARN":n;var l="loglevel";function d(){var e;if(typeof window!==t&&l){try{e=window.localStorage[l]}catch(e){}if(typeof e===t)try{var n=window.document.cookie,r=n.indexOf(encodeURIComponent(l)+"=");-1!==r&&(e=/^([^;]+)/.exec(n.slice(r))[1])}catch(e){}return void 0===a.levels[e]&&(e=void 0),e}}"string"==typeof e?l+=":"+e:"symbol"==typeof e&&(l=void 0),a.name=e,a.levels={TRACE:0,DEBUG:1,INFO:2,WARN:3,ERROR:4,SILENT:5},a.methodFactory=i||c,a.getLevel=function(){return s},a.setLevel=function(n,i){if("string"==typeof n&&void 0!==a.levels[n.toUpperCase()]&&(n=a.levels[n.toUpperCase()]),!("number"==typeof n&&n>=0&&n<=a.levels.SILENT))throw"log.setLevel() called with invalid level: "+n;if(s=n,!1!==i&&function(e){var n=(r[e]||"silent").toUpperCase();if(typeof window!==t&&l){try{return void(window.localStorage[l]=n)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"="+n+";"}catch(e){}}}(n),o.call(a,n,e),typeof console===t&&n<a.levels.SILENT)return"No console available for logging"},a.setDefaultLevel=function(e){n=e,d()||a.setLevel(e,!1)},a.resetLevel=function(){a.setLevel(n,!1),function(){if(typeof window!==t&&l){try{return void window.localStorage.removeItem(l)}catch(e){}try{window.document.cookie=encodeURIComponent(l)+"=; expires=Thu, 01 Jan 1970 00:00:00 UTC"}catch(e){}}}()},a.enableAll=function(e){a.setLevel(a.levels.TRACE,e)},a.disableAll=function(e){a.setLevel(a.levels.SILENT,e)};var u=d();null==u&&(u=n),a.setLevel(u,!1)}var d=new l,u={};d.getLogger=function(e){if("symbol"!=typeof e&&"string"!=typeof e||""===e)throw new TypeError("You must supply a name when creating a logger.");var t=u[e];return t||(t=u[e]=new l(e,d.getLevel(),d.methodFactory)),t};var h=typeof window!==t?window.log:void 0;return d.noConflict=function(){return typeof window!==t&&window.log===d&&(window.log=h),d},d.getLoggers=function(){return u},d.default=d,d},void 0===(i=r.call(t,n,t,e))||(e.exports=i)}()},686:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleEvents=void 0;var r=n(5998),i=n(1940),s=n(5617),o=n(4600),a=n(6931),c=n(3637),l=n(5492);function d(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function u(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function h(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var f=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),h(this,"interpreters",new r.NamespacedMap([[s.LEGACY_M_ROOM_MESSAGE,s.parseMRoomMessage],[a.M_MESSAGE,o.parseMMessage],[a.M_EMOTE,o.parseMMessage],[a.M_NOTICE,o.parseMMessage],[c.M_POLL_START,l.parseMPoll],[c.M_POLL_RESPONSE,l.parseMPoll],[c.M_POLL_END,l.parseMPoll]])),h(this,"_unknownInterpretOrder",[a.M_MESSAGE])}var t,n,f;return t=e,f=[{key:"defaultInstance",get:function(){return e._defaultInstance}},{key:"unknownInterpretOrder",get:function(){return e.defaultInstance.unknownInterpretOrder},set:function(t){e.defaultInstance.unknownInterpretOrder=t}},{key:"registerInterpreter",value:function(t,n){e.defaultInstance.registerInterpreter(t,n)}},{key:"parse",value:function(t){return e.defaultInstance.parse(t)}}],(n=[{key:"unknownInterpretOrder",get:function(){var e;return null!==(e=this._unknownInterpretOrder)&&void 0!==e?e:[]},set:function(e){this._unknownInterpretOrder=e}},{key:"registerInterpreter",value:function(e,t){this.interpreters.set(e,t)}},{key:"parse",value:function(e){try{if(this.interpreters.hasNamespaced(e.type))return this.interpreters.getNamespaced(e.type)(e);var t,n=function(e,t){var n="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!n){if(Array.isArray(e)||(n=function(e,t){if(e){if("string"==typeof e)return d(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?d(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){n&&(e=n);var r=0,i=function(){};return{s:i,n:function(){return r>=e.length?{done:!0}:{done:!1,value:e[r++]}},e:function(e){throw e},f:i}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var s,o=!0,a=!1;return{s:function(){n=n.call(e)},n:function(){var e=n.next();return o=e.done,e},e:function(e){a=!0,s=e},f:function(){try{o||null==n.return||n.return()}finally{if(a)throw s}}}}(this.unknownInterpretOrder);try{for(n.s();!(t=n.n()).done;){var r=t.value;if(this.interpreters.has(r)){var s=this.interpreters.get(r)(e);if(s)return s}}}catch(e){n.e(e)}finally{n.f()}return null}catch(e){if(e instanceof i.InvalidEventError)return null;throw e}}}])&&u(t.prototype,n),f&&u(t,f),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.ExtensibleEvents=f,h(f,"_defaultInstance",new f)},2508:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},1940:(e,t)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function r(e){var t="function"==typeof Map?new Map:void 0;return r=function(e){if(null===e||(n=e,-1===Function.toString.call(n).indexOf("[native code]")))return e;var n;if("function"!=typeof e)throw new TypeError("Super expression must either be null or a function");if(void 0!==t){if(t.has(e))return t.get(e);t.set(e,r)}function r(){return i(e,arguments,a(this).constructor)}return r.prototype=Object.create(e.prototype,{constructor:{value:r,enumerable:!1,writable:!0,configurable:!0}}),o(r,e)},r(e)}function i(e,t,n){return i=s()?Reflect.construct:function(e,t,n){var r=[null];r.push.apply(r,t);var i=new(Function.bind.apply(e,r));return n&&o(i,n.prototype),i},i.apply(null,arguments)}function s(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}function o(e,t){return o=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},o(e,t)}function a(e){return a=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},a(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidEventError=void 0;var c=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&o(e,t)}(l,e);var t,r,i,c=(r=l,i=s(),function(){var e,t=a(r);if(i){var s=a(this).constructor;e=Reflect.construct(t,arguments,s)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function l(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,l),c.call(this,e)}return t=l,Object.defineProperty(t,"prototype",{writable:!1}),t}(r(Error));t.InvalidEventError=c},5998:(e,t)=>{"use strict";function n(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function r(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}Object.defineProperty(t,"__esModule",{value:!0}),t.NamespacedMap=void 0;var i=function(){function e(t){var r,i,s;if(function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),r=this,i="internalMap",s=new Map,i in r?Object.defineProperty(r,i,{value:s,enumerable:!0,configurable:!0,writable:!0}):r[i]=s,t){var o,a=function(e,t){var r="undefined"!=typeof Symbol&&e[Symbol.iterator]||e["@@iterator"];if(!r){if(Array.isArray(e)||(r=function(e,t){if(e){if("string"==typeof e)return n(e,t);var r=Object.prototype.toString.call(e).slice(8,-1);return"Object"===r&&e.constructor&&(r=e.constructor.name),"Map"===r||"Set"===r?Array.from(e):"Arguments"===r||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(r)?n(e,t):void 0}}(e))||t&&e&&"number"==typeof e.length){r&&(e=r);var i=0,s=function(){};return{s,n:function(){return i>=e.length?{done:!0}:{done:!1,value:e[i++]}},e:function(e){throw e},f:s}}throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}var o,a=!0,c=!1;return{s:function(){r=r.call(e)},n:function(){var e=r.next();return a=e.done,e},e:function(e){c=!0,o=e},f:function(){try{a||null==r.return||r.return()}finally{if(c)throw o}}}}(t);try{for(a.s();!(o=a.n()).done;){var c=o.value;this.set(c[0],c[1])}}catch(e){a.e(e)}finally{a.f()}}}var t,i;return t=e,(i=[{key:"get",value:function(e){return e.name&&this.internalMap.has(e.name)?this.internalMap.get(e.name):e.altName&&this.internalMap.has(e.altName)?this.internalMap.get(e.altName):null}},{key:"set",value:function(e,t){e.name&&this.internalMap.set(e.name,t),e.altName&&this.internalMap.set(e.altName,t)}},{key:"has",value:function(e){return!!this.get(e)}},{key:"delete",value:function(e){e.name&&this.internalMap.delete(e.name),e.altName&&this.internalMap.delete(e.altName)}},{key:"hasNamespaced",value:function(e){return this.internalMap.has(e)}},{key:"getNamespaced",value:function(e){return this.internalMap.get(e)}}])&&r(t.prototype,i),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.NamespacedMap=i},4355:(e,t)=>{"use strict";function n(e){return n="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},n(e)}function r(e,t){return r=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},r(e,t)}function i(e){return i=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},i(e)}function s(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function a(e,t,n){return t&&o(e.prototype,t),n&&o(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}Object.defineProperty(t,"__esModule",{value:!0}),t.UnstableValue=t.NamespacedValue=void 0;var c=function(){function e(t,n){if(s(this,e),this.stable=t,this.unstable=n,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}return a(e,[{key:"name",get:function(){return this.stable?this.stable:this.unstable}},{key:"altName",get:function(){return this.stable?this.unstable:null}},{key:"matches",value:function(e){return!!this.name&&this.name===e||!!this.altName&&this.altName===e}},{key:"findIn",value:function(e){var t;return this.name&&(t=null==e?void 0:e[this.name]),!t&&this.altName&&(t=null==e?void 0:e[this.altName]),t}},{key:"includedIn",value:function(e){var t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}}]),e}();t.NamespacedValue=c;var l=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&r(e,t)}(l,e);var t,o,c=(t=l,o=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,r=i(t);if(o){var s=i(this).constructor;e=Reflect.construct(r,arguments,s)}else e=r.apply(this,arguments);return function(e,t){if(t&&("object"===n(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function l(e,t){var n;if(s(this,l),!(n=c.call(this,e,t)).unstable)throw new Error("Unstable value must be supplied");return n}return a(l,[{key:"name",get:function(){return this.unstable}},{key:"altName",get:function(){return this.stable}}]),l}(c);t.UnstableValue=l},4449:(e,t,n)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.EmoteEvent=void 0;var i=n(3240),s=n(6931),o=n(8472);function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function l(){return l="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=u(e)););return e}(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},l.apply(this,arguments)}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(e,t)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}var h=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&d(e,t)}(p,e);var t,n,i,h,f,g=(h=p,f=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=u(h);if(f){var n=u(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function p(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,p),g.call(this,e)}return t=p,i=[{key:"from",value:function(e,t){var n;return new p({type:s.M_EMOTE.name,content:(n={},a(n,s.M_TEXT.name,e),a(n,s.M_HTML.name,t),n)})}}],(n=[{key:"isEmote",get:function(){return!0}},{key:"isEquivalentTo",value:function(e){return(0,o.isEventTypeSame)(e,s.M_EMOTE)||l(u(p.prototype),"isEquivalentTo",this).call(this,e)}},{key:"serialize",value:function(){var e=l(u(p.prototype),"serialize",this).call(this);return e.content.msgtype="m.emote",e}}])&&c(t.prototype,n),i&&c(t,i),Object.defineProperty(t,"prototype",{writable:!1}),p}(i.MessageEvent);t.EmoteEvent=h},2869:(e,t)=>{"use strict";function n(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}Object.defineProperty(t,"__esModule",{value:!0}),t.ExtensibleEvent=void 0;var r=function(){function e(t){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.wireFormat=t}var t,r;return t=e,(r=[{key:"wireContent",get:function(){return this.wireFormat.content}}])&&n(t.prototype,r),Object.defineProperty(t,"prototype",{writable:!1}),e}();t.ExtensibleEvent=r},3240:(e,t,n)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.MessageEvent=void 0;var i=n(2869),s=n(2932),o=n(1940),a=n(6931),c=n(8472);function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?l(Object(n),!0).forEach((function(t){p(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function u(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function h(e,t){return h=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},h(e,t)}function f(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function g(e){return g=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},g(e)}function p(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var m=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&h(e,t)}(v,e);var t,n,i,l,m,y=(l=v,m=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=g(l);if(m){var n=g(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return f(e)}(this,e)});function v(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,v),p(f(t=y.call(this,e)),"text",void 0),p(f(t),"html",void 0),p(f(t),"renderings",void 0);var n=a.M_MESSAGE.findIn(t.wireContent),r=a.M_TEXT.findIn(t.wireContent),i=a.M_HTML.findIn(t.wireContent);if((0,s.isProvided)(n)){if(!Array.isArray(n))throw new o.InvalidEventError("m.message contents must be an array");var c=n.find((function(e){return!(0,s.isProvided)(e.mimetype)||"text/plain"===e.mimetype})),l=n.find((function(e){return"text/html"===e.mimetype}));if(!c)throw new o.InvalidEventError("m.message is missing a plain text representation");t.text=c.body,t.html=null==l?void 0:l.body,t.renderings=n}else{if(!(0,s.isOptionalAString)(r))throw new o.InvalidEventError("Missing textual representation for event");t.text=r,t.html=i,t.renderings=[{body:r,mimetype:"text/plain"}],t.html&&t.renderings.push({body:t.html,mimetype:"text/html"})}return t}return t=v,i=[{key:"from",value:function(e,t){var n;return new v({type:a.M_MESSAGE.name,content:(n={},p(n,a.M_TEXT.name,e),p(n,a.M_HTML.name,t),n)})}}],(n=[{key:"isEmote",get:function(){return a.M_EMOTE.matches(this.wireFormat.type)||(0,s.isProvided)(a.M_EMOTE.findIn(this.wireFormat.content))}},{key:"isNotice",get:function(){return a.M_NOTICE.matches(this.wireFormat.type)||(0,s.isProvided)(a.M_NOTICE.findIn(this.wireFormat.content))}},{key:"isEquivalentTo",value:function(e){return(0,c.isEventTypeSame)(e,a.M_MESSAGE)}},{key:"serializeMMessageOnly",value:function(){var e=p({},a.M_MESSAGE.name,this.renderings);if(1===this.renderings.length){var t=this.renderings[0].mimetype;void 0!==t&&"text/plain"!==t||(e=p({},a.M_TEXT.name,this.renderings[0].body))}return e}},{key:"serialize",value:function(){var e;return{type:"m.room.message",content:d(d({},this.serializeMMessageOnly()),{},{body:this.text,msgtype:"m.text",format:this.html?"org.matrix.custom.html":void 0,formatted_body:null!==(e=this.html)&&void 0!==e?e:void 0})}}}])&&u(t.prototype,n),i&&u(t,i),Object.defineProperty(t,"prototype",{writable:!1}),v}(i.ExtensibleEvent);t.MessageEvent=m},4808:(e,t,n)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.NoticeEvent=void 0;var i=n(3240),s=n(6931),o=n(8472);function a(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function c(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function l(){return l="undefined"!=typeof Reflect&&Reflect.get?Reflect.get:function(e,t,n){var r=function(e,t){for(;!Object.prototype.hasOwnProperty.call(e,t)&&null!==(e=u(e)););return e}(e,t);if(r){var i=Object.getOwnPropertyDescriptor(r,t);return i.get?i.get.call(arguments.length<3?e:n):i.value}},l.apply(this,arguments)}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(e,t)}function u(e){return u=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},u(e)}var h=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&d(e,t)}(p,e);var t,n,i,h,f,g=(h=p,f=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=u(h);if(f){var n=u(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return function(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}(e)}(this,e)});function p(e){return function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,p),g.call(this,e)}return t=p,i=[{key:"from",value:function(e,t){var n;return new p({type:s.M_NOTICE.name,content:(n={},a(n,s.M_TEXT.name,e),a(n,s.M_HTML.name,t),n)})}}],(n=[{key:"isNotice",get:function(){return!0}},{key:"isEquivalentTo",value:function(e){return(0,o.isEventTypeSame)(e,s.M_NOTICE)||l(u(p.prototype),"isEquivalentTo",this).call(this,e)}},{key:"serialize",value:function(){var e=l(u(p.prototype),"serialize",this).call(this);return e.content.msgtype="m.notice",e}}])&&c(t.prototype,n),i&&c(t,i),Object.defineProperty(t,"prototype",{writable:!1}),p}(i.MessageEvent);t.NoticeEvent=h},5510:(e,t,n)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.PollEndEvent=void 0;var i=n(3637),s=n(1940),o=n(1210),a=n(3240),c=n(6931),l=n(8472);function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function u(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?d(Object(n),!0).forEach((function(t){m(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function h(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function f(e,t){return f=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},f(e,t)}function g(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function p(e){return p=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},p(e)}function m(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var y=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&f(e,t)}(_,e);var t,n,d,y,v,b=(y=_,v=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=p(y);if(v){var n=p(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return g(e)}(this,e)});function _(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,_),m(g(t=b.call(this,e)),"pollEventId",void 0),m(g(t),"closingMessage",void 0);var n=t.wireContent["m.relates_to"];if(!o.REFERENCE_RELATION.matches(null==n?void 0:n.rel_type)||"string"!=typeof(null==n?void 0:n.event_id))throw new s.InvalidEventError("Relationship must be a reference to an event");return t.pollEventId=n.event_id,t.closingMessage=new a.MessageEvent(t.wireFormat),t}return t=_,d=[{key:"from",value:function(e,t){var n;return new _({type:i.M_POLL_END.name,content:(n={"m.relates_to":{rel_type:o.REFERENCE_RELATION.name,event_id:e}},m(n,i.M_POLL_END.name,{}),m(n,c.M_TEXT.name,t),n)})}}],(n=[{key:"isEquivalentTo",value:function(e){return(0,l.isEventTypeSame)(e,i.M_POLL_END)}},{key:"serialize",value:function(){return{type:i.M_POLL_END.name,content:u(m({"m.relates_to":{rel_type:o.REFERENCE_RELATION.name,event_id:this.pollEventId}},i.M_POLL_END.name,{}),this.closingMessage.serialize().content)}}}])&&h(t.prototype,n),d&&h(t,d),Object.defineProperty(t,"prototype",{writable:!1}),_}(n(2869).ExtensibleEvent);t.PollEndEvent=y},4648:(e,t,n)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.PollResponseEvent=void 0;var i=n(2869),s=n(3637),o=n(1940),a=n(1210),c=n(8472);function l(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function d(e,t){return d=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},d(e,t)}function u(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function h(e){return h=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},h(e)}function f(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var g=function(e){!function(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&d(e,t)}(y,e);var t,n,i,g,p,m=(g=y,p=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}(),function(){var e,t=h(g);if(p){var n=h(this).constructor;e=Reflect.construct(t,arguments,n)}else e=t.apply(this,arguments);return function(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return u(e)}(this,e)});function y(e){var t;!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,y),f(u(t=m.call(this,e)),"internalAnswerIds",void 0),f(u(t),"internalSpoiled",void 0),f(u(t),"pollEventId",void 0);var n=t.wireContent["m.relates_to"];if(!a.REFERENCE_RELATION.matches(null==n?void 0:n.rel_type)||"string"!=typeof(null==n?void 0:n.event_id))throw new o.InvalidEventError("Relationship must be a reference to an event");return t.pollEventId=n.event_id,t.validateAgainst(null),t}return t=y,i=[{key:"from",value:function(e,t){return new y({type:s.M_POLL_RESPONSE.name,content:f({"m.relates_to":{rel_type:a.REFERENCE_RELATION.name,event_id:t}},s.M_POLL_RESPONSE.name,{answers:e})})}}],(n=[{key:"answerIds",get:function(){return this.internalAnswerIds}},{key:"spoiled",get:function(){return this.internalSpoiled}},{key:"validateAgainst",value:function(e){var t=s.M_POLL_RESPONSE.findIn(this.wireContent);if(!Array.isArray(null==t?void 0:t.answers))return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);var n=t.answers;if(n.some((function(e){return"string"!=typeof e}))||0===n.length)return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);if(e){if(n.some((function(t){return!e.answers.some((function(e){return e.id===t}))})))return this.internalSpoiled=!0,void(this.internalAnswerIds=[]);n=n.slice(0,e.maxSelections)}this.internalAnswerIds=n,this.internalSpoiled=!1}},{key:"isEquivalentTo",value:function(e){return(0,c.isEventTypeSame)(e,s.M_POLL_RESPONSE)}},{key:"serialize",value:function(){return{type:s.M_POLL_RESPONSE.name,content:f({"m.relates_to":{rel_type:a.REFERENCE_RELATION.name,event_id:this.pollEventId}},s.M_POLL_RESPONSE.name,{answers:this.spoiled?void 0:this.answerIds})}}}])&&l(t.prototype,n),i&&l(t,i),Object.defineProperty(t,"prototype",{writable:!1}),y}(i.ExtensibleEvent);t.PollResponseEvent=g},8267:(e,t,n)=>{"use strict";function r(e){return r="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},r(e)}Object.defineProperty(t,"__esModule",{value:!0}),t.PollStartEvent=t.PollAnswerSubevent=void 0;var i=n(3637),s=n(3240),o=n(6931),a=n(1940),c=n(4355),l=n(8472),d=n(2869);function u(e,t){(null==t||t>e.length)&&(t=e.length);for(var n=0,r=new Array(t);n<t;n++)r[n]=e[n];return r}function h(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function f(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?h(Object(n),!0).forEach((function(t){w(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):h(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function g(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function p(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,r.key,r)}}function m(e,t,n){return t&&p(e.prototype,t),n&&p(e,n),Object.defineProperty(e,"prototype",{writable:!1}),e}function y(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function");e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,writable:!0,configurable:!0}}),Object.defineProperty(e,"prototype",{writable:!1}),t&&v(e,t)}function v(e,t){return v=Object.setPrototypeOf||function(e,t){return e.__proto__=t,e},v(e,t)}function b(e){var t=function(){if("undefined"==typeof Reflect||!Reflect.construct)return!1;if(Reflect.construct.sham)return!1;if("function"==typeof Proxy)return!0;try{return Boolean.prototype.valueOf.call(Reflect.construct(Boolean,[],(function(){}))),!0}catch(e){return!1}}();return function(){var n,i=E(e);if(t){var s=E(this).constructor;n=Reflect.construct(i,arguments,s)}else n=i.apply(this,arguments);return function(e,t){if(t&&("object"===r(t)||"function"==typeof t))return t;if(void 0!==t)throw new TypeError("Derived constructors may only return object or undefined");return _(e)}(this,n)}}function _(e){if(void 0===e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return e}function E(e){return E=Object.setPrototypeOf?Object.getPrototypeOf:function(e){return e.__proto__||Object.getPrototypeOf(e)},E(e)}function w(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var S=function(e){y(n,e);var t=b(n);function n(e){var r;g(this,n),w(_(r=t.call(this,e)),"id",void 0);var i=e.content.id;if(!i||"string"!=typeof i)throw new a.InvalidEventError("Answer ID must be a non-empty string");return r.id=i,r}return m(n,[{key:"serialize",value:function(){return{type:"org.matrix.sdk.poll.answer",content:f({id:this.id},this.serializeMMessageOnly())}}}],[{key:"from",value:function(e,t){return new n({type:"org.matrix.sdk.poll.answer",content:w({id:e},o.M_TEXT.name,t)})}}]),n}(s.MessageEvent);t.PollAnswerSubevent=S;var C=function(e){y(n,e);var t=b(n);function n(e){var r;g(this,n),w(_(r=t.call(this,e)),"question",void 0),w(_(r),"kind",void 0),w(_(r),"rawKind",void 0),w(_(r),"maxSelections",void 0),w(_(r),"answers",void 0);var o=i.M_POLL_START.findIn(r.wireContent);if(!o.question)throw new a.InvalidEventError("A question is required");if(r.question=new s.MessageEvent({type:"org.matrix.sdk.poll.question",content:o.question}),r.rawKind=o.kind,i.M_POLL_KIND_DISCLOSED.matches(r.rawKind)?r.kind=i.M_POLL_KIND_DISCLOSED:r.kind=i.M_POLL_KIND_UNDISCLOSED,r.maxSelections=Number.isFinite(o.max_selections)&&o.max_selections>0?o.max_selections:1,!Array.isArray(o.answers))throw new a.InvalidEventError("Poll answers must be an array");var c=o.answers.slice(0,20).map((function(e){return new S({type:"org.matrix.sdk.poll.answer",content:e})}));if(c.length<=0)throw new a.InvalidEventError("No answers available");return r.answers=c,r}return m(n,[{key:"isEquivalentTo",value:function(e){return(0,l.isEventTypeSame)(e,i.M_POLL_START)}},{key:"serialize",value:function(){var e;return{type:i.M_POLL_START.name,content:(e={},w(e,i.M_POLL_START.name,{question:this.question.serialize().content,kind:this.rawKind,max_selections:this.maxSelections,answers:this.answers.map((function(e){return e.serialize().content}))}),w(e,o.M_TEXT.name,"".concat(this.question.text,"\n").concat(this.answers.map((function(e,t){return"".concat(t+1,". ").concat(e.text)})).join("\n"))),e)}}}],[{key:"from",value:function(e,t,r){var s,a=arguments.length>3&&void 0!==arguments[3]?arguments[3]:1;return new n({type:i.M_POLL_START.name,content:(s={},w(s,o.M_TEXT.name,e),w(s,i.M_POLL_START.name,{question:w({},o.M_TEXT.name,e),kind:r instanceof c.NamespacedValue?r.name:r,max_selections:a,answers:t.map((function(e){return w({id:(t=Array(16),function(e){if(Array.isArray(e))return u(e)}(t)||function(e){if("undefined"!=typeof Symbol&&null!=e[Symbol.iterator]||null!=e["@@iterator"])return Array.from(e)}(t)||function(e,t){if(e){if("string"==typeof e)return u(e,t);var n=Object.prototype.toString.call(e).slice(8,-1);return"Object"===n&&e.constructor&&(n=e.constructor.name),"Map"===n||"Set"===n?Array.from(e):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?u(e,t):void 0}}(t)||function(){throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()).map((function(){return T.charAt(Math.floor(Math.random()*T.length))})).join("")},o.M_TEXT.name,e);var t}))}),s)})}}]),n}(d.ExtensibleEvent);t.PollStartEvent=C;var T="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789"},6931:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.M_TEXT=t.M_NOTICE=t.M_MESSAGE=t.M_HTML=t.M_EMOTE=void 0;var r=n(4355),i=new r.UnstableValue("m.message","org.matrix.msc1767.message");t.M_MESSAGE=i;var s=new r.UnstableValue("m.text","org.matrix.msc1767.text");t.M_TEXT=s;var o=new r.UnstableValue("m.html","org.matrix.msc1767.html");t.M_HTML=o;var a=new r.UnstableValue("m.emote","org.matrix.msc1767.emote");t.M_EMOTE=a;var c=new r.UnstableValue("m.notice","org.matrix.msc1767.notice");t.M_NOTICE=c},3637:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.M_POLL_START=t.M_POLL_RESPONSE=t.M_POLL_KIND_UNDISCLOSED=t.M_POLL_KIND_DISCLOSED=t.M_POLL_END=void 0;var r=n(4355),i=new r.UnstableValue("m.poll.disclosed","org.matrix.msc3381.poll.disclosed");t.M_POLL_KIND_DISCLOSED=i;var s=new r.UnstableValue("m.poll.undisclosed","org.matrix.msc3381.poll.undisclosed");t.M_POLL_KIND_UNDISCLOSED=s;var o=new r.UnstableValue("m.poll.start","org.matrix.msc3381.poll.start");t.M_POLL_START=o;var a=new r.UnstableValue("m.poll.response","org.matrix.msc3381.poll.response");t.M_POLL_RESPONSE=a;var c=new r.UnstableValue("m.poll.end","org.matrix.msc3381.poll.end");t.M_POLL_END=c},1210:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.REFERENCE_RELATION=void 0;var r=new(n(4355).NamespacedValue)("m.reference");t.REFERENCE_RELATION=r},1333:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r=n(686);Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===r[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}}))}));var i=n(2508);Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===i[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}}))}));var s=n(1940);Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===s[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}}))}));var o=n(4355);Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===o[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}}))}));var a=n(5998);Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===a[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}}))}));var c=n(2932);Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===c[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=n(2117);Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===l[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return l[e]}}))}));var d=n(8472);Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===d[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return d[e]}}))}));var u=n(5617);Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===u[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return u[e]}}))}));var h=n(4600);Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===h[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return h[e]}}))}));var f=n(5492);Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===f[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return f[e]}}))}));var g=n(1210);Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===g[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return g[e]}}))}));var p=n(2869);Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===p[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return p[e]}}))}));var m=n(6931);Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===m[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=n(3240);Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===y[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return y[e]}}))}));var v=n(4449);Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===v[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return v[e]}}))}));var b=n(4808);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var _=n(3637);Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===_[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return _[e]}}))}));var E=n(8267);Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===E[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return E[e]}}))}));var w=n(4648);Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===w[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return w[e]}}))}));var S=n(5510);Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===S[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return S[e]}}))}))},5617:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LEGACY_M_ROOM_MESSAGE=void 0,t.parseMRoomMessage=function(e){var t,n,o;if(a.M_MESSAGE.findIn(e.content)||a.M_TEXT.findIn(e.content))return new r.MessageEvent(e);var c,u,h,f=null===(t=e.content)||void 0===t?void 0:t.msgtype,g=null===(n=e.content)||void 0===n?void 0:n.body,p="org.matrix.custom.html"===(null===(o=e.content)||void 0===o?void 0:o.format)?e.content.formatted_body:null;return"m.text"===f?new r.MessageEvent(l(l({},e),{},{content:l(l({},e.content),{},(c={},d(c,a.M_TEXT.name,g),d(c,a.M_HTML.name,p),c))})):"m.notice"===f?new i.NoticeEvent(l(l({},e),{},{content:l(l({},e.content),{},(u={},d(u,a.M_TEXT.name,g),d(u,a.M_HTML.name,p),u))})):"m.emote"===f?new s.EmoteEvent(l(l({},e),{},{content:l(l({},e.content),{},(h={},d(h,a.M_TEXT.name,g),d(h,a.M_HTML.name,p),h))})):null};var r=n(3240),i=n(4808),s=n(4449),o=n(4355),a=n(6931);function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){d(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function d(e,t,n){return t in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var u=new o.NamespacedValue("m.room.message");t.LEGACY_M_ROOM_MESSAGE=u},4600:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseMMessage=function(e){return i.M_EMOTE.matches(e.type)?new s.EmoteEvent(e):i.M_NOTICE.matches(e.type)?new o.NoticeEvent(e):new r.MessageEvent(e)};var r=n(3240),i=n(6931),s=n(4449),o=n(4808)},5492:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.parseMPoll=function(e){return r.M_POLL_START.matches(e.type)?new i.PollStartEvent(e):r.M_POLL_RESPONSE.matches(e.type)?new s.PollResponseEvent(e):r.M_POLL_END.matches(e.type)?new o.PollEndEvent(e):null};var r=n(3637),i=n(8267),s=n(4648),o=n(5510)},2932:(e,t)=>{"use strict";function n(e){return null!=e}Object.defineProperty(t,"__esModule",{value:!0}),t.isOptionalAString=function(e){return n(e)&&"string"==typeof e},t.isProvided=n},2117:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LegacyMsgType=void 0,t.isEventLike=function(e,t){var n=e.content;return t===r.Text?i.M_MESSAGE.matches(e.type)||"m.room.message"===e.type&&"m.text"===(null==n?void 0:n.msgtype):t===r.Emote?i.M_EMOTE.matches(e.type)||"m.room.message"===e.type&&"m.emote"===(null==n?void 0:n.msgtype):t===r.Notice&&(i.M_NOTICE.matches(e.type)||"m.room.message"===e.type&&"m.notice"===(null==n?void 0:n.msgtype))};var r,i=n(6931);t.LegacyMsgType=r,function(e){e.Text="m.text",e.Notice="m.notice",e.Emote="m.emote"}(r||(t.LegacyMsgType=r={}))},8472:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.isEventTypeSame=function(e,t){if("string"==typeof e)return"string"==typeof t?t===e:t.matches(e);if("string"==typeof t)return e.matches(t);var n=t,r=e;return n.matches(r.name)||n.matches(r.altName)}},1470:(e,t)=>{"use strict";let n,r,i,s,o,a;Object.defineProperty(t,"__esModule",{value:!0}),t.TweakName=t.RuleId=t.PushRuleKind=t.PushRuleActionName=t.DMMemberCountCondition=t.ConditionOperator=t.ConditionKind=void 0,t.isDmMemberCountCondition=function(e){return"==2"===e||"2"===e},t.PushRuleActionName=n,function(e){e.DontNotify="dont_notify",e.Notify="notify",e.Coalesce="coalesce"}(n||(t.PushRuleActionName=n={})),t.TweakName=r,function(e){e.Highlight="highlight",e.Sound="sound"}(r||(t.TweakName=r={})),t.ConditionOperator=i,function(e){e.ExactEquals="==",e.LessThan="<",e.GreaterThan=">",e.GreaterThanOrEqual=">=",e.LessThanOrEqual="<="}(i||(t.ConditionOperator=i={})),t.DMMemberCountCondition="2",t.ConditionKind=s,function(e){e.EventMatch="event_match",e.ContainsDisplayName="contains_display_name",e.RoomMemberCount="room_member_count",e.SenderNotificationPermission="sender_notification_permission"}(s||(t.ConditionKind=s={})),t.PushRuleKind=o,function(e){e.Override="override",e.ContentSpecific="content",e.RoomSpecific="room",e.SenderSpecific="sender",e.Underride="underride"}(o||(t.PushRuleKind=o={})),t.RuleId=a,function(e){e.Master=".m.rule.master",e.ContainsDisplayName=".m.rule.contains_display_name",e.ContainsUserName=".m.rule.contains_user_name",e.AtRoomNotification=".m.rule.roomnotif",e.DM=".m.rule.room_one_to_one",e.EncryptedDM=".m.rule.encrypted_room_one_to_one",e.Message=".m.rule.message",e.EncryptedMessage=".m.rule.encrypted",e.InviteToSelf=".m.rule.invite_for_me",e.MemberEvent=".m.rule.member_event",e.IncomingCall=".m.rule.call",e.SuppressNotices=".m.rule.suppress_notices",e.Tombstone=".m.rule.tombstone"}(a||(t.RuleId=a={}))},5699:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.M_BEACON_INFO=t.M_BEACON=void 0;var r=n(7048);const i=new r.UnstableValue("m.beacon_info","org.matrix.msc3672.beacon_info");t.M_BEACON_INFO=i;const s=new r.UnstableValue("m.beacon","org.matrix.msc3672.beacon");t.M_BEACON=s},2481:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.UNSTABLE_MSC3089_TREE_SUBTYPE=t.UNSTABLE_MSC3089_LEAF=t.UNSTABLE_MSC3089_BRANCH=t.UNSTABLE_MSC3088_PURPOSE=t.UNSTABLE_MSC3088_ENABLED=t.UNSTABLE_MSC2716_MARKER=t.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=t.RoomType=t.RoomCreateTypeField=t.RelationType=t.MsgType=t.EventType=t.EVENT_VISIBILITY_CHANGE_TYPE=void 0;var r=n(7048);let i,s,o,a;t.EventType=i,function(e){e.RoomCanonicalAlias="m.room.canonical_alias",e.RoomCreate="m.room.create",e.RoomJoinRules="m.room.join_rules",e.RoomMember="m.room.member",e.RoomThirdPartyInvite="m.room.third_party_invite",e.RoomPowerLevels="m.room.power_levels",e.RoomName="m.room.name",e.RoomTopic="m.room.topic",e.RoomAvatar="m.room.avatar",e.RoomPinnedEvents="m.room.pinned_events",e.RoomEncryption="m.room.encryption",e.RoomHistoryVisibility="m.room.history_visibility",e.RoomGuestAccess="m.room.guest_access",e.RoomServerAcl="m.room.server_acl",e.RoomTombstone="m.room.tombstone",e.RoomAliases="m.room.aliases",e.SpaceChild="m.space.child",e.SpaceParent="m.space.parent",e.RoomRedaction="m.room.redaction",e.RoomMessage="m.room.message",e.RoomMessageEncrypted="m.room.encrypted",e.Sticker="m.sticker",e.CallInvite="m.call.invite",e.CallCandidates="m.call.candidates",e.CallAnswer="m.call.answer",e.CallHangup="m.call.hangup",e.CallReject="m.call.reject",e.CallSelectAnswer="m.call.select_answer",e.CallNegotiate="m.call.negotiate",e.CallSDPStreamMetadataChanged="m.call.sdp_stream_metadata_changed",e.CallSDPStreamMetadataChangedPrefix="org.matrix.call.sdp_stream_metadata_changed",e.CallReplaces="m.call.replaces",e.CallAssertedIdentity="m.call.asserted_identity",e.CallAssertedIdentityPrefix="org.matrix.call.asserted_identity",e.KeyVerificationRequest="m.key.verification.request",e.KeyVerificationStart="m.key.verification.start",e.KeyVerificationCancel="m.key.verification.cancel",e.KeyVerificationMac="m.key.verification.mac",e.KeyVerificationDone="m.key.verification.done",e.RoomMessageFeedback="m.room.message.feedback",e.Reaction="m.reaction",e.Typing="m.typing",e.Receipt="m.receipt",e.Presence="m.presence",e.FullyRead="m.fully_read",e.Tag="m.tag",e.SpaceOrder="org.matrix.msc3230.space_order",e.PushRules="m.push_rules",e.Direct="m.direct",e.IgnoredUserList="m.ignored_user_list",e.RoomKey="m.room_key",e.RoomKeyRequest="m.room_key_request",e.ForwardedRoomKey="m.forwarded_room_key",e.Dummy="m.dummy"}(i||(t.EventType=i={})),t.RelationType=s,function(e){e.Annotation="m.annotation",e.Replace="m.replace",e.Reference="m.reference",e.Thread="m.thread"}(s||(t.RelationType=s={})),t.MsgType=o,function(e){e.Text="m.text",e.Emote="m.emote",e.Notice="m.notice",e.Image="m.image",e.File="m.file",e.Audio="m.audio",e.Location="m.location",e.Video="m.video",e.KeyVerificationRequest="m.key.verification.request"}(o||(t.MsgType=o={})),t.RoomCreateTypeField="type",t.RoomType=a,function(e){e.Space="m.space",e.UnstableCall="org.matrix.msc3417.call",e.ElementVideo="io.element.video"}(a||(t.RoomType=a={}));const c=new r.UnstableValue("m.room.purpose","org.matrix.msc3088.purpose");t.UNSTABLE_MSC3088_PURPOSE=c;const l=new r.UnstableValue("m.enabled","org.matrix.msc3088.enabled");t.UNSTABLE_MSC3088_ENABLED=l;const d=new r.UnstableValue("m.data_tree","org.matrix.msc3089.data_tree");t.UNSTABLE_MSC3089_TREE_SUBTYPE=d;const u=new r.UnstableValue("m.leaf","org.matrix.msc3089.leaf");t.UNSTABLE_MSC3089_LEAF=u;const h=new r.UnstableValue("m.branch","org.matrix.msc3089.branch");t.UNSTABLE_MSC3089_BRANCH=h;const f=new r.UnstableValue("m.room.marker","org.matrix.msc2716.marker");t.UNSTABLE_MSC2716_MARKER=f;const g=new r.UnstableValue("io.element.functional_members","io.element.functional_members");t.UNSTABLE_ELEMENT_FUNCTIONAL_USERS=g;const p=new r.UnstableValue("m.visibility","org.matrix.msc3531.visibility");t.EVENT_VISIBILITY_CHANGE_TYPE=p},6548:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TEXT_NODE_TYPE=void 0;const r=new(n(7048).UnstableValue)("m.text","org.matrix.msc1767.text");t.TEXT_NODE_TYPE=r},6709:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.M_TIMESTAMP=t.M_LOCATION=t.M_ASSET=t.LocationAssetType=void 0;var r=n(7048);let i;n(6548),t.LocationAssetType=i,function(e){e.Self="m.self",e.Pin="m.pin"}(i||(t.LocationAssetType=i={}));const s=new r.UnstableValue("m.asset","org.matrix.msc3488.asset");t.M_ASSET=s;const o=new r.UnstableValue("m.ts","org.matrix.msc3488.ts");t.M_TIMESTAMP=o;const a=new r.UnstableValue("m.location","org.matrix.msc3488.location");t.M_LOCATION=a},4702:(e,t)=>{"use strict";let n,r,i,s,o,a;Object.defineProperty(t,"__esModule",{value:!0}),t.Visibility=t.RestrictedAllowType=t.Preset=t.JoinRule=t.HistoryVisibility=t.GuestAccess=void 0,t.Visibility=n,function(e){e.Public="public",e.Private="private"}(n||(t.Visibility=n={})),t.Preset=r,function(e){e.PrivateChat="private_chat",e.TrustedPrivateChat="trusted_private_chat",e.PublicChat="public_chat"}(r||(t.Preset=r={})),t.JoinRule=i,function(e){e.Public="public",e.Invite="invite",e.Private="private",e.Knock="knock",e.Restricted="restricted"}(i||(t.JoinRule=i={})),t.RestrictedAllowType=s,function(e){e.RoomMembership="m.room_membership"}(s||(t.RestrictedAllowType=s={})),t.GuestAccess=o,function(e){e.CanJoin="can_join",e.Forbidden="forbidden"}(o||(t.GuestAccess=o={})),t.HistoryVisibility=a,function(e){e.Invited="invited",e.Joined="joined",e.Shared="shared",e.WorldReadable="world_readable"}(a||(t.HistoryVisibility=a={}))},5550:(e,t)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),t.ReceiptType=void 0,t.ReceiptType=n,function(e){e.Read="m.read",e.FullyRead="m.fully_read",e.ReadPrivate="m.read.private",e.UnstableReadPrivate="org.matrix.msc2285.read.private"}(n||(t.ReceiptType=n={}))},6513:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0})},9162:(e,t)=>{"use strict";var n;let r;Object.defineProperty(t,"__esModule",{value:!0}),t.SearchOrderBy=void 0,function(e){e.RoomId="room_id",e.Sender="sender"}(n||(n={})),t.SearchOrderBy=r,function(e){e.Recent="recent",e.Rank="rank"}(r||(t.SearchOrderBy=r={}))},9953:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.M_TOPIC=void 0;const r=new(n(7048).UnstableValue)("m.topic","org.matrix.msc3765.topic");t.M_TOPIC=r},7048:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.UnstableValue=t.ServerControlledNamespacedValue=t.NamespacedValue=void 0;var i=r(n(8416));class s{constructor(e,t){if(this.stable=e,this.unstable=t,!this.unstable&&!this.stable)throw new Error("One of stable or unstable values must be supplied")}get name(){return this.stable?this.stable:this.unstable}get altName(){return this.stable?this.unstable:null}matches(e){return this.name===e||this.altName===e}findIn(e){let t;return this.name&&(t=null==e?void 0:e[this.name]),!t&&this.altName&&(t=null==e?void 0:e[this.altName]),t}includedIn(e){let t=!1;return this.name&&(t=e.includes(this.name)),!t&&this.altName&&(t=e.includes(this.altName)),t}}t.NamespacedValue=s,t.ServerControlledNamespacedValue=class extends s{constructor(...e){super(...e),(0,i.default)(this,"preferUnstable",!1)}setPreferUnstable(e){this.preferUnstable=e}get name(){return this.stable&&!this.preferUnstable?this.stable:this.unstable}},t.UnstableValue=class extends s{constructor(e,t){if(super(e,t),!this.unstable)throw new Error("Unstable value must be supplied")}get name(){return this.unstable}get altName(){return this.stable}}},771:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.TypedReEmitter=t.ReEmitter=void 0;var i=r(n(8416));class s{constructor(e){this.target=e,(0,i.default)(this,"reEmitters",new Map)}reEmit(e,t){let n=this.reEmitters.get(e);n||(n=new Map,this.reEmitters.set(e,n));for(const r of t){const t=(...t)=>{"error"===r&&0===this.target.listenerCount("error")||this.target.emit(r,...t,e)};e.on(r,t),n.set(r,t)}}stopReEmitting(e,t){const n=this.reEmitters.get(e);if(n){for(const r of t)e.off(r,n.get(r)),n.delete(r);0===n.size&&this.reEmitters.delete(e)}}}t.ReEmitter=s,t.TypedReEmitter=class extends s{constructor(e){super(e)}reEmit(e,t){super.reEmit(e,t)}stopReEmitting(e,t){super.stopReEmitting(e,t)}}},3210:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.ToDeviceMessageQueue=void 0;var i=r(n(8416)),s=n(7434),o=n(9443);t.ToDeviceMessageQueue=class{constructor(e){this.client=e,(0,i.default)(this,"sending",!1),(0,i.default)(this,"running",!0),(0,i.default)(this,"retryTimeout",null),(0,i.default)(this,"retryAttempts",0),(0,i.default)(this,"sendQueue",(async()=>{if(null!==this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null,this.sending||!this.running)return;let e;s.logger.debug("Attempting to send queued to-device messages"),this.sending=!0;try{for(;this.running&&(e=await this.client.store.getOldestToDeviceBatch(),null!==e);)await this.sendBatch(e),await this.client.store.removeToDeviceBatch(e.id),this.retryAttempts=0;if(!this.running)return;s.logger.debug("All queued to-device messages sent")}catch(t){++this.retryAttempts;const n=o.MatrixScheduler.RETRY_BACKOFF_RATELIMIT(null,this.retryAttempts,t);if(-1===n)return void(4===Math.floor(t.httpStatus/100)?(s.logger.error("Fatal error when sending to-device message - dropping to-device batch!",t),await this.client.store.removeToDeviceBatch(e.id)):s.logger.info("Automatic retry limit reached for to-device messages."));s.logger.info(`Failed to send batch of to-device messages. Will retry in ${n}ms`,t),this.retryTimeout=setTimeout(this.sendQueue,n)}finally{this.sending=!1}}))}start(){this.running=!0,this.sendQueue()}stop(){this.running=!1,null!==this.retryTimeout&&clearTimeout(this.retryTimeout),this.retryTimeout=null}async queueBatch(e){const t=[];for(let n=0;n<e.batch.length;n+=20)t.push({eventType:e.eventType,batch:e.batch.slice(n,n+20),txnId:this.client.makeTxnId()});await this.client.store.saveToDeviceBatches(t),this.sendQueue()}async sendBatch(e){const t={};for(const n of e.batch)t[n.userId]||(t[n.userId]={}),t[n.userId][n.deviceId]=n.payload;s.logger.info(`Sending batch of ${e.batch.length} to-device messages with ID ${e.id}`),await this.client.sendToDevice(e.eventType,t,e.txnId)}}},9118:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.AutoDiscoveryAction=t.AutoDiscovery=void 0;var i=r(n(8416)),s=n(7434);function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let c;t.AutoDiscoveryAction=c,function(e){e.SUCCESS="SUCCESS",e.IGNORE="IGNORE",e.PROMPT="PROMPT",e.FAIL_PROMPT="FAIL_PROMPT",e.FAIL_ERROR="FAIL_ERROR"}(c||(t.AutoDiscoveryAction=c={}));class l{static async fromDiscoveryConfig(e){const t={"m.homeserver":{state:l.FAIL_ERROR,error:l.ERROR_INVALID,base_url:null},"m.identity_server":{state:l.PROMPT,error:null,base_url:null}};if(!e||!e["m.homeserver"])return s.logger.error("No m.homeserver key in config"),t["m.homeserver"].state=l.FAIL_PROMPT,t["m.homeserver"].error=l.ERROR_INVALID,Promise.resolve(t);if(!e["m.homeserver"].base_url)return s.logger.error("No m.homeserver base_url in config"),t["m.homeserver"].state=l.FAIL_PROMPT,t["m.homeserver"].error=l.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const n=this.sanitizeWellKnownUrl(e["m.homeserver"].base_url);if(!n)return s.logger.error("Invalid base_url for m.homeserver"),t["m.homeserver"].error=l.ERROR_INVALID_HS_BASE_URL,Promise.resolve(t);const r=await this.fetchWellKnownObject(`${n}/_matrix/client/versions`);if(!r||!r.raw.versions)return s.logger.error("Invalid /versions response"),t["m.homeserver"].error=l.ERROR_INVALID_HOMESERVER,t["m.homeserver"].base_url=n,Promise.resolve(t);t["m.homeserver"]={state:l.SUCCESS,error:null,base_url:n};let i="";if(e["m.identity_server"]){const n={"m.homeserver":t["m.homeserver"],"m.identity_server":{state:l.FAIL_PROMPT,error:l.ERROR_INVALID_IS,base_url:null}};if(i=this.sanitizeWellKnownUrl(e["m.identity_server"].base_url),!i)return s.logger.error("Invalid base_url for m.identity_server"),n["m.identity_server"].error=l.ERROR_INVALID_IS_BASE_URL,Promise.resolve(n);const r=await this.fetchWellKnownObject(`${i}/_matrix/identity/api/v1`);if(!r||!r.raw||r.action!==c.SUCCESS)return s.logger.error("Invalid /api/v1 response"),n["m.identity_server"].error=l.ERROR_INVALID_IDENTITY_SERVER,n["m.identity_server"].base_url=i,Promise.resolve(n)}return i&&i.toString().length>0&&(t["m.identity_server"]={state:l.SUCCESS,error:null,base_url:i}),Object.keys(e).forEach((n=>{if("m.homeserver"===n||"m.identity_server"===n){const r=["error","state","base_url"];for(const i of Object.keys(e[n]))r.includes(i)||(t[n][i]=e[n][i])}else t[n]=e[n]})),Promise.resolve(t)}static async findClientConfig(e){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t={"m.homeserver":{state:l.FAIL_ERROR,error:l.ERROR_INVALID,base_url:null},"m.identity_server":{state:l.PROMPT,error:null,base_url:null}},n=await this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return n&&n.action===c.SUCCESS?l.fromDiscoveryConfig(n.raw):(s.logger.error("No response or error when parsing .well-known"),n.reason&&s.logger.error(n.reason),n.action===c.IGNORE?t["m.homeserver"]={state:l.PROMPT,error:null,base_url:null}:(t["m.homeserver"].state=l.FAIL_PROMPT,t["m.homeserver"].error=l.ERROR_INVALID),Promise.resolve(t))}static async getRawClientConfig(e){if(!e||"string"!=typeof e||0===e.length)throw new Error("'domain' must be a string of non-zero length");const t=await this.fetchWellKnownObject(`https://${e}/.well-known/matrix/client`);return t&&t.raw||{}}static sanitizeWellKnownUrl(e){if(!e)return!1;try{let t=null;try{t=new URL(e)}catch(e){s.logger.error("Could not parse url",e)}if(!t||!t.hostname)return!1;if("http:"!==t.protocol&&"https:"!==t.protocol)return!1;const n=t.port?`:${t.port}`:"",r=t.pathname?t.pathname:"";let i=`${t.protocol}//${t.hostname}${n}${r}`;return i.endsWith("/")&&(i=i.substring(0,i.length-1)),i}catch(e){return s.logger.error(e),!1}}static fetchWellKnownObject(e){return new Promise((t=>{const r=n(8070).getRequest();if(!r)throw new Error("No request library available");r({method:"GET",uri:e,timeout:5e3},((e,n,r)=>{if(e||(null==n?void 0:n.statusCode)<200||(null==n?void 0:n.statusCode)>=300){const r={error:e,raw:{}};return t(404===(null==n?void 0:n.statusCode)?a(a({},r),{},{action:c.IGNORE,reason:l.ERROR_MISSING_WELLKNOWN}):a(a({},r),{},{action:c.FAIL_PROMPT,reason:(null==e?void 0:e.message)||"General failure"}))}try{return t({raw:JSON.parse(r),action:c.SUCCESS})}catch(e){return t({error:e,raw:{},action:c.FAIL_PROMPT,reason:"SyntaxError"===(null==e?void 0:e.name)?l.ERROR_INVALID_JSON:l.ERROR_INVALID})}}))}))}}t.AutoDiscovery=l,(0,i.default)(l,"ERROR_INVALID","Invalid homeserver discovery response"),(0,i.default)(l,"ERROR_GENERIC_FAILURE","Failed to get autodiscovery configuration from server"),(0,i.default)(l,"ERROR_INVALID_HS_BASE_URL","Invalid base_url for m.homeserver"),(0,i.default)(l,"ERROR_INVALID_HOMESERVER","Homeserver URL does not appear to be a valid Matrix homeserver"),(0,i.default)(l,"ERROR_INVALID_IS_BASE_URL","Invalid base_url for m.identity_server"),(0,i.default)(l,"ERROR_INVALID_IDENTITY_SERVER","Identity server URL does not appear to be a valid identity server"),(0,i.default)(l,"ERROR_INVALID_IS","Invalid identity server discovery response"),(0,i.default)(l,"ERROR_MISSING_WELLKNOWN","No .well-known JSON file found"),(0,i.default)(l,"ERROR_INVALID_JSON","Invalid JSON"),(0,i.default)(l,"ALL_ERRORS",[l.ERROR_INVALID,l.ERROR_GENERIC_FAILURE,l.ERROR_INVALID_HS_BASE_URL,l.ERROR_INVALID_HOMESERVER,l.ERROR_INVALID_IS_BASE_URL,l.ERROR_INVALID_IDENTITY_SERVER,l.ERROR_INVALID_IS,l.ERROR_MISSING_WELLKNOWN,l.ERROR_INVALID_JSON]),(0,i.default)(l,"FAIL_ERROR",c.FAIL_ERROR),(0,i.default)(l,"FAIL_PROMPT",c.FAIL_PROMPT),(0,i.default)(l,"PROMPT",c.PROMPT),(0,i.default)(l,"SUCCESS",c.SUCCESS)},8743:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0});var i={};t.default=void 0;var s=r(n(4770)),o=r(n(129)),a=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=c(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(8070));function c(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(c=function(e){return e?n:t})(e)}if(Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(i,e)||e in t&&t[e]===a[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}}))})),a.getRequest())throw new Error("Multiple matrix-js-sdk entrypoints detected!");let l;a.request((function(e,t){return e.qs=o.default.stringify(e.qs||{},e.qsStringifyOptions),(0,s.default)(e,t)}));try{l=n.g.indexedDB}catch(e){}l&&a.setCryptoStoreFactory((function(){return new a.IndexedDBCryptoStore(l,"matrix-js-sdk:crypto")}));var d=a;t.default=d,n.g.matrixcs=a},2168:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RoomVersionStability=t.PendingEventOrdering=t.MatrixClient=t.ClientEvent=t.CRYPTO_ENABLED=void 0;var i=r(n(8416)),s=n(1333),o=n(4551),a=n(4369),c=n(5641),l=n(9679),d=n(7906),u=n(2931),h=Y(n(3102)),f=n(8910),g=n(1707),p=n(9118),m=Y(n(2772)),y=n(771),v=n(635),b=n(7434),_=n(1415),E=n(7715),w=n(2600),S=n(4077),C=n(1597),T=n(3998),R=n(3667),I=n(1398),k=n(4830),O=n(8070),A=n(764),D=Y(n(4656)),M=n(2481),P=n(4702),U=n(1166),L=n(8401),N=n(5537),x=n(6170),B=n(9162),j=n(1470),F=n(7626),K=n(5861),q=n(5550),$=n(11),V=n(6969),G=n(5699),W=n(3210);function H(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(H=function(e){return e?n:t})(e)}function Y(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=H(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}function z(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function J(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?z(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):z(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const Q=(0,w.isCryptoAvailable)();t.CRYPTO_ENABLED=Q;const X=6e5;let Z,ee;var te;t.PendingEventOrdering=Z,function(e){e.Chronological="chronological",e.Detached="detached"}(Z||(t.PendingEventOrdering=Z={})),t.RoomVersionStability=ee,function(e){e.Stable="stable",e.Unstable="unstable"}(ee||(t.RoomVersionStability=ee={})),function(e){e.MasterKey="master_key",e.SelfSigningKey="self_signing_key",e.UserSigningKey="user_signing_key"}(te||(te={}));const ne="$";let re;t.ClientEvent=re,function(e){e.Sync="sync",e.Event="event",e.ToDeviceEvent="toDeviceEvent",e.AccountData="accountData",e.Room="Room",e.DeleteRoom="deleteRoom",e.SyncUnexpectedError="sync.unexpectedError",e.ClientWellKnown="WellKnown.client",e.TurnServers="turnServers",e.TurnServersError="turnServers.error"}(re||(t.ClientEvent=re={}));class ie extends K.TypedEventEmitter{constructor(e){super(),(0,i.default)(this,"reEmitter",new y.TypedReEmitter(this)),(0,i.default)(this,"olmVersion",null),(0,i.default)(this,"usingExternalCrypto",!1),(0,i.default)(this,"store",void 0),(0,i.default)(this,"deviceId",void 0),(0,i.default)(this,"credentials",void 0),(0,i.default)(this,"pickleKey",void 0),(0,i.default)(this,"scheduler",void 0),(0,i.default)(this,"clientRunning",!1),(0,i.default)(this,"timelineSupport",!1),(0,i.default)(this,"urlPreviewCache",{}),(0,i.default)(this,"identityServer",void 0),(0,i.default)(this,"http",void 0),(0,i.default)(this,"crypto",void 0),(0,i.default)(this,"cryptoCallbacks",void 0),(0,i.default)(this,"callEventHandler",void 0),(0,i.default)(this,"supportsCallTransfer",!1),(0,i.default)(this,"forceTURN",!1),(0,i.default)(this,"iceCandidatePoolSize",0),(0,i.default)(this,"idBaseUrl",void 0),(0,i.default)(this,"baseUrl",void 0),(0,i.default)(this,"canSupportVoip",!1),(0,i.default)(this,"peekSync",null),(0,i.default)(this,"isGuestAccount",!1),(0,i.default)(this,"ongoingScrollbacks",{}),(0,i.default)(this,"notifTimelineSet",null),(0,i.default)(this,"cryptoStore",void 0),(0,i.default)(this,"verificationMethods",void 0),(0,i.default)(this,"fallbackICEServerAllowed",!1),(0,i.default)(this,"roomList",void 0),(0,i.default)(this,"syncApi",void 0),(0,i.default)(this,"roomNameGenerator",void 0),(0,i.default)(this,"pushRules",void 0),(0,i.default)(this,"syncLeftRoomsPromise",void 0),(0,i.default)(this,"syncedLeftRooms",!1),(0,i.default)(this,"clientOpts",void 0),(0,i.default)(this,"clientWellKnownIntervalID",void 0),(0,i.default)(this,"canResetTimelineCallback",void 0),(0,i.default)(this,"pushProcessor",new g.PushProcessor(this)),(0,i.default)(this,"serverVersionsPromise",void 0),(0,i.default)(this,"cachedCapabilities",void 0),(0,i.default)(this,"clientWellKnown",void 0),(0,i.default)(this,"clientWellKnownPromise",void 0),(0,i.default)(this,"turnServers",[]),(0,i.default)(this,"turnServersExpiry",0),(0,i.default)(this,"checkTurnServersIntervalID",null),(0,i.default)(this,"exportedOlmDeviceToImport",void 0),(0,i.default)(this,"txnCtr",0),(0,i.default)(this,"mediaHandler",new F.MediaHandler(this)),(0,i.default)(this,"pendingEventEncryption",new Map),(0,i.default)(this,"toDeviceMessageQueue",void 0),(0,i.default)(this,"startCallEventHandler",(()=>{this.isInitialSyncComplete()&&(this.callEventHandler.start(),this.off(re.Sync,this.startCallEventHandler))})),e.baseUrl=h.ensureNoTrailingSlash(e.baseUrl),e.idBaseUrl=h.ensureNoTrailingSlash(e.idBaseUrl),this.baseUrl=e.baseUrl,this.idBaseUrl=e.idBaseUrl,this.identityServer=e.identityServer,this.usingExternalCrypto=e.usingExternalCrypto,this.store=e.store||new c.StubStore,this.deviceId=e.deviceId||null;const t=e.userId||null;this.credentials={userId:t},this.http=new E.MatrixHttpApi(this,{baseUrl:e.baseUrl,idBaseUrl:e.idBaseUrl,accessToken:e.accessToken,request:e.request,prefix:E.PREFIX_R0,onlyData:!0,extraParams:e.queryParams,localTimeoutMs:e.localTimeoutMs,useAuthorizationHeader:e.useAuthorizationHeader}),e.deviceToImport?this.deviceId?b.logger.warn("not importing device because device ID is provided to constructor independently of exported data"):this.credentials.userId?b.logger.warn("not importing device because user ID is provided to constructor independently of exported data"):e.deviceToImport.deviceId?(this.deviceId=e.deviceToImport.deviceId,this.credentials.userId=e.deviceToImport.userId,this.exportedOlmDeviceToImport=e.deviceToImport.olmDevice):b.logger.warn("not importing device because no device ID in exported data"):e.pickleKey&&(this.pickleKey=e.pickleKey),this.scheduler=e.scheduler,this.scheduler&&this.scheduler.setProcessFunction((async e=>{const t=this.getRoom(e.getRoomId());e.status!==a.EventStatus.SENDING&&this.updatePendingEventStatus(t,e,a.EventStatus.SENDING);const n=await this.sendEventHttpRequest(e);return t&&t.updatePendingEvent(e,a.EventStatus.SENT,n.event_id),n})),(0,l.supportsMatrixCall)()&&(this.callEventHandler=new u.CallEventHandler(this),this.canSupportVoip=!0,this.on(re.Sync,this.startCallEventHandler)),this.timelineSupport=Boolean(e.timelineSupport),this.cryptoStore=e.cryptoStore,this.verificationMethods=e.verificationMethods,this.cryptoCallbacks=e.cryptoCallbacks||{},this.forceTURN=e.forceTURN||!1,this.iceCandidatePoolSize=void 0===e.iceCandidatePoolSize?0:e.iceCandidatePoolSize,this.supportsCallTransfer=e.supportsCallTransfer||!1,this.fallbackICEServerAllowed=e.fallbackICEServerAllowed||!1,this.roomList=new v.RoomList(this.cryptoStore),this.roomNameGenerator=e.roomNameGenerator,this.toDeviceMessageQueue=new W.ToDeviceMessageQueue(this),this.on(a.MatrixEventEvent.Decrypted,(e=>{var t,n;const r=e.getPushActions(),i=this.getPushActionsForEvent(e,!0),s=this.getRoom(e.getRoomId());if(!s)return;const o=s.getUnreadNotificationCount(O.NotificationCountType.Highlight),a=!(null==r||null===(t=r.tweaks)||void 0===t||!t.highlight),c=!(null==i||null===(n=i.tweaks)||void 0===n||!n.highlight);if((a!==c||o>0)&&!s.hasUserReadEvent(this.getUserId(),e.getId())){let e=o;c&&!a&&e++,!c&&a&&e--,s.setUnreadNotificationCount(O.NotificationCountType.Highlight,e),s.getUnreadNotificationCount(O.NotificationCountType.Total)<e&&s.setUnreadNotificationCount(O.NotificationCountType.Total,e)}})),this.on(O.RoomEvent.Receipt,((e,t)=>{if(t&&this.isRoomEncrypted(t.roomId)){const n=e.getContent();if(!(Object.keys(n).filter((e=>{for(const[t,r]of Object.entries(n[e]))if(h.isSupportedReceiptType(t)&&r&&Object.keys(r).includes(this.getUserId()))return!0;return!1})).length>0))return;const r=20,i=t.getLiveTimeline().getEvents();let s=0;for(let e=i.length-1;e>=0;e--){if(e===i.length-r)return;const n=i[e];if(t.hasUserReadEvent(this.getUserId(),n.getId()))break;const o=this.getPushActionsForEvent(n);s+=o.tweaks&&o.tweaks.highlight?1:0}t.setUnreadNotificationCount(O.NotificationCountType.Highlight,s)}}))}async startClient(e){if(this.clientRunning)return;this.clientRunning=!0,"number"==typeof e&&(e={initialSyncLimit:e});const t=this.getUserId();t&&this.store.storeUser(new T.User(t)),this.crypto&&(this.crypto.uploadDeviceKeys(),this.crypto.start()),this.canSupportVoip&&(this.checkTurnServersIntervalID=setInterval((()=>{this.checkTurnServers()}),X),this.checkTurnServers()),this.syncApi&&(b.logger.error("Still have sync object whilst not running: stopping old one"),this.syncApi.stop());try{const{serverSupport:e,stable:t}=await this.doesServerSupportThread();V.Thread.setServerSideSupport(e,t)}catch(e){V.Thread.setServerSideSupport(!1,!0)}this.clientOpts=Object.assign({},e),this.clientOpts.crypto=this.crypto,this.clientOpts.canResetEntireTimeline=e=>!!this.canResetTimelineCallback&&this.canResetTimelineCallback(e),this.clientOpts.slidingSync?this.syncApi=new $.SlidingSyncSdk(this.clientOpts.slidingSync,this,this.clientOpts):this.syncApi=new o.SyncApi(this,this.clientOpts),this.syncApi.sync(),void 0!==this.clientOpts.clientWellKnownPollPeriod&&(this.clientWellKnownIntervalID=setInterval((()=>{this.fetchClientWellKnown()}),1e3*this.clientOpts.clientWellKnownPollPeriod),this.fetchClientWellKnown()),this.toDeviceMessageQueue.start()}stopClient(){var e,t,r,i;null===(e=this.crypto)||void 0===e||e.stop(),this.clientRunning&&(b.logger.log("stopping MatrixClient"),this.clientRunning=!1,null===(t=this.syncApi)||void 0===t||t.stop(),this.syncApi=null,null===(r=this.peekSync)||void 0===r||r.stopPeeking(),null===(i=this.callEventHandler)||void 0===i||i.stop(),this.callEventHandler=null,n.g.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=null,void 0!==this.clientWellKnownIntervalID&&n.g.clearInterval(this.clientWellKnownIntervalID),this.toDeviceMessageQueue.stop())}async rehydrateDevice(){if(this.crypto)throw new Error("Cannot rehydrate device after crypto is initialized");if(!this.cryptoCallbacks.getDehydrationKey)return;const e=await this.getDehydratedDevice();if(!e)return;if(!e.device_data||!e.device_id)return void b.logger.info("no dehydrated device found");const t=new n.g.Olm.Account;try{const n=e.device_data;if(n.algorithm!==k.DEHYDRATION_ALGORITHM)return void b.logger.warn("Wrong algorithm for dehydrated device");b.logger.log("unpickling dehydrated device");const r=await this.cryptoCallbacks.getDehydrationKey(n,(e=>{t.unpickle(new Uint8Array(e),n.account)}));if(t.unpickle(r,n.account),b.logger.log("unpickled device"),!0===(await this.http.authedRequest(void 0,E.Method.Post,"/dehydrated_device/claim",void 0,{device_id:e.device_id},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).success){this.deviceId=e.device_id,b.logger.info("using dehydrated device");const n=this.pickleKey||"DEFAULT_KEY";return this.exportedOlmDeviceToImport={pickledAccount:t.pickle(n),sessions:[],pickleKey:n},t.free(),this.deviceId}return t.free(),void b.logger.info("not using dehydrated device")}catch(e){t.free(),b.logger.warn("could not unpickle",e)}}async getDehydratedDevice(){try{return await this.http.authedRequest(void 0,E.Method.Get,"/dehydrated_device",void 0,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})}catch(e){return void b.logger.info("could not get dehydrated device",e.toString())}}setDehydrationKey(e,t,n){if(this.crypto)return this.crypto.dehydrationManager.setKeyAndQueueDehydration(e,t,n);b.logger.warn("not dehydrating device if crypto is not enabled")}async createDehydratedDevice(e,t,n){if(this.crypto)return await this.crypto.dehydrationManager.setKey(e,t,n),this.crypto.dehydrationManager.dehydrateDevice();b.logger.warn("not dehydrating device if crypto is not enabled")}async exportDevice(){if(this.crypto)return{userId:this.credentials.userId,deviceId:this.deviceId,olmDevice:await this.crypto.olmDevice.export()};b.logger.warn("not exporting device if crypto is not enabled")}clearStores(){if(this.clientRunning)throw new Error("Cannot clear stores while client is running");const e=[];return e.push(this.store.deleteAllData()),this.cryptoStore&&e.push(this.cryptoStore.deleteAllData()),Promise.all(e).then()}getUserId(){return this.credentials&&this.credentials.userId?this.credentials.userId:null}getDomain(){return this.credentials&&this.credentials.userId?this.credentials.userId.replace(/^.*?:/,""):null}getUserIdLocalpart(){return this.credentials&&this.credentials.userId?this.credentials.userId.split(":")[0].substring(1):null}getDeviceId(){return this.deviceId}supportsVoip(){return this.canSupportVoip}getMediaHandler(){return this.mediaHandler}setForceTURN(e){this.forceTURN=e}setSupportsCallTransfer(e){this.supportsCallTransfer=e}createCall(e){return(0,l.createNewMatrixCall)(this,e)}getSyncState(){return this.syncApi?this.syncApi.getSyncState():null}getSyncStateData(){return this.syncApi?this.syncApi.getSyncStateData():null}isInitialSyncComplete(){const e=this.getSyncState();return!!e&&(e===o.SyncState.Prepared||e===o.SyncState.Syncing)}isGuest(){return this.isGuestAccount}setGuest(e){this.isGuestAccount=e}getScheduler(){return this.scheduler}retryImmediately(){return this.toDeviceMessageQueue.sendQueue(),this.syncApi.retryImmediately()}getNotifTimelineSet(){return this.notifTimelineSet}setNotifTimelineSet(e){this.notifTimelineSet=e}getCapabilities(e=!1){const t=(new Date).getTime();return this.cachedCapabilities&&!e&&t<this.cachedCapabilities.expiration?(b.logger.log("Returning cached capabilities"),Promise.resolve(this.cachedCapabilities.capabilities)):this.http.authedRequest(void 0,E.Method.Get,"/capabilities").catch((e=>{b.logger.error(e)})).then(((e={})=>{const n=e.capabilities||{},r=Object.keys(n).length?216e5:6e4+5e3*Math.random();return this.cachedCapabilities={capabilities:n,expiration:t+r},b.logger.log("Caching capabilities: ",n),n}))}async initCrypto(){if(!(0,w.isCryptoAvailable)())throw new Error("End-to-end encryption not supported in this js-sdk build: did you remember to load the olm library?");if(this.crypto)return void b.logger.warn("Attempt to re-initialise e2e encryption on MatrixClient");if(!this.cryptoStore)throw new Error("Cannot enable encryption: no cryptoStore provided");b.logger.log("Crypto: Starting up crypto store..."),await this.cryptoStore.startup(),b.logger.log("Crypto: initialising roomlist..."),await this.roomList.init();const e=this.getUserId();if(null===e)throw new Error("Cannot enable encryption on MatrixClient with unknown userId: ensure userId is passed in createClient().");if(null===this.deviceId)throw new Error("Cannot enable encryption on MatrixClient with unknown deviceId: ensure deviceId is passed in createClient().");const t=new w.Crypto(this,e,this.deviceId,this.store,this.cryptoStore,this.roomList,this.verificationMethods);this.reEmitter.reEmit(t,[w.CryptoEvent.KeyBackupFailed,w.CryptoEvent.KeyBackupSessionsRemaining,w.CryptoEvent.RoomKeyRequest,w.CryptoEvent.RoomKeyRequestCancellation,w.CryptoEvent.Warning,w.CryptoEvent.DevicesUpdated,w.CryptoEvent.WillUpdateDevices,w.CryptoEvent.DeviceVerificationChanged,w.CryptoEvent.UserTrustStatusChanged,w.CryptoEvent.KeysChanged]),b.logger.log("Crypto: initialising crypto object..."),await t.init({exportedOlmDevice:this.exportedOlmDeviceToImport,pickleKey:this.pickleKey}),delete this.exportedOlmDeviceToImport,this.olmVersion=w.Crypto.getOlmVersion(),t.registerEventHandlers(this),this.crypto=t}isCryptoEnabled(){return!!this.crypto}getDeviceEd25519Key(){return this.crypto?this.crypto.getDeviceEd25519Key():null}getDeviceCurve25519Key(){return this.crypto?this.crypto.getDeviceCurve25519Key():null}async uploadKeys(){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.uploadDeviceKeys()}downloadKeys(e,t){return this.crypto?this.crypto.downloadKeys(e,t):Promise.reject(new Error("End-to-end encryption disabled"))}getStoredDevicesForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevicesForUser(e)||[]}getStoredDevice(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredDevice(e,t)||null}setDeviceVerified(e,t,n=!0){const r=this.setDeviceVerification(e,t,n,null,null);return e==this.credentials.userId&&this.checkKeyBackup(),r}setDeviceBlocked(e,t,n=!0){return this.setDeviceVerification(e,t,null,n,null)}setDeviceKnown(e,t,n=!0){return this.setDeviceVerification(e,t,null,null,n)}async setDeviceVerification(e,t,n,r,i){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.setDeviceVerification(e,t,n,r,i)}requestVerificationDM(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerificationDM(e,t)}findVerificationRequestDMInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.findVerificationRequestDMInProgress(e)}getVerificationRequestsToDeviceInProgress(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getVerificationRequestsToDeviceInProgress(e)}requestVerification(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestVerification(e,t)}beginKeyVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.beginKeyVerification(e,t,n)}checkSecretStorageKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStorageKey(e,t)}setGlobalBlacklistUnverifiedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setGlobalBlacklistUnverifiedDevices(e)}getGlobalBlacklistUnverifiedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getGlobalBlacklistUnverifiedDevices()}setGlobalErrorOnUnknownDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setGlobalErrorOnUnknownDevices(e)}getGlobalErrorOnUnknownDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getGlobalErrorOnUnknownDevices()}getCrossSigningId(e=A.CrossSigningKey.Master){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCrossSigningId(e)}getStoredCrossSigningForUser(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getStoredCrossSigningForUser(e)}checkUserTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkUserTrust(e)}checkDeviceTrust(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkDeviceTrust(e,t)}checkIfOwnDeviceCrossSigned(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkIfOwnDeviceCrossSigned(e)}checkOwnCrossSigningTrust(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkOwnCrossSigningTrust(e)}checkCrossSigningPrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkCrossSigningPrivateKey(e,t)}legacyDeviceVerification(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.legacyDeviceVerification(e,t,n)}prepareToEncrypt(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.prepareToEncrypt(e)}isCrossSigningReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isCrossSigningReady()}bootstrapCrossSigning(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapCrossSigning(e)}getCryptoTrustCrossSignedDevices(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getCryptoTrustCrossSignedDevices()}setCryptoTrustCrossSignedDevices(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setCryptoTrustCrossSignedDevices(e)}countSessionsNeedingBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.countSessionsNeedingBackup()}getEventEncryptionInfo(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getEventEncryptionInfo(e)}createRecoveryKeyFromPassphrase(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.createRecoveryKeyFromPassphrase(e)}isSecretStorageReady(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStorageReady()}bootstrapSecretStorage(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.bootstrapSecretStorage(e)}addSecretStorageKey(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.addSecretStorageKey(e,t,n)}hasSecretStorageKey(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.hasSecretStorageKey(e)}storeSecret(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.storeSecret(e,t,n)}getSecret(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getSecret(e)}isSecretStored(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.isSecretStored(e)}requestSecret(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.requestSecret(e,t)}getDefaultSecretStorageKeyId(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.getDefaultSecretStorageKeyId()}setDefaultSecretStorageKeyId(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.setDefaultSecretStorageKeyId(e)}checkSecretStoragePrivateKey(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.checkSecretStoragePrivateKey(e,t)}async getEventSenderDeviceInfo(e){return this.crypto?this.crypto.getEventSenderDeviceInfo(e):null}async isEventSenderVerified(e){const t=await this.getEventSenderDeviceInfo(e);return!!t&&t.isVerified()}cancelAndResendEventRoomKeyRequest(e){return e.cancelAndResendKeyRequest(this.crypto,this.getUserId())}setRoomEncryption(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.setRoomEncryption(e,t)}isRoomEncrypted(e){const t=this.getRoom(e);return!!t&&(!!t.currentState.getStateEvents(M.EventType.RoomEncryption,"")||this.roomList.isRoomEncrypted(e))}encryptAndSendToDevices(e,t){if(!this.crypto)throw new Error("End-to-End encryption disabled");return this.crypto.encryptAndSendToDevices(e,t)}forceDiscardSession(e){if(!this.crypto)throw new Error("End-to-End encryption disabled");this.crypto.forceDiscardSession(e)}exportRoomKeys(){return this.crypto?this.crypto.exportRoomKeys():Promise.reject(new Error("End-to-end encryption disabled"))}importRoomKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.importRoomKeys(e,t)}checkKeyBackup(){return this.crypto.backupManager.checkKeyBackup()}async getKeyBackupVersion(){let e;try{e=await this.http.authedRequest(void 0,E.Method.Get,"/room_keys/version",void 0,void 0,{prefix:E.PREFIX_UNSTABLE})}catch(e){if("M_NOT_FOUND"===e.errcode)return null;throw e}return N.BackupManager.checkBackupVersion(e),e}isKeyBackupTrusted(e){return this.crypto.backupManager.isKeyBackupTrusted(e)}getKeyBackupEnabled(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.getKeyBackupEnabled()}enableKeyBackup(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.enableKeyBackup(e)}disableKeyBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.disableKeyBackup()}async prepareKeyBackupVersion(e,t={secureSecretStorage:!1}){if(!this.crypto)throw new Error("End-to-end encryption disabled");const{algorithm:n,auth_data:r,recovery_key:i,privateKey:s}=await this.crypto.backupManager.prepareKeyBackupVersion(e);return t.secureSecretStorage&&(await this.storeSecret("m.megolm_backup.v1",(0,m.encodeBase64)(s)),b.logger.info("Key backup private key stored in secret storage")),{algorithm:n,auth_data:r,recovery_key:i}}isKeyBackupKeyStored(){return Promise.resolve(this.isSecretStored("m.megolm_backup.v1"))}async createKeyBackupVersion(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.createKeyBackupVersion(e);const t={algorithm:e.algorithm,auth_data:e.auth_data};await this.crypto.signObject(t.auth_data),this.cryptoCallbacks.getCrossSigningKey&&this.crypto.crossSigningInfo.getId()&&await this.crypto.crossSigningInfo.signObject(t.auth_data,"master");const n=await this.http.authedRequest(void 0,E.Method.Post,"/room_keys/version",void 0,t,{prefix:E.PREFIX_UNSTABLE});return await this.checkKeyBackup(),this.getKeyBackupEnabled()||b.logger.error("Key backup not usable even though we just created it"),n}deleteKeyBackupVersion(e){if(!this.crypto)throw new Error("End-to-end encryption disabled");this.crypto.backupManager.version&&this.crypto.backupManager.disableKeyBackup();const t=h.encodeUri("/room_keys/version/$version",{$version:e});return this.http.authedRequest(void 0,E.Method.Delete,t,void 0,void 0,{prefix:E.PREFIX_UNSTABLE})}makeKeyBackupPath(e,t,n){let r;return r=void 0!==t?h.encodeUri("/room_keys/keys/$roomId/$sessionId",{$roomId:e,$sessionId:t}):void 0!==e?h.encodeUri("/room_keys/keys/$roomId",{$roomId:e}):"/room_keys/keys",{path:r,queryData:void 0===n?void 0:{version:n}}}sendKeyBackup(e,t,n,r){if(!this.crypto)throw new Error("End-to-end encryption disabled");const i=this.makeKeyBackupPath(e,t,n);return this.http.authedRequest(void 0,E.Method.Put,i.path,i.queryData,r,{prefix:E.PREFIX_UNSTABLE})}async scheduleAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");await this.crypto.backupManager.scheduleAllGroupSessionsForBackup()}flagAllGroupSessionsForBackup(){if(!this.crypto)throw new Error("End-to-end encryption disabled");return this.crypto.backupManager.flagAllGroupSessionsForBackup()}isValidRecoveryKey(e){try{return(0,S.decodeRecoveryKey)(e),!0}catch(e){return!1}}keyBackupKeyFromPassword(e,t){return(0,C.keyFromAuthData)(t.auth_data,e)}keyBackupKeyFromRecoveryKey(e){return(0,S.decodeRecoveryKey)(e)}async restoreKeyBackupWithPassword(e,t,n,r,i){const s=await(0,C.keyFromAuthData)(r.auth_data,e);return this.restoreKeyBackup(s,t,n,r,i)}async restoreKeyBackupWithSecretStorage(e,t,n,r){const i=await this.getSecret("m.megolm_backup.v1"),s=(0,w.fixBackupKey)(i);if(s){const[e]=await this.crypto.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",s,[e])}const o=(0,m.decodeBase64)(s||i);return this.restoreKeyBackup(o,t,n,e,r)}restoreKeyBackupWithRecoveryKey(e,t,n,r,i){const s=(0,S.decodeRecoveryKey)(e);return this.restoreKeyBackup(s,t,n,r,i)}async restoreKeyBackupWithCache(e,t,n,r){const i=await this.crypto.getSessionBackupPrivateKey();if(!i)throw new Error("Couldn't get key");return this.restoreKeyBackup(i,e,t,n,r)}async restoreKeyBackup(e,t,n,r,i){const s=null==i?void 0:i.cacheCompleteCallback,o=null==i?void 0:i.progressCallback;if(!this.crypto)throw new Error("End-to-end encryption disabled");let a=0,c=[];const l=this.makeKeyBackupPath(t,n,r.version),d=await N.BackupManager.makeAlgorithm(r,(async()=>e)),u=d.untrusted;try{if(!await d.keyMatches(e))return Promise.reject(new E.MatrixError({errcode:ie.RESTORE_BACKUP_ERROR_BAD_KEY}));this.crypto.storeSessionBackupPrivateKey(e).catch((e=>{b.logger.warn("Error caching session backup key:",e)})).then(s),o&&o({stage:"fetch"});const r=await this.http.authedRequest(void 0,E.Method.Get,l.path,l.queryData,void 0,{prefix:E.PREFIX_UNSTABLE});if(r.rooms){const e=r.rooms;for(const[t,n]of Object.entries(e)){if(!n.sessions)continue;a+=Object.keys(n.sessions).length;const e=await d.decryptSessions(n.sessions);for(const n of e)n.room_id=t,c.push(n)}}else if(r.sessions){const e=r.sessions;a=Object.keys(e).length,c=await d.decryptSessions(e);for(const e of c)e.room_id=t}else{a=1;try{const[e]=await d.decryptSessions({[n]:r});e.room_id=t,e.session_id=n,c.push(e)}catch(e){b.logger.log("Failed to decrypt megolm session from backup",e)}}}finally{d.free()}return await this.importRoomKeys(c,{progressCallback:o,untrusted:u,source:"backup"}),await this.checkKeyBackup(),{total:a,imported:c.length}}deleteKeysFromBackup(e,t,n){if(!this.crypto)throw new Error("End-to-end encryption disabled");const r=this.makeKeyBackupPath(e,t,n);return this.http.authedRequest(void 0,E.Method.Delete,r.path,r.queryData,void 0,{prefix:E.PREFIX_UNSTABLE})}async sendSharedHistoryKeys(e,t){if(!this.crypto)throw new Error("End-to-end encryption disabled");const n=this.roomList.getRoomEncryption(e);if(!n)return void b.logger.error("Unknown room. Not sharing decryption keys");const r=await this.crypto.downloadKeys(t),i={};for(const[e,t]of Object.entries(r))i[e]=Object.values(t);const s=this.crypto.getRoomDecryptor(e,n.algorithm);s.sendSharedHistoryInboundSessions?await s.sendSharedHistoryInboundSessions(i):b.logger.warn("Algorithm does not support sharing previous keys",n.algorithm)}getMediaConfig(e){return this.http.authedRequest(e,E.Method.Get,"/config",void 0,void 0,{prefix:E.PREFIX_MEDIA_R0})}getRoom(e){return this.store.getRoom(e)}getRooms(){return this.store.getRooms()}getVisibleRooms(){const e=this.store.getRooms(),t=new Set;for(const n of e){const e=n.currentState.getStateEvents(M.EventType.RoomCreate,"");if(e){const n=e.getContent().predecessor;n&&n.room_id&&t.add(n.room_id)}}return e.filter((e=>!e.currentState.getStateEvents(M.EventType.RoomTombstone,"")||!t.has(e.roomId)))}getUser(e){return this.store.getUser(e)}getUsers(){return this.store.getUsers()}setAccountData(e,t,n){const r=h.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e}),i=(0,E.retryNetworkOperation)(5,(()=>this.http.authedRequest(void 0,E.Method.Put,r,void 0,t)));return n&&i.then((e=>n(null,e)),n),i}getAccountData(e){return this.store.getAccountData(e)}async getAccountDataFromServer(e){if(this.isInitialSyncComplete()){const t=this.store.getAccountData(e);return t?t.getContent():null}const t=h.encodeUri("/user/$userId/account_data/$type",{$userId:this.credentials.userId,$type:e});try{return await this.http.authedRequest(void 0,E.Method.Get,t)}catch(e){var n;if("M_NOT_FOUND"===(null===(n=e.data)||void 0===n?void 0:n.errcode))return null;throw e}}getIgnoredUsers(){const e=this.getAccountData("m.ignored_user_list");return e&&e.getContent()&&e.getContent().ignored_users?Object.keys(e.getContent().ignored_users):[]}setIgnoredUsers(e,t){const n={ignored_users:{}};return e.forEach((e=>{n.ignored_users[e]={}})),this.setAccountData("m.ignored_user_list",n,t)}isUserIgnored(e){return this.getIgnoredUsers().includes(e)}async joinRoom(e,t,n){if(h.isFunction(t))throw new Error("Expected 'opts' object, got function.");void 0===(t=t||{}).syncRoom&&(t.syncRoom=!0);const r=this.getRoom(e);if(r&&r.hasMembershipState(this.credentials.userId,"join"))return Promise.resolve(r);let i=Promise.resolve();t.inviteSignUrl&&(i=this.http.requestOtherUrl(void 0,E.Method.Post,t.inviteSignUrl,{mxid:this.credentials.userId}));const s={};t.viaServers&&(s.server_name=t.viaServers);const a={qsStringifyOptions:{arrayFormat:"repeat"}};try{const r={},c=await i;c&&(r.third_party_signed=c);const l=h.encodeUri("/join/$roomid",{$roomid:e}),d=(await this.http.authedRequest(void 0,E.Method.Post,l,s,r,a)).room_id,u=new o.SyncApi(this,this.clientOpts).createRoom(d);return t.syncRoom,null==n||n(null,u),u}catch(e){throw null==n||n(e),e}}resendEvent(e,t){return this.toDeviceMessageQueue.sendQueue(),this.updatePendingEventStatus(t,e,a.EventStatus.SENDING),this.encryptAndSendEvent(t,e)}cancelPendingEvent(e){if(![a.EventStatus.QUEUED,a.EventStatus.NOT_SENT,a.EventStatus.ENCRYPTING].includes(e.status))throw new Error("cannot cancel an event with status "+e.status);e.status===a.EventStatus.ENCRYPTING?this.pendingEventEncryption.delete(e.getId()):this.scheduler&&e.status===a.EventStatus.QUEUED&&this.scheduler.removeEventFromQueue(e);const t=this.getRoom(e.getRoomId());this.updatePendingEventStatus(t,e,a.EventStatus.CANCELLED)}setRoomName(e,t,n){return this.sendStateEvent(e,M.EventType.RoomName,{name:t},void 0,n)}setRoomTopic(e,t,n){const r="function"==typeof n,i=r?void 0:n,s=r?n:void 0,o=D.makeTopicContent(t,i);return this.sendStateEvent(e,M.EventType.RoomTopic,o,void 0,s)}getRoomTags(e,t){const n=h.encodeUri("/user/$userId/rooms/$roomId/tags",{$userId:this.credentials.userId,$roomId:e});return this.http.authedRequest(t,E.Method.Get,n)}setRoomTag(e,t,n,r){const i=h.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(r,E.Method.Put,i,void 0,n)}deleteRoomTag(e,t,n){const r=h.encodeUri("/user/$userId/rooms/$roomId/tags/$tag",{$userId:this.credentials.userId,$roomId:e,$tag:t});return this.http.authedRequest(n,E.Method.Delete,r)}setRoomAccountData(e,t,n,r){const i=h.encodeUri("/user/$userId/rooms/$roomId/account_data/$type",{$userId:this.credentials.userId,$roomId:e,$type:t});return this.http.authedRequest(r,E.Method.Put,i,void 0,n)}setPowerLevel(e,t,n,r,i){let s={users:{}};(null==r?void 0:r.getType())===M.EventType.RoomPowerLevels&&(s=h.deepCopy(r.getContent())),s.users[t]=n;const o=h.encodeUri("/rooms/$roomId/state/m.room.power_levels",{$roomId:e});return this.http.authedRequest(i,E.Method.Put,o,void 0,s)}async unstable_createLiveBeacon(e,t){return this.unstable_setLiveBeacon(e,t)}async unstable_setLiveBeacon(e,t){const n=this.getUserId();return this.sendStateEvent(e,G.M_BEACON_INFO.name,t,n)}sendEvent(e,t,n,r,i,s){var o,a;if(null!==(o=t)&&void 0!==o&&o.startsWith(ne)||null===t||(s=i,i=r,r=n,n=t,t=null),t&&(null===(a=r["m.relates_to"])||void 0===a||!a.rel_type)){var c,l;const n=!(null===(c=r["m.relates_to"])||void 0===c||!c["m.in_reply_to"]);r["m.relates_to"]=J(J({},r["m.relates_to"]),{},{rel_type:V.THREAD_RELATION_TYPE.name,event_id:t,is_falling_back:!n});const i=null===(l=this.getRoom(e))||void 0===l?void 0:l.getThread(t);var d,u;i&&!n&&(r["m.relates_to"]["m.in_reply_to"]={event_id:null!==(d=null===(u=i.lastReply((e=>e.isRelation(V.THREAD_RELATION_TYPE.name)&&!e.status)))||void 0===u?void 0:u.getId())&&void 0!==d?d:t})}return this.sendCompleteEvent(e,t,{type:n,content:r},i,s)}sendCompleteEvent(e,t,n,r,i){h.isFunction(r)&&(i=r,r=void 0),r||(r=this.makeTxnId());const s=new a.MatrixEvent(Object.assign(n,{event_id:"~"+e+":"+r,user_id:this.credentials.userId,sender:this.credentials.userId,room_id:e,origin_server_ts:(new Date).getTime()})),o=this.getRoom(e),c=null==o?void 0:o.getThread(t);c&&s.setThread(c),this.reEmitter.reEmit(s,[a.MatrixEventEvent.Replaced,a.MatrixEventEvent.VisibilityChange]),null==o||o.reEmitter.reEmit(s,[a.MatrixEventEvent.BeforeRedaction]);const l=s.getAssociatedId();if(null!=l&&l.startsWith("~")){const e=o.getPendingEvents().find((e=>e.getId()===l));e.once(a.MatrixEventEvent.LocalEventIdReplaced,(()=>{s.updateAssociatedId(e.getId())}))}const d=s.getType();return b.logger.log(`sendEvent of type ${d} in ${e} with txnId ${r}`),s.setTxnId(r),s.setStatus(a.EventStatus.SENDING),null==o||o.addPendingEvent(s,r),s.status===a.EventStatus.NOT_SENT?Promise.reject(new Error("Event blocked by other events not yet sent")):this.encryptAndSendEvent(o,s,i)}encryptAndSendEvent(e,t,n){let r=!1;return Promise.resolve().then((()=>{const n=this.encryptEventIfNeeded(t,e);return n?(this.pendingEventEncryption.set(t.getId(),n),this.updatePendingEventStatus(e,t,a.EventStatus.ENCRYPTING),n.then((()=>{this.pendingEventEncryption.has(t.getId())?this.updatePendingEventStatus(e,t,a.EventStatus.SENDING):r=!0}))):null})).then((()=>{if(r)return{};let n;return this.scheduler&&(n=this.scheduler.queueEvent(t),n&&this.scheduler.getQueueForEvent(t).length>1&&this.updatePendingEventStatus(e,t,a.EventStatus.QUEUED)),n||(n=this.sendEventHttpRequest(t),e&&(n=n.then((n=>(e.updatePendingEvent(t,a.EventStatus.SENT,n.event_id),n))))),n})).then((e=>(null==n||n(null,e),e))).catch((r=>{b.logger.error("Error sending event",r.stack||r);try{t.error=r,this.updatePendingEventStatus(e,t,a.EventStatus.NOT_SENT),r.event=t,null==n||n(r)}catch(e){b.logger.error("Exception in error handler!",e.stack||r)}throw r}))}encryptEventIfNeeded(e,t){if(e.isEncrypted())return null;if(e.isRedaction())return null;if(!this.isRoomEncrypted(e.getRoomId()))return null;if(!this.crypto&&this.usingExternalCrypto)return null;if(e.getType()===M.EventType.Reaction)return null;if(!this.crypto)throw new Error("This room is configured to use encryption, but your client does not support encryption.");return this.crypto.encryptEvent(e,t)}getEncryptedIfNeededEventType(e,t){return t===M.EventType.Reaction?t:this.isRoomEncrypted(e)?M.EventType.RoomMessageEncrypted:t}updatePendingEventStatus(e,t,n){e?e.updatePendingEvent(t,n):t.setStatus(n)}sendEventHttpRequest(e){let t=e.getTxnId();t||(t=this.makeTxnId(),e.setTxnId(t));const n={$roomId:e.getRoomId(),$eventType:e.getWireType(),$stateKey:e.getStateKey(),$txnId:t};let r;if(e.isState()){let t="/rooms/$roomId/state/$eventType";e.getStateKey()&&e.getStateKey().length>0&&(t="/rooms/$roomId/state/$eventType/$stateKey"),r=h.encodeUri(t,n)}else if(e.isRedaction()){const t="/rooms/$roomId/redact/$redactsEventId/$txnId";r=h.encodeUri(t,Object.assign({$redactsEventId:e.event.redacts},n))}else r=h.encodeUri("/rooms/$roomId/send/$eventType/$txnId",n);return this.http.authedRequest(void 0,E.Method.Put,r,void 0,e.getWireContent()).then((t=>(b.logger.log(`Event sent to ${e.getRoomId()} with event id ${t.event_id}`),t)))}redactEvent(e,t,n,r,i){var s;null!==(s=n)&&void 0!==s&&s.startsWith(ne)||(i=r,r=n,n=t,t=null);const o=("object"==typeof i?i:{}).reason,a="function"==typeof i?i:void 0;return this.sendCompleteEvent(e,t,{type:M.EventType.RoomRedaction,content:{reason:o},redacts:n},r,a)}sendMessage(e,t,n,r,i){"string"!=typeof t&&null!==t&&(i=r,r=n,n=t,t=null),h.isFunction(r)&&(i=r,r=void 0);let o=M.EventType.RoomMessage,a=n;const c=(e={},t=!0)=>{let n=null;if(e.msgtype===M.MsgType.Text?n=s.MessageEvent.from(e.body,e.formatted_body).serialize():e.msgtype===M.MsgType.Emote?n=s.EmoteEvent.from(e.body,e.formatted_body).serialize():e.msgtype===M.MsgType.Notice&&(n=s.NoticeEvent.from(e.body,e.formatted_body).serialize()),n&&e["m.new_content"]&&t){const t=c(e["m.new_content"],!1);t&&(n.content["m.new_content"]=t.content)}if(n)for(const[t,r]of Object.entries(e))n.content.hasOwnProperty(t)||(n.content[t]=r);return n},l=c(a);return l&&(o=l.type,a=l.content),this.sendEvent(e,t,o,a,r,i)}sendTextMessage(e,t,n,r,i){var s;null!==(s=t)&&void 0!==s&&s.startsWith(ne)||null===t||(i=r,r=n,n=t,t=null);const o=D.makeTextMessage(n);return this.sendMessage(e,t,o,r,i)}sendNotice(e,t,n,r,i){var s;null!==(s=t)&&void 0!==s&&s.startsWith(ne)||null===t||(i=r,r=n,n=t,t=null);const o=D.makeNotice(n);return this.sendMessage(e,t,o,r,i)}sendEmoteMessage(e,t,n,r,i){var s;null!==(s=t)&&void 0!==s&&s.startsWith(ne)||null===t||(i=r,r=n,n=t,t=null);const o=D.makeEmoteMessage(n);return this.sendMessage(e,t,o,r,i)}sendImageMessage(e,t,n,r,i="Image",s){var o;null!==(o=t)&&void 0!==o&&o.startsWith(ne)||null===t||(s=i,i=r||"Image",r=n,n=t,t=null),h.isFunction(i)&&(s=i,i=void 0);const a={msgtype:M.MsgType.Image,url:n,info:r,body:i};return this.sendMessage(e,t,a,void 0,s)}sendStickerMessage(e,t,n,r,i="Sticker",s){var o;null!==(o=t)&&void 0!==o&&o.startsWith(ne)||null===t||(s=i,i=r||"Sticker",r=n,n=t,t=null),h.isFunction(i)&&(s=i,i=void 0);const a={url:n,info:r,body:i};return this.sendEvent(e,t,M.EventType.Sticker,a,void 0,s)}sendHtmlMessage(e,t,n,r,i){var s;null!==(s=t)&&void 0!==s&&s.startsWith(ne)||null===t||(i=r,r=n,n=t,t=null);const o=D.makeHtmlMessage(n,r);return this.sendMessage(e,t,o,void 0,i)}sendHtmlNotice(e,t,n,r,i){var s;null!==(s=t)&&void 0!==s&&s.startsWith(ne)||null===t||(i=r,r=n,n=t,t=null);const o=D.makeHtmlNotice(n,r);return this.sendMessage(e,t,o,void 0,i)}sendHtmlEmote(e,t,n,r,i){var s;null!==(s=t)&&void 0!==s&&s.startsWith(ne)||null===t||(i=r,r=n,n=t,t=null);const o=D.makeHtmlEmote(n,r);return this.sendMessage(e,t,o,void 0,i)}sendReceipt(e,t,n,r){if("function"==typeof n&&(r=n,n={}),this.isGuest())return Promise.resolve({});const i=h.encodeUri("/rooms/$roomId/receipt/$receiptType/$eventId",{$roomId:e.getRoomId(),$receiptType:t,$eventId:e.getId()}),s=this.http.authedRequest(r,E.Method.Post,i,void 0,n||{}),o=this.getRoom(e.getRoomId());return o&&o.addLocalEchoReceipt(this.credentials.userId,e,t),s}async sendReadReceipt(e,t=q.ReceiptType.Read,n){const r=e.getId(),i=this.getRoom(e.getRoomId());if(i&&i.hasPendingEvent(r))throw new Error(`Cannot set read receipt to a pending event (${r})`);return this.sendReceipt(e,t,{},n)}async setRoomReadMarkers(e,t,n,r){const i=this.getRoom(e);if(i&&i.hasPendingEvent(t))throw new Error(`Cannot set read marker to a pending event (${t})`);let s,o;if(n){if(s=n.getId(),null!=i&&i.hasPendingEvent(s))throw new Error(`Cannot set read receipt to a pending event (${s})`);null==i||i.addLocalEchoReceipt(this.credentials.userId,n,q.ReceiptType.Read)}if(r){if(o=r.getId(),null!=i&&i.hasPendingEvent(o))throw new Error(`Cannot set read receipt to a pending event (${o})`);null==i||i.addLocalEchoReceipt(this.credentials.userId,r,q.ReceiptType.ReadPrivate)}return await this.setRoomReadMarkersHttpRequest(e,t,s,o)}getUrlPreview(e,t,n){t=6e4*Math.floor(t/6e4);const r=new URL(e);r.hash="";const i=t+"_"+(e=r.toString()),s=this.urlPreviewCache[i];if(s)return n&&s.then(n).catch(n),s;const o=this.http.authedRequest(n,E.Method.Get,"/preview_url",{url:e,ts:t.toString()},void 0,{prefix:E.PREFIX_MEDIA_R0});return this.urlPreviewCache[i]=o,o}sendTyping(e,t,n,r){if(this.isGuest())return Promise.resolve({});const i=h.encodeUri("/rooms/$roomId/typing/$userId",{$roomId:e,$userId:this.credentials.userId}),s={typing:t};return t&&(s.timeout=n||2e4),this.http.authedRequest(r,E.Method.Put,i,void 0,s)}getRoomUpgradeHistory(e,t=!1){let n=this.getRoom(e);if(!n)return[];const r=[n];let i=n.currentState.getStateEvents(M.EventType.RoomCreate,"");for(;i;){const e=i.getContent().predecessor;if(!e||!e.room_id)break;{const n=this.getRoom(e.room_id);if(!n)break;if(t){const e=n.currentState.getStateEvents(M.EventType.RoomTombstone,"");if(!e||e.getContent().replacement_room!==n.roomId)break}r.splice(0,0,n),i=n.currentState.getStateEvents(M.EventType.RoomCreate,"")}}let s=n.currentState.getStateEvents(M.EventType.RoomTombstone,"");for(;s;){const e=this.getRoom(s.getContent().replacement_room);if(!e)break;if(e.roomId===n.roomId)break;if(t){if(i=e.currentState.getStateEvents(M.EventType.RoomCreate,""),!i||!i.getContent().predecessor)break;if(i.getContent().predecessor.room_id!==n.roomId)break}if(r.push(e),new Set(r.map((e=>e.roomId))).size<r.length)return r.slice(0,r.length-1);n=e,s=n.currentState.getStateEvents(M.EventType.RoomTombstone,"")}return r}invite(e,t,n,r){return this.membershipChange(e,t,"invite",r,n)}inviteByEmail(e,t,n){return this.inviteByThreePid(e,"email",t,n)}async inviteByThreePid(e,t,n,r){var i;const s=h.encodeUri("/rooms/$roomId/invite",{$roomId:e}),o=this.getIdentityServerUrl(!0);if(!o)return Promise.reject(new E.MatrixError({error:"No supplied identity server URL",errcode:"ORG.MATRIX.JSSDK_MISSING_PARAM"}));const a={id_server:o,medium:t,address:n};if(null!==(i=this.identityServer)&&void 0!==i&&i.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();e&&(a.id_access_token=e)}return this.http.authedRequest(r,E.Method.Post,s,void 0,a)}leave(e,t){return this.membershipChange(e,void 0,"leave",void 0,t)}leaveRoomChain(e,t=!0){const n=this.getRoomUpgradeHistory(e);let r=n;if(!t){r=[];for(const t of n)if(r.push(t),t.roomId===e)break}const i={},s=[],o=e=>this.leave(e).then((()=>{i[e]=null})).catch((t=>(i[e]=t,null)));for(const e of r)s.push(o(e.roomId));return Promise.all(s).then((()=>i))}ban(e,t,n,r){return this.membershipChange(e,t,"ban",n,r)}forget(e,t,n){void 0===t&&(t=!0);const r=this.membershipChange(e,void 0,"forget",void 0,n);return t?r.then((t=>(this.store.removeRoom(e),this.emit(re.DeleteRoom,e),t))):r}unban(e,t,n){const r=h.encodeUri("/rooms/$roomId/unban",{$roomId:e}),i={user_id:t};return this.http.authedRequest(n,E.Method.Post,r,void 0,i)}kick(e,t,n,r){const i=h.encodeUri("/rooms/$roomId/kick",{$roomId:e}),s={user_id:t,reason:n};return this.http.authedRequest(r,E.Method.Post,i,void 0,s)}membershipChange(e,t,n,r,i){h.isFunction(r)&&(i=r,r=void 0);const s=h.encodeUri("/rooms/$room_id/$membership",{$room_id:e,$membership:n});return this.http.authedRequest(i,E.Method.Post,s,void 0,{user_id:t,reason:r})}getPushActionsForEvent(e,t=!1){return e.getPushActions()&&!t||e.setPushActions(this.pushProcessor.actionsForEvent(e)),e.getPushActions()}setProfileInfo(e,t,n){const r=h.encodeUri("/profile/$userId/$info",{$userId:this.credentials.userId,$info:e});return this.http.authedRequest(n,E.Method.Put,r,void 0,t)}async setDisplayName(e,t){const n=await this.setProfileInfo("displayname",{displayname:e},t),r=this.getUser(this.getUserId());return r&&(r.displayName=e,r.emit(T.UserEvent.DisplayName,r.events.presence,r)),n}async setAvatarUrl(e,t){const n=await this.setProfileInfo("avatar_url",{avatar_url:e},t),r=this.getUser(this.getUserId());return r&&(r.avatarUrl=e,r.emit(T.UserEvent.AvatarUrl,r.events.presence,r)),n}mxcUrlToHttp(e,t,n,r,i){return(0,R.getHttpUriForMxc)(this.baseUrl,e,t,n,r,i)}setPresence(e,t){const n=h.encodeUri("/presence/$userId/status",{$userId:this.credentials.userId});if("string"==typeof e&&(e={presence:e}),-1===["offline","online","unavailable"].indexOf(e.presence))throw new Error("Bad presence value: "+e.presence);return this.http.authedRequest(t,E.Method.Put,n,void 0,e)}getPresence(e,t){const n=h.encodeUri("/presence/$userId/status",{$userId:e});return this.http.authedRequest(t,E.Method.Get,n)}scrollback(e,t=30,n){h.isFunction(t)&&(n=t,t=void 0);let r=0,i=this.ongoingScrollbacks[e.roomId]||{};if(i.promise)return i.promise;if(i.errorTs){const e=Date.now()-i.errorTs;r=Math.max(3e3-e,0)}if(null===e.oldState.paginationToken)return Promise.resolve(e);const s=this.store.scrollback(e,t).length;if(s===t)return Promise.resolve(e);t-=s;const o=new Promise(((i,s)=>{(0,h.sleep)(r).then((()=>this.createMessagesRequest(e.roomId,e.oldState.paginationToken,t,f.Direction.Backward))).then((t=>{var r;const s=t.chunk.map(this.getEventMapper());if(t.state){const n=t.state.map(this.getEventMapper());e.currentState.setUnknownStateEvents(n)}const[o,a]=e.partitionThreadedEvents(s);this.processBeaconEvents(e,o),e.addEventsToTimeline(o,!0,e.getLiveTimeline()),this.processThreadEvents(e,a,!0),e.oldState.paginationToken=t.end,0===t.chunk.length&&(e.oldState.paginationToken=null),this.store.storeEvents(e,s,t.end,!0),this.ongoingScrollbacks[e.roomId]=null,null===(r=n)||void 0===r||r(null,e),i(e)})).catch((t=>{var r;this.ongoingScrollbacks[e.roomId]={errorTs:Date.now()},null===(r=n)||void 0===r||r(t),s(t)}))}));return i={promise:o,errorTs:null},this.ongoingScrollbacks[e.roomId]=i,o}getEventMapper(e){return(0,U.eventMapperFor)(this,e||{})}async getEventTimeline(e,t){var n,r,i;if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const s=h.encodeUri("/rooms/$roomId/context/$eventId",{$roomId:e.room.roomId,$eventId:t});let o;this.clientOpts.lazyLoadMembers&&(o={filter:JSON.stringify(d.Filter.LAZY_LOADING_MESSAGES_FILTER)});const a=await this.http.authedRequest(void 0,E.Method.Get,s,o);if(!a.event)throw new Error("'event' not in '/context' result - homeserver too old?");if(e.getTimelineForEvent(t))return e.getTimelineForEvent(t);const c=this.getEventMapper(),l=c(a.event),u=[...a.events_after.reverse().map(c),l,...a.events_before.map(c)];if(this.supportsExperimentalThreads()){if(!e.canContain(l))return;if(V.Thread.hasServerSideSupport&&e.thread){const n=e.thread,r={direction:f.Direction.Backward,limit:50};await n.fetchInitialEvents();let i=n.liveTimeline.getPaginationToken(f.Direction.Backward);for(;!n.findEventById(t)&&(i&&(r.from=i),({nextBatch:i}=await n.fetchEvents(r)),i););return n.liveTimeline}}let g=e.getTimelineForEvent(u[0].getId());g?g.getState(f.EventTimeline.BACKWARDS).setUnknownStateEvents(a.state.map(c)):(g=e.addTimeline(),g.initialiseState(a.state.map(c)),g.getState(f.EventTimeline.FORWARDS).paginationToken=a.end);const[p,m]=e.room.partitionThreadedEvents(u);return e.addEventsToTimeline(p,!0,g,a.start),this.processThreadEvents(e.room,m,!0),this.processBeaconEvents(e.room,p),null!==(n=null!==(r=e.getTimelineForEvent(t))&&void 0!==r?r:null===(i=e.room.findThreadForEvent(l))||void 0===i?void 0:i.liveTimeline)&&void 0!==n?n:g}async getLatestTimeline(e){var t;if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");const n=h.encodeUri("/rooms/$roomId/messages",{$roomId:e.room.roomId}),r={dir:"b"};this.clientOpts.lazyLoadMembers&&(r.filter=JSON.stringify(d.Filter.LAZY_LOADING_MESSAGES_FILTER));const i=null===(t=(await this.http.authedRequest(void 0,E.Method.Get,n,r)).chunk)||void 0===t?void 0:t[0];if(!i)throw new Error("No message returned from /messages when trying to construct getLatestTimeline");return this.getEventTimeline(e,i.event_id)}createMessagesRequest(e,t,n=30,r,i){const s=h.encodeUri("/rooms/$roomId/messages",{$roomId:e}),o={limit:n.toString(),dir:r};t&&(o.from=t);let a=null;var c;return this.clientOpts.lazyLoadMembers&&(a=Object.assign({},d.Filter.LAZY_LOADING_MESSAGES_FILTER)),i&&(a=a||{},Object.assign(a,null===(c=i.getRoomTimelineFilterComponent())||void 0===c?void 0:c.toJSON())),a&&(o.filter=JSON.stringify(a)),this.http.authedRequest(void 0,E.Method.Get,s,o)}paginateEventTimeline(e,t){const n=e.getTimelineSet()===this.notifTimelineSet,r=(t=t||{}).backwards||!1;if(n&&!r)throw new Error("paginateNotifTimeline can only paginate backwards");const i=r?f.EventTimeline.BACKWARDS:f.EventTimeline.FORWARDS,s=e.getPaginationToken(i),o=e.paginationRequests[i];if(o)return o;let a,c,l;if(n){var d;a="/notifications",c={limit:(null!==(d=t.limit)&&void 0!==d?d:30).toString(),only:"highlight"},"end"!==s&&(c.from=s),l=this.http.authedRequest(void 0,E.Method.Get,"/notifications",c).then((async t=>{const n=t.next_token,s=[];for(let e=0;e<t.notifications.length;e++){const n=t.notifications[e],r=this.getEventMapper()(n.event);r.setPushActions(g.PushProcessor.actionListToActionsObject(n.actions)),r.event.room_id=n.room_id,s[e]=r}const o=e.getTimelineSet();return o.addEventsToTimeline(s,r,e,n),this.processBeaconEvents(o.room,s),r&&!t.next_token&&e.setPaginationToken(null,i),!!t.next_token})).finally((()=>{e.paginationRequests[i]=null})),e.paginationRequests[i]=l}else{const n=this.getRoom(e.getRoomId());if(!n)throw new Error("Unknown room "+e.getRoomId());l=this.createMessagesRequest(e.getRoomId(),s,t.limit,i,e.getFilter()).then((t=>{if(t.state){const n=e.getState(i),r=t.state.map(this.getEventMapper());n.setUnknownStateEvents(r)}const s=t.end,o=t.chunk.map(this.getEventMapper()),a=e.getTimelineSet(),[c,l]=a.room.partitionThreadedEvents(o);return a.addEventsToTimeline(c,r,e,s),this.processBeaconEvents(a.room,c),this.processThreadEvents(n,l,r),r&&t.end==t.start&&e.setPaginationToken(null,i),t.end!=t.start})).finally((()=>{e.paginationRequests[i]=null})),e.paginationRequests[i]=l}return l}resetNotifTimelineSet(){this.notifTimelineSet&&this.notifTimelineSet.resetLiveTimeline("end",null)}peekInRoom(e){return this.peekSync&&this.peekSync.stopPeeking(),this.peekSync=new o.SyncApi(this,this.clientOpts),this.peekSync.peek(e)}stopPeeking(){this.peekSync&&(this.peekSync.stopPeeking(),this.peekSync=null)}setGuestAccess(e,t){const n=this.sendStateEvent(e,M.EventType.RoomGuestAccess,{guest_access:t.allowJoin?"can_join":"forbidden"},"");let r=Promise.resolve(void 0);return t.allowRead&&(r=this.sendStateEvent(e,M.EventType.RoomHistoryVisibility,{history_visibility:"world_readable"},"")),Promise.all([r,n]).then()}requestRegisterEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/register/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestRegisterMsisdnToken(e,t,n,r,i){return this.requestTokenFromEndpoint("/register/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:i})}requestAdd3pidEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/account/3pid/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestAdd3pidMsisdnToken(e,t,n,r,i){return this.requestTokenFromEndpoint("/account/3pid/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:i})}requestPasswordEmailToken(e,t,n,r){return this.requestTokenFromEndpoint("/account/password/email/requestToken",{email:e,client_secret:t,send_attempt:n,next_link:r})}requestPasswordMsisdnToken(e,t,n,r,i){return this.requestTokenFromEndpoint("/account/password/msisdn/requestToken",{country:e,phone_number:t,client_secret:n,send_attempt:r,next_link:i})}async requestTokenFromEndpoint(e,t){const n=Object.assign({},t);if(!await this.doesServerSupportSeparateAddAndBind()&&this.idBaseUrl){var r;const e=new URL(this.idBaseUrl);if(n.id_server=e.host,null!==(r=this.identityServer)&&void 0!==r&&r.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();e&&(n.id_access_token=e)}}return this.http.request(void 0,E.Method.Post,e,void 0,n)}getRoomPushRule(e,t){if(!this.pushRules)throw new Error("SyncApi.sync() must be done before accessing to push rules.");if(this.pushRules[e]&&this.pushRules[e].room)for(let n=0;n<this.pushRules[e].room.length;n++){const r=this.pushRules[e].room[n];if(r.rule_id===t)return r}}setRoomMutePushRule(e,t,n){let r,i=!1;const s=this.getRoomPushRule(e,t);if(null!=s&&s.actions.includes(O.PushRuleActionName.DontNotify)&&(i=!0),n)if(s){if(!i){const n=h.defer();this.deletePushRule(e,j.PushRuleKind.RoomSpecific,s.rule_id).then((()=>{this.addPushRule(e,j.PushRuleKind.RoomSpecific,t,{actions:[O.PushRuleActionName.DontNotify]}).then((()=>{n.resolve()})).catch((e=>{n.reject(e)}))})).catch((e=>{n.reject(e)})),r=n.promise}}else r=this.addPushRule(e,j.PushRuleKind.RoomSpecific,t,{actions:[O.PushRuleActionName.DontNotify]});else i&&(r=this.deletePushRule(e,j.PushRuleKind.RoomSpecific,s.rule_id));if(r)return new Promise(((e,t)=>{r.then((()=>{this.getPushRules().then((t=>{this.pushRules=t,e()})).catch((e=>{t(e)}))})).catch((e=>{this.getPushRules().then((n=>{this.pushRules=n,t(e)})).catch((n=>{t(e)}))}))}))}searchMessageText(e,t){const n={search_term:e.query};return"keys"in e&&(n.keys=e.keys),this.search({body:{search_categories:{room_events:n}}},t)}searchRoomEvents(e){const t={search_categories:{room_events:{search_term:e.term,filter:e.filter,order_by:B.SearchOrderBy.Recent,event_context:{before_limit:1,after_limit:1,include_profile:!0}}}},n={_query:t,results:[],highlights:[]};return this.search({body:t}).then((e=>this.processRoomEventsSearch(n,e)))}backPaginateRoomEventsSearch(e){if(!e.next_batch)return Promise.reject(new Error("Cannot backpaginate event search any further"));if(e.pendingRequest)return e.pendingRequest;const t={body:e._query,next_batch:e.next_batch},n=this.search(t).then((t=>this.processRoomEventsSearch(e,t))).finally((()=>{e.pendingRequest=null}));return e.pendingRequest=n,n}processRoomEventsSearch(e,t){var n,r;const i=t.search_categories.room_events;e.count=i.count,e.next_batch=i.next_batch;const s=new Set(i.highlights);e.highlights.forEach((e=>{s.add(e)})),e.highlights=Array.from(s);const o=this.getEventMapper(),a=null!==(n=null===(r=i.results)||void 0===r?void 0:r.length)&&void 0!==n?n:0;for(let t=0;t<a;t++){const n=I.SearchResult.fromJson(i.results[t],o),r=this.getRoom(n.context.getEvent().getRoomId());if(r)for(const e of n.context.getTimeline()){const t=r.getMember(e.getSender());!e.sender&&t&&(e.sender=t)}e.results.push(n)}return e}syncLeftRooms(){if(this.syncedLeftRooms)return Promise.resolve([]);if(this.syncLeftRoomsPromise)return this.syncLeftRoomsPromise;const e=new o.SyncApi(this,this.clientOpts);return this.syncLeftRoomsPromise=e.syncLeftRooms(),this.syncLeftRoomsPromise.then((()=>{b.logger.log("Marking success of sync left room request"),this.syncedLeftRooms=!0})).finally((()=>{this.syncLeftRoomsPromise=null})),this.syncLeftRoomsPromise}createFilter(e){const t=h.encodeUri("/user/$userId/filter",{$userId:this.credentials.userId});return this.http.authedRequest(void 0,E.Method.Post,t,void 0,e).then((t=>{const n=d.Filter.fromJson(this.credentials.userId,t.filter_id,e);return this.store.storeFilter(n),n}))}getFilter(e,t,n){if(n){const n=this.store.getFilter(e,t);if(n)return Promise.resolve(n)}const r=h.encodeUri("/user/$userId/filter/$filterId",{$userId:e,$filterId:t});return this.http.authedRequest(void 0,E.Method.Get,r).then((n=>{const r=d.Filter.fromJson(e,t,n);return this.store.storeFilter(r),r}))}async getOrCreateFilter(e,t){const n=this.store.getFilterIdByName(e);let r;if(n){try{const e=await this.getFilter(this.credentials.userId,n,!0);if(e){const i=e.getDefinition(),s=t.getDefinition();h.deepCompare(i,s)&&(r=n)}}catch(e){if("M_UNKNOWN"!==e.errcode&&"M_NOT_FOUND"!==e.errcode)throw e}r||this.store.setFilterIdByName(e,void 0)}if(r)return r;const i=await this.createFilter(t.getDefinition());return this.store.setFilterIdByName(e,i.filterId),i.filterId}getOpenIdToken(){const e=h.encodeUri("/user/$userId/openid/request_token",{$userId:this.credentials.userId});return this.http.authedRequest(void 0,E.Method.Post,e,void 0,{})}turnServer(e){return this.http.authedRequest(e,E.Method.Get,"/voip/turnServer")}getTurnServers(){return this.turnServers||[]}getTurnServersExpiry(){return this.turnServersExpiry}get pollingTurnServers(){return null!==this.checkTurnServersIntervalID}async checkTurnServers(){if(!this.canSupportVoip)return;let e=!1;const t=this.turnServersExpiry-Date.now();if(t>X)b.logger.debug("TURN creds are valid for another "+t+" ms: not fetching new ones."),e=!0;else{b.logger.debug("Fetching new TURN credentials");try{const t=await this.turnServer();if(t.uris){b.logger.log("Got TURN URIs: "+t.uris+" refresh in "+t.ttl+" secs");const n={urls:t.uris,username:t.username,credential:t.password};this.turnServers=[n],this.turnServersExpiry=Date.now()+1e3*t.ttl,e=!0,this.emit(re.TurnServers,this.turnServers)}}catch(e){b.logger.error("Failed to get TURN URIs",e),403===e.httpStatus?(b.logger.info("TURN access unavailable for this account: stopping credentials checks"),null!==this.checkTurnServersIntervalID&&n.g.clearInterval(this.checkTurnServersIntervalID),this.checkTurnServersIntervalID=null,this.emit(re.TurnServersError,e,!0)):this.emit(re.TurnServersError,e,!1)}}return e}setFallbackICEServerAllowed(e){this.fallbackICEServerAllowed=e}isFallbackICEServerAllowed(){return this.fallbackICEServerAllowed}isSynapseAdministrator(){const e=h.encodeUri("/_synapse/admin/v1/users/$userId/admin",{$userId:this.getUserId()});return this.http.authedRequest(void 0,E.Method.Get,e,void 0,void 0,{prefix:""}).then((e=>e.admin))}whoisSynapseUser(e){const t=h.encodeUri("/_synapse/admin/v1/whois/$userId",{$userId:e});return this.http.authedRequest(void 0,E.Method.Get,t,void 0,void 0,{prefix:""})}deactivateSynapseUser(e){const t=h.encodeUri("/_synapse/admin/v1/deactivate/$userId",{$userId:e});return this.http.authedRequest(void 0,E.Method.Post,t,void 0,void 0,{prefix:""})}async fetchClientWellKnown(){this.clientWellKnownPromise=p.AutoDiscovery.getRawClientConfig(this.getDomain()),this.clientWellKnown=await this.clientWellKnownPromise,this.emit(re.ClientWellKnown,this.clientWellKnown)}getClientWellKnown(){return this.clientWellKnown}waitForClientWellKnown(){return this.clientWellKnownPromise}storeClientOptions(){const e=["boolean","string","number"],t=Object.entries(this.clientOpts).filter((([t,n])=>e.includes(typeof n))).reduce(((e,[t,n])=>(e[t]=n,e)),{});return this.store.storeClientOptions(t)}async _unstable_getSharedRooms(e){const t=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666"),n=await this.doesServerSupportUnstableFeature("uk.half-shot.msc2666.mutual_rooms");if(!t&&!n)throw Error("Server does not support mutual_rooms API");const r=h.encodeUri(`/uk.half-shot.msc2666/user/${n?"mutual_rooms":"shared_rooms"}/$userId`,{$userId:e});return(await this.http.authedRequest(void 0,E.Method.Get,r,void 0,void 0,{prefix:E.PREFIX_UNSTABLE})).joined}getVersions(){return this.serverVersionsPromise||(this.serverVersionsPromise=this.http.request(void 0,E.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:""}).catch((e=>{throw this.serverVersionsPromise=null,e}))),this.serverVersionsPromise}async isVersionSupported(e){const{versions:t}=await this.getVersions();return t&&t.includes(e)}async doesServerSupportLazyLoading(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return t&&t.includes("r0.5.0")||n&&n["m.lazy_load_members"]}async doesServerRequireIdServerParam(){const e=await this.getVersions();if(!e)return!0;const t=e.versions;if(t&&t.includes("r0.6.0"))return!1;const n=e.unstable_features;return!n||void 0===n["m.require_identity_server"]||n["m.require_identity_server"]}async doesServerAcceptIdentityAccessToken(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return t&&t.includes("r0.6.0")||n&&n["m.id_access_token"]}async doesServerSupportSeparateAddAndBind(){const e=await this.getVersions();if(!e)return!1;const t=e.versions,n=e.unstable_features;return(null==t?void 0:t.includes("r0.6.0"))||(null==n?void 0:n["m.separate_add_and_bind"])}async doesServerSupportUnstableFeature(e){const t=await this.getVersions();if(!t)return!1;const n=t.unstable_features;return n&&!!n[e]}async doesServerForceEncryptionForPreset(e){const t=await this.getVersions();if(!t)return!1;const n=t.unstable_features,r=e.includes("_chat")?e.substring(0,e.indexOf("_chat")):e;return n&&!!n[`io.element.e2ee_forced.${r}`]}async doesServerSupportThread(){try{const e=await this.doesServerSupportUnstableFeature("org.matrix.msc3440"),t=await this.doesServerSupportUnstableFeature("org.matrix.msc3440.stable");return{serverSupport:e||t,stable:t}}catch(e){return null}}doesServerSupportLogoutDevices(){return this.isVersionSupported("r0.6.1")}hasLazyLoadMembersEnabled(){return!!this.clientOpts.lazyLoadMembers}setCanResetTimelineCallback(e){this.canResetTimelineCallback=e}getCanResetTimelineCallback(){return this.canResetTimelineCallback}async relations(e,t,n,r,i={direction:f.Direction.Backward}){const s=this.getEncryptedIfNeededEventType(e,r),o=await this.fetchRelations(e,t,n,s,i),a=this.getEventMapper(),c=o.original_event?a(o.original_event):void 0;let l=o.chunk.map(a);if(s===M.EventType.RoomMessageEncrypted){const e=c?l.concat(c):l;await Promise.all(e.map((e=>this.decryptEventIfNeeded(e)))),null!==r&&(l=l.filter((e=>e.getType()===r)))}return c&&n===M.RelationType.Replace&&(l=l.filter((e=>e.getSender()===c.getSender()))),{originalEvent:c,events:l,nextBatch:o.next_batch,prevBatch:o.prev_batch}}getCrossSigningCacheCallbacks(){var e;return null===(e=this.crypto)||void 0===e?void 0:e.crossSigningInfo.getCacheCallbacks()}generateClientSecret(){return(0,L.randomString)(32)}decryptEventIfNeeded(e,t){return e.shouldAttemptDecryption()&&e.attemptDecryption(this.crypto,t),e.isBeingDecrypted()?e.getDecryptionPromise():Promise.resolve()}termsUrlForService(e,t){switch(e){case _.SERVICE_TYPES.IS:return t+E.PREFIX_IDENTITY_V2+"/terms";case _.SERVICE_TYPES.IM:return t+"/_matrix/integrations/v1/terms";default:throw new Error("Unsupported service type")}}getHomeserverUrl(){return this.baseUrl}getIdentityServerUrl(e=!1){return e&&(this.idBaseUrl.startsWith("http://")||this.idBaseUrl.startsWith("https://"))?this.idBaseUrl.split("://")[1]:this.idBaseUrl}setIdentityServerUrl(e){this.idBaseUrl=h.ensureNoTrailingSlash(e),this.http.setIdBaseUrl(this.idBaseUrl)}getAccessToken(){return this.http.opts.accessToken||null}setAccessToken(e){this.http.opts.accessToken=e}isLoggedIn(){return void 0!==this.http.opts.accessToken}makeTxnId(){return"m"+(new Date).getTime()+"."+this.txnCtr++}isUsernameAvailable(e){return this.http.authedRequest(void 0,E.Method.Get,"/register/available",{username:e}).then((e=>e.available)).catch((e=>"M_USER_IN_USE"!==e.errcode&&Promise.reject(e)))}register(e,t,n,r,i,s,o,a){!0===i?i={email:!0}:null!=i&&!1!==i||(i={}),"function"==typeof o&&(a=o,o=void 0),n&&(r.session=n);const c={auth:r,refresh_token:!0};return null!=e&&(c.username=e),null!=t&&(c.password=t),i.email&&(c.bind_email=!0),i.msisdn&&(c.bind_msisdn=!0),null!=s&&(c.guest_access_token=s),null!=o&&(c.inhibit_login=o),null!=t&&(c.x_show_msisdn=!0),this.registerRequest(c,void 0,a)}registerGuest(e,t){return(e=e||{}).body=e.body||{},this.registerRequest(e.body,"guest",t)}registerRequest(e,t,n){const r={};return t&&(r.kind=t),this.http.request(n,E.Method.Post,"/register",r,e)}refreshToken(e){return this.http.authedRequest(void 0,E.Method.Post,"/refresh",void 0,{refresh_token:e},{prefix:E.PREFIX_V1,inhibitLogoutEmit:!0})}loginFlows(e){return this.http.request(e,E.Method.Get,"/login")}login(e,t,n){const r={type:e};return Object.assign(r,t),this.http.authedRequest(((e,t)=>{t&&t.access_token&&t.user_id&&(this.http.opts.accessToken=t.access_token,this.credentials={userId:t.user_id}),n&&n(e,t)}),E.Method.Post,"/login",void 0,r)}loginWithPassword(e,t,n){return this.login("m.login.password",{user:e,password:t},n)}loginWithSAML2(e,t){return this.login("m.login.saml2",{relay_state:e},t)}getCasLoginUrl(e){return this.getSsoLoginUrl(e,"cas")}getSsoLoginUrl(e,t="sso",n){let r="/login/"+t+"/redirect";return n&&(r+="/"+n),this.http.getUrl(r,{redirectUrl:e},E.PREFIX_R0)}loginWithToken(e,t){return this.login("m.login.token",{token:e},t)}async logout(e,t=!1){var n,r;if(null!==(n=this.crypto)&&void 0!==n&&null!==(r=n.backupManager)&&void 0!==r&&r.getKeyBackupEnabled())try{for(;await this.crypto.backupManager.backupPendingKeys(200)>0;);}catch(e){b.logger.error("Key backup request failed when logging out. Some keys may be missing from backup",e)}return t&&this.stopClient(),this.http.authedRequest(e,E.Method.Post,"/logout")}deactivateAccount(e,t){if("function"==typeof t)throw new Error("deactivateAccount no longer accepts a callback parameter");const n={};return e&&(n.auth=e),void 0!==t&&(n.erase=t),this.http.authedRequest(void 0,E.Method.Post,"/account/deactivate",void 0,n)}getFallbackAuthUrl(e,t){const n=h.encodeUri("/auth/$loginType/fallback/web",{$loginType:e});return this.http.getUrl(n,{session:t},E.PREFIX_R0)}async createRoom(e,t){var n;const r=(e.invite_3pid||[]).filter((e=>!e.id_access_token));if(r.length>0&&null!==(n=this.identityServer)&&void 0!==n&&n.getAccessToken&&await this.doesServerAcceptIdentityAccessToken()){const e=await this.identityServer.getAccessToken();if(e)for(const t of r)t.id_access_token=e}return this.http.authedRequest(t,E.Method.Post,"/createRoom",void 0,e)}fetchRelations(e,t,n,r,i={direction:f.Direction.Backward}){const s=h.encodeParams(i);let o="/rooms/$roomId/relations/$eventId";null!==n?(o+="/$relationType",null!==r&&(o+="/$eventType")):null!==r&&(b.logger.warn(`eventType: ${r} ignored when fetching\n relations as relationType is null`),r=null);const a=h.encodeUri(o+"?"+s,{$roomId:e,$eventId:t,$relationType:n,$eventType:r});return this.http.authedRequest(void 0,E.Method.Get,a,null,null,{prefix:E.PREFIX_UNSTABLE})}roomState(e,t){const n=h.encodeUri("/rooms/$roomId/state",{$roomId:e});return this.http.authedRequest(t,E.Method.Get,n)}fetchRoomEvent(e,t,n){const r=h.encodeUri("/rooms/$roomId/event/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(n,E.Method.Get,r)}members(e,t,n,r,i){const s={};t&&(s.membership=t),n&&(s.not_membership=n),r&&(s.at=r);const o=h.encodeParams(s),a=h.encodeUri("/rooms/$roomId/members?"+o,{$roomId:e});return this.http.authedRequest(i,E.Method.Get,a)}upgradeRoom(e,t){const n=h.encodeUri("/rooms/$roomId/upgrade",{$roomId:e});return this.http.authedRequest(void 0,E.Method.Post,n,void 0,{new_version:t})}getStateEvent(e,t,n,r){const i={$roomId:e,$eventType:t,$stateKey:n};let s=h.encodeUri("/rooms/$roomId/state/$eventType",i);return void 0!==n&&(s=h.encodeUri(s+"/$stateKey",i)),this.http.authedRequest(r,E.Method.Get,s)}sendStateEvent(e,t,n,r="",i){const s={$roomId:e,$eventType:t,$stateKey:r};let o=h.encodeUri("/rooms/$roomId/state/$eventType",s);return void 0!==r&&(o=h.encodeUri(o+"/$stateKey",s)),this.http.authedRequest(i,E.Method.Put,o,void 0,n)}roomInitialSync(e,t,n){var r,i;h.isFunction(t)&&(n=t,t=void 0);const s=h.encodeUri("/rooms/$roomId/initialSync",{$roomId:e});return this.http.authedRequest(n,E.Method.Get,s,{limit:null!==(r=null===(i=t)||void 0===i?void 0:i.toString())&&void 0!==r?r:"30"})}async setRoomReadMarkersHttpRequest(e,t,n,r){const i=h.encodeUri("/rooms/$roomId/read_markers",{$roomId:e}),s={[q.ReceiptType.FullyRead]:t,[q.ReceiptType.Read]:n},o=await h.getPrivateReadReceiptField(this);return o&&(s[o]=r),this.http.authedRequest(void 0,E.Method.Post,i,void 0,s)}getJoinedRooms(){const e=h.encodeUri("/joined_rooms",{});return this.http.authedRequest(void 0,E.Method.Get,e)}getJoinedRoomMembers(e){const t=h.encodeUri("/rooms/$roomId/joined_members",{$roomId:e});return this.http.authedRequest(void 0,E.Method.Get,t)}publicRooms(e,t){"function"==typeof e&&(t=e,e={}),void 0===e&&(e={});const n={};return e.server&&(n.server=e.server,delete e.server),0===Object.keys(e).length&&0===Object.keys(n).length?this.http.authedRequest(t,E.Method.Get,"/publicRooms"):this.http.authedRequest(t,E.Method.Post,"/publicRooms",n,e)}createAlias(e,t,n){const r=h.encodeUri("/directory/room/$alias",{$alias:e}),i={room_id:t};return this.http.authedRequest(n,E.Method.Put,r,void 0,i)}deleteAlias(e,t){const n=h.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,E.Method.Delete,n)}getLocalAliases(e){const t=h.encodeUri("/rooms/$roomId/aliases",{$roomId:e}),n=E.PREFIX_V3;return this.http.authedRequest(void 0,E.Method.Get,t,null,null,{prefix:n})}getRoomIdForAlias(e,t){const n=h.encodeUri("/directory/room/$alias",{$alias:e});return this.http.authedRequest(t,E.Method.Get,n)}resolveRoomAlias(e,t){const n=h.encodeUri("/directory/room/$alias",{$alias:e});return this.http.request(t,E.Method.Get,n)}getRoomDirectoryVisibility(e,t){const n=h.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(t,E.Method.Get,n)}setRoomDirectoryVisibility(e,t,n){const r=h.encodeUri("/directory/list/room/$roomId",{$roomId:e});return this.http.authedRequest(n,E.Method.Put,r,void 0,{visibility:t})}setRoomDirectoryVisibilityAppService(e,t,n,r){const i=h.encodeUri("/directory/list/appservice/$networkId/$roomId",{$networkId:e,$roomId:t});return this.http.authedRequest(r,E.Method.Put,i,void 0,{visibility:n})}searchUserDirectory(e){const t={search_term:e.term};return void 0!==e.limit&&(t.limit=e.limit),this.http.authedRequest(void 0,E.Method.Post,"/user_directory/search",void 0,t)}uploadContent(e,t){return this.http.uploadContent(e,t)}cancelUpload(e){return this.http.cancelUpload(e)}getCurrentUploads(){return this.http.getCurrentUploads()}getProfileInfo(e,t,n){h.isFunction(t)&&(n=t,t=void 0);const r=t?h.encodeUri("/profile/$userId/$info",{$userId:e,$info:t}):h.encodeUri("/profile/$userId",{$userId:e});return this.http.authedRequest(n,E.Method.Get,r)}getThreePids(e){return this.http.authedRequest(e,E.Method.Get,"/account/3pid")}addThreePid(e,t,n){const r={threePidCreds:e,bind:t};return this.http.authedRequest(n,E.Method.Post,"/account/3pid",null,r)}async addThreePidOnly(e){const t=await this.isVersionSupported("r0.6.0")?E.PREFIX_R0:E.PREFIX_UNSTABLE;return this.http.authedRequest(void 0,E.Method.Post,"/account/3pid/add",null,e,{prefix:t})}async bindThreePid(e){const t=await this.isVersionSupported("r0.6.0")?E.PREFIX_R0:E.PREFIX_UNSTABLE;return this.http.authedRequest(void 0,E.Method.Post,"/account/3pid/bind",null,e,{prefix:t})}async unbindThreePid(e,t){const n={medium:e,address:t,id_server:this.getIdentityServerUrl(!0)},r=await this.isVersionSupported("r0.6.0")?E.PREFIX_R0:E.PREFIX_UNSTABLE;return this.http.authedRequest(void 0,E.Method.Post,"/account/3pid/unbind",null,n,{prefix:r})}deleteThreePid(e,t){return this.http.authedRequest(void 0,E.Method.Post,"/account/3pid/delete",null,{medium:e,address:t})}setPassword(e,t,n,r){"function"==typeof n&&(r=n),"boolean"!=typeof n&&(n=void 0);const i={auth:e,new_password:t,logout_devices:n};return this.http.authedRequest(r,E.Method.Post,"/account/password",null,i)}getDevices(){return this.http.authedRequest(void 0,E.Method.Get,"/devices")}getDevice(e){const t=h.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,E.Method.Get,t)}setDeviceDetails(e,t){const n=h.encodeUri("/devices/$device_id",{$device_id:e});return this.http.authedRequest(void 0,E.Method.Put,n,void 0,t)}deleteDevice(e,t){const n=h.encodeUri("/devices/$device_id",{$device_id:e}),r={};return t&&(r.auth=t),this.http.authedRequest(void 0,E.Method.Delete,n,void 0,r)}deleteMultipleDevices(e,t){const n={devices:e};return t&&(n.auth=t),this.http.authedRequest(void 0,E.Method.Post,"/delete_devices",void 0,n)}getPushers(e){return this.http.authedRequest(e,E.Method.Get,"/pushers")}setPusher(e,t){return this.http.authedRequest(t,E.Method.Post,"/pushers/set",null,e)}getPushRules(e){return this.http.authedRequest(e,E.Method.Get,"/pushrules/").then((e=>g.PushProcessor.rewriteDefaultRules(e)))}addPushRule(e,t,n,r,i){const s=h.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(i,E.Method.Put,s,void 0,r)}deletePushRule(e,t,n,r){const i=h.encodeUri("/pushrules/"+e+"/$kind/$ruleId",{$kind:t,$ruleId:n});return this.http.authedRequest(r,E.Method.Delete,i)}setPushRuleEnabled(e,t,n,r,i){const s=h.encodeUri("/pushrules/"+e+"/$kind/$ruleId/enabled",{$kind:t,$ruleId:n});return this.http.authedRequest(i,E.Method.Put,s,void 0,{enabled:r})}setPushRuleActions(e,t,n,r,i){const s=h.encodeUri("/pushrules/"+e+"/$kind/$ruleId/actions",{$kind:t,$ruleId:n});return this.http.authedRequest(i,E.Method.Put,s,void 0,{actions:r})}search(e,t){const n={};return e.next_batch&&(n.next_batch=e.next_batch),this.http.authedRequest(t,E.Method.Post,"/search",n,e.body)}uploadKeysRequest(e,t,n){return this.http.authedRequest(n,E.Method.Post,"/keys/upload",void 0,e)}uploadKeySignatures(e){return this.http.authedRequest(void 0,E.Method.Post,"/keys/signatures/upload",void 0,e,{prefix:E.PREFIX_UNSTABLE})}downloadKeysForUsers(e,t){if(h.isFunction(t))throw new Error("downloadKeysForUsers no longer accepts a callback parameter");const n={device_keys:{}};return"token"in(t=t||{})&&(n.token=t.token),e.forEach((e=>{n.device_keys[e]=[]})),this.http.authedRequest(void 0,E.Method.Post,"/keys/query",void 0,n)}claimOneTimeKeys(e,t="signed_curve25519",n){const r={};void 0===t&&(t="signed_curve25519");for(let n=0;n<e.length;++n){const i=e[n][0],s=e[n][1],o=r[i]||{};r[i]=o,o[s]=t}const i={one_time_keys:r};return n&&(i.timeout=n),this.http.authedRequest(void 0,E.Method.Post,"/keys/claim",void 0,i)}getKeyChanges(e,t){const n={from:e,to:t};return this.http.authedRequest(void 0,E.Method.Get,"/keys/changes",n)}uploadDeviceSigningKeys(e,t){const n=Object.assign({},t);return e&&Object.assign(n,{auth:e}),this.http.authedRequest(void 0,E.Method.Post,"/keys/device_signing/upload",void 0,n,{prefix:E.PREFIX_UNSTABLE})}registerWithIdentityServer(e){if(!this.idBaseUrl)throw new Error("No identity server base URL set");const t=this.idBaseUrl+E.PREFIX_IDENTITY_V2+"/account/register";return this.http.requestOtherUrl(void 0,E.Method.Post,t,null,e)}requestEmailToken(e,t,n,r,i,s){const o={client_secret:t,email:e,send_attempt:null==n?void 0:n.toString(),next_link:r};return this.http.idServerRequest(i,E.Method.Post,"/validate/email/requestToken",o,E.PREFIX_IDENTITY_V2,s)}requestMsisdnToken(e,t,n,r,i,s,o){const a={client_secret:n,country:e,phone_number:t,send_attempt:null==r?void 0:r.toString(),next_link:i};return this.http.idServerRequest(s,E.Method.Post,"/validate/msisdn/requestToken",a,E.PREFIX_IDENTITY_V2,o)}submitMsisdnToken(e,t,n,r){const i={sid:e,client_secret:t,token:n};return this.http.idServerRequest(void 0,E.Method.Post,"/validate/msisdn/submitToken",i,E.PREFIX_IDENTITY_V2,r)}submitMsisdnTokenOtherUrl(e,t,n,r){const i={sid:t,client_secret:n,token:r};return this.http.requestOtherUrl(void 0,E.Method.Post,e,void 0,i)}getIdentityHashDetails(e){return this.http.idServerRequest(void 0,E.Method.Get,"/hash_details",null,E.PREFIX_IDENTITY_V2,e)}async identityHashedLookup(e,t){const r={},i=await this.getIdentityHashDetails(t);if(!i||!i.lookup_pepper||!i.algorithms)throw new Error("Unsupported identity server: bad response");r.pepper=i.lookup_pepper;const s={};if(i.algorithms.includes("sha256")){const t=new n.g.Olm.Utility;r.addresses=e.map((e=>{const n=e[0].toLowerCase(),i=e[1].toLowerCase(),o=t.sha256(`${n} ${i} ${r.pepper}`).replace(/\+/g,"-").replace(/\//g,"_");return s[o]=e[0],o})),r.algorithm="sha256"}else{if(!i.algorithms.includes("none"))throw new Error("Unsupported identity server: unknown hash algorithm");r.addresses=e.map((e=>{const t=`${e[0].toLowerCase()} ${e[1].toLowerCase()}`;return s[t]=e[0],t})),r.algorithm="none"}const o=await this.http.idServerRequest(void 0,E.Method.Post,"/lookup",r,E.PREFIX_IDENTITY_V2,t);if(!o||!o.mappings)return[];const a=[];for(const e of Object.keys(o.mappings)){const t=o.mappings[e],n=s[e];if(!n)throw new Error("Identity server returned more results than expected");a.push({address:n,mxid:t})}return a}async lookupThreePid(e,t,n,r){const i=(await this.identityHashedLookup([[t,e]],r)).find((e=>e.address===t));if(!i)return n&&n(null,{}),{};const s={address:t,medium:e,mxid:i.mxid};return n&&n(null,s),s}async bulkLookupThreePids(e,t){const n=await this.identityHashedLookup(e.map((e=>[e[1],e[0]])),t),r=[];for(const t of n){const n=e.find((e=>e[1]===t.address));if(!n)throw new Error("Identity sever returned unexpected results");r.push([n[0],t.address,t.mxid])}return{threepids:r}}getIdentityAccount(e){return this.http.idServerRequest(void 0,E.Method.Get,"/account",void 0,E.PREFIX_IDENTITY_V2,e)}sendToDevice(e,t,n){const r=h.encodeUri("/sendToDevice/$eventType/$txnId",{$eventType:e,$txnId:n||this.makeTxnId()}),i={messages:t},s=Object.keys(t).reduce(((e,n)=>(e[n]=Object.keys(t[n]),e)),{});return b.logger.log(`PUT ${r}`,s),this.http.authedRequest(void 0,E.Method.Put,r,void 0,i)}queueToDevice(e){return this.toDeviceMessageQueue.queueBatch(e)}getThirdpartyProtocols(){return this.http.authedRequest(void 0,E.Method.Get,"/thirdparty/protocols").then((e=>{if(!e||"object"!=typeof e)throw new Error(`/thirdparty/protocols did not return an object: ${e}`);return e}))}getThirdpartyLocation(e,t){const n=h.encodeUri("/thirdparty/location/$protocol",{$protocol:e});return this.http.authedRequest(void 0,E.Method.Get,n,t)}getThirdpartyUser(e,t){const n=h.encodeUri("/thirdparty/user/$protocol",{$protocol:e});return this.http.authedRequest(void 0,E.Method.Get,n,t)}getTerms(e,t){const n=this.termsUrlForService(e,t);return this.http.requestOtherUrl(void 0,E.Method.Get,n)}agreeToTerms(e,t,n,r){const i=this.termsUrlForService(e,t),s={Authorization:"Bearer "+n};return this.http.requestOtherUrl(void 0,E.Method.Post,i,null,{user_accepts:r},{headers:s})}reportEvent(e,t,n,r){const i=h.encodeUri("/rooms/$roomId/report/$eventId",{$roomId:e,$eventId:t});return this.http.authedRequest(void 0,E.Method.Post,i,null,{score:n,reason:r})}getRoomHierarchy(e,t,n,r=!1,i){const s=h.encodeUri("/rooms/$roomId/hierarchy",{$roomId:e}),o={suggested_only:String(r),max_depth:null==n?void 0:n.toString(),from:i,limit:null==t?void 0:t.toString()};return this.http.authedRequest(void 0,E.Method.Get,s,o,void 0,{prefix:E.PREFIX_V1}).catch((e=>{if("M_UNRECOGNIZED"===e.errcode)return this.http.authedRequest(void 0,E.Method.Get,s,o,void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc2946"});throw e}))}async unstableCreateFileTree(e){const{room_id:t}=await this.createRoom({name:e,preset:P.Preset.PrivateChat,power_level_content_override:J(J({},x.DEFAULT_TREE_POWER_LEVELS_TEMPLATE),{},{users:{[this.getUserId()]:100}}),creation_content:{[M.RoomCreateTypeField]:M.RoomType.Space},initial_state:[{type:M.UNSTABLE_MSC3088_PURPOSE.name,state_key:M.UNSTABLE_MSC3089_TREE_SUBTYPE.name,content:{[M.UNSTABLE_MSC3088_ENABLED.name]:!0}},{type:M.EventType.RoomEncryption,state_key:"",content:{algorithm:m.MEGOLM_ALGORITHM}}]});return new x.MSC3089TreeSpace(this,t)}unstableGetFileTreeSpace(e){var t,n;const r=this.getRoom(e);if("join"!==(null==r?void 0:r.getMyMembership()))return null;const i=r.currentState.getStateEvents(M.EventType.RoomCreate,""),s=r.currentState.getStateEvents(M.UNSTABLE_MSC3088_PURPOSE.name,M.UNSTABLE_MSC3089_TREE_SUBTYPE.name);if(!i)throw new Error("Expected single room create event");return null!=s&&null!==(t=s.getContent())&&void 0!==t&&t[M.UNSTABLE_MSC3088_ENABLED.name]?(null===(n=i.getContent())||void 0===n?void 0:n[M.RoomCreateTypeField])!==M.RoomType.Space?null:new x.MSC3089TreeSpace(this,e):null}slidingSync(e,t){const n={};e.pos&&(n.pos=e.pos,delete e.pos),e.timeout&&(n.timeout=e.timeout,delete e.timeout);const r=e.clientTimeout;return delete e.clientTimeout,this.http.authedRequest(void 0,E.Method.Post,"/sync",n,e,{prefix:"/_matrix/client/unstable/org.matrix.msc3575",baseUrl:t,localTimeoutMs:r})}supportsExperimentalThreads(){var e;return(null===(e=this.clientOpts)||void 0===e?void 0:e.experimentalThreadSupport)||!1}async getRoomSummary(e,t){const n=h.encodeUri("/rooms/$roomid/summary",{$roomid:e});return this.http.authedRequest(void 0,E.Method.Get,n,{via:t},null,{qsStringifyOptions:{arrayFormat:"repeat"},prefix:"/_matrix/client/unstable/im.nheko.summary"})}processThreadEvents(e,t,n){e.processThreadedEvents(t,n)}processBeaconEvents(e,t){null!=t&&t.length&&e&&e.currentState.processBeaconEvents(t,this)}async whoami(){return this.http.authedRequest(void 0,E.Method.Get,"/account/whoami")}timestampToEvent(e,t,n){const r=h.encodeUri("/rooms/$roomId/timestamp_to_event",{$roomId:e});return this.http.authedRequest(void 0,E.Method.Get,r,{ts:t.toString(),dir:n},void 0,{prefix:"/_matrix/client/unstable/org.matrix.msc3030"})}}t.MatrixClient=ie,(0,i.default)(ie,"RESTORE_BACKUP_ERROR_BAD_KEY","RESTORE_BACKUP_ERROR_BAD_KEY")},4656:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.makeBeaconInfoContent=t.makeBeaconContent=t.getTextForLocationEvent=void 0,t.makeEmoteMessage=function(e){return{msgtype:o.MsgType.Emote,body:e}},t.makeHtmlEmote=function(e,t){return{msgtype:o.MsgType.Emote,format:"org.matrix.custom.html",body:e,formatted_body:t}},t.makeHtmlMessage=function(e,t){return{msgtype:o.MsgType.Text,format:"org.matrix.custom.html",body:e,formatted_body:t}},t.makeHtmlNotice=function(e,t){return{msgtype:o.MsgType.Notice,format:"org.matrix.custom.html",body:e,formatted_body:t}},t.makeLocationContent=void 0,t.makeNotice=function(e){return{msgtype:o.MsgType.Notice,body:e}},t.makeTextMessage=function(e){return{msgtype:o.MsgType.Text,body:e}},t.parseTopicContent=t.parseLocationEvent=t.parseBeaconInfoContent=t.parseBeaconContent=t.makeTopicContent=void 0;var i=r(n(8416)),s=n(1333),o=n(2481),a=n(6548),c=n(6709),l=n(9953);function d(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}const u=(e,t,n,r)=>{const i=`at ${new Date(n).toISOString()}`;return[t===c.LocationAssetType.Self?"User":void 0,"Location",r?`"${r}"`:void 0,e,i].filter(Boolean).join(" ")};t.getTextForLocationEvent=u;const h=(e,t,n,r,s)=>{const l=null!=e?e:u(t,s||c.LocationAssetType.Self,n,r),h=n?{[c.M_TIMESTAMP.name]:n}:{};return function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?d(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):d(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({msgtype:o.MsgType.Location,body:l,geo_uri:t,[c.M_LOCATION.name]:{description:r,uri:t},[c.M_ASSET.name]:{type:s||c.LocationAssetType.Self},[a.TEXT_NODE_TYPE.name]:l},h)};t.makeLocationContent=h,t.parseLocationEvent=e=>{var t,n;const r=c.M_LOCATION.findIn(e),i=c.M_ASSET.findIn(e),s=c.M_TIMESTAMP.findIn(e),o=a.TEXT_NODE_TYPE.findIn(e),l=null!==(t=null==r?void 0:r.uri)&&void 0!==t?t:null==e?void 0:e.geo_uri,d=null==r?void 0:r.description,u=null!==(n=null==i?void 0:i.type)&&void 0!==n?n:c.LocationAssetType.Self,f=null!=o?o:e.body;return h(f,l,s,d,u)},t.makeTopicContent=(e,t)=>{const n=[{body:e,mimetype:"text/plain"}];return(0,s.isProvided)(t)&&n.push({body:t,mimetype:"text/html"}),{topic:e,[l.M_TOPIC.name]:n}},t.parseTopicContent=e=>{var t,n,r;const i=l.M_TOPIC.findIn(e);return{text:null!==(t=null==i||null===(n=i.find((e=>!(0,s.isProvided)(e.mimetype)||"text/plain"===e.mimetype)))||void 0===n?void 0:n.body)&&void 0!==t?t:e.topic,html:null==i||null===(r=i.find((e=>"text/html"===e.mimetype)))||void 0===r?void 0:r.body}},t.makeBeaconInfoContent=(e,t,n,r,i)=>({description:n,timeout:e,live:t,[c.M_TIMESTAMP.name]:i||Date.now(),[c.M_ASSET.name]:{type:null!=r?r:c.LocationAssetType.Self}}),t.parseBeaconInfoContent=e=>{const{description:t,timeout:n,live:r}=e,i=c.M_TIMESTAMP.findIn(e),s=c.M_ASSET.findIn(e);return{description:t,timeout:n,live:r,assetType:null==s?void 0:s.type,timestamp:i}},t.makeBeaconContent=(e,t,n,r)=>({[c.M_LOCATION.name]:{description:r,uri:e},[c.M_TIMESTAMP.name]:t,"m.relates_to":{rel_type:s.REFERENCE_RELATION.name,event_id:n}}),t.parseBeaconContent=e=>{const{description:t,uri:n}=c.M_LOCATION.findIn(e);return{description:t,uri:n,timestamp:c.M_TIMESTAMP.findIn(e)}}},3667:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.getHttpUriForMxc=function(e,t,n,i,s,o=!1){if("string"!=typeof t||!t)return"";if(0!==t.indexOf("mxc://"))return o?t:"";let a=t.slice(6),c="/_matrix/media/r0/download/";const l={};n&&(l.width=Math.round(n).toString()),i&&(l.height=Math.round(i).toString()),s&&(l.method=s),Object.keys(l).length>0&&(c="/_matrix/media/r0/thumbnail/");const d=a.indexOf("#");let u="";d>=0&&(u=a.slice(d),a=a.slice(0,d));return e+c+a+(0===Object.keys(l).length?"":"?"+r.encodeParams(l))+u};var r=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=i(t);if(n&&n.has(e))return n.get(e);var r={},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var a=s?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}(n(3102));function i(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(i=function(e){return e?n:t})(e)}},3075:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.UserTrustLevel=t.DeviceTrustLevel=t.CrossSigningLevel=t.CrossSigningInfo=void 0,t.createCryptoStoreCacheCallbacks=function(e,t){return{getCrossSigningKeyCache:async function(n,r){const i=await new Promise((t=>e.doTxn("readonly",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(r=>{e.getSecretStorePrivateKey(r,t,n)}))));if(i&&i.ciphertext){const e=Buffer.from(t.pickleKey),r=await(0,c.decryptAES)(i,e,n);return(0,s.decodeBase64)(r)}return i},storeCrossSigningKeyCache:async function(n,r){if(!(r instanceof Uint8Array))throw new Error(`storeCrossSigningKeyCache expects Uint8Array, got ${r}`);const i=Buffer.from(t.pickleKey),o=await(0,c.encryptAES)((0,s.encodeBase64)(r),i,n);return e.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.storeSecretStorePrivateKey(t,n,o)}))}}},t.requestKeysDuringVerification=function(e,t,n){if(e.getUserId()===t)return o.logger.log("Cross-signing: Self-verification done; requesting keys"),new Promise(((t,r)=>{const i=e,a=i.crypto.crossSigningInfo,c=new u(a.userId,{getCrossSigningKey:async e=>{o.logger.debug("Cross-signing: requesting secret",e,n);const{promise:t}=i.requestSecret(`m.cross_signing.${e}`,[n]),r=await t,a=(0,s.decodeBase64)(r);return Uint8Array.from(a)}},a.getCacheCallbacks());c.keys=a.keys;const d=new Promise((e=>{setTimeout(e,l,new Error("Timeout"))})),h=(async()=>{if(!await i.crypto.getSessionBackupPrivateKey()){o.logger.info("No cached backup key found. Requesting...");const e=i.requestSecret("m.megolm_backup.v1",[n]),t=await e.promise;o.logger.info("Got key backup key, decoding...");const r=(0,s.decodeBase64)(t);o.logger.info("Decoded backup key, storing..."),await i.crypto.storeSessionBackupPrivateKey(Uint8Array.from(r)),o.logger.info("Backup key stored. Starting backup restore...");const a=await i.getKeyBackupVersion();i.restoreKeyBackupWithCache(void 0,void 0,a).then((()=>{o.logger.info("Backup restored.")}))}})();return Promise.race([Promise.all([c.getCrossSigningKey("master"),c.getCrossSigningKey("self_signing"),c.getCrossSigningKey("user_signing"),h]),d]).then(t,r)})).catch((e=>{o.logger.warn("Cross-signing: failure while requesting keys:",e)}))};var i=r(n(8416)),s=n(2772),o=n(7434),a=n(7585),c=n(2611);const l=6e4;function d(e){return Object.values(e.keys)[0]}class u{constructor(e,t={},n={}){this.userId=e,this.callbacks=t,this.cacheCallbacks=n,(0,i.default)(this,"keys",{}),(0,i.default)(this,"firstUse",!0),(0,i.default)(this,"crossSigningVerifiedBefore",!1)}static fromStorage(e,t){const n=new u(t);for(const t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}toStorage(){return{keys:this.keys,firstUse:this.firstUse,crossSigningVerifiedBefore:this.crossSigningVerifiedBefore}}async getCrossSigningKey(e,t){const r=["master","self_signing","user_signing"].indexOf(e)>=0;if(!this.callbacks.getCrossSigningKey)throw new Error("No getCrossSigningKey callback supplied");function i(e){if(!e)return;const r=new n.g.Olm.PkSigning,i=r.init_with_seed(e);if(i===t)return[i,r];r.free()}let s;void 0===t&&(t=this.getId(e)),this.cacheCallbacks.getCrossSigningKeyCache&&r&&(s=await this.cacheCallbacks.getCrossSigningKeyCache(e,t));const o=i(s);if(o)return o;s=await this.callbacks.getCrossSigningKey(e,t);const a=i(s);if(a)return this.cacheCallbacks.storeCrossSigningKeyCache&&r&&await this.cacheCallbacks.storeCrossSigningKeyCache(e,s),a;if(!s)throw new Error("getCrossSigningKey callback for "+e+" returned falsey");throw new Error("Key type "+e+" from getCrossSigningKey callback did not match")}async isStoredInSecretStorage(e){const t=await e.isStored("m.cross_signing.master")||{};function n(e){for(const n of Object.keys(t))e[n]||delete t[n]}for(const t of["self_signing","user_signing"])n(await e.isStored(`m.cross_signing.${t}`)||{});return Object.keys(t).length?t:null}static async storeInSecretStorage(e,t){for(const[n,r]of e){const e=(0,s.encodeBase64)(r);await t.store(`m.cross_signing.${n}`,e)}}static async getFromSecretStorage(e,t){const n=await t.get(`m.cross_signing.${e}`);return n?(0,s.decodeBase64)(n):null}async isStoredInKeyCache(e){const t=this.cacheCallbacks;if(!t)return!1;const n=e?[e]:["master","self_signing","user_signing"];for(const e of n)if(!await t.getCrossSigningKeyCache(e))return!1;return!0}async getCrossSigningKeysFromCache(){const e=new Map,t=this.cacheCallbacks;if(!t)return e;for(const n of["master","self_signing","user_signing"]){const r=await t.getCrossSigningKeyCache(n);r&&e.set(n,r)}return e}getId(e="master"){return this.keys[e]?d(this.keys[e]):null}async resetKeys(e){if(!this.callbacks.saveCrossSigningKeys)throw new Error("No saveCrossSigningKeys callback supplied");if(void 0===e||e&h.MASTER||!this.keys.master)e=h.MASTER|h.USER_SIGNING|h.SELF_SIGNING;else if(0===e)return;const t={},r={};let i,o;try{if(e&h.MASTER?(i=new n.g.Olm.PkSigning,t.master=i.generate_seed(),o=i.init_with_seed(t.master),r.master={user_id:this.userId,usage:["master"],keys:{["ed25519:"+o]:o}}):[o,i]=await this.getCrossSigningKey("master"),e&h.SELF_SIGNING){const e=new n.g.Olm.PkSigning;try{t.self_signing=e.generate_seed();const n=e.init_with_seed(t.self_signing);r.self_signing={user_id:this.userId,usage:["self_signing"],keys:{["ed25519:"+n]:n}},(0,s.pkSign)(r.self_signing,i,this.userId,o)}finally{e.free()}}if(e&h.USER_SIGNING){const e=new n.g.Olm.PkSigning;try{t.user_signing=e.generate_seed();const n=e.init_with_seed(t.user_signing);r.user_signing={user_id:this.userId,usage:["user_signing"],keys:{["ed25519:"+n]:n}},(0,s.pkSign)(r.user_signing,i,this.userId,o)}finally{e.free()}}Object.assign(this.keys,r),this.callbacks.saveCrossSigningKeys(t)}finally{i&&i.free()}}clearKeys(){this.keys={}}setKeys(e){const t={};if(e.master){if(e.master.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in master key from "+this.userId;throw o.logger.error(t),new Error(t)}this.keys.master?d(e.master)!==this.getId()&&(this.firstUse=!1):this.firstUse=!0,t.master=e.master}else{if(!this.keys.master)throw new Error("Tried to set cross-signing keys without a master key");t.master=this.keys.master}const n=d(t.master);if(e.user_signing){if(e.user_signing.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in user_signing key from "+this.userId;throw o.logger.error(t),new Error(t)}try{(0,s.pkVerify)(e.user_signing,n,this.userId)}catch(e){throw o.logger.error("invalid signature on user-signing key"),e}}if(e.self_signing){if(e.self_signing.user_id!==this.userId){const t="Mismatched user ID "+e.master.user_id+" in self_signing key from "+this.userId;throw o.logger.error(t),new Error(t)}try{(0,s.pkVerify)(e.self_signing,n,this.userId)}catch(e){throw o.logger.error("invalid signature on self-signing key"),e}}e.master&&(this.keys.master=e.master,this.keys.self_signing=null,this.keys.user_signing=null),e.self_signing&&(this.keys.self_signing=e.self_signing),e.user_signing&&(this.keys.user_signing=e.user_signing)}updateCrossSigningVerifiedBefore(e){!this.crossSigningVerifiedBefore&&e&&(this.crossSigningVerifiedBefore=!0)}async signObject(e,t){if(!this.keys[t])throw new Error("Attempted to sign with "+t+" key but no such key present");const[n,r]=await this.getCrossSigningKey(t);try{return(0,s.pkSign)(e,r,this.userId,n),e}finally{r.free()}}async signUser(e){if(this.keys.user_signing)return this.signObject(e.keys.master,"user_signing");o.logger.info("No user signing key: not signing user")}async signDevice(e,t){if(e!==this.userId)throw new Error(`Trying to sign ${e}'s device; can only sign our own device`);if(this.keys.self_signing)return this.signObject({algorithms:t.algorithms,keys:t.keys,device_id:t.deviceId,user_id:e},"self_signing");o.logger.info("No self signing key: not signing device")}checkUserTrust(e){if(this.userId===e.userId&&this.getId()&&this.getId()===e.getId()&&this.getId("self_signing")&&this.getId("self_signing")===e.getId("self_signing"))return new f(!0,!0,this.firstUse);if(!this.keys.user_signing)return new f(!1,!1,e.firstUse);let t;const n=e.keys.master,r=this.getId("user_signing");try{(0,s.pkVerify)(n,r,this.userId),t=!0}catch(e){t=!1}return new f(t,e.crossSigningVerifiedBefore,e.firstUse)}checkDeviceTrust(e,t,n,r){const i=this.checkUserTrust(e),o=e.keys.self_signing;if(!o)return new g(!1,!1,n,r);const a=function(e,t){return{algorithms:e.algorithms,keys:e.keys,device_id:e.deviceId,user_id:t,signatures:e.signatures}}(t,e.userId);try{return(0,s.pkVerify)(o,e.getId(),e.userId),(0,s.pkVerify)(a,d(o),e.userId),g.fromUserTrustLevel(i,n,r)}catch(e){return new g(!1,!1,n,r)}}getCacheCallbacks(){return this.cacheCallbacks}}let h;t.CrossSigningInfo=u,t.CrossSigningLevel=h,function(e){e[e.MASTER=4]="MASTER",e[e.USER_SIGNING=2]="USER_SIGNING",e[e.SELF_SIGNING=1]="SELF_SIGNING"}(h||(t.CrossSigningLevel=h={}));class f{constructor(e,t,n){this.crossSigningVerified=e,this.crossSigningVerifiedBefore=t,this.tofu=n}isVerified(){return this.isCrossSigningVerified()}isCrossSigningVerified(){return this.crossSigningVerified}wasCrossSigningVerified(){return this.crossSigningVerifiedBefore}isTofu(){return this.tofu}}t.UserTrustLevel=f;class g{constructor(e,t,n,r){this.crossSigningVerified=e,this.tofu=t,this.localVerified=n,this.trustCrossSignedDevices=r}static fromUserTrustLevel(e,t,n){return new g(e.isCrossSigningVerified(),e.isTofu(),t,n)}isVerified(){return Boolean(this.isLocallyVerified()||this.trustCrossSignedDevices&&this.isCrossSigningVerified())}isCrossSigningVerified(){return this.crossSigningVerified}isLocallyVerified(){return this.localVerified}isTofu(){return this.tofu}}t.DeviceTrustLevel=g},6670:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.TrackingStatus=t.DeviceList=void 0;var i=r(n(8416)),s=n(7434),o=n(3272),a=n(3075),c=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=f(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(2772)),l=n(7585),d=n(3102),u=n(5861),h=n(2600);function f(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(f=function(e){return e?n:t})(e)}let g;t.TrackingStatus=g,function(e){e[e.NotTracked=0]="NotTracked",e[e.PendingDownload=1]="PendingDownload",e[e.DownloadInProgress=2]="DownloadInProgress",e[e.UpToDate=3]="UpToDate"}(g||(t.TrackingStatus=g={}));class p extends u.TypedEventEmitter{constructor(e,t,n,r=250){super(),this.cryptoStore=t,this.keyDownloadChunkSize=r,(0,i.default)(this,"devices",{}),(0,i.default)(this,"crossSigningInfo",{}),(0,i.default)(this,"userByIdentityKey",{}),(0,i.default)(this,"deviceTrackingStatus",{}),(0,i.default)(this,"syncToken",null),(0,i.default)(this,"keyDownloadsInProgressByUser",{}),(0,i.default)(this,"dirty",!1),(0,i.default)(this,"savePromise",null),(0,i.default)(this,"resolveSavePromise",null),(0,i.default)(this,"savePromiseTime",null),(0,i.default)(this,"saveTimer",null),(0,i.default)(this,"hasFetched",null),(0,i.default)(this,"serialiser",void 0),this.serialiser=new m(e,n,this)}async load(){await this.cryptoStore.doTxn("readonly",[l.IndexedDBCryptoStore.STORE_DEVICE_DATA],(e=>{this.cryptoStore.getEndToEndDeviceData(e,(e=>{this.hasFetched=Boolean(e&&e.devices),this.devices=e?e.devices:{},this.crossSigningInfo=e&&e.crossSigningInfo||{},this.deviceTrackingStatus=e?e.trackingStatus:{},this.syncToken=e?e.syncToken:null,this.userByIdentityKey={};for(const e of Object.keys(this.devices)){const t=this.devices[e];for(const n of Object.keys(t)){const r=t[n].keys["curve25519:"+n];void 0!==r&&(this.userByIdentityKey[r]=e)}}}))}));for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]==g.DownloadInProgress&&(this.deviceTrackingStatus[e]=g.PendingDownload)}stop(){null!==this.saveTimer&&clearTimeout(this.saveTimer)}async saveIfDirty(e=500){if(!this.dirty)return Promise.resolve(!1);const t=Date.now()+e;this.savePromiseTime&&t<this.savePromiseTime&&(clearTimeout(this.saveTimer),this.saveTimer=null,this.savePromiseTime=null);let n=this.savePromise;if(null===n&&(n=new Promise((e=>{this.resolveSavePromise=e})),this.savePromise=n),null===this.saveTimer){const n=this.resolveSavePromise;this.savePromiseTime=t,this.saveTimer=setTimeout((()=>{s.logger.log("Saving device tracking data",this.syncToken),this.savePromiseTime=null,this.saveTimer=null,this.savePromise=null,this.resolveSavePromise=null,this.cryptoStore.doTxn("readwrite",[l.IndexedDBCryptoStore.STORE_DEVICE_DATA],(e=>{this.cryptoStore.storeEndToEndDeviceData({devices:this.devices,crossSigningInfo:this.crossSigningInfo,trackingStatus:this.deviceTrackingStatus,syncToken:this.syncToken},e)})).then((()=>{this.dirty=!1,n(!0)}),(e=>{s.logger.error("Failed to save device tracking data",this.syncToken),s.logger.error(e)}))}),e)}return n}getSyncToken(){return this.syncToken}setSyncToken(e){this.syncToken=e}downloadKeys(e,t){const n=[],r=[];if(e.forEach((e=>{const i=this.deviceTrackingStatus[e];this.keyDownloadsInProgressByUser[e]?(s.logger.log(`downloadKeys: already have a download in progress for ${e}: awaiting its result`),r.push(this.keyDownloadsInProgressByUser[e])):(t||i!=g.UpToDate)&&n.push(e)})),0!=n.length){s.logger.log("downloadKeys: downloading for",n);const e=this.doKeyDownload(n);r.push(e)}return 0===r.length&&s.logger.log("downloadKeys: already have all necessary keys"),Promise.all(r).then((()=>this.getDevicesFromStore(e)))}getDevicesFromStore(e){const t={};return e.forEach((e=>{t[e]={},(this.getStoredDevicesForUser(e)||[]).forEach((function(n){t[e][n.deviceId]=n}))})),t}getKnownUserIds(){return Object.keys(this.devices)}getStoredDevicesForUser(e){const t=this.devices[e];if(!t)return null;const n=[];for(const e in t)t.hasOwnProperty(e)&&n.push(o.DeviceInfo.fromStorage(t[e],e));return n}getRawStoredDevicesForUser(e){return this.devices[e]}getStoredCrossSigningForUser(e){return this.crossSigningInfo[e]?a.CrossSigningInfo.fromStorage(this.crossSigningInfo[e],e):null}storeCrossSigningForUser(e,t){this.crossSigningInfo[e]=t,this.dirty=!0}getStoredDevice(e,t){const n=this.devices[e];if(n&&n[t])return o.DeviceInfo.fromStorage(n[t],t)}getUserByIdentityKey(e,t){return e!==c.OLM_ALGORITHM&&e!==c.MEGOLM_ALGORITHM?null:this.userByIdentityKey[t]}getDeviceByIdentityKey(e,t){const n=this.getUserByIdentityKey(e,t);if(!n)return null;const r=this.devices[n];if(!r)return null;for(const e in r){if(!r.hasOwnProperty(e))continue;const n=r[e];for(const r in n.keys)if(n.keys.hasOwnProperty(r)&&0===r.indexOf("curve25519:")&&n.keys[r]==t)return o.DeviceInfo.fromStorage(n,e)}return null}storeDevicesForUser(e,t){this.setRawStoredDevicesForUser(e,t),this.dirty=!0}startTrackingDeviceList(e){if("string"!=typeof e)throw new Error("userId must be a string; was "+e);this.deviceTrackingStatus[e]||(s.logger.log("Now tracking device list for "+e),this.deviceTrackingStatus[e]=g.PendingDownload,this.dirty=!0)}stopTrackingDeviceList(e){this.deviceTrackingStatus[e]&&(s.logger.log("No longer tracking device list for "+e),this.deviceTrackingStatus[e]=g.NotTracked,this.dirty=!0)}stopTrackingAllDeviceLists(){for(const e of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[e]=g.NotTracked;this.dirty=!0}invalidateUserDeviceList(e){this.deviceTrackingStatus[e]&&(s.logger.log("Marking device list outdated for",e),this.deviceTrackingStatus[e]=g.PendingDownload,this.dirty=!0)}refreshOutdatedDeviceLists(){this.saveIfDirty();const e=[];for(const t of Object.keys(this.deviceTrackingStatus))this.deviceTrackingStatus[t]==g.PendingDownload&&e.push(t);return this.doKeyDownload(e)}setRawStoredDevicesForUser(e,t){if(void 0!==this.devices[e])for(const[t,n]of Object.entries(this.devices[e])){const e=n.keys["curve25519:"+t];delete this.userByIdentityKey[e]}this.devices[e]=t;for(const[n,r]of Object.entries(t)){const t=r.keys["curve25519:"+n];this.userByIdentityKey[t]=e}}setRawStoredCrossSigningForUser(e,t){this.crossSigningInfo[e]=t}doKeyDownload(e){if(0===e.length)return Promise.resolve();const t=this.serialiser.updateDevicesForUsers(e,this.syncToken).then((()=>{n(!0)}),(t=>{throw s.logger.error("Error downloading keys for "+e+":",t),n(!1),t}));e.forEach((e=>{this.keyDownloadsInProgressByUser[e]=t,this.deviceTrackingStatus[e]==g.PendingDownload&&(this.deviceTrackingStatus[e]=g.DownloadInProgress)}));const n=n=>{this.emit(h.CryptoEvent.WillUpdateDevices,e,!this.hasFetched),e.forEach((e=>{this.dirty=!0,this.keyDownloadsInProgressByUser[e]===t?(delete this.keyDownloadsInProgressByUser[e],this.deviceTrackingStatus[e]==g.DownloadInProgress&&(n?(this.deviceTrackingStatus[e]=g.UpToDate,s.logger.log("Device list for",e,"now up to date")):this.deviceTrackingStatus[e]=g.PendingDownload)):s.logger.log("Another update in the queue for",e,"- not marking up-to-date")})),this.saveIfDirty(),this.emit(h.CryptoEvent.DevicesUpdated,e,!this.hasFetched),this.hasFetched=!0};return t}}t.DeviceList=p;class m{constructor(e,t,n){this.baseApis=e,this.olmDevice=t,this.deviceList=n,(0,i.default)(this,"downloadInProgress",!1),(0,i.default)(this,"keyDownloadsQueuedByUser",{}),(0,i.default)(this,"queuedQueryDeferred",null),(0,i.default)(this,"syncToken",null)}updateDevicesForUsers(e,t){return e.forEach((e=>{this.keyDownloadsQueuedByUser[e]=!0})),this.queuedQueryDeferred||(this.queuedQueryDeferred=(0,d.defer)()),this.syncToken=t,this.downloadInProgress?(s.logger.log("Queued key download for",e),this.queuedQueryDeferred.promise):this.doQueuedQueries()}doQueuedQueries(){if(this.downloadInProgress)throw new Error("DeviceListUpdateSerialiser.doQueuedQueries called with request active");const e=Object.keys(this.keyDownloadsQueuedByUser);this.keyDownloadsQueuedByUser={};const t=this.queuedQueryDeferred;this.queuedQueryDeferred=null,s.logger.log("Starting key download for",e),this.downloadInProgress=!0;const n={};this.syncToken&&(n.token=this.syncToken);const r=[];for(let t=0;t<e.length;t+=this.deviceList.keyDownloadChunkSize){const i=e.slice(t,t+this.deviceList.keyDownloadChunkSize);r.push((()=>this.baseApis.downloadKeysForUsers(i,n)))}return(0,d.chunkPromises)(r,3).then((async t=>{const n=Object.assign({},...t.map((e=>e.device_keys||{}))),r=Object.assign({},...t.map((e=>e.master_keys||{}))),i=Object.assign({},...t.map((e=>e.self_signing_keys||{}))),o=Object.assign({},...t.map((e=>e.user_signing_keys||{})));for(const t of e){await(0,d.sleep)(5);try{await this.processQueryResponseForUser(t,n[t],{master:r[t],self_signing:i[t],user_signing:o[t]})}catch(e){s.logger.error(`Error processing keys for ${t}:`,e)}}})).then((()=>{s.logger.log("Completed key download for "+e),this.downloadInProgress=!1,t.resolve(),this.queuedQueryDeferred&&this.doQueuedQueries()}),(n=>{s.logger.warn("Error downloading keys for "+e+":",n),this.downloadInProgress=!1,t.reject(n)})),t.promise}async processQueryResponseForUser(e,t,n){s.logger.log("got device keys for "+e+":",t),s.logger.log("got cross-signing keys for "+e+":",n);{const n={},r=this.deviceList.getRawStoredDevicesForUser(e);r&&Object.keys(r).forEach((e=>{const t=o.DeviceInfo.fromStorage(r[e],e);n[e]=t})),await async function(e,t,n,r,i,o){let a=!1;for(const e in n)if(n.hasOwnProperty(e)&&!(e in r)){if(t===i&&e===o){s.logger.warn(`Local device ${e} missing from sync, skipping removal`);continue}s.logger.log("Device "+t+":"+e+" has been removed"),delete n[e],a=!0}for(const i in r){if(!r.hasOwnProperty(i))continue;const o=r[i];o.user_id===t?o.device_id===i?await y(e,n,o)&&(a=!0):s.logger.warn("Mismatched device_id "+o.device_id+" in keys from "+t+":"+i):s.logger.warn("Mismatched user_id "+o.user_id+" in keys from "+t+":"+i)}return a}(this.olmDevice,e,n,t||{},this.baseApis.getUserId(),this.baseApis.deviceId);const i={};Object.keys(n).forEach((e=>{i[e]=n[e].toStorage()})),this.deviceList.setRawStoredDevicesForUser(e,i)}if(n&&(n.master||n.self_signing||n.user_signing)){const t=this.deviceList.getStoredCrossSigningForUser(e)||new a.CrossSigningInfo(e);t.setKeys(n),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage()),this.deviceList.emit(h.CryptoEvent.UserCrossSigningUpdated,e)}}}async function y(e,t,n){if(!n.keys)return!1;const r=n.device_id,i=n.user_id,a="ed25519:"+r,l=n.keys[a];if(!l)return s.logger.warn("Device "+i+":"+r+" has no ed25519 key"),!1;const d=n.unsigned||{},u=n.signatures||{};try{await c.verifySignature(e,n,i,r,l)}catch(e){return s.logger.warn("Unable to verify signature on device "+i+":"+r+":"+e),!1}let h;if(r in t){if(h=t[r],h.getFingerprint()!=l)return s.logger.warn("Ed25519 key for device "+i+":"+r+" has changed"),!1}else t[r]=h=new o.DeviceInfo(r);return h.keys=n.keys||{},h.algorithms=n.algorithms||[],h.unsigned=d,h.signatures=u,!0}},636:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.EncryptionSetupOperation=t.EncryptionSetupBuilder=void 0;var i=r(n(8416)),s=n(7434),o=n(4369),a=n(3075),c=n(7585),l=n(7715),d=n(8070),u=n(5861);t.EncryptionSetupBuilder=class{constructor(e,t){(0,i.default)(this,"accountDataClientAdapter",void 0),(0,i.default)(this,"crossSigningCallbacks",void 0),(0,i.default)(this,"ssssCryptoCallbacks",void 0),(0,i.default)(this,"crossSigningKeys",null),(0,i.default)(this,"keySignatures",null),(0,i.default)(this,"keyBackupInfo",null),(0,i.default)(this,"sessionBackupPrivateKey",void 0),this.accountDataClientAdapter=new f(e),this.crossSigningCallbacks=new g,this.ssssCryptoCallbacks=new p(t)}addCrossSigningKeys(e,t){this.crossSigningKeys={authUpload:e,keys:t}}addSessionBackup(e){this.keyBackupInfo=e}addSessionBackupPrivateKeyToCache(e){this.sessionBackupPrivateKey=e}addKeySignature(e,t,n){this.keySignatures||(this.keySignatures={});const r=this.keySignatures[e]||{};this.keySignatures[e]=r,r[t]=n}async setAccountData(e,t){await this.accountDataClientAdapter.setAccountData(e,t)}buildOperation(){const e=this.accountDataClientAdapter.values;return new h(e,this.crossSigningKeys,this.keyBackupInfo,this.keySignatures)}async persist(e){if(this.crossSigningKeys){const t=(0,a.createCryptoStoreCacheCallbacks)(e.cryptoStore,e.olmDevice);for(const e of["master","self_signing","user_signing"]){s.logger.log(`Cache ${e} cross-signing private key locally`);const n=this.crossSigningCallbacks.privateKeys.get(e);await t.storeCrossSigningKeyCache(e,n)}await e.cryptoStore.doTxn("readwrite",[c.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{e.cryptoStore.storeCrossSigningKeys(t,this.crossSigningKeys.keys)}))}this.sessionBackupPrivateKey&&await e.storeSessionBackupPrivateKey(this.sessionBackupPrivateKey)}};class h{constructor(e,t,n,r){this.accountData=e,this.crossSigningKeys=t,this.keyBackupInfo=n,this.keySignatures=r}async apply(e){const t=e.baseApis;if(this.crossSigningKeys){const n={};for(const[e,t]of Object.entries(this.crossSigningKeys.keys))n[e+"_key"]=t;await this.crossSigningKeys.authUpload((e=>t.uploadDeviceSigningKeys(e,n))),e.crossSigningInfo.setKeys(this.crossSigningKeys.keys)}if(this.accountData)for(const[e,n]of this.accountData)await t.setAccountData(e,n);this.keySignatures&&await t.uploadKeySignatures(this.keySignatures),this.keyBackupInfo&&(this.keyBackupInfo.version?await t.http.authedRequest(void 0,l.Method.Put,"/room_keys/version/"+this.keyBackupInfo.version,void 0,{algorithm:this.keyBackupInfo.algorithm,auth_data:this.keyBackupInfo.auth_data},{prefix:l.PREFIX_UNSTABLE}):await t.http.authedRequest(void 0,l.Method.Post,"/room_keys/version",void 0,this.keyBackupInfo,{prefix:l.PREFIX_UNSTABLE}))}}t.EncryptionSetupOperation=h;class f extends u.TypedEventEmitter{constructor(e){super(),this.existingValues=e,(0,i.default)(this,"values",new Map)}getAccountDataFromServer(e){return Promise.resolve(this.getAccountData(e))}getAccountData(e){const t=this.values.get(e);if(t)return t;const n=this.existingValues[e];return n?n.getContent():null}setAccountData(e,t){const n=this.values.get(e);return this.values.set(e,t),Promise.resolve().then((()=>{const r=new o.MatrixEvent({type:e,content:t});return this.emit(d.ClientEvent.AccountData,r,n),{}}))}}class g{constructor(){(0,i.default)(this,"privateKeys",new Map)}getCrossSigningKeyCache(e,t){return this.getCrossSigningKey(e,t)}storeCrossSigningKeyCache(e,t){return this.privateKeys.set(e,t),Promise.resolve()}getCrossSigningKey(e,t){return Promise.resolve(this.privateKeys.get(e))}saveCrossSigningKeys(e){for(const[t,n]of Object.entries(e))this.privateKeys.set(t,n)}}class p{constructor(e){this.delegateCryptoCallbacks=e,(0,i.default)(this,"privateKeys",new Map)}async getSecretStorageKey({keys:e},t){var n;for(const t of Object.keys(e)){const e=this.privateKeys.get(t);if(e)return[t,e]}if(null!=this&&null!==(n=this.delegateCryptoCallbacks)&&void 0!==n&&n.getSecretStorageKey){const n=await this.delegateCryptoCallbacks.getSecretStorageKey({keys:e},t);if(n){const[e,t]=n;this.privateKeys.set(e,t)}return n}return null}addPrivateKey(e,t,n){var r,i;this.privateKeys.set(e,n),null===(r=this.delegateCryptoCallbacks)||void 0===r||null===(i=r.cacheSecretStorageKey)||void 0===i||i.call(r,e,t,n)}}},2573:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.WITHHELD_MESSAGES=t.OlmDevice=void 0;var i=r(n(8416)),s=n(7434),o=n(7585),a=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=c(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(1994));function c(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(c=function(e){return e?n:t})(e)}function l(e){if(void 0===e)throw new Error("payloadString undefined");if(e.length>49152){const t=new Error("Message too long ("+e.length+" bytes). The maximum for an encrypted message is 49152 bytes.");throw t.data={errcode:"M_TOO_LARGE",error:"Payload too large for encrypted message"},t}}t.OlmDevice=class{constructor(e){this.cryptoStore=e,(0,i.default)(this,"pickleKey","DEFAULT_KEY"),(0,i.default)(this,"deviceCurve25519Key",null),(0,i.default)(this,"deviceEd25519Key",null),(0,i.default)(this,"maxOneTimeKeys",null),(0,i.default)(this,"outboundGroupSessionStore",{}),(0,i.default)(this,"inboundGroupSessionMessageIndexes",{}),(0,i.default)(this,"sessionsInProgress",{}),(0,i.default)(this,"olmPrekeyPromise",Promise.resolve())}static getOlmVersion(){return n.g.Olm.get_library_version()}async init({pickleKey:e,fromExportedDevice:t}={}){let r;const i=new n.g.Olm.Account;try{t?(e&&s.logger.warn("ignoring opts.pickleKey because opts.fromExportedDevice is present."),this.pickleKey=t.pickleKey,await this.initialiseFromExportedDevice(t,i)):(e&&(this.pickleKey=e),await this.initialiseAccount(i)),r=JSON.parse(i.identity_keys()),this.maxOneTimeKeys=i.max_number_of_one_time_keys()}finally{i.free()}this.deviceCurve25519Key=r.curve25519,this.deviceEd25519Key=r.ed25519}async initialiseFromExportedDevice(e,t){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT,o.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.storeAccount(t,e.pickledAccount),e.sessions.forEach((e=>{const{deviceKey:n,sessionId:r}=e,i={session:e.session,lastReceivedMessageTs:e.lastReceivedMessageTs};this.cryptoStore.storeEndToEndSession(n,r,i,t)}))})),t.unpickle(this.pickleKey,e.pickledAccount)}async initialiseAccount(e){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getAccount(t,(n=>{null!==n?e.unpickle(this.pickleKey,n):(e.create(),n=e.pickle(this.pickleKey),this.cryptoStore.storeAccount(t,n))}))}))}getAccount(e,t){this.cryptoStore.getAccount(e,(e=>{const r=new n.g.Olm.Account;try{r.unpickle(this.pickleKey,e),t(r)}finally{r.free()}}))}storeAccount(e,t){this.cryptoStore.storeAccount(e,t.pickle(this.pickleKey))}async export(){const e={pickleKey:this.pickleKey};return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_ACCOUNT,o.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getAccount(t,(t=>{e.pickledAccount=t})),e.sessions=[],this.cryptoStore.getAllEndToEndSessions(t,(t=>{e.sessions.push(t)}))})),e}getSession(e,t,n,r){this.cryptoStore.getEndToEndSession(e,t,n,(e=>{this.unpickleSession(e,r)}))}unpickleSession(e,t){const r=new n.g.Olm.Session;try{r.unpickle(this.pickleKey,e.session),t(Object.assign({},e,{session:r}))}finally{r.free()}}saveSession(e,t,n){const r=t.session.session_id(),i=Object.assign(t,{session:t.session.pickle(this.pickleKey)});this.cryptoStore.storeEndToEndSession(e,r,i,n)}getUtility(e){const t=new n.g.Olm.Utility;try{return e(t)}finally{t.free()}}async sign(e){let t;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(n=>{this.getAccount(n,(n=>{t=n.sign(e)}))})),t}async getOneTimeKeys(){let e;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(t=>{e=JSON.parse(t.one_time_keys())}))})),e}maxNumberOfOneTimeKeys(){return this.maxOneTimeKeys}async markKeysAsPublished(){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.mark_keys_as_published(),this.storeAccount(e,t)}))}))}generateOneTimeKeys(e){return this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(n=>{n.generate_one_time_keys(e),this.storeAccount(t,n)}))}))}async generateFallbackKey(){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.generate_fallback_key(),this.storeAccount(e,t)}))}))}async getFallbackKey(){let e;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.getAccount(t,(t=>{e=JSON.parse(t.unpublished_fallback_key())}))})),e}async forgetOldFallbackKey(){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.getAccount(e,(t=>{t.forget_old_fallback_key(),this.storeAccount(e,t)}))}))}async createOutboundSession(e,t){let r;return await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT,o.IndexedDBCryptoStore.STORE_SESSIONS],(i=>{this.getAccount(i,(s=>{const o=new n.g.Olm.Session;try{o.create_outbound(s,e,t),r=o.session_id(),this.storeAccount(i,s);const n={session:o,lastReceivedMessageTs:Date.now()};this.saveSession(e,n,i)}finally{o.free()}}))}),s.logger.withPrefix("[createOutboundSession]")),r}async createInboundSession(e,t,r){if(0!==t)throw new Error("Need messageType == 0 to create inbound session");let i;return await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_ACCOUNT,o.IndexedDBCryptoStore.STORE_SESSIONS],(s=>{this.getAccount(s,(o=>{const a=new n.g.Olm.Session;try{a.create_inbound_from(o,e,r),o.remove_one_time_keys(a),this.storeAccount(s,o);const n=a.decrypt(t,r),c={session:a,lastReceivedMessageTs:Date.now()};this.saveSession(e,c,s),i={payload:n,session_id:a.session_id()}}finally{a.free()}}))}),s.logger.withPrefix("[createInboundSession]")),i}async getSessionIdsForDevice(e){const t=s.logger.withPrefix("[getSessionIdsForDevice]");if(this.sessionsInProgress[e]){t.debug(`Waiting for Olm session for ${e} to be created`);try{await this.sessionsInProgress[e]}catch(e){}}let n;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getEndToEndSessions(e,t,(e=>{n=Object.keys(e)}))}),t),n}async getSessionIdForDevice(e,t=!1,n){const r=await this.getSessionInfoForDevice(e,t,n);if(0===r.length)return null;let i=0;for(let e=1;e<r.length;e++){const t=r[e],n=void 0===t.lastReceivedMessageTs?0:t.lastReceivedMessageTs,s=r[i],o=void 0===s.lastReceivedMessageTs?0:s.lastReceivedMessageTs;(n>o||n===o&&t.sessionId<s.sessionId)&&(i=e)}return r[i].sessionId}async getSessionInfoForDevice(e,t=!1,n=s.logger){if(n=n.withPrefix("[getSessionInfoForDevice]"),this.sessionsInProgress[e]&&!t){n.debug(`Waiting for Olm session for ${e} to be created`);try{await this.sessionsInProgress[e]}catch(e){}}const r=[];return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_SESSIONS],(t=>{this.cryptoStore.getEndToEndSessions(e,t,(e=>{const t=Object.keys(e).sort();for(const n of t)this.unpickleSession(e[n],(e=>{r.push({lastReceivedMessageTs:e.lastReceivedMessageTs,hasReceivedMessage:e.session.has_received_message(),sessionId:n})}))}))}),n),r}async encryptMessage(e,t,n){let r;return l(n),await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_SESSIONS],(i=>{this.getSession(e,t,i,(o=>{const a=o.session.describe();s.logger.log("encryptMessage: Olm Session ID "+t+" to "+e+": "+a),r=o.session.encrypt(n),this.saveSession(e,o,i)}))}),s.logger.withPrefix("[encryptMessage]")),r}async decryptMessage(e,t,n,r){let i;return await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_SESSIONS],(o=>{this.getSession(e,t,o,(a=>{const c=a.session.describe();s.logger.log("decryptMessage: Olm Session ID "+t+" from "+e+": "+c),i=a.session.decrypt(n,r),a.lastReceivedMessageTs=Date.now(),this.saveSession(e,a,o)}))}),s.logger.withPrefix("[decryptMessage]")),i}async matchesSession(e,t,n,r){if(0!==n)return!1;let i;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_SESSIONS],(n=>{this.getSession(e,t,n,(e=>{i=e.session.matches_inbound(r)}))}),s.logger.withPrefix("[matchesSession]")),i}async recordSessionProblem(e,t,n){await this.cryptoStore.storeEndToEndSessionProblem(e,t,n)}sessionMayHaveProblems(e,t){return this.cryptoStore.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.cryptoStore.filterOutNotifiedErrorDevices(e)}saveOutboundGroupSession(e){this.outboundGroupSessionStore[e.session_id()]=e.pickle(this.pickleKey)}getOutboundGroupSession(e,t){const r=this.outboundGroupSessionStore[e];if(void 0===r)throw new Error("Unknown outbound group session "+e);const i=new n.g.Olm.OutboundGroupSession;try{return i.unpickle(this.pickleKey,r),t(i)}finally{i.free()}}createOutboundGroupSession(){const e=new n.g.Olm.OutboundGroupSession;try{return e.create(),this.saveOutboundGroupSession(e),e.session_id()}finally{e.free()}}encryptGroupMessage(e,t){return s.logger.log(`encrypting msg with megolm session ${e}`),l(t),this.getOutboundGroupSession(e,(e=>{const n=e.encrypt(t);return this.saveOutboundGroupSession(e),n}))}getOutboundGroupSessionKey(e){return this.getOutboundGroupSession(e,(function(e){return{chain_index:e.message_index(),key:e.session_key()}}))}unpickleInboundGroupSession(e,t){const r=new n.g.Olm.InboundGroupSession;try{return r.unpickle(this.pickleKey,e.session),t(r)}finally{r.free()}}getInboundGroupSession(e,t,n,r,i){this.cryptoStore.getEndToEndInboundGroupSession(t,n,r,((t,n)=>{if(null!==t){if(null!==e&&e!==t.room_id)throw new Error("Mismatched room_id for inbound group session (expected "+t.room_id+", was "+e+")");this.unpickleInboundGroupSession(t,(e=>{i(e,t,n)}))}else i(null,null,n)}))}async addInboundGroupSession(e,t,r,i,a,c,l,d={}){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD,o.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(o=>{this.getInboundGroupSession(e,t,i,o,((u,h)=>{const f=new n.g.Olm.InboundGroupSession;try{if(l?f.import_session(a):f.create(a),i!=f.session_id())throw new Error("Mismatched group session ID from senderKey: "+t);if(u&&(s.logger.log("Update for megolm session "+t+"/"+i),u.first_known_index()<=f.first_known_index()&&(u.first_known_index()!=f.first_known_index()||d.untrusted||!h.untrusted)))return void s.logger.log(`Keeping existing megolm session ${i}`);s.logger.info("Storing megolm session "+t+"/"+i+" with first index "+f.first_known_index());const n=Object.assign({},d,{room_id:e,session:f.pickle(this.pickleKey),keysClaimed:c,forwardingCurve25519KeyChain:r});this.cryptoStore.storeEndToEndInboundGroupSession(t,i,n,o),!u&&d.sharedHistory&&this.cryptoStore.addSharedHistoryInboundGroupSession(e,t,i,o)}finally{f.free()}}))}),s.logger.withPrefix("[addInboundGroupSession]"))}async addInboundGroupSessionWithheld(e,t,n,r,i){await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(s=>{this.cryptoStore.storeEndToEndInboundGroupSessionWithheld(t,n,{room_id:e,code:r,reason:i},s)}))}async decryptGroupMessage(e,t,n,r,i,c){let l,d;if(await this.cryptoStore.doTxn("readwrite",[o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(s=>{this.getInboundGroupSession(e,t,n,s,((e,o,h)=>{if(null===e)return h&&(d=new a.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",u(h),{session:t+"|"+n})),void(l=null);let f;try{f=e.decrypt(r)}catch(e){return void(d=e&&"OLM.UNKNOWN_MESSAGE_INDEX"===e.message&&h?new a.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",u(h),{session:t+"|"+n}):e)}let g=f.plaintext;if(void 0===g)g=f;else{const e=t+"|"+n+"|"+f.message_index;if(e in this.inboundGroupSessionMessageIndexes){const t=this.inboundGroupSessionMessageIndexes[e];if(t.id!==i||t.timestamp!==c)return void(d=new Error("Duplicate message index, possible replay attack: "+e))}this.inboundGroupSessionMessageIndexes[e]={id:i,timestamp:c}}o.session=e.pickle(this.pickleKey),this.cryptoStore.storeEndToEndInboundGroupSession(t,n,o,s),l={result:g,keysClaimed:o.keysClaimed||{},senderKey:t,forwardingCurve25519KeyChain:o.forwardingCurve25519KeyChain||[],untrusted:o.untrusted}}))}),s.logger.withPrefix("[decryptGroupMessage]")),d)throw d;return l}async hasInboundSessionKeys(e,t,n){let r;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(i=>{this.cryptoStore.getEndToEndInboundGroupSession(t,n,i,(i=>{null!==i?e!==i.room_id?(s.logger.warn(`requested keys for inbound group session ${t}|${n}, with incorrect room_id (expected ${i.room_id}, was ${e})`),r=!1):r=!0:r=!1}))}),s.logger.withPrefix("[hasInboundSessionKeys]")),r}async getInboundGroupSessionKey(e,t,n,r){let i;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,o.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(s=>{this.getInboundGroupSession(e,t,n,s,((e,t)=>{if(null===e)return void(i=null);void 0===r&&(r=e.first_known_index());const n=e.export_session(r),s=(t.keysClaimed||{}).ed25519||null;i={chain_index:r,key:n,forwarding_curve25519_key_chain:t.forwardingCurve25519KeyChain||[],sender_claimed_ed25519_key:s,shared_history:t.sharedHistory||!1}}))}),s.logger.withPrefix("[getInboundGroupSessionKey]")),i}exportInboundGroupSession(e,t,n){return this.unpickleInboundGroupSession(n,(r=>{const i=r.first_known_index();return{sender_key:e,sender_claimed_keys:n.keysClaimed,room_id:n.room_id,session_id:t,session_key:r.export_session(i),forwarding_curve25519_key_chain:n.forwardingCurve25519KeyChain||[],first_known_index:r.first_known_index(),"org.matrix.msc3061.shared_history":n.sharedHistory||!1}}))}async getSharedHistoryInboundGroupSessions(e){let t;return await this.cryptoStore.doTxn("readonly",[o.IndexedDBCryptoStore.STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS],(n=>{t=this.cryptoStore.getSharedHistoryInboundGroupSessions(e,n)}),s.logger.withPrefix("[getSharedHistoryInboundGroupSessionsForRoom]")),t}verifySignature(e,t,n){this.getUtility((function(r){r.ed25519_verify(e,t,n)}))}};const d={"m.unverified":"The sender has disabled encrypting to unverified devices.","m.blacklisted":"The sender has blocked you.","m.unauthorised":"You are not authorised to read the message.","m.no_olm":"Unable to establish a secure channel."};function u(e){return e.code&&e.code in d?d[e.code]:e.reason?e.reason:"decryption key withheld"}t.WITHHELD_MESSAGES=d},6617:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RoomKeyRequestState=t.OutgoingRoomKeyRequestManager=void 0;var i=r(n(8416)),s=n(7434),o=n(2481);let a;function c(e){return e.room_id+" / "+e.session_id}function l(e){return"["+e.map((e=>`${e.userId}:${e.deviceId}`)).join(",")+"]"}t.RoomKeyRequestState=a,function(e){e[e.Unsent=0]="Unsent",e[e.Sent=1]="Sent",e[e.CancellationPending=2]="CancellationPending",e[e.CancellationPendingAndWillResend=3]="CancellationPendingAndWillResend"}(a||(t.RoomKeyRequestState=a={})),t.OutgoingRoomKeyRequestManager=class{constructor(e,t,n){this.baseApis=e,this.deviceId=t,this.cryptoStore=n,(0,i.default)(this,"sendOutgoingRoomKeyRequestsTimer",null),(0,i.default)(this,"sendOutgoingRoomKeyRequestsRunning",!1),(0,i.default)(this,"clientRunning",!1)}start(){this.clientRunning=!0}stop(){s.logger.log("stopping OutgoingRoomKeyRequestManager"),this.clientRunning=!1}sendQueuedRequests(){this.startTimer()}async queueRoomKeyRequest(e,t,n=!1){const r=await this.cryptoStore.getOutgoingRoomKeyRequest(e);if(r)switch(r.state){case a.CancellationPendingAndWillResend:case a.Unsent:return;case a.CancellationPending:{const e=n?a.CancellationPendingAndWillResend:a.Sent;await this.cryptoStore.updateOutgoingRoomKeyRequest(r.requestId,a.CancellationPending,{state:e,cancellationTxnId:this.baseApis.makeTxnId()});break}case a.Sent:if(n){const i=a.CancellationPendingAndWillResend,o=await this.cryptoStore.updateOutgoingRoomKeyRequest(r.requestId,a.Sent,{state:i,cancellationTxnId:this.baseApis.makeTxnId(),requestTxnId:this.baseApis.makeTxnId()});if(!o)return this.queueRoomKeyRequest(e,t,n);try{await this.sendOutgoingRoomKeyRequestCancellation(o,!0)}catch(e){s.logger.error("Error sending room key request cancellation; will retry later.",e)}}break;default:throw new Error("unhandled state: "+r.state)}else await this.cryptoStore.getOrAddOutgoingRoomKeyRequest({requestBody:e,recipients:t,requestId:this.baseApis.makeTxnId(),state:a.Unsent})}cancelRoomKeyRequest(e){return this.cryptoStore.getOutgoingRoomKeyRequest(e).then((t=>{if(t)switch(t.state){case a.CancellationPending:case a.CancellationPendingAndWillResend:return;case a.Unsent:return s.logger.log("deleting unnecessary room key request for "+c(e)),this.cryptoStore.deleteOutgoingRoomKeyRequest(t.requestId,a.Unsent);case a.Sent:return this.cryptoStore.updateOutgoingRoomKeyRequest(t.requestId,a.Sent,{state:a.CancellationPending,cancellationTxnId:this.baseApis.makeTxnId()}).then((t=>{t?this.sendOutgoingRoomKeyRequestCancellation(t).catch((e=>{s.logger.error("Error sending room key request cancellation; will retry later.",e),this.startTimer()})):s.logger.log("Tried to cancel room key request for "+c(e)+" but it was already cancelled in another tab")}));default:throw new Error("unhandled state: "+t.state)}}))}getOutgoingSentRoomKeyRequest(e,t){return this.cryptoStore.getOutgoingRoomKeyRequestsByTarget(e,t,[a.Sent])}async cancelAndResendAllOutgoingRequests(){const e=await this.cryptoStore.getAllOutgoingRoomKeyRequestsByState(a.Sent);return Promise.all(e.map((({requestBody:e,recipients:t})=>this.queueRoomKeyRequest(e,t,!0))))}startTimer(){this.sendOutgoingRoomKeyRequestsTimer||(this.sendOutgoingRoomKeyRequestsTimer=setTimeout((()=>{if(this.sendOutgoingRoomKeyRequestsRunning)throw new Error("RoomKeyRequestSend already in progress!");this.sendOutgoingRoomKeyRequestsRunning=!0,this.sendOutgoingRoomKeyRequests().finally((()=>{this.sendOutgoingRoomKeyRequestsRunning=!1})).catch((e=>{s.logger.warn(`error in OutgoingRoomKeyRequestManager: ${e}`)}))}),500))}sendOutgoingRoomKeyRequests(){return this.clientRunning?this.cryptoStore.getOutgoingRoomKeyRequestByState([a.CancellationPending,a.CancellationPendingAndWillResend,a.Unsent]).then((e=>{if(!e)return void(this.sendOutgoingRoomKeyRequestsTimer=null);let t;switch(e.state){case a.Unsent:t=this.sendOutgoingRoomKeyRequest(e);break;case a.CancellationPending:t=this.sendOutgoingRoomKeyRequestCancellation(e);break;case a.CancellationPendingAndWillResend:t=this.sendOutgoingRoomKeyRequestCancellation(e,!0)}return t.then((()=>this.sendOutgoingRoomKeyRequests())).catch((e=>{s.logger.error("Error sending room key request; will retry later.",e),this.sendOutgoingRoomKeyRequestsTimer=null}))})):(this.sendOutgoingRoomKeyRequestsTimer=null,Promise.resolve())}sendOutgoingRoomKeyRequest(e){s.logger.log(`Requesting keys for ${c(e.requestBody)} from ${l(e.recipients)}(id ${e.requestId})`);const t={action:"request",requesting_device_id:this.deviceId,request_id:e.requestId,body:e.requestBody};return this.sendMessageToDevices(t,e.recipients,e.requestTxnId||e.requestId).then((()=>this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,a.Unsent,{state:a.Sent})))}sendOutgoingRoomKeyRequestCancellation(e,t=!1){s.logger.log(`Sending cancellation for key request for ${c(e.requestBody)} to ${l(e.recipients)} (cancellation id ${e.cancellationTxnId})`);const n={action:"request_cancellation",requesting_device_id:this.deviceId,request_id:e.requestId};return this.sendMessageToDevices(n,e.recipients,e.cancellationTxnId).then((()=>t?this.cryptoStore.updateOutgoingRoomKeyRequest(e.requestId,a.CancellationPendingAndWillResend,{state:a.Unsent}):this.cryptoStore.deleteOutgoingRoomKeyRequest(e.requestId,a.CancellationPending)))}sendMessageToDevices(e,t,n){const r={};for(const n of t)r[n.userId]||(r[n.userId]={}),r[n.userId][n.deviceId]=e;return this.baseApis.sendToDevice(o.EventType.RoomKeyRequest,r,n)}}},635:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RoomList=void 0;var i=r(n(8416)),s=n(7585);t.RoomList=class{constructor(e){this.cryptoStore=e,(0,i.default)(this,"roomEncryption",{})}async init(){await this.cryptoStore.doTxn("readwrite",[s.IndexedDBCryptoStore.STORE_ROOMS],(e=>{this.cryptoStore.getEndToEndRooms(e,(e=>{this.roomEncryption=e}))}))}getRoomEncryption(e){return this.roomEncryption[e]||null}isRoomEncrypted(e){return Boolean(this.getRoomEncryption(e))}async setRoomEncryption(e,t){this.roomEncryption[e]=t,await this.cryptoStore.doTxn("readwrite",[s.IndexedDBCryptoStore.STORE_ROOMS],(n=>{this.cryptoStore.storeEndToEndRoom(e,t,n)}))}}},4823:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SecretStorage=t.SECRET_STORAGE_ALGORITHM_V1_AES=void 0;var i=r(n(8416)),s=n(7434),o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=d(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(2772)),a=n(8401),c=n(2611),l=n(8070);function d(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(d=function(e){return e?n:t})(e)}const u="m.secret_storage.v1.aes-hmac-sha2";t.SECRET_STORAGE_ALGORITHM_V1_AES=u,t.SecretStorage=class{constructor(e,t,n){this.accountDataAdapter=e,this.cryptoCallbacks=t,this.baseApis=n,(0,i.default)(this,"requests",new Map)}async getDefaultKeyId(){const e=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.default_key");return e?e.key:null}setDefaultKeyId(e){return new Promise(((t,n)=>{const r=n=>{"m.secret_storage.default_key"===n.getType()&&n.getContent().key===e&&(this.accountDataAdapter.removeListener(l.ClientEvent.AccountData,r),t())};this.accountDataAdapter.on(l.ClientEvent.AccountData,r),this.accountDataAdapter.setAccountData("m.secret_storage.default_key",{key:e}).catch((e=>{this.accountDataAdapter.removeListener(l.ClientEvent.AccountData,r),n(e)}))}))}async addKey(e,t,n){const r={algorithm:e};if(t||(t={}),t.name&&(r.name=t.name),e!==u)throw new Error(`Unknown key algorithm ${e}`);if(t.passphrase&&(r.passphrase=t.passphrase),t.key){const{iv:e,mac:n}=await(0,c.calculateKeyCheck)(t.key);r.iv=e,r.mac=n}if(!n)do{n=(0,a.randomString)(32)}while(await this.accountDataAdapter.getAccountDataFromServer(`m.secret_storage.key.${n}`));return await this.accountDataAdapter.setAccountData(`m.secret_storage.key.${n}`,r),{keyId:n,keyInfo:r}}async getKey(e){if(e||(e=await this.getDefaultKeyId()),!e)return null;const t=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);return t?[e,t]:null}async hasKey(e){return Boolean(await this.getKey(e))}async checkKey(e,t){if(t.algorithm===u){if(t.mac){const{mac:n}=await(0,c.calculateKeyCheck)(e,t.iv);return t.mac.replace(/=+$/g,"")===n.replace(/=+$/g,"")}return!0}throw new Error("Unknown algorithm")}async store(e,t,n){const r={};if(!n){const e=await this.getDefaultKeyId();if(!e)throw new Error("No keys specified and no default key present");n=[e]}if(0===n.length)throw new Error("Zero keys given to encrypt with!");for(const i of n){const n=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+i);if(!n)throw new Error("Unknown key: "+i);if(n.algorithm===u){const s={[i]:n},[,o]=await this.getSecretStorageKey(s,e);r[i]=await o.encrypt(t)}else s.logger.warn("unknown algorithm for secret storage key "+i+": "+n.algorithm)}await this.accountDataAdapter.setAccountData(e,{encrypted:r})}async get(e){const t=await this.accountDataAdapter.getAccountDataFromServer(e);if(!t)return;if(!t.encrypted)throw new Error("Content is not encrypted!");const n={};for(const e of Object.keys(t.encrypted)){const r=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e),i=t.encrypted[e];r.algorithm===u&&i.iv&&i.ciphertext&&i.mac&&(n[e]=r)}if(0===Object.keys(n).length)throw new Error(`Could not decrypt ${e} because none of the keys it is encrypted with are for a supported algorithm`);let r,i;try{[r,i]=await this.getSecretStorageKey(n,e);const s=t.encrypted[r];return s.passthrough?(0,o.encodeBase64)(i.get_private_key()):i.decrypt(s)}finally{i&&i.free&&i.free()}}async isStored(e){const t=await this.accountDataAdapter.getAccountDataFromServer(e);if(null==t||!t.encrypted)return null;const n={};for(const e of Object.keys(t.encrypted)){const r=await this.accountDataAdapter.getAccountDataFromServer("m.secret_storage.key."+e);if(!r)continue;const i=t.encrypted[e];r.algorithm===u&&i.iv&&i.ciphertext&&i.mac&&(n[e]=r)}return Object.keys(n).length?n:null}request(e,t){const n=this.baseApis.makeTxnId();let r,i;const o=new Promise(((e,t)=>{r=e,i=t}));this.requests.set(n,{name:e,devices:t,resolve:r,reject:i});const a={name:e,action:"request",requesting_device_id:this.baseApis.deviceId,request_id:n},c={};for(const e of t)c[e]=a;return s.logger.info(`Request secret ${e} from ${t}, id ${n}`),this.baseApis.sendToDevice("m.secret.request",{[this.baseApis.getUserId()]:c}),{requestId:n,promise:o,cancel:e=>{const r={action:"request_cancellation",requesting_device_id:this.baseApis.deviceId,request_id:n},s={};for(const e of t)s[e]=r;this.baseApis.sendToDevice("m.secret.request",{[this.baseApis.getUserId()]:s}),i(new Error(e||"Cancelled"))}}}async onRequestReceived(e){const t=e.getSender(),n=e.getContent();if(t!==this.baseApis.getUserId()||!(n.name&&n.action&&n.requesting_device_id&&n.request_id))return;const r=n.requesting_device_id;if("request_cancellation"===n.action);else if("request"===n.action){if(r===this.baseApis.deviceId)return;if(s.logger.info("received request for secret ("+t+", "+r+", "+n.request_id+")"),!this.cryptoCallbacks.onSecretRequested)return;const e=await this.cryptoCallbacks.onSecretRequested(t,r,n.request_id,n.name,this.baseApis.checkDeviceTrust(t,r));if(e){s.logger.info(`Preparing ${n.name} secret for ${r}`);const i={type:"m.secret.send",content:{request_id:n.request_id,secret:e}},a={algorithm:o.OLM_ALGORITHM,sender_key:this.baseApis.crypto.olmDevice.deviceCurve25519Key,ciphertext:{}};await o.ensureOlmSessionsForDevices(this.baseApis.crypto.olmDevice,this.baseApis,{[t]:[this.baseApis.getStoredDevice(t,r)]}),await o.encryptMessageForDevice(a.ciphertext,this.baseApis.getUserId(),this.baseApis.deviceId,this.baseApis.crypto.olmDevice,t,this.baseApis.getStoredDevice(t,r),i);const c={[t]:{[r]:a}};s.logger.info(`Sending ${n.name} secret for ${r}`),this.baseApis.sendToDevice("m.room.encrypted",c)}else s.logger.info(`Request denied for ${n.name} secret for ${r}`)}}onSecretReceived(e){if(e.getSender()!==this.baseApis.getUserId())return;const t=e.getContent();s.logger.log("got secret share for request",t.request_id);const n=this.requests.get(t.request_id);if(n){const r=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(o.OLM_ALGORITHM,e.getSenderKey());if(!r)return void s.logger.log("secret share from unknown device with key",e.getSenderKey());if(!n.devices.includes(r.deviceId))return void s.logger.log("unsolicited secret share from device",r.deviceId);s.logger.log(`Successfully received secret ${n.name} from ${r.deviceId}`),n.resolve(t.secret)}}async getSecretStorageKey(e,t){if(!this.cryptoCallbacks.getSecretStorageKey)throw new Error("No getSecretStorageKey callback supplied");const n=await this.cryptoCallbacks.getSecretStorageKey({keys:e},t);if(!n)throw new Error("getSecretStorageKey callback returned falsey");if(n.length<2)throw new Error("getSecretStorageKey callback returned invalid data");const[r,i]=n;if(!e[r])throw new Error("App returned unknown key from getSecretStorageKey!");if(e[r].algorithm===u)return[r,{encrypt:function(e){return(0,c.encryptAES)(e,i,t)},decrypt:function(e){return(0,c.decryptAES)(e,i,t)}}];throw new Error("Unknown key type: "+e[r].algorithm)}}},2611:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.calculateKeyCheck=function(e,t){return l(d,e,"",t)},t.decryptAES=function(e,t,n){return s?async function(e,t,n){const[r,o]=await c(t,n),a=(0,i.decodeBase64)(e.ciphertext);if(!await s.verify({name:"HMAC"},o,(0,i.decodeBase64)(e.mac),a))throw new Error(`Error decrypting secret ${n}: bad MAC`);const l=await s.decrypt({name:"AES-CTR",counter:(0,i.decodeBase64)(e.iv),length:64},r,a);return(new TextDecoder).decode(new Uint8Array(l))}(e,t,n):async function(e,t,n){const s=(0,r.getCrypto)();if(!s)throw new Error("No usable crypto implementation");const[o,c]=a(t,n);if(s.createHmac("sha256",c).update(Buffer.from(e.ciphertext,"base64")).digest("base64").replace(/=+$/g,"")!==e.mac.replace(/=+$/g,""))throw new Error(`Error decrypting secret ${n}: bad MAC`);const l=s.createDecipheriv("aes-256-ctr",o,(0,i.decodeBase64)(e.iv));return l.update(e.ciphertext,"base64","utf8")+l.final("utf8")}(e,t,n)},t.encryptAES=l;var r=n(3102),i=n(2772);const s="undefined"!=typeof window&&window.crypto?window.crypto.subtle||window.crypto.webkitSubtle:null,o=new Uint8Array(8);function a(e,t){const n=(0,r.getCrypto)(),i=n.createHmac("sha256",o).update(e).digest(),s=Buffer.alloc(1,1),a=n.createHmac("sha256",i).update(t,"utf8").update(s).digest();return s[0]=2,[a,n.createHmac("sha256",i).update(a).update(t,"utf8").update(s).digest()]}async function c(e,t){const n=await s.importKey("raw",e,{name:"HKDF"},!1,["deriveBits"]),r=await s.deriveBits({name:"HKDF",salt:o,info:(new TextEncoder).encode(t),hash:"SHA-256"},n,512),i=r.slice(0,32),a=r.slice(32),c=s.importKey("raw",i,{name:"AES-CTR"},!1,["encrypt","decrypt"]),l=s.importKey("raw",a,{name:"HMAC",hash:{name:"SHA-256"}},!1,["sign","verify"]);return Promise.all([c,l])}function l(e,t,n,o){return s?async function(e,t,n,r){let o;r?o=(0,i.decodeBase64)(r):(o=new Uint8Array(16),window.crypto.getRandomValues(o),o[8]&=127);const[a,l]=await c(t,n),d=(new TextEncoder).encode(e),u=await s.encrypt({name:"AES-CTR",counter:o,length:64},a,d),h=await s.sign({name:"HMAC"},l,u);return{iv:(0,i.encodeBase64)(o),ciphertext:(0,i.encodeBase64)(u),mac:(0,i.encodeBase64)(h)}}(e,t,n,o):async function(e,t,n,s){const o=(0,r.getCrypto)();if(!o)throw new Error("No usable crypto implementation");let c;s?c=(0,i.decodeBase64)(s):(c=o.randomBytes(16),c[8]&=127);const[l,d]=a(t,n),u=o.createCipheriv("aes-256-ctr",l,c),h=Buffer.concat([u.update(e,"utf8"),u.final()]),f=o.createHmac("sha256",d).update(h).digest("base64");return{iv:(0,i.encodeBase64)(c),ciphertext:h.toString("base64"),mac:f}}(e,t,n,o)}const d="\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"},1897:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.UnknownDeviceError=t.EncryptionAlgorithm=t.ENCRYPTION_CLASSES=t.DecryptionError=t.DecryptionAlgorithm=t.DECRYPTION_CLASSES=void 0,t.registerAlgorithm=function(e,t,n){s.set(e,t),o.set(e,n)};var i=r(n(8416));const s=new Map;t.ENCRYPTION_CLASSES=s;const o=new Map;t.DECRYPTION_CLASSES=o,t.EncryptionAlgorithm=class{constructor(e){(0,i.default)(this,"userId",void 0),(0,i.default)(this,"deviceId",void 0),(0,i.default)(this,"crypto",void 0),(0,i.default)(this,"olmDevice",void 0),(0,i.default)(this,"baseApis",void 0),(0,i.default)(this,"roomId",void 0),this.userId=e.userId,this.deviceId=e.deviceId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis,this.roomId=e.roomId}prepareToEncrypt(e){}onRoomMembership(e,t,n){}},t.DecryptionAlgorithm=class{constructor(e){(0,i.default)(this,"userId",void 0),(0,i.default)(this,"crypto",void 0),(0,i.default)(this,"olmDevice",void 0),(0,i.default)(this,"baseApis",void 0),(0,i.default)(this,"roomId",void 0),this.userId=e.userId,this.crypto=e.crypto,this.olmDevice=e.olmDevice,this.baseApis=e.baseApis,this.roomId=e.roomId}async onRoomKeyEvent(e){}async importRoomKey(e,t){}hasKeysForKeyRequest(e){return Promise.resolve(!1)}shareKeysWithDevice(e){throw new Error("shareKeysWithDevice not supported for this DecryptionAlgorithm")}async retryDecryptionFromSender(e){return!1}};class a extends Error{constructor(e,t,n){super(t),this.code=e,(0,i.default)(this,"detailedString",void 0),this.code=e,this.name="DecryptionError",this.detailedString=function(e,t){let n=e.name+"[msg: "+e.message;return t&&(n+=", "+Object.keys(t).map((e=>e+": "+t[e])).join(", ")),n+="]",n}(this,n)}}t.DecryptionError=a;class c extends Error{constructor(e,t){super(e),this.devices=t,this.name="UnknownDeviceError",this.devices=t}}t.UnknownDeviceError=c},1994:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),n(3072),n(7125);var r=n(1897);Object.keys(r).forEach((function(e){"default"!==e&&"__esModule"!==e&&(e in t&&t[e]===r[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return r[e]}}))}))},7125:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.isRoomSharedHistory=d;var i=r(n(8416)),s=n(7434),o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=l(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(2772)),a=n(1897),c=n(2573);function l(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(l=function(e){return e?n:t})(e)}function d(e){var t,n;const r=null==e||null===(t=e.currentState)||void 0===t?void 0:t.getStateEvents("m.room.history_visibility",""),i=null==r||null===(n=r.getContent())||void 0===n?void 0:n.history_visibility;return["world_readable","shared"].includes(i)}class u{constructor(e,t=!1){this.sessionId=e,this.sharedHistory=t,(0,i.default)(this,"useCount",0),(0,i.default)(this,"creationTime",void 0),(0,i.default)(this,"sharedWithDevices",{}),(0,i.default)(this,"blockedDevicesNotified",{}),this.creationTime=(new Date).getTime()}needsRotation(e,t){const n=(new Date).getTime()-this.creationTime;return(this.useCount>=e||n>=t)&&(s.logger.log("Rotating megolm session after "+this.useCount+" messages, "+n+"ms"),!0)}markSharedWithDevice(e,t,n,r){this.sharedWithDevices[e]||(this.sharedWithDevices[e]={}),this.sharedWithDevices[e][t]={deviceKey:n,messageIndex:r}}markNotifiedBlockedDevice(e,t){this.blockedDevicesNotified[e]||(this.blockedDevicesNotified[e]={}),this.blockedDevicesNotified[e][t]=!0}sharedWithTooManyDevices(e){for(const t in this.sharedWithDevices)if(this.sharedWithDevices.hasOwnProperty(t)){if(!e.hasOwnProperty(t))return s.logger.log("Starting new megolm session because we shared with "+t),!0;for(const n in this.sharedWithDevices[t])if(this.sharedWithDevices[t].hasOwnProperty(n)&&!e[t].hasOwnProperty(n))return s.logger.log("Starting new megolm session because we shared with "+t+":"+n),!0}return!1}}class h extends a.EncryptionAlgorithm{constructor(e){var t,n,r,s;super(e),(0,i.default)(this,"setupPromise",Promise.resolve(null)),(0,i.default)(this,"outboundSessions",{}),(0,i.default)(this,"sessionRotationPeriodMsgs",void 0),(0,i.default)(this,"sessionRotationPeriodMs",void 0),(0,i.default)(this,"encryptionPreparation",void 0),this.sessionRotationPeriodMsgs=null!==(t=null===(n=e.config)||void 0===n?void 0:n.rotation_period_msgs)&&void 0!==t?t:100,this.sessionRotationPeriodMs=null!==(r=null===(s=e.config)||void 0===s?void 0:s.rotation_period_ms)&&void 0!==r?r:6048e5}async ensureOutboundSession(e,t,n,r=!1){const i=this.setupPromise.then((async i=>{const o=d(e),a=await this.prepareSession(t,o,i);try{await this.shareSession(t,o,r,n,a)}catch(e){s.logger.error(`Failed to ensure outbound session in ${this.roomId}`,e)}return a}));return i.catch((e=>{s.logger.error(`Failed to setup outbound session in ${this.roomId}`,e)})),this.setupPromise=i,i}async prepareSession(e,t,n){var r,i;return n&&t!==n.sharedHistory&&(n=null),null!==(r=n)&&void 0!==r&&r.needsRotation(this.sessionRotationPeriodMsgs,this.sessionRotationPeriodMs)&&(s.logger.log("Starting new megolm session because we need to rotate."),n=null),null!==(i=n)&&void 0!==i&&i.sharedWithTooManyDevices(e)&&(n=null),n||(s.logger.log(`Starting new megolm session for room ${this.roomId}`),n=await this.prepareNewSession(t),s.logger.log(`Started new megolm session ${n.sessionId} for room ${this.roomId}`),this.outboundSessions[n.sessionId]=n),n}async shareSession(e,t,n,r,i){const a={};for(const[t,n]of Object.entries(e))for(const[e,r]of Object.entries(n))r.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&(i.sharedWithDevices[t]&&void 0!==i.sharedWithDevices[t][e]||(a[t]=a[t]||[],a[t].push(r)));const c=this.olmDevice.getOutboundGroupSessionKey(i.sessionId),l={type:"m.room_key",content:{algorithm:o.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:i.sessionId,session_key:c.key,chain_index:c.chain_index,"org.matrix.msc3061.shared_history":t}},[d,u]=await o.getExistingOlmSessions(this.olmDevice,this.baseApis,a);await Promise.all([(async()=>{s.logger.debug(`Sharing keys with existing Olm sessions in ${this.roomId}`,u),await this.shareKeyWithOlmSessions(i,c,l,u),s.logger.debug(`Shared keys with existing Olm sessions in ${this.roomId}`)})(),(async()=>{s.logger.debug(`Sharing keys (start phase 1) with new Olm sessions in ${this.roomId}`,d);const e=[],t=Date.now(),r=[];await this.shareKeyWithDevices(i,c,l,d,e,n?1e4:2e3,r),s.logger.debug(`Shared keys (end phase 1) with new Olm sessions in ${this.roomId}`),!n&&Date.now()-t<1e4?(async()=>{const t={},n=new Set;for(const e of r)n.add(e);const o=[];for(const{userId:r,deviceInfo:i}of e){const e=r.slice(r.indexOf(":")+1);n.has(e)?(t[r]=t[r]||[],t[r].push(i)):o.push({userId:r,deviceInfo:i})}s.logger.debug(`Sharing keys (start phase 2) with new Olm sessions in ${this.roomId}`),await this.shareKeyWithDevices(i,c,l,t,o,3e4),s.logger.debug(`Shared keys (end phase 2) with new Olm sessions in ${this.roomId}`),await this.notifyFailedOlmDevices(i,c,o)})():await this.notifyFailedOlmDevices(i,c,e),s.logger.debug(`Shared keys (all phases done) with new Olm sessions in ${this.roomId}`)})(),(async()=>{s.logger.debug(`There are ${Object.entries(r).length} blocked devices in ${this.roomId}`,Object.entries(r)),s.logger.debug(`Notifying newly blocked devices in ${this.roomId}`);const e={};let t=0;for(const[n,s]of Object.entries(r))for(const[r,o]of Object.entries(s))i.blockedDevicesNotified[n]&&void 0!==i.blockedDevicesNotified[n][r]||(e[n]=e[n]||{},e[n][r]={device:o},t++);await this.notifyBlockedDevices(i,e),s.logger.debug(`Notified ${t} newly blocked devices in ${this.roomId}`,e)})()])}async prepareNewSession(e){const t=this.olmDevice.createOutboundGroupSession(),n=this.olmDevice.getOutboundGroupSessionKey(t);return await this.olmDevice.addInboundGroupSession(this.roomId,this.olmDevice.deviceCurve25519Key,[],t,n.key,{ed25519:this.olmDevice.deviceEd25519Key},!1,{sharedHistory:e}),this.crypto.backupManager.backupGroupSession(this.olmDevice.deviceCurve25519Key,t),new u(t,e)}getDevicesWithoutSessions(e,t,n=[]){for(const[r,i]of Object.entries(t)){const t=e[r];for(const e of i){const i=e.deviceId;t[i].sessionId||(n.push({userId:r,deviceInfo:e}),delete t[i])}}return n}splitDevices(e){let t=[];const n=[t];for(const[r,i]of Object.entries(e)){for(const e of Object.values(i))t.push({userId:r,deviceInfo:e.device});t.length>20&&(t=[],n.push(t))}return 0===t.length&&n.pop(),n}encryptAndSendKeysToDevices(e,t,n,r){return this.crypto.encryptAndSendToDevices(n,r).then((()=>{for(const r of n)e.markSharedWithDevice(r.userId,r.deviceInfo.deviceId,r.deviceInfo.getIdentityKey(),t)})).catch((e=>{throw s.logger.error("failed to encryptAndSendToDevices",e),e}))}async sendBlockedNotificationsToDevices(e,t,n){const r={};for(const e of t){const t=e.userId,i=e.deviceInfo,s=i.deviceInfo.deviceId,o=Object.assign({},n);o.code=i.code,o.reason=i.reason,"m.no_olm"===o.code&&(delete o.room_id,delete o.session_id),r[t]||(r[t]={}),r[t][s]=o}await this.baseApis.sendToDevice("m.room_key.withheld",r);for(const t of Object.keys(r))for(const n of Object.keys(r[t]))e.markNotifiedBlockedDevice(t,n)}async reshareKeyWithDevice(e,t,n,r){const i=this.outboundSessions[t];if(!i)return void s.logger.debug(`megolm session ${t} not found: not re-sharing keys`);if(void 0===i.sharedWithDevices[n])return void s.logger.debug(`megolm session ${t} never shared with user ${n}`);const a=i.sharedWithDevices[n][r.deviceId];if(void 0===a)return void s.logger.debug("megolm session ID "+t+" never shared with device "+n+":"+r.deviceId);if(a.deviceKey!==r.getIdentityKey())return void s.logger.warn(`Session has been shared with device ${r.deviceId} but with identity key ${a.deviceKey}. Key is now ${r.getIdentityKey()}!`);const c=await this.olmDevice.getInboundGroupSessionKey(this.roomId,e,t,a.messageIndex);if(!c)return void s.logger.warn(`No inbound session key found for megolm ${t}: not re-sharing keys`);await o.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[n]:[r]});const l={type:"m.forwarded_room_key",content:{algorithm:o.MEGOLM_ALGORITHM,room_id:this.roomId,session_id:t,session_key:c.key,chain_index:c.chain_index,sender_key:e,sender_claimed_ed25519_key:c.sender_claimed_ed25519_key,forwarding_curve25519_key_chain:c.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":c.shared_history||!1}},d={algorithm:o.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};await o.encryptMessageForDevice(d.ciphertext,this.userId,this.deviceId,this.olmDevice,n,r,l),await this.baseApis.sendToDevice("m.room.encrypted",{[n]:{[r.deviceId]:d}}),s.logger.debug(`Re-shared key for megolm session ${t} with ${n}:${r.deviceId}`)}async shareKeyWithDevices(e,t,n,r,i,a,c){var l;s.logger.debug(`Ensuring Olm sessions for devices in ${this.roomId}`);const d=await o.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,r,!1,a,c,null===(l=s.logger.withPrefix)||void 0===l?void 0:l.call(s.logger,`[${this.roomId}]`));s.logger.debug(`Ensured Olm sessions for devices in ${this.roomId}`),this.getDevicesWithoutSessions(d,r,i),s.logger.debug(`Sharing keys with newly created Olm sessions in ${this.roomId}`),await this.shareKeyWithOlmSessions(e,t,n,d),s.logger.debug(`Shared keys with newly created Olm sessions in ${this.roomId}`)}async shareKeyWithOlmSessions(e,t,n,r){const i=this.splitDevices(r);for(let r=0;r<i.length;r++){const o=`megolm keys for ${e.sessionId} in ${this.roomId} (slice ${r+1}/${i.length})`;try{s.logger.debug(`Sharing ${o}`,i[r].map((e=>`${e.userId}/${e.deviceInfo.deviceId}`))),await this.encryptAndSendKeysToDevices(e,t.chain_index,i[r],n),s.logger.debug(`Shared ${o}`)}catch(e){throw s.logger.error(`Failed to share ${o}`),e}}}async notifyFailedOlmDevices(e,t,n){s.logger.debug(`Notifying ${n.length} devices we failed to create Olm sessions in ${this.roomId}`);for(const{userId:r,deviceInfo:i}of n){const n=i.deviceId;e.markSharedWithDevice(r,n,i.getIdentityKey(),t.chain_index)}const r=await this.olmDevice.filterOutNotifiedErrorDevices(n);s.logger.debug(`Need to notify ${r.length} failed devices which haven't been notified before in ${this.roomId}`);const i={};for(const{userId:e,deviceInfo:t}of r)i[e]=i[e]||{},i[e][t.deviceId]={device:{code:"m.no_olm",reason:c.WITHHELD_MESSAGES["m.no_olm"],deviceInfo:t}};await this.notifyBlockedDevices(e,i),s.logger.debug(`Notified ${r.length} devices we failed to create Olm sessions in ${this.roomId}`)}async notifyBlockedDevices(e,t){const n={room_id:this.roomId,session_id:e.sessionId,algorithm:o.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key},r=this.splitDevices(t);for(let t=0;t<r.length;t++)try{await this.sendBlockedNotificationsToDevices(e,r[t],n),s.logger.log(`Completed blacklist notification for ${e.sessionId} in ${this.roomId} (slice ${t+1}/${r.length})`)}catch(n){throw s.logger.log(`blacklist notification for ${e.sessionId} in ${this.roomId} (slice ${t+1}/${r.length}) failed`),n}}prepareToEncrypt(e){if(null==this.encryptionPreparation)s.logger.debug(`Preparing to encrypt events for ${this.roomId}`),this.encryptionPreparation={startTime:Date.now(),promise:(async()=>{try{s.logger.debug(`Getting devices in ${this.roomId}`);const[t,n]=await this.getDevicesInRoom(e);this.crypto.getGlobalErrorOnUnknownDevices()&&this.removeUnknownDevices(t),s.logger.debug(`Ensuring outbound session in ${this.roomId}`),await this.ensureOutboundSession(e,t,n,!0),s.logger.debug(`Ready to encrypt events for ${this.roomId}`)}catch(e){s.logger.error(`Failed to prepare to encrypt events for ${this.roomId}`,e)}finally{delete this.encryptionPreparation}})()};else{const e=Date.now()-this.encryptionPreparation.startTime;s.logger.debug(`Already started preparing to encrypt for ${this.roomId} ${e} ms ago, skipping`)}}async encryptMessage(e,t,n){if(s.logger.log(`Starting to encrypt event for ${this.roomId}`),null!=this.encryptionPreparation)try{await this.encryptionPreparation.promise}catch(e){}const[r,i]=await this.getDevicesInRoom(e);this.crypto.getGlobalErrorOnUnknownDevices()&&this.checkForUnknownDevices(r);const a=await this.ensureOutboundSession(e,r,i),c={room_id:this.roomId,type:t,content:n},l=this.olmDevice.encryptGroupMessage(a.sessionId,JSON.stringify(c)),d={algorithm:o.MEGOLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:l,session_id:a.sessionId,device_id:this.deviceId};return a.useCount++,d}forceDiscardSession(){this.setupPromise=this.setupPromise.then((()=>null))}checkForUnknownDevices(e){const t={};if(Object.keys(e).forEach((n=>{Object.keys(e[n]).forEach((r=>{const i=e[n][r];i.isUnverified()&&!i.isKnown()&&(t[n]||(t[n]={}),t[n][r]=i)}))})),Object.keys(t).length)throw new a.UnknownDeviceError("This room contains unknown devices which have not been verified. We strongly recommend you verify them before continuing.",t)}removeUnknownDevices(e){for(const[t,n]of Object.entries(e)){for(const[e,t]of Object.entries(n))t.isUnverified()&&!t.isKnown()&&delete n[e];0===Object.keys(n).length&&delete e[t]}}async getDevicesInRoom(e){const t=(await e.getEncryptionTargetMembers()).map((function(e){return e.userId}));let n=this.crypto.getGlobalBlacklistUnverifiedDevices();"boolean"==typeof e.getBlacklistUnverifiedDevices()&&(n=e.getBlacklistUnverifiedDevices());const r=await this.crypto.downloadKeys(t,!1),i={};for(const e in r){if(!r.hasOwnProperty(e))continue;const t=r[e];for(const r in t){if(!t.hasOwnProperty(r))continue;const s=this.crypto.checkDeviceTrust(e,r);if(t[r].isBlocked()||!s.isVerified()&&n){i[e]||(i[e]={});const n=t[r].isBlocked();i[e][r]={code:n?"m.blacklisted":"m.unverified",reason:c.WITHHELD_MESSAGES[n?"m.blacklisted":"m.unverified"],deviceInfo:t[r]},delete t[r]}}}return[r,i]}}class f extends a.DecryptionAlgorithm{constructor(...e){super(...e),(0,i.default)(this,"pendingEvents",new Map),(0,i.default)(this,"olmlib",o)}async decryptEvent(e){const t=e.getWireContent();if(!t.sender_key||!t.session_id||!t.ciphertext)throw new a.DecryptionError("MEGOLM_MISSING_FIELDS","Missing fields in input");let n;this.addEventToPendingList(e);try{n=await this.olmDevice.decryptGroupMessage(e.getRoomId(),t.sender_key,t.session_id,t.ciphertext,e.getId(),e.getTs())}catch(n){if("DecryptionError"===n.name)throw n;let r="OLM_DECRYPT_GROUP_MESSAGE_ERROR";throw n&&"OLM.UNKNOWN_MESSAGE_INDEX"===n.message&&(this.requestKeysForEvent(e),r="OLM_UNKNOWN_MESSAGE_INDEX"),new a.DecryptionError(r,n?n.toString():"Unknown Error: Error is undefined",{session:t.sender_key+"|"+t.session_id})}if(null===n){this.crypto.backupManager.queryKeyBackupRateLimited(e.getRoomId(),t.session_id).catch((()=>{})),this.requestKeysForEvent(e);const n=await this.olmDevice.sessionMayHaveProblems(t.sender_key,e.getTs()-12e4);if(n){let e=g[n.type]||g.unknown;throw n.fixed&&(e+=" Trying to create a new secure channel and re-requesting the keys."),new a.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID",e,{session:t.sender_key+"|"+t.session_id})}throw new a.DecryptionError("MEGOLM_UNKNOWN_INBOUND_SESSION_ID","The sender's device has not sent us the keys for this message.",{session:t.sender_key+"|"+t.session_id})}this.removeEventFromPendingList(e);const r=JSON.parse(n.result);if(r.room_id!==e.getRoomId())throw new a.DecryptionError("MEGOLM_BAD_ROOM","Message intended for room "+r.room_id);return{clearEvent:r,senderCurve25519Key:n.senderKey,claimedEd25519Key:n.keysClaimed.ed25519,forwardingCurve25519KeyChain:n.forwardingCurve25519KeyChain,untrusted:n.untrusted}}requestKeysForEvent(e){const t=e.getWireContent(),n=e.getKeyRequestRecipients(this.userId);this.crypto.requestRoomKey({room_id:e.getRoomId(),algorithm:t.algorithm,sender_key:t.sender_key,session_id:t.session_id},n)}addEventToPendingList(e){var t;const n=e.getWireContent(),r=n.sender_key,i=n.session_id;this.pendingEvents.has(r)||this.pendingEvents.set(r,new Map);const s=this.pendingEvents.get(r);s.has(i)||s.set(i,new Set),null===(t=s.get(i))||void 0===t||t.add(e)}removeEventFromPendingList(e){const t=e.getWireContent(),n=t.sender_key,r=t.session_id,i=this.pendingEvents.get(n),s=null==i?void 0:i.get(r);s&&(s.delete(e),0===s.size&&i.delete(r),0===i.size&&this.pendingEvents.delete(n))}async onRoomKeyEvent(e){const t=e.getContent();let n,r=e.getSenderKey(),i=[],o=!1;if(!(t.room_id&&t.session_key&&t.session_id&&t.algorithm))return void s.logger.error("key event is missing fields");if(!r)return void s.logger.error("key event has no sender key (not encrypted?)");if("m.forwarded_room_key"==e.getType()){if(o=!0,i=Array.isArray(t.forwarding_curve25519_key_chain)?t.forwarding_curve25519_key_chain:[],i=i.slice(),i.push(r),!t.sender_key)return void s.logger.error("forwarded_room_key event is missing sender_key field");r=t.sender_key;const e=t.sender_claimed_ed25519_key;if(!e)return void s.logger.error("forwarded_room_key_event is missing sender_claimed_ed25519_key field");n={ed25519:e}}else n=e.getKeysClaimed();const a={};t["org.matrix.msc3061.shared_history"]&&(a.sharedHistory=!0);try{await this.olmDevice.addInboundGroupSession(t.room_id,r,i,t.session_id,t.session_key,n,o,a),await this.retryDecryption(r,t.session_id)&&this.crypto.cancelRoomKeyRequest({algorithm:t.algorithm,room_id:t.room_id,session_id:t.session_id,sender_key:r}),await this.crypto.backupManager.backupGroupSession(r,t.session_id)}catch(e){s.logger.error(`Error handling m.room_key_event: ${e}`)}}async onRoomKeyWithheldEvent(e){const t=e.getContent(),n=t.sender_key;if("m.no_olm"===t.code){const r=e.getSender();if(s.logger.warn(`${r}:${n} was unable to establish an olm session with us`),await this.olmDevice.getSessionIdForDevice(n))return s.logger.debug("New session already created. Not creating a new one."),await this.olmDevice.recordSessionProblem(n,"no_olm",!0),void this.retryDecryptionFromSender(n);let i=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,n);if(!i&&(await this.crypto.downloadKeys([r],!1),i=this.crypto.deviceList.getDeviceByIdentityKey(t.algorithm,n),!i))return s.logger.info("Couldn't find device for identity key "+n+": not establishing session"),await this.olmDevice.recordSessionProblem(n,"no_olm",!1),void this.retryDecryptionFromSender(n);await o.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[r]:[i]},!1);const a={algorithm:o.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};await o.encryptMessageForDevice(a.ciphertext,this.userId,void 0,this.olmDevice,r,i,{type:"m.dummy"}),await this.olmDevice.recordSessionProblem(n,"no_olm",!0),this.retryDecryptionFromSender(n),await this.baseApis.sendToDevice("m.room.encrypted",{[r]:{[i.deviceId]:a}})}else await this.olmDevice.addInboundGroupSessionWithheld(t.room_id,n,t.session_id,t.code,t.reason)}hasKeysForKeyRequest(e){const t=e.requestBody;return this.olmDevice.hasInboundSessionKeys(t.room_id,t.sender_key,t.session_id)}shareKeysWithDevice(e){const t=e.userId,n=e.deviceId,r=this.crypto.getStoredDevice(t,n),i=e.requestBody;this.olmlib.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[t]:[r]}).then((e=>e[t][n].sessionId?(s.logger.log("sharing keys for session "+i.sender_key+"|"+i.session_id+" with device "+t+":"+n),this.buildKeyForwardingMessage(i.room_id,i.sender_key,i.session_id)):null)).then((e=>{const i={algorithm:o.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};return this.olmlib.encryptMessageForDevice(i.ciphertext,this.userId,void 0,this.olmDevice,t,r,e).then((()=>{const e={[t]:{[n]:i}};return this.baseApis.sendToDevice("m.room.encrypted",e)}))}))}async buildKeyForwardingMessage(e,t,n){const r=await this.olmDevice.getInboundGroupSessionKey(e,t,n);return{type:"m.forwarded_room_key",content:{algorithm:o.MEGOLM_ALGORITHM,room_id:e,sender_key:t,sender_claimed_ed25519_key:r.sender_claimed_ed25519_key,session_id:n,session_key:r.key,chain_index:r.chain_index,forwarding_curve25519_key_chain:r.forwarding_curve25519_key_chain,"org.matrix.msc3061.shared_history":r.shared_history||!1}}}importRoomKey(e,t={}){const n={};return(t.untrusted||e.untrusted)&&(n.untrusted=!0),e["org.matrix.msc3061.shared_history"]&&(n.sharedHistory=!0),this.olmDevice.addInboundGroupSession(e.room_id,e.sender_key,e.forwarding_curve25519_key_chain,e.session_id,e.session_key,e.sender_claimed_keys,!0,n).then((()=>{"backup"!==t.source&&this.crypto.backupManager.backupGroupSession(e.sender_key,e.session_id).catch((e=>{s.logger.log("Failed to back up megolm session",e)})),this.retryDecryption(e.sender_key,e.session_id)}))}async retryDecryption(e,t){var n;const r=this.pendingEvents.get(e);if(!r)return!0;const i=r.get(t);return!(i&&(s.logger.debug("Retrying decryption on events",[...i]),await Promise.all([...i].map((async e=>{try{await e.attemptDecryption(this.crypto,{isRetry:!0})}catch(e){}}))),null!==(n=this.pendingEvents.get(e))&&void 0!==n&&n.has(t)))}async retryDecryptionFromSender(e){const t=this.pendingEvents.get(e);return!t||(this.pendingEvents.delete(e),await Promise.all([...t].map((async([e,t])=>{await Promise.all([...t].map((async e=>{try{await e.attemptDecryption(this.crypto)}catch(e){}})))}))),!this.pendingEvents.has(e))}async sendSharedHistoryInboundSessions(e){await o.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,e),s.logger.log("sendSharedHistoryInboundSessions to users",Object.keys(e));const t=await this.olmDevice.getSharedHistoryInboundGroupSessions(this.roomId);s.logger.log("shared-history sessions",t);for(const[n,r]of t){const t=await this.buildKeyForwardingMessage(this.roomId,n,r),i=[],a={};for(const[n,r]of Object.entries(e)){a[n]={};for(const e of r){const r={algorithm:o.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};a[n][e.deviceId]=r,i.push(o.encryptMessageForDevice(r.ciphertext,this.userId,void 0,this.olmDevice,n,e,t))}}await Promise.all(i);for(const e of Object.keys(a)){for(const t of Object.keys(a[e]))0===Object.keys(a[e][t].ciphertext).length&&(s.logger.log("No ciphertext for device "+e+":"+t+": pruning"),delete a[e][t]);0===Object.keys(a[e]).length&&(s.logger.log("Pruned all devices for user "+e),delete a[e])}if(0===Object.keys(a).length)return void s.logger.log("No users left to send to: aborting");await this.baseApis.sendToDevice("m.room.encrypted",a)}}}const g={no_olm:"The sender was unable to establish a secure channel.",unknown:"The secure channel with the sender was corrupted."};(0,a.registerAlgorithm)(o.MEGOLM_ALGORITHM,h,f)},3072:(e,t,n)=>{"use strict";var r=n(4836)(n(8416)),i=n(7434),s=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=c(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(2772)),o=n(3272),a=n(1897);function c(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(c=function(e){return e?n:t})(e)}const l=o.DeviceInfo.DeviceVerification;class d extends a.EncryptionAlgorithm{constructor(...e){super(...e),(0,r.default)(this,"sessionPrepared",!1),(0,r.default)(this,"prepPromise",null)}ensureSession(e){return this.prepPromise?this.prepPromise:this.sessionPrepared?Promise.resolve():(this.prepPromise=this.crypto.downloadKeys(e).then((()=>this.crypto.ensureOlmSessionsForUsers(e))).then((()=>{this.sessionPrepared=!0})).finally((()=>{this.prepPromise=null})),this.prepPromise)}async encryptMessage(e,t,n){const r=(await e.getEncryptionTargetMembers()).map((function(e){return e.userId}));await this.ensureSession(r);const i={room_id:e.roomId,type:t,content:n},o={algorithm:s.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}},a=[];for(let e=0;e<r.length;++e){const t=r[e],n=this.crypto.getStoredDevicesForUser(t)||[];for(let e=0;e<n.length;++e){const r=n[e];r.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&r.verified!=l.BLOCKED&&a.push(s.encryptMessageForDevice(o.ciphertext,this.userId,this.deviceId,this.olmDevice,t,r,i))}}return Promise.all(a).then((()=>o))}}class u extends a.DecryptionAlgorithm{async decryptEvent(e){const t=e.getWireContent(),n=t.sender_key,r=t.ciphertext;if(!r)throw new a.DecryptionError("OLM_MISSING_CIPHERTEXT","Missing ciphertext");if(!(this.olmDevice.deviceCurve25519Key in r))throw new a.DecryptionError("OLM_NOT_INCLUDED_IN_RECIPIENTS","Not included in recipients");const i=r[this.olmDevice.deviceCurve25519Key];let s;try{s=await this.decryptMessage(n,i)}catch(e){throw new a.DecryptionError("OLM_BAD_ENCRYPTED_MESSAGE","Bad Encrypted Message",{sender:n,err:e})}const o=JSON.parse(s);if(o.recipient!=this.userId)throw new a.DecryptionError("OLM_BAD_RECIPIENT","Message was intented for "+o.recipient);if(o.recipient_keys.ed25519!=this.olmDevice.deviceEd25519Key)throw new a.DecryptionError("OLM_BAD_RECIPIENT_KEY","Message not intended for this device",{intended:o.recipient_keys.ed25519,our_key:this.olmDevice.deviceEd25519Key});if(o.sender!=e.getSender())throw new a.DecryptionError("OLM_FORWARDED_MESSAGE","Message forwarded from "+o.sender,{reported_sender:e.getSender()});if(o.room_id!==e.getRoomId())throw new a.DecryptionError("OLM_BAD_ROOM","Message intended for room "+o.room_id,{reported_room:e.getRoomId()||"ROOM_ID_UNDEFINED"});return{clearEvent:o,senderCurve25519Key:n,claimedEd25519Key:(o.keys||{}).ed25519||null}}decryptMessage(e,t){if(0!==t.type)return this.reallyDecryptMessage(e,t);{const n=this.olmDevice.olmPrekeyPromise.then((()=>this.reallyDecryptMessage(e,t)));return this.olmDevice.olmPrekeyPromise=n.catch((()=>{})),n}}async reallyDecryptMessage(e,t){const n=await this.olmDevice.getSessionIdsForDevice(e),r={};for(let s=0;s<n.length;s++){const o=n[s];try{const n=await this.olmDevice.decryptMessage(e,o,t.type,t.body);return i.logger.log("Decrypted Olm message from "+e+" with session "+o),n}catch(n){if(await this.olmDevice.matchesSession(e,o,t.type,t.body))throw new Error("Error decrypting prekey message with existing session id "+o+": "+n.message);r[o]=n.message}}if(0!==t.type){if(0===n.length)throw new Error("No existing sessions");throw new Error("Error decrypting non-prekey message with existing sessions: "+JSON.stringify(r))}let s;try{s=await this.olmDevice.createInboundSession(e,t.type,t.body)}catch(e){throw r["(new)"]=e.message,new Error("Error decrypting prekey message: "+JSON.stringify(r))}return i.logger.log("created new inbound Olm session ID "+s.session_id+" with "+e),s.payload}}(0,a.registerAlgorithm)(s.OLM_ALGORITHM,d,u)},764:(e,t)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),t.CrossSigningKey=void 0,t.CrossSigningKey=n,function(e){e.Master="master",e.SelfSigning="self_signing",e.UserSigning="user_signing"}(n||(t.CrossSigningKey=n={}))},5537:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.algorithmsByName=t.DefaultAlgorithm=t.Curve25519=t.BackupManager=t.Aes256=void 0;var i=r(n(8416)),s=n(2168),o=n(7434),a=n(2772),c=n(1597),l=n(3102),d=n(7585),u=n(4077),h=n(2611),f=n(7048),g=n(2600);class p{constructor(e,t){this.baseApis=e,this.getKey=t,(0,i.default)(this,"algorithm",void 0),(0,i.default)(this,"backupInfo",void 0),(0,i.default)(this,"checkedForBackup",void 0),(0,i.default)(this,"sendingBackups",void 0),(0,i.default)(this,"sessionLastCheckAttemptedTime",{}),this.checkedForBackup=!1,this.sendingBackups=!1}get version(){return this.backupInfo&&this.backupInfo.version}static checkBackupVersion(e){const t=b[e.algorithm];if(!t)throw new Error("Unknown backup algorithm: "+e.algorithm);if("object"!=typeof e.auth_data)throw new Error("Invalid backup data returned");return t.checkBackupVersion(e)}static makeAlgorithm(e,t){const n=b[e.algorithm];if(!n)throw new Error("Unknown backup algorithm");return n.init(e.auth_data,t)}async enableKeyBackup(e){this.backupInfo=e,this.algorithm&&this.algorithm.free(),this.algorithm=await p.makeAlgorithm(e,this.getKey),this.baseApis.emit(g.CryptoEvent.KeyBackupStatus,!0),this.scheduleKeyBackupSend()}disableKeyBackup(){this.algorithm&&this.algorithm.free(),this.algorithm=void 0,this.backupInfo=void 0,this.baseApis.emit(g.CryptoEvent.KeyBackupStatus,!1)}getKeyBackupEnabled(){return this.checkedForBackup?Boolean(this.algorithm):null}async prepareKeyBackupVersion(e,t){const n=t?b[t]:_;if(!n)throw new Error("Unknown backup algorithm");const[r,i]=await n.prepare(e),s=(0,u.encodeRecoveryKey)(r);return{algorithm:n.algorithmName,auth_data:i,recovery_key:s,privateKey:r}}async createKeyBackupVersion(e){this.algorithm=await p.makeAlgorithm(e,this.getKey)}async checkAndStart(){if(o.logger.log("Checking key backup status..."),this.baseApis.isGuest())return o.logger.log("Skipping key backup check since user is guest"),this.checkedForBackup=!0,null;let e;try{e=await this.baseApis.getKeyBackupVersion()}catch(e){return o.logger.log("Error checking for active key backup",e),404===e.httpStatus&&(this.checkedForBackup=!0),null}this.checkedForBackup=!0;const t=await this.isKeyBackupTrusted(e);return t.usable&&!this.backupInfo?(o.logger.log("Found usable key backup v"+e.version+": enabling key backups"),await this.enableKeyBackup(e)):!t.usable&&this.backupInfo?(o.logger.log("No usable key backup: disabling key backup"),this.disableKeyBackup()):t.usable||this.backupInfo?t.usable&&this.backupInfo&&(e.version!==this.backupInfo.version?(o.logger.log("On backup version "+this.backupInfo.version+" but found version "+e.version+": switching."),this.disableKeyBackup(),await this.enableKeyBackup(e),await this.scheduleAllGroupSessionsForBackup()):o.logger.log("Backup version "+e.version+" still current")):o.logger.log("No usable key backup: not enabling key backup"),{backupInfo:e,trustInfo:t}}async checkKeyBackup(){return this.checkedForBackup=!1,this.checkAndStart()}async queryKeyBackupRateLimited(e,t){if(!this.backupInfo)return;const n=(new Date).getTime();(!this.sessionLastCheckAttemptedTime[t]||n-this.sessionLastCheckAttemptedTime[t]>5e3)&&(this.sessionLastCheckAttemptedTime[t]=n,await this.baseApis.restoreKeyBackupWithCache(e,t,this.backupInfo,{}))}async isKeyBackupTrusted(e){const t={usable:!1,trusted_locally:!1,sigs:[]};if(!(e&&e.algorithm&&e.auth_data&&e.auth_data.signatures))return o.logger.info("Key backup is absent or missing required data"),t;const n=await this.baseApis.crypto.getSessionBackupPrivateKey();if(n){let r;try{r=await p.makeAlgorithm(e,(async()=>n)),await r.keyMatches(n)&&(o.logger.info("Backup is trusted locally"),t.trusted_locally=!0)}catch{}finally{r&&r.free()}}const r=e.auth_data.signatures[this.baseApis.getUserId()]||{};for(const n of Object.keys(r)){const r=n.split(":");if("ed25519"!==r[0]){o.logger.log("Ignoring unknown signature type: "+r[0]);continue}const i={deviceId:r[1]},s=this.baseApis.crypto.crossSigningInfo.getId();if(s===i.deviceId){i.crossSigningId=!0;try{await(0,a.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,this.baseApis.getUserId(),i.deviceId,s),i.valid=!0}catch(e){o.logger.warn("Bad signature from cross signing key "+s,e),i.valid=!1}t.sigs.push(i);continue}const c=this.baseApis.crypto.deviceList.getStoredDevice(this.baseApis.getUserId(),i.deviceId);if(c){i.device=c,i.deviceTrust=this.baseApis.checkDeviceTrust(this.baseApis.getUserId(),i.deviceId);try{await(0,a.verifySignature)(this.baseApis.crypto.olmDevice,e.auth_data,this.baseApis.getUserId(),c.deviceId,c.getFingerprint()),i.valid=!0}catch(t){o.logger.info("Bad signature from key ID "+n+" userID "+this.baseApis.getUserId()+" device ID "+c.deviceId+" fingerprint: "+c.getFingerprint(),e.auth_data,t),i.valid=!1}}else i.valid=null,o.logger.info("Ignoring signature from unknown key "+n);t.sigs.push(i)}return t.usable=t.sigs.some((e=>e.valid&&(e.device&&e.deviceTrust.isVerified()||e.crossSigningId))),t.usable=t.usable||t.trusted_locally,t}async scheduleKeyBackupSend(e=1e4){if(!this.sendingBackups){this.sendingBackups=!0;try{const t=Math.random()*e;await(0,l.sleep)(t);let n=0;for(;;){if(!this.algorithm)return;try{if(0===await this.backupPendingKeys(200))return;n=0}catch(e){if(n++,o.logger.log("Key backup request failed",e),e.data&&("M_NOT_FOUND"==e.data.errcode||"M_WRONG_ROOM_KEYS_VERSION"==e.data.errcode))throw await this.checkKeyBackup(),this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupFailed,e.data.errcode),e}n&&await(0,l.sleep)(1e3*Math.pow(2,Math.min(n-1,4)))}}finally{this.sendingBackups=!1}}}async backupPendingKeys(e){const t=await this.baseApis.crypto.cryptoStore.getSessionsNeedingBackup(e);if(!t.length)return 0;let n=await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupSessionsRemaining,n);const r={};for(const e of t){const t=e.sessionData.room_id;void 0===r[t]&&(r[t]={sessions:{}});const n=this.baseApis.crypto.olmDevice.exportInboundGroupSession(e.senderKey,e.sessionId,e.sessionData);n.algorithm=a.MEGOLM_ALGORITHM;const i=(n.forwarding_curve25519_key_chain||[]).length,s=this.baseApis.crypto.deviceList.getUserByIdentityKey(a.MEGOLM_ALGORITHM,e.senderKey),o=this.baseApis.crypto.deviceList.getDeviceByIdentityKey(a.MEGOLM_ALGORITHM,e.senderKey),c=this.baseApis.crypto.checkDeviceInfoTrust(s,o).isVerified();r[t].sessions[e.sessionId]={first_message_index:n.first_known_index,forwarded_count:i,is_verified:c,session_data:await this.algorithm.encryptSession(n)}}return await this.baseApis.sendKeyBackup(void 0,void 0,this.backupInfo.version,{rooms:r}),await this.baseApis.crypto.cryptoStore.unmarkSessionsNeedingBackup(t),n=await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup(),this.baseApis.crypto.emit(g.CryptoEvent.KeyBackupSessionsRemaining,n),t.length}async backupGroupSession(e,t){await this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([{senderKey:e,sessionId:t}]),this.backupInfo&&this.scheduleKeyBackupSend()}async scheduleAllGroupSessionsForBackup(){await this.flagAllGroupSessionsForBackup(),this.scheduleKeyBackupSend(0)}async flagAllGroupSessionsForBackup(){await this.baseApis.crypto.cryptoStore.doTxn("readwrite",[d.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS,d.IndexedDBCryptoStore.STORE_BACKUP],(e=>{this.baseApis.crypto.cryptoStore.getAllEndToEndInboundGroupSessions(e,(t=>{null!==t&&this.baseApis.crypto.cryptoStore.markSessionsNeedingBackup([t],e)}))}));const e=await this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup();return this.baseApis.emit(g.CryptoEvent.KeyBackupSessionsRemaining,e),e}countSessionsNeedingBackup(){return this.baseApis.crypto.cryptoStore.countSessionsNeedingBackup()}}t.BackupManager=p;class m{constructor(e,t,n){this.authData=e,this.publicKey=t,this.getKey=n}static async init(e,t){if(!e||!("public_key"in e))throw new Error("auth_data missing required information");const r=new n.g.Olm.PkEncryption;return r.set_recipient_key(e.public_key),new m(e,r,t)}static async prepare(e){const t=new n.g.Olm.PkDecryption;try{const r={};if(e)if(e instanceof Uint8Array)r.public_key=t.init_with_private_key(e);else{const n=await(0,c.keyFromPassphrase)(e);r.private_key_salt=n.salt,r.private_key_iterations=n.iterations,r.public_key=t.init_with_private_key(n.key)}else r.public_key=t.generate_key();return(new n.g.Olm.PkEncryption).set_recipient_key(r.public_key),[t.get_private_key(),r]}finally{t.free()}}static checkBackupVersion(e){if(!("public_key"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!0}async encryptSession(e){const t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,this.publicKey.encrypt(JSON.stringify(t))}async decryptSessions(e){const t=await this.getKey(),r=new n.g.Olm.PkDecryption;try{if(r.init_with_private_key(t)!==this.authData.public_key)throw{errcode:s.MatrixClient.RESTORE_BACKUP_ERROR_BAD_KEY};const n=[];for(const[t,i]of Object.entries(e))try{const e=JSON.parse(r.decrypt(i.session_data.ephemeral,i.session_data.mac,i.session_data.ciphertext));e.session_id=t,n.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,i)}return n}finally{r.free()}}async keyMatches(e){const t=new n.g.Olm.PkDecryption;let r;try{r=t.init_with_private_key(e)}finally{t.free()}return r===this.authData.public_key}free(){this.publicKey.free()}}t.Curve25519=m,(0,i.default)(m,"algorithmName","m.megolm_backup.v1.curve25519-aes-sha2");const y=new f.UnstableValue(null,"org.matrix.msc3270.v1.aes-hmac-sha2");class v{constructor(e,t){this.authData=e,this.key=t}static async init(e,t){if(!e)throw new Error("auth_data missing");const n=await t();if(e.mac){const{mac:t}=await(0,h.calculateKeyCheck)(n,e.iv);if(e.mac.replace(/=+$/g,"")!==t.replace(/=+/g,""))throw new Error("Key does not match")}return new v(e,n)}static async prepare(e){let t;const n={};if(e)if(e instanceof Uint8Array)t=new Uint8Array(e);else{const r=await(0,c.keyFromPassphrase)(e);n.private_key_salt=r.salt,n.private_key_iterations=r.iterations,t=r.key}else t=function(e){var t;const n=(0,l.getCrypto)();if(n)return n.randomBytes(32);if(null!==(t=window)&&void 0!==t&&t.crypto){const e=new Uint8Array(32);return window.crypto.getRandomValues(e),e}throw new Error("No usable crypto implementation")}();const{iv:r,mac:i}=await(0,h.calculateKeyCheck)(t);return n.iv=r,n.mac=i,[t,n]}static checkBackupVersion(e){if(!("iv"in e.auth_data)||!("mac"in e.auth_data))throw new Error("Invalid backup data returned")}get untrusted(){return!1}encryptSession(e){const t=Object.assign({},e);return delete t.session_id,delete t.room_id,delete t.first_known_index,(0,h.encryptAES)(JSON.stringify(t),this.key,e.session_id)}async decryptSessions(e){const t=[];for(const[n,r]of Object.entries(e))try{const e=JSON.parse(await(0,h.decryptAES)(r.session_data,this.key,n));e.session_id=n,t.push(e)}catch(e){o.logger.log("Failed to decrypt megolm session from backup",e,r)}return t}async keyMatches(e){if(this.authData.mac){const{mac:t}=await(0,h.calculateKeyCheck)(e,this.authData.iv);return this.authData.mac.replace(/=+$/g,"")===t.replace(/=+/g,"")}return!0}free(){this.key.fill(0)}}t.Aes256=v,(0,i.default)(v,"algorithmName",y.name);const b={[m.algorithmName]:m,[v.algorithmName]:v};t.algorithmsByName=b;const _=m;t.DefaultAlgorithm=_},4830:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.DehydrationManager=t.DEHYDRATION_ALGORITHM=void 0;var i=r(n(8416)),s=r(n(9141)),o=n(2772),a=n(7585),c=n(2611),l=n(7434),d=n(7715);const u="org.matrix.msc2697.v1.olm.libolm_pickle";t.DEHYDRATION_ALGORITHM=u;const h=6048e5;t.DehydrationManager=class{constructor(e){this.crypto=e,(0,i.default)(this,"inProgress",!1),(0,i.default)(this,"timeoutId",void 0),(0,i.default)(this,"key",void 0),(0,i.default)(this,"keyInfo",void 0),(0,i.default)(this,"deviceDisplayName",void 0),this.getDehydrationKeyFromCache()}getDehydrationKeyFromCache(){return this.crypto.cryptoStore.doTxn("readonly",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.getSecretStorePrivateKey(e,(async e=>{if(e){const{key:t,keyInfo:r,deviceDisplayName:i,time:s}=e,a=Buffer.from(this.crypto.olmDevice.pickleKey),l=await(0,c.decryptAES)(t,a,u);this.key=(0,o.decodeBase64)(l),this.keyInfo=r,this.deviceDisplayName=i;const d=Date.now(),f=Math.max(1,s+h-d);this.timeoutId=n.g.setTimeout(this.dehydrateDevice.bind(this),f)}}),"dehydration")}))}async setKeyAndQueueDehydration(e,t={},n=void 0){await this.setKey(e,t,n)||this.dehydrateDevice()}async setKey(e,t={},r=void 0){if(!e)return this.timeoutId&&(n.g.clearTimeout(this.timeoutId),this.timeoutId=void 0),await this.crypto.cryptoStore.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",null)})),this.key=void 0,void(this.keyInfo=void 0);let i=this.key&&e.length==this.key.length;for(let t=0;i&&t<e.length;t++)e[t]!=this.key[t]&&(i=!1);return i||(this.key=e,this.keyInfo=t,this.deviceDisplayName=r),i}async dehydrateDevice(){if(this.inProgress)l.logger.log("Dehydration already in progress -- not starting new dehydration");else{this.inProgress=!0,this.timeoutId&&(n.g.clearTimeout(this.timeoutId),this.timeoutId=void 0);try{const e=Buffer.from(this.crypto.olmDevice.pickleKey),t=await(0,c.encryptAES)((0,o.encodeBase64)(this.key),e,u);await this.crypto.cryptoStore.doTxn("readwrite",[a.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.crypto.cryptoStore.storeSecretStorePrivateKey(e,"dehydration",{keyInfo:this.keyInfo,key:t,deviceDisplayName:this.deviceDisplayName,time:Date.now()})})),l.logger.log("Attempting to dehydrate device"),l.logger.log("Creating account");const r=new n.g.Olm.Account;r.create();const i=JSON.parse(r.identity_keys()),f=r.max_number_of_one_time_keys();r.generate_one_time_keys(f/2),r.generate_fallback_key();const g=JSON.parse(r.one_time_keys()),p=JSON.parse(r.fallback_key());r.mark_keys_as_published();const m=r.pickle(new Uint8Array(this.key)),y={algorithm:u,account:m};this.keyInfo.passphrase&&(y.passphrase=this.keyInfo.passphrase),l.logger.log("Uploading account to server");const v=(await this.crypto.baseApis.http.authedRequest(void 0,d.Method.Put,"/dehydrated_device",void 0,{device_data:y,initial_device_display_name:this.deviceDisplayName},{prefix:"/_matrix/client/unstable/org.matrix.msc2697.v2"})).device_id;l.logger.log("Preparing device keys",v);const b={algorithms:this.crypto.supportedAlgorithms,device_id:v,user_id:this.crypto.userId,keys:{[`ed25519:${v}`]:i.ed25519,[`curve25519:${v}`]:i.curve25519}},_=r.sign(s.default.stringify(b));b.signatures={[this.crypto.userId]:{[`ed25519:${v}`]:_}},this.crypto.crossSigningInfo.getId("self_signing")&&await this.crypto.crossSigningInfo.signObject(b,"self_signing"),l.logger.log("Preparing one-time keys");const E={};for(const[e,t]of Object.entries(g.curve25519)){const n={key:t},i=r.sign(s.default.stringify(n));n.signatures={[this.crypto.userId]:{[`ed25519:${v}`]:i}},E[`signed_curve25519:${e}`]=n}l.logger.log("Preparing fallback keys");const w={};for(const[e,t]of Object.entries(p.curve25519)){const n={key:t,fallback:!0},i=r.sign(s.default.stringify(n));n.signatures={[this.crypto.userId]:{[`ed25519:${v}`]:i}},w[`signed_curve25519:${e}`]=n}return l.logger.log("Uploading keys to server"),await this.crypto.baseApis.http.authedRequest(void 0,d.Method.Post,"/keys/upload/"+encodeURI(v),void 0,{device_keys:b,one_time_keys:E,"org.matrix.msc2732.fallback_keys":w}),l.logger.log("Done dehydrating"),this.timeoutId=n.g.setTimeout(this.dehydrateDevice.bind(this),h),v}finally{this.inProgress=!1}}}stop(){this.timeoutId&&(n.g.clearTimeout(this.timeoutId),this.timeoutId=void 0)}}},3272:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.DeviceInfo=void 0;var i,s=r(n(8416));!function(e){e[e.Blocked=-1]="Blocked",e[e.Unverified=0]="Unverified",e[e.Verified=1]="Verified"}(i||(i={}));class o{static fromStorage(e,t){const n=new o(t);for(const t in e)e.hasOwnProperty(t)&&(n[t]=e[t]);return n}constructor(e){this.deviceId=e,(0,s.default)(this,"algorithms",void 0),(0,s.default)(this,"keys",{}),(0,s.default)(this,"verified",i.Unverified),(0,s.default)(this,"known",!1),(0,s.default)(this,"unsigned",{}),(0,s.default)(this,"signatures",{})}toStorage(){return{algorithms:this.algorithms,keys:this.keys,verified:this.verified,known:this.known,unsigned:this.unsigned,signatures:this.signatures}}getFingerprint(){return this.keys["ed25519:"+this.deviceId]}getIdentityKey(){return this.keys["curve25519:"+this.deviceId]}getDisplayName(){return this.unsigned.device_display_name||null}isBlocked(){return this.verified==i.Blocked}isVerified(){return this.verified==i.Verified}isUnverified(){return this.verified==i.Unverified}isKnown(){return!0===this.known}}t.DeviceInfo=o,(0,s.default)(o,"DeviceVerification",{VERIFIED:i.Verified,UNVERIFIED:i.Unverified,BLOCKED:i.Blocked})},2600:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.IncomingRoomKeyRequest=t.CryptoEvent=t.Crypto=void 0,t.fixBackupKey=V,t.isCryptoAvailable=function(){return Boolean(n.g.Olm)},t.verificationMethods=void 0;var i=r(n(8416)),s=r(n(9141)),o=n(2481),a=n(771),c=n(7434),l=n(2573),d=x(n(2772)),u=n(6670),h=n(3272),f=x(n(1994)),g=n(3075),p=n(636),m=n(4823),y=n(6617),v=n(7585),b=n(1696),_=n(6381),E=n(1597),w=n(4077),S=n(5279),C=n(2842),T=n(9588),R=n(4028),I=n(9489),k=n(2611),O=n(4830),A=n(5537),D=n(7366),M=n(2848),P=n(4369),U=n(2168),L=n(5861);function N(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(N=function(e){return e?n:t})(e)}function x(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=N(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}function B(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}const j=h.DeviceInfo.DeviceVerification,F={[b.ReciprocateQRCode.NAME]:b.ReciprocateQRCode,[_.SAS.NAME]:_.SAS,[b.SHOW_QR_CODE_METHOD]:R.IllegalMethod,[b.SCAN_QR_CODE_METHOD]:R.IllegalMethod},K={RECIPROCATE_QR_CODE:b.ReciprocateQRCode.NAME,SAS:_.SAS.NAME};let q;t.verificationMethods=K,t.CryptoEvent=q,function(e){e.DeviceVerificationChanged="deviceVerificationChanged",e.UserTrustStatusChanged="userTrustStatusChanged",e.UserCrossSigningUpdated="userCrossSigningUpdated",e.RoomKeyRequest="crypto.roomKeyRequest",e.RoomKeyRequestCancellation="crypto.roomKeyRequestCancellation",e.KeyBackupStatus="crypto.keyBackupStatus",e.KeyBackupFailed="crypto.keyBackupFailed",e.KeyBackupSessionsRemaining="crypto.keyBackupSessionsRemaining",e.KeySignatureUploadFailure="crypto.keySignatureUploadFailure",e.VerificationRequest="crypto.verification.request",e.Warning="crypto.warning",e.WillUpdateDevices="crypto.willUpdateDevices",e.DevicesUpdated="crypto.devicesUpdated",e.KeysChanged="crossSigning.keysChanged"}(q||(t.CryptoEvent=q={}));class $ extends L.TypedEventEmitter{static getOlmVersion(){return l.OlmDevice.getOlmVersion()}constructor(e,t,n,r,s,o,h){if(super(),this.baseApis=e,this.userId=t,this.deviceId=n,this.clientStore=r,this.cryptoStore=s,this.roomList=o,(0,i.default)(this,"backupManager",void 0),(0,i.default)(this,"crossSigningInfo",void 0),(0,i.default)(this,"olmDevice",void 0),(0,i.default)(this,"deviceList",void 0),(0,i.default)(this,"dehydrationManager",void 0),(0,i.default)(this,"secretStorage",void 0),(0,i.default)(this,"reEmitter",void 0),(0,i.default)(this,"verificationMethods",void 0),(0,i.default)(this,"supportedAlgorithms",void 0),(0,i.default)(this,"outgoingRoomKeyRequestManager",void 0),(0,i.default)(this,"toDeviceVerificationRequests",void 0),(0,i.default)(this,"inRoomVerificationRequests",void 0),(0,i.default)(this,"trustCrossSignedDevices",!0),(0,i.default)(this,"lastOneTimeKeyCheck",null),(0,i.default)(this,"oneTimeKeyCheckInProgress",!1),(0,i.default)(this,"roomEncryptors",new Map),(0,i.default)(this,"roomDecryptors",new Map),(0,i.default)(this,"deviceKeys",{}),(0,i.default)(this,"globalBlacklistUnverifiedDevices",!1),(0,i.default)(this,"globalErrorOnUnknownDevices",!0),(0,i.default)(this,"receivedRoomKeyRequests",[]),(0,i.default)(this,"receivedRoomKeyRequestCancellations",[]),(0,i.default)(this,"processingRoomKeyRequests",!1),(0,i.default)(this,"lazyLoadMembers",!1),(0,i.default)(this,"roomDeviceTrackingState",{}),(0,i.default)(this,"lastNewSessionForced",{}),(0,i.default)(this,"sendKeyRequestsImmediately",!1),(0,i.default)(this,"oneTimeKeyCount",void 0),(0,i.default)(this,"needsNewFallback",void 0),(0,i.default)(this,"fallbackCleanup",void 0),(0,i.default)(this,"onDeviceListUserCrossSigningUpdated",(async e=>{if(e===this.userId){const t=this.deviceList.getStoredCrossSigningForUser(e),n=t?t.getId():null,r=this.crossSigningInfo.getId();r&&n&&r===n?await this.checkOwnCrossSigningTrust():(this.storeTrustedSelfKeys(null),this.emit(q.KeysChanged,{}),this.emit(q.UserTrustStatusChanged,this.userId,this.checkUserTrust(e)))}else{await this.checkDeviceVerifications(e);const t=this.deviceList.getStoredCrossSigningForUser(e);t&&(t.updateCrossSigningVerifiedBefore(this.checkUserTrust(e).isCrossSigningVerified()),this.deviceList.setRawStoredCrossSigningForUser(e,t.toStorage())),this.emit(q.UserTrustStatusChanged,e,this.checkUserTrust(e))}})),(0,i.default)(this,"onMembership",((e,t,n)=>{try{this.onRoomMembership(e,t,n)}catch(e){c.logger.error("Error handling membership change:",e)}})),(0,i.default)(this,"onToDeviceEvent",(e=>{try{c.logger.log(`received to_device ${e.getType()} from: ${e.getSender()} id: ${e.getId()}`),"m.room_key"==e.getType()||"m.forwarded_room_key"==e.getType()?this.onRoomKeyEvent(e):"m.room_key_request"==e.getType()?this.onRoomKeyRequestEvent(e):"m.secret.request"===e.getType()?this.secretStorage.onRequestReceived(e):"m.secret.send"===e.getType()?this.secretStorage.onSecretReceived(e):"m.room_key.withheld"===e.getType()?this.onRoomKeyWithheldEvent(e):e.getContent().transaction_id?this.onKeyVerificationMessage(e):"m.bad.encrypted"===e.getContent().msgtype?this.onToDeviceBadEncrypted(e):(e.isBeingDecrypted()||e.shouldAttemptDecryption())&&(e.isBeingDecrypted()||e.attemptDecryption(this),e.once(P.MatrixEventEvent.Decrypted,(e=>{this.onToDeviceEvent(e)})))}catch(e){c.logger.error("Error handling toDeviceEvent:",e)}})),(0,i.default)(this,"onTimelineEvent",((e,t,n,r,{liveEvent:i=!0}={})=>{C.InRoomChannel.validateEvent(e,this.baseApis)&&this.handleVerificationEvent(e,this.inRoomVerificationRequests,(e=>{const t=new C.InRoomChannel(this.baseApis,e.getRoomId());return new S.VerificationRequest(t,this.verificationMethods,this.baseApis)}),i)})),this.reEmitter=new a.TypedReEmitter(this),h){this.verificationMethods=new Map;for(const e of h)"string"==typeof e?F[e]&&this.verificationMethods.set(e,F[e]):e.NAME?this.verificationMethods.set(e.NAME,e):c.logger.warn(`Excluding unknown verification method ${e}`)}else this.verificationMethods=new Map(Object.entries(F));this.backupManager=new A.BackupManager(e,(async()=>{const e=await this.getSessionBackupPrivateKey();if(e)return e;const t=await this.getSecret("m.megolm_backup.v1");if(t){const e=V(t);if(e){const[t]=await this.getSecretStorageKey();await this.storeSecret("m.megolm_backup.v1",e,[t])}return d.decodeBase64(e||t)}if(this.baseApis.cryptoCallbacks&&this.baseApis.cryptoCallbacks.getBackupKey)return this.baseApis.cryptoCallbacks.getBackupKey();throw new Error("Unable to get private key")})),this.olmDevice=new l.OlmDevice(s),this.deviceList=new u.DeviceList(e,s,this.olmDevice),this.deviceList.on(q.UserCrossSigningUpdated,this.onDeviceListUserCrossSigningUpdated),this.reEmitter.reEmit(this.deviceList,[q.DevicesUpdated,q.WillUpdateDevices]),this.supportedAlgorithms=Array.from(f.DECRYPTION_CLASSES.keys()),this.outgoingRoomKeyRequestManager=new y.OutgoingRoomKeyRequestManager(e,this.deviceId,this.cryptoStore),this.toDeviceVerificationRequests=new T.ToDeviceRequests,this.inRoomVerificationRequests=new C.InRoomRequests;const p=this.baseApis.cryptoCallbacks||{},v=(0,g.createCryptoStoreCacheCallbacks)(s,this.olmDevice);this.crossSigningInfo=new g.CrossSigningInfo(t,p,v),this.secretStorage=new m.SecretStorage(e,p,e),this.dehydrationManager=new O.DehydrationManager(this),!p.getCrossSigningKey&&p.getSecretStorageKey&&(p.getCrossSigningKey=async e=>g.CrossSigningInfo.getFromSecretStorage(e,this.secretStorage))}async init({exportedOlmDevice:e,pickleKey:t}={}){c.logger.log("Crypto: initialising Olm..."),await n.g.Olm.init(),c.logger.log(e?"Crypto: initialising Olm device from exported device...":"Crypto: initialising Olm device..."),await this.olmDevice.init({fromExportedDevice:e,pickleKey:t}),c.logger.log("Crypto: loading device list..."),await this.deviceList.load(),this.deviceKeys["ed25519:"+this.deviceId]=this.olmDevice.deviceEd25519Key,this.deviceKeys["curve25519:"+this.deviceId]=this.olmDevice.deviceCurve25519Key,c.logger.log("Crypto: fetching own devices...");let r=this.deviceList.getRawStoredDevicesForUser(this.userId);if(r||(r={}),!r[this.deviceId]){c.logger.log("Crypto: adding this device to the store...");const e={keys:this.deviceKeys,algorithms:this.supportedAlgorithms,verified:j.VERIFIED,known:!0};r[this.deviceId]=e,this.deviceList.storeDevicesForUser(this.userId,r),this.deviceList.saveIfDirty()}await this.cryptoStore.doTxn("readonly",[v.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.getCrossSigningKeys(e,(e=>{e&&0!==Object.keys(e).length&&(c.logger.log("Loaded cross-signing public keys from crypto store"),this.crossSigningInfo.setKeys(e))}))})),this.deviceList.startTrackingDeviceList(this.userId),c.logger.log("Crypto: checking for key backup..."),this.backupManager.checkAndStart()}getCryptoTrustCrossSignedDevices(){return this.trustCrossSignedDevices}setCryptoTrustCrossSignedDevices(e){this.trustCrossSignedDevices=e;for(const e of this.deviceList.getKnownUserIds()){const t=this.deviceList.getRawStoredDevicesForUser(e);for(const n of Object.keys(t)){const t=this.checkDeviceTrust(e,n);if(!t.isLocallyVerified()&&t.isCrossSigningVerified()){const t=this.deviceList.getStoredDevice(e,n);this.emit(q.DeviceVerificationChanged,e,n,t)}}}}async createRecoveryKeyFromPassphrase(e){const t=new n.g.Olm.PkDecryption;try{const n={};if(e){const r=await(0,E.keyFromPassphrase)(e);n.passphrase={algorithm:"m.pbkdf2",iterations:r.iterations,salt:r.salt},n.pubkey=t.init_with_private_key(r.key)}else n.pubkey=t.generate_key();const r=t.get_private_key();return{keyInfo:n,encodedPrivateKey:(0,w.encodeRecoveryKey)(r),privateKey:r}}finally{t&&t.free()}}async isCrossSigningReady(){const e=this.crossSigningInfo.getId(),t=await this.crossSigningInfo.isStoredInKeyCache()||await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage);return!(!e||!t)}async isSecretStorageReady(){const e=await this.secretStorage.hasKey(),t=await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),n=!this.backupManager.getKeyBackupEnabled()||await this.baseApis.isKeyBackupKeyStored();return!!(e&&t&&n)}async bootstrapCrossSigning({authUploadDeviceSigningKeys:e,setupNewCrossSigning:t}={}){c.logger.log("Bootstrapping cross-signing");const n=this.baseApis.cryptoCallbacks,r=new p.EncryptionSetupBuilder(this.baseApis.store.accountData,n),i=new g.CrossSigningInfo(this.userId,r.crossSigningCallbacks,r.crossSigningCallbacks),s=this.crossSigningInfo.getId(),o=await this.crossSigningInfo.isStoredInKeyCache(),a=await this.crossSigningInfo.isStoredInSecretStorage(this.secretStorage),l=o||a;c.logger.log({setupNewCrossSigning:t,publicKeysOnDevice:s,privateKeysInCache:o,privateKeysInStorage:a,privateKeysExistSomewhere:l}),!l||t?(c.logger.log("Cross-signing private keys not found locally or in secret storage, creating new keys"),await(async()=>{i.resetKeys(),await this.signObject(i.keys.master),r.addCrossSigningKeys(e,i.keys);const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),n=await i.signDevice(this.userId,t);r.addKeySignature(this.userId,this.deviceId,n),this.backupManager.backupInfo&&(await i.signObject(this.backupManager.backupInfo.auth_data,"master"),r.addSessionBackup(this.backupManager.backupInfo))})()):s&&o?c.logger.log("Cross-signing public keys trusted and private keys found locally"):a&&(c.logger.log("Cross-signing private keys not found locally, but they are available in secret storage, reading storage and caching locally"),await this.checkOwnCrossSigningTrust({allowPrivateKeyRequests:!0}));const d=r.crossSigningCallbacks.privateKeys;if(d.size&&!this.baseApis.cryptoCallbacks.saveCrossSigningKeys){const e=new m.SecretStorage(r.accountDataClientAdapter,r.ssssCryptoCallbacks);await e.hasKey()&&(c.logger.log("Storing new cross-signing private keys in secret storage"),await g.CrossSigningInfo.storeInSecretStorage(d,e))}const u=r.buildOperation();await u.apply(this),await r.persist(this),c.logger.log("Cross-signing ready")}async bootstrapSecretStorage({createSecretStorageKey:e=(async()=>({})),keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:r,getKeyBackupPassphrase:i}={}){c.logger.log("Bootstrapping Secure Secret Storage");const s=this.baseApis.cryptoCallbacks,o=new p.EncryptionSetupBuilder(this.baseApis.store.accountData,s),a=new m.SecretStorage(o.accountDataClientAdapter,o.ssssCryptoCallbacks);let l=null;const u=async(e,t)=>{t&&(e.key=t);const{keyId:n,keyInfo:r}=await a.addKey(m.SECRET_STORAGE_ALGORITHM_V1_AES,e);return t&&o.ssssCryptoCallbacks.addPrivateKey(n,r,t),await a.setDefaultKeyId(n),n},h=async e=>{if(this.crossSigningInfo.getId()&&await this.crossSigningInfo.isStoredInKeyCache("master"))try{c.logger.log("Adding cross-signing signature to key backup"),await this.crossSigningInfo.signObject(e,"master")}catch(e){c.logger.error("Signing key backup with cross-signing keys failed",e)}else c.logger.warn("Cross-signing keys not available, skipping signature on key backup")},f=await this.getSecretStorageKey(),[y,v]=f||[null,null],b=!r&&v&&v.algorithm===m.SECRET_STORAGE_ALGORITHM_V1_AES;if(c.logger.log({keyBackupInfo:t,setupNewKeyBackup:n,setupNewSecretStorage:r,storageExists:b,oldKeyInfo:v}),b||t)if(!b&&t){c.logger.log("Secret storage does not exist, using key backup key");const e=await this.getSessionBackupPrivateKey()||await i(),n={};t.auth_data.private_key_salt&&t.auth_data.private_key_iterations&&(n.passphrase={algorithm:"m.pbkdf2",iterations:t.auth_data.private_key_iterations,salt:t.auth_data.private_key_salt,bits:256}),l=await u(n,e),await a.store("m.megolm_backup.v1",d.encodeBase64(e),[l]),await h(t.auth_data),o.addSessionBackup(t)}else c.logger.log("Secret storage exists"),v&&v.algorithm===m.SECRET_STORAGE_ALGORITHM_V1_AES&&await(async(e,t)=>{if(!t.mac){const n=await this.baseApis.cryptoCallbacks.getSecretStorageKey({keys:{[e]:t}},"");if(n){const r=n[1];o.ssssCryptoCallbacks.addPrivateKey(e,t,r);const{iv:i,mac:s}=await(0,k.calculateKeyCheck)(r);t.iv=i,t.mac=s,await o.setAccountData(`m.secret_storage.key.${e}`,t)}}})(y,v);else{c.logger.log("Secret storage does not exist, creating new storage key");const{keyInfo:t={},privateKey:n}=await e();l=await u(t,n)}if(!this.baseApis.cryptoCallbacks.saveCrossSigningKeys&&await this.isCrossSigningReady()&&(l||!await this.crossSigningInfo.isStoredInSecretStorage(a))){c.logger.log("Copying cross-signing private keys from cache to secret storage");const e=await this.crossSigningInfo.getCrossSigningKeysFromCache();await g.CrossSigningInfo.storeInSecretStorage(e,a)}if(n&&!t){c.logger.log("Creating new message key backup version");const e=await this.baseApis.prepareKeyBackupVersion(null,{secureSecretStorage:!1}),t=(0,w.decodeRecoveryKey)(e.recovery_key);await a.store("m.megolm_backup.v1",d.encodeBase64(t));const n={algorithm:e.algorithm,auth_data:e.auth_data};await h(n.auth_data),await this.signObject(n.auth_data),o.addSessionBackup(n)}const _=await a.get("m.megolm_backup.v1");if(_){c.logger.info("Got session backup key from secret storage: caching");const e=V(_);e&&await a.store("m.megolm_backup.v1",e,[l||y]);const t=new Uint8Array(d.decodeBase64(e||_));o.addSessionBackupPrivateKeyToCache(t)}else if(this.backupManager.getKeyBackupEnabled()){const e=await this.getSessionBackupPrivateKey()||await i();if(!e)return void c.logger.error("Key backup is enabled but couldn't get key backup key!");c.logger.info("Got session backup key from cache/user that wasn't in SSSS: saving to SSSS"),await a.store("m.megolm_backup.v1",d.encodeBase64(e))}const E=o.buildOperation();await E.apply(this),await o.persist(this),c.logger.log("Secure Secret Storage ready")}addSecretStorageKey(e,t,n){return this.secretStorage.addKey(e,t,n)}hasSecretStorageKey(e){return this.secretStorage.hasKey(e)}getSecretStorageKey(e){return this.secretStorage.getKey(e)}storeSecret(e,t,n){return this.secretStorage.store(e,t,n)}getSecret(e){return this.secretStorage.get(e)}isSecretStored(e){return this.secretStorage.isStored(e)}requestSecret(e,t){return t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(this.userId))),this.secretStorage.request(e,t)}getDefaultSecretStorageKeyId(){return this.secretStorage.getDefaultKeyId()}setDefaultSecretStorageKeyId(e){return this.secretStorage.setDefaultKeyId(e)}checkSecretStorageKey(e,t){return this.secretStorage.checkKey(e,t)}checkSecretStoragePrivateKey(e,t){let r=null;try{return r=new n.g.Olm.PkDecryption,r.init_with_private_key(e)===t}finally{r&&r.free()}}async getSessionBackupPrivateKey(){let e=await new Promise((e=>{this.cryptoStore.doTxn("readonly",[v.IndexedDBCryptoStore.STORE_ACCOUNT],(t=>{this.cryptoStore.getSecretStorePrivateKey(t,e,"m.megolm_backup.v1")}))}));if(e&&"string"==typeof e&&(e=new Uint8Array(d.decodeBase64(V(e)||e)),await this.storeSessionBackupPrivateKey(e)),e&&e.ciphertext){const t=Buffer.from(this.olmDevice.pickleKey),n=await(0,k.decryptAES)(e,t,"m.megolm_backup.v1");e=d.decodeBase64(n)}return e}async storeSessionBackupPrivateKey(e){if(!(e instanceof Uint8Array))throw new Error(`storeSessionBackupPrivateKey expects Uint8Array, got ${e}`);const t=Buffer.from(this.olmDevice.pickleKey),n=await(0,k.encryptAES)(d.encodeBase64(e),t,"m.megolm_backup.v1");return this.cryptoStore.doTxn("readwrite",[v.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeSecretStorePrivateKey(e,"m.megolm_backup.v1",n)}))}checkCrossSigningPrivateKey(e,t){let r=null;try{return r=new n.g.Olm.PkSigning,r.init_with_seed(e)===t}finally{r&&r.free()}}async afterCrossSigningLocalKeyChange(){c.logger.info("Starting cross-signing key change post-processing");const e=this.deviceList.getStoredDevice(this.userId,this.deviceId),t=await this.crossSigningInfo.signDevice(this.userId,e);c.logger.info(`Starting background key sig upload for ${this.deviceId}`);const n=({shouldEmit:e=!1})=>this.baseApis.uploadKeySignatures({[this.userId]:{[this.deviceId]:t}}).then((t=>{const{failures:r}=t||{};if(Object.keys(r||[]).length>0)throw e&&this.baseApis.emit(q.KeySignatureUploadFailure,r,"afterCrossSigningLocalKeyChange",n),new I.KeySignatureUploadError("Key upload failed",{failures:r});c.logger.info(`Finished background key sig upload for ${this.deviceId}`)})).catch((e=>{c.logger.error(`Error during background key sig upload for ${this.deviceId}`,e)}));n({shouldEmit:!0});const r=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(r){c.logger.info("Starting device verification upgrade");const e={};for(const[t,n]of Object.entries(this.deviceList.crossSigningInfo)){const r=await this.checkForDeviceVerificationUpgrade(t,g.CrossSigningInfo.fromStorage(n,t));r&&(e[t]=r)}if(Object.keys(e).length>0){c.logger.info(`Found ${Object.keys(e).length} verif users to upgrade`);try{const t=await r({users:e});if(t)for(const n of t)n in e&&await this.baseApis.setDeviceVerified(n,e[n].crossSigningInfo.getId())}catch(e){c.logger.log("shouldUpgradeDeviceVerifications threw an error: not upgrading",e)}}c.logger.info("Finished device verification upgrade")}c.logger.info("Finished cross-signing key change post-processing")}async checkForDeviceVerificationUpgrade(e,t){const n=this.crossSigningInfo.checkUserTrust(t);if(t.firstUse&&!n.isVerified()){const n=this.deviceList.getRawStoredDevicesForUser(e),r=await this.checkForValidDeviceSignature(e,t.keys.master,n);if(r.length)return{devices:r.map((e=>h.DeviceInfo.fromStorage(n[e],e))),crossSigningInfo:t}}}async checkForValidDeviceSignature(e,t,n){const r=[];if(n&&t.signatures&&t.signatures[e])for(const i of Object.keys(t.signatures[e])){const[,s]=i.split(":",2);if(s in n&&n[s].verified===j.VERIFIED)try{await d.verifySignature(this.olmDevice,t,e,s,n[s].keys[i]),r.push(s)}catch(e){}}return r}getCrossSigningId(e){return this.crossSigningInfo.getId(e)}getStoredCrossSigningForUser(e){return this.deviceList.getStoredCrossSigningForUser(e)}checkUserTrust(e){const t=this.deviceList.getStoredCrossSigningForUser(e);return t?this.crossSigningInfo.checkUserTrust(t):new g.UserTrustLevel(!1,!1,!1)}checkDeviceTrust(e,t){const n=this.deviceList.getStoredDevice(e,t);return this.checkDeviceInfoTrust(e,n)}checkDeviceInfoTrust(e,t){const n=!(!t||!t.isVerified()),r=this.deviceList.getStoredCrossSigningForUser(e);if(t&&r){const i=this.trustCrossSignedDevices||e===this.userId;return this.crossSigningInfo.checkDeviceTrust(r,t,n,i)}return new g.DeviceTrustLevel(!1,!1,n,!1)}checkIfOwnDeviceCrossSigned(e){const t=this.deviceList.getStoredDevice(this.userId,e),n=this.deviceList.getStoredCrossSigningForUser(this.userId);return n.checkDeviceTrust(n,t,!1,!0).isCrossSigningVerified()}async checkOwnCrossSigningTrust({allowPrivateKeyRequests:e=!1}={}){const t=this.userId;await this.downloadKeys([this.userId]);const n=await this.crossSigningInfo.getCrossSigningKeysFromCache(),r=this.deviceList.getStoredCrossSigningForUser(t);if(!r)return void c.logger.error("Got cross-signing update event for user "+t+" but no new cross-signing information found!");const i=r.getId(),s=this.crossSigningInfo.getId()!==i,o=r.getId()&&!n.has("master");if(s&&c.logger.info("Got new master public key",i),e&&(s||o)){c.logger.info("Attempting to retrieve cross-signing master private key");let e=null;try{e=(await this.crossSigningInfo.getCrossSigningKey("master",i))[1],c.logger.info("Got cross-signing master private key")}finally{e&&e.free()}}const a=this.crossSigningInfo.getId("self_signing"),l=this.crossSigningInfo.getId("user_signing");this.storeTrustedSelfKeys(r.keys);const d=a!==r.getId("self_signing"),u=l!==r.getId("user_signing"),h=r.getId("self_signing")&&!n.has("self_signing"),f=r.getId("user_signing")&&!n.has("user_signing"),g={};if(d&&c.logger.info("Got new self-signing key",r.getId("self_signing")),e&&(d||h)){c.logger.info("Attempting to retrieve cross-signing self-signing private key");let e=null;try{e=(await this.crossSigningInfo.getCrossSigningKey("self_signing",r.getId("self_signing")))[1],c.logger.info("Got cross-signing self-signing private key")}finally{e&&e.free()}const t=this.deviceList.getStoredDevice(this.userId,this.deviceId),n=await this.crossSigningInfo.signDevice(this.userId,t);g[this.deviceId]=n}if(u&&c.logger.info("Got new user-signing key",r.getId("user_signing")),e&&(u||f)){c.logger.info("Attempting to retrieve cross-signing user-signing private key");let e=null;try{e=(await this.crossSigningInfo.getCrossSigningKey("user_signing",r.getId("user_signing")))[1],c.logger.info("Got cross-signing user-signing private key")}finally{e&&e.free()}}if(s){const e=this.crossSigningInfo.keys.master;await this.signObject(e);const t=e.signatures[this.userId]["ed25519:"+this.deviceId];g[this.crossSigningInfo.getId()]=Object.assign({},e,{signatures:{[this.userId]:{["ed25519:"+this.deviceId]:t}}})}const p=Object.keys(g);if(p.length){const e=({shouldEmit:t=!1})=>(c.logger.info(`Starting background key sig upload for ${p}`),this.baseApis.uploadKeySignatures({[this.userId]:g}).then((n=>{const{failures:r}=n||{};if(c.logger.info(`Finished background key sig upload for ${p}`),Object.keys(r||[]).length>0)throw t&&this.baseApis.emit(q.KeySignatureUploadFailure,r,"checkOwnCrossSigningTrust",e),new I.KeySignatureUploadError("Key upload failed",{failures:r})})).catch((e=>{c.logger.error(`Error during background key sig upload for ${p}`,e)})));e({shouldEmit:!0})}this.emit(q.UserTrustStatusChanged,t,this.checkUserTrust(t)),s&&(this.emit(q.KeysChanged,{}),await this.afterCrossSigningLocalKeyChange()),await this.backupManager.checkKeyBackup()}async storeTrustedSelfKeys(e){e?this.crossSigningInfo.setKeys(e):this.crossSigningInfo.clearKeys(),await this.cryptoStore.doTxn("readwrite",[v.IndexedDBCryptoStore.STORE_ACCOUNT],(e=>{this.cryptoStore.storeCrossSigningKeys(e,this.crossSigningInfo.keys)}))}async checkDeviceVerifications(e){const t=this.baseApis.cryptoCallbacks.shouldUpgradeDeviceVerifications;if(t){if(c.logger.info(`Starting device verification upgrade for ${e}`),this.crossSigningInfo.keys.user_signing){const n=this.deviceList.getStoredCrossSigningForUser(e);if(n){const r=await this.checkForDeviceVerificationUpgrade(e,n);r&&(await t({users:{[e]:r}})).includes(e)&&await this.baseApis.setDeviceVerified(e,n.getId())}}c.logger.info(`Finished device verification upgrade for ${e}`)}}enableLazyLoading(){this.lazyLoadMembers=!0}registerEventHandlers(e){e.on(M.RoomMemberEvent.Membership,this.onMembership),e.on(U.ClientEvent.ToDeviceEvent,this.onToDeviceEvent),e.on(D.RoomEvent.Timeline,this.onTimelineEvent),e.on(P.MatrixEventEvent.Decrypted,this.onTimelineEvent)}start(){this.outgoingRoomKeyRequestManager.start()}stop(){this.outgoingRoomKeyRequestManager.stop(),this.deviceList.stop(),this.dehydrationManager.stop()}getDeviceEd25519Key(){return this.olmDevice.deviceEd25519Key}getDeviceCurve25519Key(){return this.olmDevice.deviceCurve25519Key}setGlobalBlacklistUnverifiedDevices(e){this.globalBlacklistUnverifiedDevices=e}getGlobalBlacklistUnverifiedDevices(){return this.globalBlacklistUnverifiedDevices}setGlobalErrorOnUnknownDevices(e){this.globalErrorOnUnknownDevices=e}getGlobalErrorOnUnknownDevices(){return this.globalErrorOnUnknownDevices}uploadDeviceKeys(){const e={algorithms:this.supportedAlgorithms,device_id:this.deviceId,keys:this.deviceKeys,user_id:this.userId};return this.signObject(e).then((()=>this.baseApis.uploadKeysRequest({device_keys:e})))}updateOneTimeKeyCount(e){if(!isFinite(e))throw new TypeError("Parameter for updateOneTimeKeyCount has to be a number");this.oneTimeKeyCount=e}setNeedsNewFallback(e){this.needsNewFallback=!!e}getNeedsNewFallback(){return this.needsNewFallback}maybeUploadOneTimeKeys(){if(this.oneTimeKeyCheckInProgress)return;const e=Date.now();if(null!==this.lastOneTimeKeyCheck&&e-this.lastOneTimeKeyCheck<6e4)return;this.lastOneTimeKeyCheck=e;const t=this.olmDevice.maxNumberOfOneTimeKeys(),n=Math.floor(t/2),r=async e=>{for(;n>e||this.getNeedsNewFallback();){if(n>e){c.logger.info("generating oneTimeKeys");const t=Math.min(n-e,5);await this.olmDevice.generateOneTimeKeys(t)}if(this.getNeedsNewFallback()){const e=await this.olmDevice.getFallbackKey();e.curve25519&&0!=Object.keys(e.curve25519).length||(c.logger.info("generating fallback key"),this.fallbackCleanup&&(clearTimeout(this.fallbackCleanup),delete this.fallbackCleanup),await this.olmDevice.generateFallbackKey())}c.logger.info("calling uploadOneTimeKeys");const t=await this.uploadOneTimeKeys();if(!t.one_time_key_counts||!t.one_time_key_counts.signed_curve25519)throw new Error("response for uploading keys does not contain one_time_key_counts.signed_curve25519");e=t.one_time_key_counts.signed_curve25519}};this.oneTimeKeyCheckInProgress=!0,Promise.resolve().then((()=>void 0!==this.oneTimeKeyCount?Promise.resolve(this.oneTimeKeyCount):this.baseApis.uploadKeysRequest({}).then((e=>e.one_time_key_counts.signed_curve25519||0)))).then((e=>r(e))).catch((e=>{c.logger.error("Error uploading one-time keys",e.stack||e)})).finally((()=>{this.oneTimeKeyCount=void 0,this.oneTimeKeyCheckInProgress=!1}))}async uploadOneTimeKeys(){const e=[];let t;if(this.getNeedsNewFallback()){t={};const n=await this.olmDevice.getFallbackKey();for(const[r,i]of Object.entries(n.curve25519)){const n={key:i,fallback:!0};t["signed_curve25519:"+r]=n,e.push(this.signObject(n))}this.setNeedsNewFallback(!1)}const n=await this.olmDevice.getOneTimeKeys(),r={};for(const t in n.curve25519)if(n.curve25519.hasOwnProperty(t)){const i={key:n.curve25519[t]};r["signed_curve25519:"+t]=i,e.push(this.signObject(i))}await Promise.all(e);const i={one_time_keys:r};t&&(i["org.matrix.msc2732.fallback_keys"]=t,i.fallback_keys=t);const s=await this.baseApis.uploadKeysRequest(i);return t&&(this.fallbackCleanup=setTimeout((()=>{delete this.fallbackCleanup,this.olmDevice.forgetOldFallbackKey()}),36e5)),await this.olmDevice.markKeysAsPublished(),s}downloadKeys(e,t){return this.deviceList.downloadKeys(e,t)}getStoredDevicesForUser(e){return this.deviceList.getStoredDevicesForUser(e)}getStoredDevice(e,t){return this.deviceList.getStoredDevice(e,t)}saveDeviceList(e){return this.deviceList.saveIfDirty(e)}async setDeviceVerification(e,t,n,r,i){void 0===n&&(n=null),void 0===r&&(r=null),void 0===i&&(i=null);const s=this.deviceList.getStoredCrossSigningForUser(e);if(s&&s.getId()===t){if(null!==r||null!==i)throw new Error("Cannot set blocked or known for a cross-signing key");if(!n)throw new Error("Cannot set a cross-signing key as unverified");if(this.crossSigningInfo.getId()||e!==this.crossSigningInfo.userId||(this.storeTrustedSelfKeys(s.keys),this.emit(q.UserTrustStatusChanged,this.userId,this.checkUserTrust(e))),e!==this.userId){c.logger.info("Master key "+s.getId()+" for "+e+" marked verified. Signing...");const n=await this.crossSigningInfo.signUser(s);if(n){const r=async({shouldEmit:i=!1})=>{c.logger.info("Uploading signature for "+e+"...");const s=await this.baseApis.uploadKeySignatures({[e]:{[t]:n}}),{failures:o}=s||{};if(Object.keys(o||[]).length>0)throw i&&this.baseApis.emit(q.KeySignatureUploadFailure,o,"setDeviceVerification",r),new I.KeySignatureUploadError("Key upload failed",{failures:o})};await r({shouldEmit:!0})}return n}return s}const o=this.deviceList.getRawStoredDevicesForUser(e);if(!o||!o[t])throw new Error("Unknown device "+e+":"+t);const a=o[t];let l=a.verified;n?l=j.VERIFIED:null!==n&&l==j.VERIFIED&&(l=j.UNVERIFIED),r?l=j.BLOCKED:null!==r&&l==j.BLOCKED&&(l=j.UNVERIFIED);let d=a.known;if(null!==i&&(d=i),a.verified===l&&a.known===d||(a.verified=l,a.known=d,this.deviceList.storeDevicesForUser(e,o),this.deviceList.saveIfDirty()),n&&e===this.userId){let n;if(c.logger.info("Own device "+t+" marked verified: signing"),this.checkDeviceTrust(e,t).isCrossSigningVerified()?c.logger.log(`Own device ${t} already cross-signing verified`):n=await this.crossSigningInfo.signDevice(e,h.DeviceInfo.fromStorage(a,t)),n){const r=async({shouldEmit:i=!1})=>{c.logger.info("Uploading signature for "+t);const s=await this.baseApis.uploadKeySignatures({[e]:{[t]:n}}),{failures:o}=s||{};if(Object.keys(o||[]).length>0)throw i&&this.baseApis.emit(q.KeySignatureUploadFailure,o,"setDeviceVerification",r),new I.KeySignatureUploadError("Key upload failed",{failures:o})};await r({shouldEmit:!0})}}const u=h.DeviceInfo.fromStorage(a,t);return this.emit(q.DeviceVerificationChanged,e,t,u),u}findVerificationRequestDMInProgress(e){return this.inRoomVerificationRequests.findRequestInProgress(e)}getVerificationRequestsToDeviceInProgress(e){return this.toDeviceVerificationRequests.getRequestsInProgress(e)}requestVerificationDM(e,t){const n=this.inRoomVerificationRequests.findRequestInProgress(t);if(n)return Promise.resolve(n);const r=new C.InRoomChannel(this.baseApis,t,e);return this.requestVerificationWithChannel(e,r,this.inRoomVerificationRequests)}requestVerification(e,t){t||(t=Object.keys(this.deviceList.getRawStoredDevicesForUser(e)));const n=this.toDeviceVerificationRequests.findRequestInProgress(e,t);if(n)return Promise.resolve(n);const r=new T.ToDeviceChannel(this.baseApis,e,t,T.ToDeviceChannel.makeTransactionId());return this.requestVerificationWithChannel(e,r,this.toDeviceVerificationRequests)}async requestVerificationWithChannel(e,t,n){let r=new S.VerificationRequest(t,this.verificationMethods,this.baseApis);t.transactionId&&n.setRequestByChannel(t,r),await r.sendRequest();const i=n.getRequestByChannel(t);return i?r=i:(c.logger.log(`Crypto: adding new request to requestsByTxnId with id ${t.transactionId} ${t.roomId}`),n.setRequestByChannel(t,r)),r}beginKeyVerification(e,t,n,r=null){let i;if(r){if(i=this.toDeviceVerificationRequests.getRequestBySenderAndTxnId(t,r),!i)throw new Error(`No request found for user ${t} with transactionId ${r}`)}else{r=T.ToDeviceChannel.makeTransactionId();const e=new T.ToDeviceChannel(this.baseApis,t,[n],r,n);i=new S.VerificationRequest(e,this.verificationMethods,this.baseApis),this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(t,r,i)}return i.beginKeyVerification(e,{userId:t,deviceId:n})}async legacyDeviceVerification(e,t,n){const r=T.ToDeviceChannel.makeTransactionId(),i=new T.ToDeviceChannel(this.baseApis,e,[t],r,t),s=new S.VerificationRequest(i,this.verificationMethods,this.baseApis);this.toDeviceVerificationRequests.setRequestBySenderAndTxnId(e,r,s);const o=s.beginKeyVerification(n,{userId:e,deviceId:t});return await Promise.race([o.verify(),s.waitFor((e=>e.started))]),s}async getOlmSessionsForUser(e){const t=this.getStoredDevicesForUser(e)||[],n={};for(let e=0;e<t.length;++e){const r=t[e],i=r.getIdentityKey(),s=await this.olmDevice.getSessionInfoForDevice(i);n[r.deviceId]={deviceIdKey:i,sessions:s}}return n}getEventSenderDeviceInfo(e){const t=e.getSenderKey(),n=e.getWireContent().algorithm;if(!t||!n)return null;if(e.getForwardingCurve25519KeyChain().length>0)return null;if(e.isKeySourceUntrusted())return null;const r=this.deviceList.getDeviceByIdentityKey(n,t);if(null===r)return null;const i=e.getClaimedEd25519Key();return i?i!==r.getFingerprint()?(c.logger.warn("Event "+e.getId()+" claims ed25519 key "+i+" but sender device has key "+r.getFingerprint()),null):r:(c.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),null)}getEventEncryptionInfo(e){const t={};if(t.senderKey=e.getSenderKey(),t.algorithm=e.getWireContent().algorithm,!t.senderKey||!t.algorithm)return t.encrypted=!1,t;t.encrypted=!0,e.getForwardingCurve25519KeyChain().length>0||e.isKeySourceUntrusted()?t.authenticated=!1:t.authenticated=!0,t.sender=this.deviceList.getDeviceByIdentityKey(t.algorithm,t.senderKey);const n=e.getClaimedEd25519Key();return n||(c.logger.warn("Event "+e.getId()+" claims no ed25519 key: cannot verify sending device"),t.mismatchedSender=!0),t.sender&&n!==t.sender.getFingerprint()&&(c.logger.warn("Event "+e.getId()+" claims ed25519 key "+n+"but sender device has key "+t.sender.getFingerprint()),t.mismatchedSender=!0),t}forceDiscardSession(e){const t=this.roomEncryptors.get(e);if(void 0===t)throw new Error("Room not encrypted");if(void 0===t.forceDiscardSession)throw new Error("Room encryption algorithm doesn't support session discarding");t.forceDiscardSession()}async setRoomEncryption(e,t,n){if(!t.algorithm)return void c.logger.log("Ignoring setRoomEncryption with no algorithm");const r=this.roomList.getRoomEncryption(e);if(r&&JSON.stringify(r)!=JSON.stringify(t))return void c.logger.error("Ignoring m.room.encryption event which requests a change of config in "+e);if(this.roomEncryptors.get(e))return;let i=null;r||(i=this.roomList.setRoomEncryption(e,t));const s=f.ENCRYPTION_CLASSES.get(t.algorithm);if(!s)throw new Error("Unable to encrypt with "+t.algorithm);const o=new s({userId:this.userId,deviceId:this.deviceId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:e,config:t});this.roomEncryptors.set(e,o),i&&await i,this.lazyLoadMembers?c.logger.log("Enabling encryption in "+e):(c.logger.log("Enabling encryption in "+e+"; starting to track device lists for all users therein"),await this.trackRoomDevices(e),n||this.deviceList.refreshOutdatedDeviceLists())}trackRoomDevices(e){let t=this.roomDeviceTrackingState[e];return t||(t=(async()=>{if(!this.roomEncryptors.has(e))return;const t=this.clientStore.getRoom(e);if(!t)throw new Error(`Unable to start tracking devices in unknown room ${e}`);c.logger.log(`Starting to track devices for room ${e} ...`),(await t.getEncryptionTargetMembers()).forEach((e=>{this.deviceList.startTrackingDeviceList(e.userId)}))})(),this.roomDeviceTrackingState[e]=t.catch((t=>{throw this.roomDeviceTrackingState[e]=null,t}))),t}ensureOlmSessionsForUsers(e,t){const n={};for(let t=0;t<e.length;++t){const r=e[t];n[r]=[];const i=this.getStoredDevicesForUser(r)||[];for(let e=0;e<i.length;++e){const t=i[e];t.getIdentityKey()!=this.olmDevice.deviceCurve25519Key&&t.verified!=j.BLOCKED&&n[r].push(t)}}return d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,n,t)}async exportRoomKeys(){const e=[];return await this.cryptoStore.doTxn("readonly",[v.IndexedDBCryptoStore.STORE_INBOUND_GROUP_SESSIONS],(t=>{this.cryptoStore.getAllEndToEndInboundGroupSessions(t,(t=>{if(null===t)return;const n=this.olmDevice.exportInboundGroupSession(t.senderKey,t.sessionId,t.sessionData);delete n.first_known_index,n.algorithm=d.MEGOLM_ALGORITHM,e.push(n)}))})),e}importRoomKeys(e,t={}){let n=0,r=0;const i=e.length;function s(){t.progressCallback({stage:"load_keys",successes:n,failures:r,total:i})}return Promise.all(e.map((e=>e.room_id&&e.algorithm?this.getRoomDecryptor(e.room_id,e.algorithm).importRoomKey(e,t).finally((()=>{n++,t.progressCallback&&s()})):(c.logger.warn("ignoring room key entry with missing fields",e),r++,t.progressCallback&&s(),null)))).then()}countSessionsNeedingBackup(){return this.backupManager.countSessionsNeedingBackup()}prepareToEncrypt(e){const t=this.roomEncryptors.get(e.roomId);t&&t.prepareToEncrypt(e)}async encryptEvent(e,t){if(!t)throw new Error("Cannot send encrypted messages in unknown rooms");const n=e.getRoomId(),r=this.roomEncryptors.get(n);if(!r)throw new Error("Room was previously configured to use encryption, but is no longer. Perhaps the homeserver is hiding the configuration event.");this.roomDeviceTrackingState[n]||this.trackRoomDevices(n),await this.roomDeviceTrackingState[n];let i=e.getContent();const s=i["m.relates_to"];s&&(i=Object.assign({},i),delete i["m.relates_to"]);const o=i["io.element.performance_metrics"];o&&(i=Object.assign({},i),delete i["io.element.performance_metrics"]);const a=await r.encryptMessage(t,e.getType(),i);s&&(a["m.relates_to"]=s),o&&(a["io.element.performance_metrics"]=o),e.makeEncrypted("m.room.encrypted",a,this.olmDevice.deviceCurve25519Key,this.olmDevice.deviceEd25519Key)}async decryptEvent(e){if(e.isRedacted()){const t=new P.MatrixEvent(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?B(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):B(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({room_id:e.getRoomId()},e.getUnsigned().redacted_because)),n=await this.decryptEvent(t);return{clearEvent:{room_id:e.getRoomId(),type:"m.room.message",content:{},unsigned:{redacted_because:n.clearEvent}}}}{const t=e.getWireContent();return this.getRoomDecryptor(e.getRoomId(),t.algorithm).decryptEvent(e)}}async handleDeviceListChanges(e,t){e.oldSyncToken&&await this.evalDeviceListChanges(t)}requestRoomKey(e,t,n=!1){return this.outgoingRoomKeyRequestManager.queueRoomKeyRequest(e,t,n).then((()=>{this.sendKeyRequestsImmediately&&this.outgoingRoomKeyRequestManager.sendQueuedRequests()})).catch((e=>{c.logger.error("Error requesting key for event",e)}))}cancelRoomKeyRequest(e){this.outgoingRoomKeyRequestManager.cancelRoomKeyRequest(e).catch((e=>{c.logger.warn("Error clearing pending room key requests",e)}))}async cancelAndResendAllOutgoingKeyRequests(){await this.outgoingRoomKeyRequestManager.cancelAndResendAllOutgoingRequests()}async onCryptoEvent(e){const t=e.getRoomId(),n=e.getContent();try{await this.setRoomEncryption(t,n,!0)}catch(e){c.logger.error("Error configuring encryption in room "+t+":",e)}}async onSyncWillProcess(e){e.oldSyncToken||(c.logger.log("Initial sync performed - resetting device tracking state"),this.deviceList.stopTrackingAllDeviceLists(),this.deviceList.startTrackingDeviceList(this.userId),this.roomDeviceTrackingState={}),this.sendKeyRequestsImmediately=!1}async onSyncCompleted(e){this.deviceList.setSyncToken(e.nextSyncToken),this.deviceList.saveIfDirty(),this.deviceList.startTrackingDeviceList(this.userId),this.deviceList.refreshOutdatedDeviceLists(),e.catchingUp||(this.maybeUploadOneTimeKeys(),this.processReceivedRoomKeyRequests(),this.outgoingRoomKeyRequestManager.sendQueuedRequests(),this.sendKeyRequestsImmediately=!0)}async evalDeviceListChanges(e){if(e.changed&&Array.isArray(e.changed)&&e.changed.forEach((e=>{this.deviceList.invalidateUserDeviceList(e)})),e.left&&Array.isArray(e.left)&&e.left.length){const t=new Set(await this.getTrackedE2eUsers());e.left.forEach((e=>{t.has(e)||this.deviceList.stopTrackingDeviceList(e)}))}}async getTrackedE2eUsers(){const e=[];for(const t of this.getTrackedE2eRooms()){const n=await t.getEncryptionTargetMembers();for(const t of n)e.push(t.userId)}return e}getTrackedE2eRooms(){return this.clientStore.getRooms().filter((e=>{if(!this.roomEncryptors.get(e.roomId))return!1;if(!this.roomDeviceTrackingState[e.roomId])return!1;const t=e.getMyMembership();return"join"===t||"invite"===t}))}async encryptAndSendToDevices(e,t){const n={eventType:o.EventType.RoomMessageEncrypted,batch:[]};try{await Promise.all(e.map((async({userId:e,deviceInfo:r})=>{const i=r.deviceId,s={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};n.batch.push({userId:e,deviceId:i,payload:s}),await d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,{[e]:[r]}),await d.encryptMessageForDevice(s.ciphertext,this.userId,this.deviceId,this.olmDevice,e,r,t)}))),n.batch=n.batch.filter((e=>Object.keys(e.payload.ciphertext).length>0||(c.logger.log(`No ciphertext for device ${e.userId}:${e.deviceId}: pruning`),!1)));try{await this.baseApis.queueToDevice(n)}catch(e){throw c.logger.error("sendToDevice failed",e),e}}catch(e){throw c.logger.error("encryptAndSendToDevices promises failed",e),e}}onRoomKeyEvent(e){const t=e.getContent();t.room_id&&t.algorithm?(this.backupManager.checkedForBackup||this.backupManager.checkAndStart(),this.getRoomDecryptor(t.room_id,t.algorithm).onRoomKeyEvent(e)):c.logger.error("key event is missing fields")}onRoomKeyWithheldEvent(e){const t=e.getContent();if(!(("m.no_olm"===t.code||t.room_id&&t.session_id)&&t.algorithm&&t.sender_key))return void c.logger.error("key withheld event is missing fields");c.logger.info(`Got room key withheld event from ${e.getSender()} (${t.sender_key}) for ${t.algorithm}/${t.room_id}/${t.session_id} with reason ${t.code} (${t.reason})`);const n=this.getRoomDecryptor(t.room_id,t.algorithm);if(n.onRoomKeyWithheldEvent&&n.onRoomKeyWithheldEvent(e),!t.room_id){const e=this.getRoomDecryptors(t.algorithm);for(const n of e)n.retryDecryptionFromSender(t.sender_key)}}onKeyVerificationMessage(e){T.ToDeviceChannel.validateEvent(e,this.baseApis)&&this.handleVerificationEvent(e,this.toDeviceVerificationRequests,(e=>{if(!T.ToDeviceChannel.canCreateRequest(T.ToDeviceChannel.getEventType(e)))return;const t=e.getContent(),n=t&&t.from_device;if(!n)return;const r=e.getSender(),i=new T.ToDeviceChannel(this.baseApis,r,[n]);return new S.VerificationRequest(i,this.verificationMethods,this.baseApis)}))}async handleVerificationEvent(e,t,n,r=!0){if(e.isSending()&&e.status!=P.EventStatus.SENT){let t,n;try{await new Promise(((r,i)=>{t=r,n=()=>{e.status==P.EventStatus.CANCELLED&&i(new Error("Event status set to CANCELLED."))},e.once(P.MatrixEventEvent.LocalEventIdReplaced,t),e.on(P.MatrixEventEvent.Status,n)}))}catch(e){return void c.logger.error("error while waiting for the verification event to be sent: ",e)}finally{e.removeListener(P.MatrixEventEvent.LocalEventIdReplaced,t),e.removeListener(P.MatrixEventEvent.Status,n)}}let i=t.getRequest(e),s=!1;if(!i){if(i=n(e),!i)return void c.logger.log(`Crypto: could not find VerificationRequest for ${e.getType()}, and could not create one, so ignoring.`);s=!0,t.setRequest(e,i)}e.setVerificationRequest(i);try{await i.channel.handleEvent(e,i,r)}catch(e){c.logger.error("error while handling verification event",e)}s&&!i.initiatedByMe&&!i.invalid&&!i.observeOnly&&this.baseApis.emit(q.VerificationRequest,i)}async onToDeviceBadEncrypted(e){const t=e.getWireContent(),n=e.getSender(),r=t.algorithm,i=t.sender_key,s=()=>{const e=this.getRoomDecryptors(d.MEGOLM_ALGORITHM);for(const t of e)t.retryDecryptionFromSender(i)};if(void 0===n||void 0===i||void 0===i)return;this.lastNewSessionForced[n]=this.lastNewSessionForced[n]||{};const o=this.lastNewSessionForced[n][i]||0;if(o+36e5>Date.now())return c.logger.debug("New session already forced with device "+n+":"+i+" at "+o+": not forcing another"),await this.olmDevice.recordSessionProblem(i,"wedged",!0),void s();let a=this.deviceList.getDeviceByIdentityKey(r,i);if(!a&&(await this.downloadKeys([n],!1),a=this.deviceList.getDeviceByIdentityKey(r,i),!a))return c.logger.info("Couldn't find device for identity key "+i+": not re-establishing session"),await this.olmDevice.recordSessionProblem(i,"wedged",!1),void s();const l={};l[n]=[a],await d.ensureOlmSessionsForDevices(this.olmDevice,this.baseApis,l,!0),this.lastNewSessionForced[n][i]=Date.now();const u={algorithm:d.OLM_ALGORITHM,sender_key:this.olmDevice.deviceCurve25519Key,ciphertext:{}};await d.encryptMessageForDevice(u.ciphertext,this.userId,this.deviceId,this.olmDevice,n,a,{type:"m.dummy"}),await this.olmDevice.recordSessionProblem(i,"wedged",!0),s(),await this.baseApis.sendToDevice("m.room.encrypted",{[n]:{[a.deviceId]:u}});const h=await this.outgoingRoomKeyRequestManager.getOutgoingSentRoomKeyRequest(n,a.deviceId);for(const e of h)this.requestRoomKey(e.requestBody,e.recipients,!0)}onRoomMembership(e,t,n){const r=t.roomId,i=this.roomEncryptors.get(r);i&&(this.roomDeviceTrackingState[r]&&("join"==t.membership?(c.logger.log("Join event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId)):"invite"==t.membership&&this.clientStore.getRoom(r).shouldEncryptForInvitedMembers()&&(c.logger.log("Invite event for "+t.userId+" in "+r),this.deviceList.startTrackingDeviceList(t.userId))),i.onRoomMembership(e,t,n))}onRoomKeyRequestEvent(e){const t=e.getContent();if("request"===t.action){const t=new G(e);this.receivedRoomKeyRequests.push(t)}else if("request_cancellation"===t.action){const t=new W(e);this.receivedRoomKeyRequestCancellations.push(t)}}async processReceivedRoomKeyRequests(){if(!this.processingRoomKeyRequests){this.processingRoomKeyRequests=!0;try{const e=this.receivedRoomKeyRequests;this.receivedRoomKeyRequests=[];const t=this.receivedRoomKeyRequestCancellations;this.receivedRoomKeyRequestCancellations=[],await Promise.all(e.map((e=>this.processReceivedRoomKeyRequest(e)))),await Promise.all(t.map((e=>this.processReceivedRoomKeyRequestCancellation(e))))}catch(e){c.logger.error(`Error processing room key requsts: ${e}`)}finally{this.processingRoomKeyRequests=!1}}}async processReceivedRoomKeyRequest(e){const t=e.userId,n=e.deviceId,r=e.requestBody,i=r.room_id,s=r.algorithm;if(c.logger.log(`m.room_key_request from ${t}:${n} for ${i} / ${r.session_id} (id ${e.requestId})`),t!==this.userId){if(!this.roomEncryptors.get(i))return void c.logger.debug(`room key request for unencrypted room ${i}`);const e=this.roomEncryptors.get(i),s=this.deviceList.getStoredDevice(t,n);if(!s)return void c.logger.debug(`Ignoring keyshare for unknown device ${t}:${n}`);try{await e.reshareKeyWithDevice(r.sender_key,r.session_id,t,s)}catch(e){c.logger.warn("Failed to re-share keys for session "+r.session_id+" with device "+t+":"+s.deviceId,e)}return}if(n===this.deviceId)return void c.logger.log("Ignoring room key request from ourselves");if(!this.roomDecryptors.has(i))return void c.logger.log(`room key request for unencrypted room ${i}`);const o=this.roomDecryptors.get(i).get(s);if(o)if(await o.hasKeysForKeyRequest(e)){if(e.share=()=>{o.shareKeysWithDevice(e)},this.checkDeviceTrust(t,n).isVerified())return c.logger.log("device is already verified: sharing keys"),void e.share();this.emit(q.RoomKeyRequest,e)}else c.logger.log(`room key request for unknown session ${i} / `+r.session_id);else c.logger.log(`room key request for unknown alg ${s} in room ${i}`)}async processReceivedRoomKeyRequestCancellation(e){c.logger.log(`m.room_key_request cancellation for ${e.userId}:${e.deviceId} (id ${e.requestId})`),this.emit(q.RoomKeyRequestCancellation,e)}getRoomDecryptor(e,t){let n,r;if((e=e||null)&&(n=this.roomDecryptors.get(e),n||(n=new Map,this.roomDecryptors.set(e,n)),r=n.get(t),r))return r;const i=f.DECRYPTION_CLASSES.get(t);if(!i)throw new f.DecryptionError("UNKNOWN_ENCRYPTION_ALGORITHM",'Unknown encryption algorithm "'+t+'".');return r=new i({userId:this.userId,crypto:this,olmDevice:this.olmDevice,baseApis:this.baseApis,roomId:e}),n&&n.set(t,r),r}getRoomDecryptors(e){const t=[];for(const n of this.roomDecryptors.values())n.has(e)&&t.push(n.get(e));return t}async signObject(e){const t=e.signatures||{},n=e.unsigned;delete e.signatures,delete e.unsigned,t[this.userId]=t[this.userId]||{},t[this.userId]["ed25519:"+this.deviceId]=await this.olmDevice.sign(s.default.stringify(e)),e.signatures=t,void 0!==n&&(e.unsigned=n)}}function V(e){if("string"!=typeof e||e.indexOf(",")<0)return null;const t=Uint8Array.from(e.split(","),(e=>parseInt(e)));return d.encodeBase64(t)}t.Crypto=$;class G{constructor(e){(0,i.default)(this,"userId",void 0),(0,i.default)(this,"deviceId",void 0),(0,i.default)(this,"requestId",void 0),(0,i.default)(this,"requestBody",void 0),(0,i.default)(this,"share",void 0);const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id,this.requestBody=t.body||{},this.share=()=>{throw new Error("don't know how to share keys for this request yet")}}}t.IncomingRoomKeyRequest=G;class W{constructor(e){(0,i.default)(this,"userId",void 0),(0,i.default)(this,"deviceId",void 0),(0,i.default)(this,"requestId",void 0);const t=e.getContent();this.userId=e.getSender(),this.deviceId=t.requesting_device_id,this.requestId=t.request_id}}},1597:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.deriveKey=c,t.keyFromAuthData=function(e,t){if(!n.g.Olm)throw new Error("Olm is not available");if(!e.private_key_salt||!e.private_key_iterations)throw new Error("Salt and/or iterations not found: this backup cannot be restored with a passphrase");return c(t,e.private_key_salt,e.private_key_iterations,e.private_key_bits||a)},t.keyFromPassphrase=async function(e){if(!n.g.Olm)throw new Error("Olm is not available");const t=(0,r.randomString)(32);return{key:await c(e,t,o,a),salt:t,iterations:o}};var r=n(8401),i=n(3102);const s="undefined"!=typeof window&&window.crypto?window.crypto.subtle||window.crypto.webkitSubtle:null,o=5e5,a=256;async function c(e,t,r,o=a){return s?async function(e,t,r,i){const s=n.g.crypto.subtle,o=n.g.TextEncoder;if(!s||!o)throw new Error("Password-based backup is not avaiable on this platform");const a=await s.importKey("raw",(new o).encode(e),{name:"PBKDF2"},!1,["deriveBits"]),c=await s.deriveBits({name:"PBKDF2",salt:(new o).encode(t),iterations:r,hash:"SHA-512"},a,i);return new Uint8Array(c)}(e,t,r,o):async function(e,t,n,r){const s=(0,i.getCrypto)();if(!s)throw new Error("No usable crypto implementation");return s.pbkdf2Sync(e,Buffer.from(t,"binary"),n,r,"sha512")}(e,t,r,o)}},2772:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.OLM_ALGORITHM=t.MEGOLM_BACKUP_ALGORITHM=t.MEGOLM_ALGORITHM=void 0,t.decodeBase64=function(e){return Buffer.from(e,"base64")},t.encodeBase64=h,t.encodeUnpaddedBase64=function(e){return h(e).replace(/=+$/g,"")},t.encryptMessageForDevice=async function(e,t,n,r,i,s,a){const c=s.getIdentityKey(),l=await r.getSessionIdForDevice(c);if(null===l)return;o.logger.log("Using sessionid "+l+" for device "+i+":"+s.deviceId);const d={sender:t,sender_device:n,keys:{ed25519:r.deviceEd25519Key},recipient:i,recipient_keys:{ed25519:s.getFingerprint()}};Object.assign(d,a),e[c]=await r.encryptMessage(c,l,JSON.stringify(d))},t.ensureOlmSessionsForDevices=async function(e,t,n,r=!1,i,s,a=o.logger){"number"==typeof r&&(a=s,s=i,i=r,r=!1);const c=[],l={},u={};for(const[,t]of Object.entries(n))for(const n of t){const t=n.getIdentityKey();t!==e.deviceCurve25519Key&&(e.sessionsInProgress[t]||(e.sessionsInProgress[t]=new Promise((n=>{u[t]=r=>{delete e.sessionsInProgress[t],n(r)}}))))}for(const[t,i]of Object.entries(n)){l[t]={};for(const n of i){const i=n.deviceId,s=n.getIdentityKey();if(s===e.deviceCurve25519Key){a.info("Attempted to start session with ourself! Ignoring"),l[t][i]={device:n,sessionId:null};continue}const o=`for ${s} (${t}:${i})`,d=await e.getSessionIdForDevice(s,!!u[s],a);null!==d&&u[s]&&u[s](),(null===d||r)&&(r?a.info(`Forcing new Olm session ${o}`):a.info(`Making new Olm session ${o}`),c.push([t,i])),l[t][i]={device:n,sessionId:d}}}if(0===c.length)return l;const h="signed_curve25519";let f,g=`one-time keys for ${c.length} devices`;try{a.debug(`Claiming ${g}`),f=await t.claimOneTimeKeys(c,h,i),a.debug(`Claimed ${g}`)}catch(e){for(const e of Object.values(u))e();throw a.log(`Failed to claim ${g}`,e,c),e}s&&"failures"in f&&s.push(...Object.keys(f.failures));const p=f.one_time_keys||{},m=[];for(const[t,i]of Object.entries(n)){const n=p[t]||{};for(let s=0;s<i.length;s++){const o=i[s],c=o.deviceId,f=o.getIdentityKey();if(f===e.deviceCurve25519Key)continue;if(l[t][c].sessionId&&!r)continue;const g=n[c]||{};let p=null;for(const e in g)0===e.indexOf(h+":")&&(p=g[e]);p?m.push(d(e,p,t,o).then((e=>{u[f]&&u[f](e),l[t][c].sessionId=e}),(e=>{throw u[f]&&u[f](),e}))):(a.warn(`No one-time keys (alg=${h}) for device ${t}:${c}`),u[f]&&u[f]())}}return g=`Olm sessions for ${m.length} devices`,a.debug(`Starting ${g}`),await Promise.all(m),a.debug(`Started ${g}`),l},t.getExistingOlmSessions=async function(e,t,n){const r={},i={},s=[];for(const[t,o]of Object.entries(n))for(const n of o){const o=n.deviceId,a=n.getIdentityKey();s.push((async()=>{const s=await e.getSessionIdForDevice(a,!0);null===s?(r[t]=r[t]||[],r[t].push(n)):(i[t]=i[t]||{},i[t][o]={device:n,sessionId:s})})())}return await Promise.all(s),[r,i]},t.pkSign=function(e,t,r,i){let o=!1;if(t instanceof Uint8Array){const e=new n.g.Olm.PkSigning;i=e.init_with_seed(t),t=e,o=!0}const a=e.signatures||{};delete e.signatures;const c=e.unsigned;e.unsigned&&delete e.unsigned;try{const n=a[r]||{};return a[r]=n,n["ed25519:"+i]=t.sign(s.default.stringify(e))}finally{e.signatures=a,c&&(e.unsigned=c),o&&t.free()}},t.pkVerify=function(e,t,r){const i="ed25519:"+t;if(!(e.signatures&&e.signatures[r]&&e.signatures[r][i]))throw new Error("No signature");const o=e.signatures[r][i],a=new n.g.Olm.Utility,c=e.signatures;delete e.signatures;const l=e.unsigned;e.unsigned&&delete e.unsigned;try{a.ed25519_verify(t,s.default.stringify(e),o)}finally{e.signatures=c,l&&(e.unsigned=l),a.free()}},t.verifySignature=u;var i,s=r(n(9141)),o=n(7434);!function(e){e.Olm="m.olm.v1.curve25519-aes-sha2",e.Megolm="m.megolm.v1.aes-sha2",e.MegolmBackup="m.megolm_backup.v1.curve25519-aes-sha2"}(i||(i={}));const a=i.Olm;t.OLM_ALGORITHM=a;const c=i.Megolm;t.MEGOLM_ALGORITHM=c;const l=i.MegolmBackup;async function d(e,t,n,r){const i=r.deviceId;try{await u(e,t,n,i,r.getFingerprint())}catch(e){return o.logger.error("Unable to verify signature on one-time key for device "+n+":"+i+":",e),null}let s;try{s=await e.createOutboundSession(r.getIdentityKey(),t.key)}catch(e){return o.logger.error("Error starting olm session with device "+n+":"+i+": "+e),null}return o.logger.log("Started new olm sessionid "+s+" for device "+n+":"+i),s}async function u(e,t,n,r,i){const o="ed25519:"+r,a=((t.signatures||{})[n]||{})[o];if(!a)throw Error("No signature");const c=Object.assign({},t);"unsigned"in c&&delete c.unsigned,delete c.signatures;const l=s.default.stringify(c);e.verifySignature(i,l,a)}function h(e){return Buffer.from(e).toString("base64")}t.MEGOLM_BACKUP_ALGORITHM=l},4077:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.decodeRecoveryKey=function(e){const t=r.decode(e.replace(/ /g,""));let i=0;for(const e of t)i^=e;if(0!==i)throw new Error("Incorrect parity");for(let e=0;e<s.length;++e)if(t[e]!==s[e])throw new Error("Incorrect prefix");if(t.length!==s.length+n.g.Olm.PRIVATE_KEY_LENGTH+1)throw new Error("Incorrect length");return Uint8Array.from(t.slice(s.length,s.length+n.g.Olm.PRIVATE_KEY_LENGTH))},t.encodeRecoveryKey=function(e){const t=Buffer.alloc(s.length+e.length+1);t.set(s,0),t.set(e,s.length);let n=0;for(let e=0;e<t.length-1;++e)n^=t[e];return t[t.length-1]=n,r.encode(t).match(/.{1,4}/g).join(" ")};var r=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=i(t);if(n&&n.has(e))return n.get(e);var r={},s=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var o in e)if("default"!==o&&Object.prototype.hasOwnProperty.call(e,o)){var a=s?Object.getOwnPropertyDescriptor(e,o):null;a&&(a.get||a.set)?Object.defineProperty(r,o,a):r[o]=e[o]}return r.default=e,n&&n.set(e,r),r}(n(7191));function i(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(i=function(e){return e?n:t})(e)}const s=[139,1]},5251:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.VERSION=t.Backend=void 0,t.upgradeDatabase=function(e,t){s.logger.log(`Upgrading IndexedDBCryptoStore from version ${t} to ${c}`),t<1&&function(e){const t=e.createObjectStore("outgoingRoomKeyRequests",{keyPath:"requestId"});t.createIndex("session",["requestBody.room_id","requestBody.session_id"]),t.createIndex("state","state")}(e),t<2&&e.createObjectStore("account"),t<3&&e.createObjectStore("sessions",{keyPath:["deviceKey","sessionId"]}).createIndex("deviceKey","deviceKey"),t<4&&e.createObjectStore("inbound_group_sessions",{keyPath:["senderCurve25519Key","sessionId"]}),t<5&&e.createObjectStore("device_data"),t<6&&e.createObjectStore("rooms"),t<7&&e.createObjectStore("sessions_needing_backup",{keyPath:["senderCurve25519Key","sessionId"]}),t<8&&e.createObjectStore("inbound_group_sessions_withheld",{keyPath:["senderCurve25519Key","sessionId"]}),t<9&&(e.createObjectStore("session_problems",{keyPath:["deviceKey","time"]}).createIndex("deviceKey","deviceKey"),e.createObjectStore("notified_error_devices",{keyPath:["userId","deviceId"]})),t<10&&e.createObjectStore("shared_history_inbound_group_sessions",{keyPath:["roomId"]})};var i=r(n(8416)),s=n(7434),o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=a(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102));function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(a=function(e){return e?n:t})(e)}const c=10;function l(e,t){e._mx_abortexception=t;try{e.abort()}catch(t){}}function d(e){return new Promise(((t,n)=>{e.oncomplete=()=>{void 0!==e._mx_abortexception&&n(e._mx_abortexception),t(null)},e.onerror=t=>{void 0!==e._mx_abortexception?n(e._mx_abortexception):(s.logger.log("Error performing indexeddb txn",t),n(e.error))},e.onabort=t=>{void 0!==e._mx_abortexception?n(e._mx_abortexception):(s.logger.log("Error performing indexeddb txn",t),n(e.error))}}))}t.VERSION=c,t.Backend=class{constructor(e){this.db=e,(0,i.default)(this,"nextTxnId",0),e.onversionchange=()=>{s.logger.log(`versionchange for indexeddb ${this.db.name}: closing`),e.close()}}async startup(){return this}async deleteAllData(){throw Error("This is not implemented, call IDBFactory::deleteDatabase(dbName) instead.")}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return new Promise(((n,r)=>{const i=this.db.transaction("outgoingRoomKeyRequests","readwrite");i.onerror=r,this._getOutgoingRoomKeyRequest(i,t,(r=>{if(r)return s.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),void n(r);s.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),i.oncomplete=()=>{n(e)},i.objectStore("outgoingRoomKeyRequests").add(e)}))}))}getOutgoingRoomKeyRequest(e){return new Promise(((t,n)=>{const r=this.db.transaction("outgoingRoomKeyRequests","readonly");r.onerror=n,this._getOutgoingRoomKeyRequest(r,e,(e=>{t(e)}))}))}_getOutgoingRoomKeyRequest(e,t,n){const r=e.objectStore("outgoingRoomKeyRequests").index("session").openCursor([t.room_id,t.session_id]);r.onsuccess=()=>{const e=r.result;if(!e)return void n(null);const i=e.value;o.deepCompare(i.requestBody,t)?n(i):e.continue()}}getOutgoingRoomKeyRequestByState(e){if(0===e.length)return Promise.resolve(null);let t,n=0;const r=this.db.transaction("outgoingRoomKeyRequests","readonly"),i=r.objectStore("outgoingRoomKeyRequests"),s=e[n];return i.index("state").openCursor(s).onsuccess=function r(){const i=this.result;if(i)return void(t=i.value);if(n++,n>=e.length)return;const s=e[n];this.source.openCursor(s).onsuccess=r},d(r).then((()=>t))}getAllOutgoingRoomKeyRequestsByState(e){return new Promise(((t,n)=>{const r=this.db.transaction("outgoingRoomKeyRequests","readonly").objectStore("outgoingRoomKeyRequests").index("state").getAll(e);r.onsuccess=()=>t(r.result),r.onerror=()=>n(r.error)}))}getOutgoingRoomKeyRequestsByTarget(e,t,n){let r=0;const i=[],s=this.db.transaction("outgoingRoomKeyRequests","readonly"),o=s.objectStore("outgoingRoomKeyRequests"),a=n[r];return o.index("state").openCursor(a).onsuccess=function s(){const o=this.result;if(o){const n=o.value;n.recipients.includes({userId:e,deviceId:t})&&i.push(n),o.continue()}else{if(r++,r>=n.length)return;const e=n[r];this.source.openCursor(e).onsuccess=s}},d(s).then((()=>i))}updateOutgoingRoomKeyRequest(e,t,n){let r=null;const i=this.db.transaction("outgoingRoomKeyRequests","readwrite");return i.objectStore("outgoingRoomKeyRequests").openCursor(e).onsuccess=function(){const e=this.result;if(!e)return;const i=e.value;i.state==t?(Object.assign(i,n),e.update(i),r=i):s.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${i.state}`)},d(i).then((()=>r))}deleteOutgoingRoomKeyRequest(e,t){const n=this.db.transaction("outgoingRoomKeyRequests","readwrite"),r=n.objectStore("outgoingRoomKeyRequests").openCursor(e);return r.onsuccess=()=>{const e=r.result;if(!e)return;const n=e.value;n.state==t?e.delete():s.logger.warn(`Cannot delete room key request in state ${n.state} (expected ${t})`)},d(n)}getAccount(e,t){const n=e.objectStore("account").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}storeAccount(e,t){e.objectStore("account").put(t,"-")}getCrossSigningKeys(e,t){const n=e.objectStore("account").get("crossSigningKeys");n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}getSecretStorePrivateKey(e,t,n){const r=e.objectStore("account").get(`ssss_cache:${n}`);r.onsuccess=function(){try{t(r.result||null)}catch(t){l(e,t)}}}storeCrossSigningKeys(e,t){e.objectStore("account").put(t,"crossSigningKeys")}storeSecretStorePrivateKey(e,t,n){e.objectStore("account").put(n,`ssss_cache:${t}`)}countEndToEndSessions(e,t){const n=e.objectStore("sessions").count();n.onsuccess=function(){try{t(n.result)}catch(t){l(e,t)}}}getEndToEndSessions(e,t,n){const r=t.objectStore("sessions").index("deviceKey").openCursor(e),i={};r.onsuccess=function(){const e=r.result;if(e)i[e.value.sessionId]={session:e.value.session,lastReceivedMessageTs:e.value.lastReceivedMessageTs},e.continue();else try{n(i)}catch(e){l(t,e)}}}getEndToEndSession(e,t,n,r){const i=n.objectStore("sessions").get([e,t]);i.onsuccess=function(){try{i.result?r({session:i.result.session,lastReceivedMessageTs:i.result.lastReceivedMessageTs}):r(null)}catch(e){l(n,e)}}}getAllEndToEndSessions(e,t){const n=e.objectStore("sessions").openCursor();n.onsuccess=function(){try{const e=n.result;e?(t(e.value),e.continue()):t(null)}catch(t){l(e,t)}}}storeEndToEndSession(e,t,n,r){r.objectStore("sessions").put({deviceKey:e,sessionId:t,session:n.session,lastReceivedMessageTs:n.lastReceivedMessageTs})}async storeEndToEndSessionProblem(e,t,n){const r=this.db.transaction("session_problems","readwrite");return r.objectStore("session_problems").put({deviceKey:e,type:t,fixed:n,time:Date.now()}),d(r)}async getEndToEndSessionProblem(e,t){let n;const r=this.db.transaction("session_problems","readwrite"),i=r.objectStore("session_problems").index("deviceKey").getAll(e);return i.onsuccess=()=>{const e=i.result;if(!e.length)return void(n=null);e.sort(((e,t)=>e.time-t.time));const r=e[e.length-1];for(const i of e)if(i.time>t)return void(n=Object.assign({},i,{fixed:r.fixed}));n=r.fixed?null:r},await d(r),n}async filterOutNotifiedErrorDevices(e){const t=this.db.transaction("notified_error_devices","readwrite").objectStore("notified_error_devices"),n=[];return await Promise.all(e.map((e=>new Promise((r=>{const{userId:i,deviceInfo:s}=e,o=t.get([i,s.deviceId]);o.onsuccess=function(){o.result||(t.put({userId:i,deviceId:s.deviceId}),n.push(e)),r()}}))))),n}getEndToEndInboundGroupSession(e,t,n,r){let i=!1,s=!1;const o=n.objectStore("inbound_group_sessions").get([e,t]);o.onsuccess=function(){try{i=o.result?o.result.session:null,!1!==s&&r(i,s)}catch(e){l(n,e)}};const a=n.objectStore("inbound_group_sessions_withheld").get([e,t]);a.onsuccess=function(){try{s=a.result?a.result.session:null,!1!==i&&r(i,s)}catch(e){l(n,e)}}}getAllEndToEndInboundGroupSessions(e,t){const n=e.objectStore("inbound_group_sessions").openCursor();n.onsuccess=function(){const r=n.result;if(r){try{t({senderKey:r.value.senderCurve25519Key,sessionId:r.value.sessionId,sessionData:r.value.session})}catch(t){l(e,t)}r.continue()}else try{t(null)}catch(t){l(e,t)}}}addEndToEndInboundGroupSession(e,t,n,r){const i=r.objectStore("inbound_group_sessions").add({senderCurve25519Key:e,sessionId:t,session:n});i.onerror=n=>{"ConstraintError"===i.error.name?(n.stopPropagation(),n.preventDefault(),s.logger.log("Ignoring duplicate inbound group session: "+e+" / "+t)):l(r,new Error("Failed to add inbound group session: "+i.error))}}storeEndToEndInboundGroupSession(e,t,n,r){r.objectStore("inbound_group_sessions").put({senderCurve25519Key:e,sessionId:t,session:n})}storeEndToEndInboundGroupSessionWithheld(e,t,n,r){r.objectStore("inbound_group_sessions_withheld").put({senderCurve25519Key:e,sessionId:t,session:n})}getEndToEndDeviceData(e,t){const n=e.objectStore("device_data").get("-");n.onsuccess=function(){try{t(n.result||null)}catch(t){l(e,t)}}}storeEndToEndDeviceData(e,t){t.objectStore("device_data").put(e,"-")}storeEndToEndRoom(e,t,n){n.objectStore("rooms").put(t,e)}getEndToEndRooms(e,t){const n={},r=e.objectStore("rooms").openCursor();r.onsuccess=function(){const i=r.result;if(i)n[i.key]=i.value,i.continue();else try{t(n)}catch(t){l(e,t)}}}getSessionsNeedingBackup(e){return new Promise(((t,n)=>{const r=[],i=this.db.transaction(["sessions_needing_backup","inbound_group_sessions"],"readonly");i.onerror=n,i.oncomplete=function(){t(r)};const s=i.objectStore("sessions_needing_backup"),o=i.objectStore("inbound_group_sessions"),a=s.openCursor();a.onsuccess=function(){const t=a.result;if(t){const n=o.get(t.key);n.onsuccess=function(){r.push({senderKey:n.result.senderCurve25519Key,sessionId:n.result.sessionId,sessionData:n.result.session})},(!e||r.length<e)&&t.continue()}}}))}countSessionsNeedingBackup(e){e||(e=this.db.transaction("sessions_needing_backup","readonly"));const t=e.objectStore("sessions_needing_backup");return new Promise(((e,n)=>{const r=t.count();r.onerror=n,r.onsuccess=()=>e(r.result)}))}async unmarkSessionsNeedingBackup(e,t){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const n=t.objectStore("sessions_needing_backup");await Promise.all(e.map((e=>new Promise(((t,r)=>{const i=n.delete([e.senderKey,e.sessionId]);i.onsuccess=t,i.onerror=r})))))}async markSessionsNeedingBackup(e,t){t||(t=this.db.transaction("sessions_needing_backup","readwrite"));const n=t.objectStore("sessions_needing_backup");await Promise.all(e.map((e=>new Promise(((t,r)=>{const i=n.put({senderCurve25519Key:e.senderKey,sessionId:e.sessionId});i.onsuccess=t,i.onerror=r})))))}addSharedHistoryInboundGroupSession(e,t,n,r){r||(r=this.db.transaction("shared_history_inbound_group_sessions","readwrite"));const i=r.objectStore("shared_history_inbound_group_sessions"),s=i.get([e]);s.onsuccess=()=>{const{sessions:r}=s.result||{sessions:[]};r.push([t,n]),i.put({roomId:e,sessions:r})}}getSharedHistoryInboundGroupSessions(e,t){t||(t=this.db.transaction("shared_history_inbound_group_sessions","readonly"));const n=t.objectStore("shared_history_inbound_group_sessions").get([e]);return new Promise(((e,t)=>{n.onsuccess=()=>{const{sessions:t}=n.result||{sessions:[]};e(t)},n.onerror=t}))}doTxn(e,t,n,r=s.logger){const i=this.db.transaction(t,e),o=d(i),a=n(i);return o.then((()=>a))}}},7585:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.IndexedDBCryptoStore=void 0;var i=r(n(8416)),s=n(7434),o=n(4250),a=n(1045),c=h(n(5251)),l=n(9489),d=h(n(3415));function u(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(u=function(e){return e?n:t})(e)}function h(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=u(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}class f{static exists(e,t){return d.exists(e,t)}constructor(e,t){this.indexedDB=e,this.dbName=t,(0,i.default)(this,"backendPromise",null),(0,i.default)(this,"backend",null)}startup(){return this.backendPromise||(this.backendPromise=new Promise(((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));s.logger.log(`connecting to indexeddb ${this.dbName}`);const n=this.indexedDB.open(this.dbName,c.VERSION);n.onupgradeneeded=e=>{const t=n.result,r=e.oldVersion;c.upgradeDatabase(t,r)},n.onblocked=()=>{s.logger.log("can't yet open IndexedDBCryptoStore because it is open elsewhere")},n.onerror=e=>{s.logger.log("Error connecting to indexeddb",e),t(n.error)},n.onsuccess=()=>{const t=n.result;s.logger.log(`connected to indexeddb ${this.dbName}`),e(new c.Backend(t))}})).then((e=>e.doTxn("readonly",[f.STORE_INBOUND_GROUP_SESSIONS,f.STORE_INBOUND_GROUP_SESSIONS_WITHHELD],(t=>{e.getEndToEndInboundGroupSession("","",t,(()=>{}))})).then((()=>e)))).catch((e=>{if("VersionError"===e.name)throw s.logger.warn("Crypto DB is too new for us to use!",e),new l.InvalidCryptoStoreError(l.InvalidCryptoStoreError.TOO_NEW);s.logger.warn(`unable to connect to indexeddb ${this.dbName}: falling back to localStorage store: ${e}`);try{return new o.LocalStorageCryptoStore(n.g.localStorage)}catch(e){return s.logger.warn(`unable to open localStorage: falling back to in-memory store: ${e}`),new a.MemoryCryptoStore}})).then((e=>(this.backend=e,e)))),this.backendPromise}deleteAllData(){return new Promise(((e,t)=>{if(!this.indexedDB)return void t(new Error("no indexeddb support available"));s.logger.log(`Removing indexeddb instance: ${this.dbName}`);const n=this.indexedDB.deleteDatabase(this.dbName);n.onblocked=()=>{s.logger.log("can't yet delete IndexedDBCryptoStore because it is open elsewhere")},n.onerror=e=>{s.logger.log("Error deleting data from indexeddb",e),t(n.error)},n.onsuccess=()=>{s.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}})).catch((e=>{s.logger.warn(`unable to delete IndexedDBCryptoStore: ${e}`)}))}getOrAddOutgoingRoomKeyRequest(e){return this.backend.getOrAddOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequest(e){return this.backend.getOutgoingRoomKeyRequest(e)}getOutgoingRoomKeyRequestByState(e){return this.backend.getOutgoingRoomKeyRequestByState(e)}getAllOutgoingRoomKeyRequestsByState(e){return this.backend.getAllOutgoingRoomKeyRequestsByState(e)}getOutgoingRoomKeyRequestsByTarget(e,t,n){return this.backend.getOutgoingRoomKeyRequestsByTarget(e,t,n)}updateOutgoingRoomKeyRequest(e,t,n){return this.backend.updateOutgoingRoomKeyRequest(e,t,n)}deleteOutgoingRoomKeyRequest(e,t){return this.backend.deleteOutgoingRoomKeyRequest(e,t)}getAccount(e,t){this.backend.getAccount(e,t)}storeAccount(e,t){this.backend.storeAccount(e,t)}getCrossSigningKeys(e,t){this.backend.getCrossSigningKeys(e,t)}getSecretStorePrivateKey(e,t,n){this.backend.getSecretStorePrivateKey(e,t,n)}storeCrossSigningKeys(e,t){this.backend.storeCrossSigningKeys(e,t)}storeSecretStorePrivateKey(e,t,n){this.backend.storeSecretStorePrivateKey(e,t,n)}countEndToEndSessions(e,t){this.backend.countEndToEndSessions(e,t)}getEndToEndSession(e,t,n,r){this.backend.getEndToEndSession(e,t,n,r)}getEndToEndSessions(e,t,n){this.backend.getEndToEndSessions(e,t,n)}getAllEndToEndSessions(e,t){this.backend.getAllEndToEndSessions(e,t)}storeEndToEndSession(e,t,n,r){this.backend.storeEndToEndSession(e,t,n,r)}storeEndToEndSessionProblem(e,t,n){return this.backend.storeEndToEndSessionProblem(e,t,n)}getEndToEndSessionProblem(e,t){return this.backend.getEndToEndSessionProblem(e,t)}filterOutNotifiedErrorDevices(e){return this.backend.filterOutNotifiedErrorDevices(e)}getEndToEndInboundGroupSession(e,t,n,r){this.backend.getEndToEndInboundGroupSession(e,t,n,r)}getAllEndToEndInboundGroupSessions(e,t){this.backend.getAllEndToEndInboundGroupSessions(e,t)}addEndToEndInboundGroupSession(e,t,n,r){this.backend.addEndToEndInboundGroupSession(e,t,n,r)}storeEndToEndInboundGroupSession(e,t,n,r){this.backend.storeEndToEndInboundGroupSession(e,t,n,r)}storeEndToEndInboundGroupSessionWithheld(e,t,n,r){this.backend.storeEndToEndInboundGroupSessionWithheld(e,t,n,r)}storeEndToEndDeviceData(e,t){this.backend.storeEndToEndDeviceData(e,t)}getEndToEndDeviceData(e,t){this.backend.getEndToEndDeviceData(e,t)}storeEndToEndRoom(e,t,n){this.backend.storeEndToEndRoom(e,t,n)}getEndToEndRooms(e,t){this.backend.getEndToEndRooms(e,t)}getSessionsNeedingBackup(e){return this.backend.getSessionsNeedingBackup(e)}countSessionsNeedingBackup(e){return this.backend.countSessionsNeedingBackup(e)}unmarkSessionsNeedingBackup(e,t){return this.backend.unmarkSessionsNeedingBackup(e,t)}markSessionsNeedingBackup(e,t){return this.backend.markSessionsNeedingBackup(e,t)}addSharedHistoryInboundGroupSession(e,t,n,r){this.backend.addSharedHistoryInboundGroupSession(e,t,n,r)}getSharedHistoryInboundGroupSessions(e,t){return this.backend.getSharedHistoryInboundGroupSessions(e,t)}doTxn(e,t,n,r){return this.backend.doTxn(e,t,n,r)}}t.IndexedDBCryptoStore=f,(0,i.default)(f,"STORE_ACCOUNT","account"),(0,i.default)(f,"STORE_SESSIONS","sessions"),(0,i.default)(f,"STORE_INBOUND_GROUP_SESSIONS","inbound_group_sessions"),(0,i.default)(f,"STORE_INBOUND_GROUP_SESSIONS_WITHHELD","inbound_group_sessions_withheld"),(0,i.default)(f,"STORE_SHARED_HISTORY_INBOUND_GROUP_SESSIONS","shared_history_inbound_group_sessions"),(0,i.default)(f,"STORE_DEVICE_DATA","device_data"),(0,i.default)(f,"STORE_ROOMS","rooms"),(0,i.default)(f,"STORE_BACKUP","sessions_needing_backup")},4250:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.LocalStorageCryptoStore=void 0;var r=n(7434),i=n(1045);const s="crypto.",o=s+"account",a=s+"cross_signing_keys",c=s+"notified_error_devices",l=s+"device_data",d=s+"inboundgroupsessions/",u=s+"inboundgroupsessions.withheld/",h=s+"rooms/",f=s+"sessionsneedingbackup";function g(e){return s+"sessions/"+e}function p(e){return s+"session.problems/"+e}function m(e,t){return d+e+"/"+t}function y(e,t){return u+e+"/"+t}function v(e){return h+e}class b extends i.MemoryCryptoStore{static exists(e){const t=e.length;for(let n=0;n<t;n++)if(e.key(n).startsWith(s))return!0;return!1}constructor(e){super(),this.store=e}countEndToEndSessions(e,t){let n=0;for(let e=0;e<this.store.length;++e)this.store.key(e).startsWith(g(""))&&++n;t(n)}_getEndToEndSessions(e){const t=_(this.store,g(e)),n={};for(const[e,r]of Object.entries(t||{}))n[e]="string"==typeof r?{session:r}:r;return n}getEndToEndSession(e,t,n,r){r(this._getEndToEndSessions(e)[t]||{})}getEndToEndSessions(e,t,n){n(this._getEndToEndSessions(e)||{})}getAllEndToEndSessions(e,t){for(let e=0;e<this.store.length;++e)if(this.store.key(e).startsWith(g(""))){const n=this.store.key(e).split("/")[1];for(const e of Object.values(this._getEndToEndSessions(n)))t(e)}}storeEndToEndSession(e,t,n,r){const i=this._getEndToEndSessions(e)||{};i[t]=n,E(this.store,g(e),i)}async storeEndToEndSessionProblem(e,t,n){const r=p(e),i=_(this.store,r)||[];i.push({type:t,fixed:n,time:Date.now()}),i.sort(((e,t)=>e.time-t.time)),E(this.store,r,i)}async getEndToEndSessionProblem(e,t){const n=p(e),r=_(this.store,n)||[];if(!r.length)return null;const i=r[r.length-1];for(const e of r)if(e.time>t)return Object.assign({},e,{fixed:i.fixed});return i.fixed?null:i}async filterOutNotifiedErrorDevices(e){const t=_(this.store,c)||{},n=[];for(const r of e){const{userId:e,deviceInfo:i}=r;e in t?i.deviceId in t[e]||(n.push(r),t[e][i.deviceId]=!0):(n.push(r),t[e]={[i.deviceId]:!0})}return E(this.store,c,t),n}getEndToEndInboundGroupSession(e,t,n,r){r(_(this.store,m(e,t)),_(this.store,y(e,t)))}getAllEndToEndInboundGroupSessions(e,t){for(let e=0;e<this.store.length;++e){const n=this.store.key(e);n.startsWith(d)&&t({senderKey:n.slice(28,71),sessionId:n.slice(72),sessionData:_(this.store,n)})}t(null)}addEndToEndInboundGroupSession(e,t,n,r){_(this.store,m(e,t))||this.storeEndToEndInboundGroupSession(e,t,n,r)}storeEndToEndInboundGroupSession(e,t,n,r){E(this.store,m(e,t),n)}storeEndToEndInboundGroupSessionWithheld(e,t,n,r){E(this.store,y(e,t),n)}getEndToEndDeviceData(e,t){t(_(this.store,l))}storeEndToEndDeviceData(e,t){E(this.store,l,e)}storeEndToEndRoom(e,t,n){E(this.store,v(e),t)}getEndToEndRooms(e,t){const n={},r=v("");for(let e=0;e<this.store.length;++e){const t=this.store.key(e);t.startsWith(r)&&(n[t.slice(r.length)]=_(this.store,t))}t(n)}getSessionsNeedingBackup(e){const t=_(this.store,f)||{},n=[];for(const r in t)if(Object.prototype.hasOwnProperty.call(t,r)){const t=r.slice(0,43),i=r.slice(44);if(this.getEndToEndInboundGroupSession(t,i,null,(e=>{n.push({senderKey:t,sessionId:i,sessionData:e})})),e&&n.length>=e)break}return Promise.resolve(n)}countSessionsNeedingBackup(){const e=_(this.store,f)||{};return Promise.resolve(Object.keys(e).length)}unmarkSessionsNeedingBackup(e){const t=_(this.store,f)||{};for(const n of e)delete t[n.senderKey+"/"+n.sessionId];return E(this.store,f,t),Promise.resolve()}markSessionsNeedingBackup(e){const t=_(this.store,f)||{};for(const n of e)t[n.senderKey+"/"+n.sessionId]=!0;return E(this.store,f,t),Promise.resolve()}deleteAllData(){return this.store.removeItem(o),Promise.resolve()}getAccount(e,t){t(_(this.store,o))}storeAccount(e,t){E(this.store,o,t)}getCrossSigningKeys(e,t){t(_(this.store,a))}getSecretStorePrivateKey(e,t,n){t(_(this.store,s+`ssss_cache.${n}`))}storeCrossSigningKeys(e,t){E(this.store,a,t)}storeSecretStorePrivateKey(e,t,n){E(this.store,s+`ssss_cache.${t}`,n)}doTxn(e,t,n){return Promise.resolve(n(null))}}function _(e,t){try{return JSON.parse(e.getItem(t))}catch(e){r.logger.log("Error: Failed to get key %s: %s",t,e.stack||e),r.logger.log(e.stack)}return null}function E(e,t,n){e.setItem(t,JSON.stringify(n))}t.LocalStorageCryptoStore=b},1045:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryCryptoStore=void 0;var i=r(n(8416)),s=n(7434),o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=a(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102));function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(a=function(e){return e?n:t})(e)}function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}t.MemoryCryptoStore=class{constructor(){(0,i.default)(this,"outgoingRoomKeyRequests",[]),(0,i.default)(this,"account",null),(0,i.default)(this,"crossSigningKeys",null),(0,i.default)(this,"privateKeys",{}),(0,i.default)(this,"sessions",{}),(0,i.default)(this,"sessionProblems",{}),(0,i.default)(this,"notifiedErrorDevices",{}),(0,i.default)(this,"inboundGroupSessions",{}),(0,i.default)(this,"inboundGroupSessionsWithheld",{}),(0,i.default)(this,"deviceData",null),(0,i.default)(this,"rooms",{}),(0,i.default)(this,"sessionsNeedingBackup",{}),(0,i.default)(this,"sharedHistoryInboundGroupSessions",{})}async startup(){return this}deleteAllData(){return Promise.resolve()}getOrAddOutgoingRoomKeyRequest(e){const t=e.requestBody;return o.promiseTry((()=>{const n=this._getOutgoingRoomKeyRequest(t);return n?(s.logger.log(`already have key request outstanding for ${t.room_id} / ${t.session_id}: not sending another`),n):(s.logger.log(`enqueueing key request for ${t.room_id} / `+t.session_id),this.outgoingRoomKeyRequests.push(e),e)}))}getOutgoingRoomKeyRequest(e){return Promise.resolve(this._getOutgoingRoomKeyRequest(e))}_getOutgoingRoomKeyRequest(e){for(const t of this.outgoingRoomKeyRequests)if(o.deepCompare(t.requestBody,e))return t;return null}getOutgoingRoomKeyRequestByState(e){for(const t of this.outgoingRoomKeyRequests)for(const n of e)if(t.state===n)return Promise.resolve(t);return Promise.resolve(null)}getAllOutgoingRoomKeyRequestsByState(e){return Promise.resolve(this.outgoingRoomKeyRequests.filter((t=>t.state==e)))}getOutgoingRoomKeyRequestsByTarget(e,t,n){const r=[];for(const i of this.outgoingRoomKeyRequests)for(const s of n)i.state===s&&i.recipients.includes({userId:e,deviceId:t})&&r.push(i);return Promise.resolve(r)}updateOutgoingRoomKeyRequest(e,t,n){for(const r of this.outgoingRoomKeyRequests)if(r.requestId===e)return r.state!==t?(s.logger.warn(`Cannot update room key request from ${t} as it was already updated to ${r.state}`),Promise.resolve(null)):(Object.assign(r,n),Promise.resolve(r));return Promise.resolve(null)}deleteOutgoingRoomKeyRequest(e,t){for(let n=0;n<this.outgoingRoomKeyRequests.length;n++){const r=this.outgoingRoomKeyRequests[n];if(r.requestId===e)return r.state!=t?(s.logger.warn(`Cannot delete room key request in state ${r.state} (expected ${t})`),Promise.resolve(null)):(this.outgoingRoomKeyRequests.splice(n,1),Promise.resolve(r))}return Promise.resolve(null)}getAccount(e,t){t(this.account)}storeAccount(e,t){this.account=t}getCrossSigningKeys(e,t){t(this.crossSigningKeys)}getSecretStorePrivateKey(e,t,n){t(this.privateKeys[n]||null)}storeCrossSigningKeys(e,t){this.crossSigningKeys=t}storeSecretStorePrivateKey(e,t,n){this.privateKeys[t]=n}countEndToEndSessions(e,t){t(Object.keys(this.sessions).length)}getEndToEndSession(e,t,n,r){r((this.sessions[e]||{})[t]||null)}getEndToEndSessions(e,t,n){n(this.sessions[e]||{})}getAllEndToEndSessions(e,t){Object.entries(this.sessions).forEach((([e,n])=>{Object.entries(n).forEach((([n,r])=>{t(l(l({},r),{},{deviceKey:e,sessionId:n}))}))}))}storeEndToEndSession(e,t,n,r){let i=this.sessions[e];void 0===i&&(i={},this.sessions[e]=i),i[t]=n}async storeEndToEndSessionProblem(e,t,n){const r=this.sessionProblems[e]=this.sessionProblems[e]||[];r.push({type:t,fixed:n,time:Date.now()}),r.sort(((e,t)=>e.time-t.time))}async getEndToEndSessionProblem(e,t){const n=this.sessionProblems[e]||[];if(!n.length)return null;const r=n[n.length-1];for(const e of n)if(e.time>t)return Object.assign({},e,{fixed:r.fixed});return r.fixed?null:r}async filterOutNotifiedErrorDevices(e){const t=this.notifiedErrorDevices,n=[];for(const r of e){const{userId:e,deviceInfo:i}=r;e in t?i.deviceId in t[e]||(n.push(r),t[e][i.deviceId]=!0):(n.push(r),t[e]={[i.deviceId]:!0})}return n}getEndToEndInboundGroupSession(e,t,n,r){const i=e+"/"+t;r(this.inboundGroupSessions[i]||null,this.inboundGroupSessionsWithheld[i]||null)}getAllEndToEndInboundGroupSessions(e,t){for(const e of Object.keys(this.inboundGroupSessions))t({senderKey:e.slice(0,43),sessionId:e.slice(44),sessionData:this.inboundGroupSessions[e]});t(null)}addEndToEndInboundGroupSession(e,t,n,r){const i=e+"/"+t;void 0===this.inboundGroupSessions[i]&&(this.inboundGroupSessions[i]=n)}storeEndToEndInboundGroupSession(e,t,n,r){this.inboundGroupSessions[e+"/"+t]=n}storeEndToEndInboundGroupSessionWithheld(e,t,n,r){const i=e+"/"+t;this.inboundGroupSessionsWithheld[i]=n}getEndToEndDeviceData(e,t){t(this.deviceData)}storeEndToEndDeviceData(e,t){this.deviceData=e}storeEndToEndRoom(e,t,n){this.rooms[e]=t}getEndToEndRooms(e,t){t(this.rooms)}getSessionsNeedingBackup(e){const t=[];for(const n in this.sessionsNeedingBackup)if(this.inboundGroupSessions[n]&&(t.push({senderKey:n.slice(0,43),sessionId:n.slice(44),sessionData:this.inboundGroupSessions[n]}),e&&n.length>=e))break;return Promise.resolve(t)}countSessionsNeedingBackup(){return Promise.resolve(Object.keys(this.sessionsNeedingBackup).length)}unmarkSessionsNeedingBackup(e){for(const t of e){const e=t.senderKey+"/"+t.sessionId;delete this.sessionsNeedingBackup[e]}return Promise.resolve()}markSessionsNeedingBackup(e){for(const t of e){const e=t.senderKey+"/"+t.sessionId;this.sessionsNeedingBackup[e]=!0}return Promise.resolve()}addSharedHistoryInboundGroupSession(e,t,n){const r=this.sharedHistoryInboundGroupSessions[e]||[];r.push([t,n]),this.sharedHistoryInboundGroupSessions[e]=r}getSharedHistoryInboundGroupSessions(e){return Promise.resolve(this.sharedHistoryInboundGroupSessions[e]||[])}doTxn(e,t,n){return Promise.resolve(n(null))}}},1631:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.VerificationEvent=t.VerificationBase=t.SwitchStartEventError=void 0;var i=r(n(8416)),s=n(4369),o=n(7434),a=n(3272),c=n(6702),l=n(3075),d=n(5861);const u=new Error("Verification timed out");class h extends Error{constructor(e){super(),this.startEvent=e}}let f;t.SwitchStartEventError=h,t.VerificationEvent=f,function(e){e.Cancel="cancel"}(f||(t.VerificationEvent=f={}));class g extends d.TypedEventEmitter{constructor(e,t,n,r,s,o){super(),this.channel=e,this.baseApis=t,this.userId=n,this.deviceId=r,this.startEvent=s,this.request=o,(0,i.default)(this,"cancelled",!1),(0,i.default)(this,"_done",!1),(0,i.default)(this,"promise",null),(0,i.default)(this,"transactionTimeoutTimer",null),(0,i.default)(this,"expectedEvent",void 0),(0,i.default)(this,"resolve",void 0),(0,i.default)(this,"reject",void 0),(0,i.default)(this,"resolveEvent",void 0),(0,i.default)(this,"rejectEvent",void 0),(0,i.default)(this,"started",void 0),(0,i.default)(this,"doVerification",void 0)}get initiatedByMe(){if(!this.startEvent)return!0;const e=this.startEvent.getSender(),t=this.startEvent.getContent();return e===this.baseApis.getUserId()&&t.from_device===this.baseApis.getDeviceId()}get hasBeenCancelled(){return this.cancelled}resetTimer(){o.logger.info("Refreshing/starting the verification transaction timeout timer"),null!==this.transactionTimeoutTimer&&clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=setTimeout((()=>{this._done||this.cancelled||(o.logger.info("Triggering verification timeout"),this.cancel(u))}),6e5)}endTimer(){null!==this.transactionTimeoutTimer&&(clearTimeout(this.transactionTimeoutTimer),this.transactionTimeoutTimer=null)}send(e,t){return this.channel.send(e,t)}waitForEvent(e){if(this._done)return Promise.reject(new Error("Verification is already done"));const t=this.request.getEventFromOtherParty(e);return t?Promise.resolve(t):(this.expectedEvent=e,new Promise(((e,t)=>{this.resolveEvent=e,this.rejectEvent=t})))}canSwitchStartEvent(e){return!1}switchStartEvent(e){if(this.canSwitchStartEvent(e))if(o.logger.log("Verification Base: switching verification start event",{restartingFlow:!!this.rejectEvent}),this.rejectEvent){const t=this.rejectEvent;this.rejectEvent=void 0,t(new h(e))}else this.startEvent=e}handleEvent(e){if(!this._done)if(e.getType()===this.expectedEvent)"m.key.verification.done"!==this.expectedEvent&&(this.expectedEvent=void 0,this.rejectEvent=void 0,this.resetTimer(),this.resolveEvent(e));else if("m.key.verification.cancel"===e.getType()){const t=this.reject;if(this.reject=void 0,t){const n=e.getContent(),{reason:r,code:i}=n;t(new Error(`Other side cancelled verification because ${r} (${i})`))}}else if(this.expectedEvent){const t=new Error("Unexpected message: expecting "+this.expectedEvent+" but got "+e.getType());if(this.expectedEvent=void 0,this.rejectEvent){const e=this.rejectEvent;this.rejectEvent=void 0,e(t)}this.cancel(t)}}done(){if(this.endTimer(),!this._done)return this.request.onVerifierFinished(),this.resolve(),(0,l.requestKeysDuringVerification)(this.baseApis,this.userId,this.deviceId)}cancel(e){if(this.endTimer(),!this._done){if(this.cancelled=!0,this.request.onVerifierCancelled(),this.userId&&this.deviceId)if(e===u){const e=(0,c.newTimeoutError)();this.send(e.getType(),e.getContent())}else if(e instanceof s.MatrixEvent){if(e.getSender()!==this.userId){const t=e.getContent();"m.key.verification.cancel"===e.getType()?(t.code=t.code||"m.unknown",t.reason=t.reason||t.body||"Unknown reason",this.send("m.key.verification.cancel",t)):this.send("m.key.verification.cancel",{code:"m.unknown",reason:t.body||"Unknown reason"})}}else this.send("m.key.verification.cancel",{code:"m.unknown",reason:e.toString()});null!==this.promise?this.reject&&this.reject(e):this.promise=Promise.reject(e),this.emit(f.Cancel,e)}}verify(){return this.promise||(this.promise=new Promise(((e,t)=>{this.resolve=(...t)=>{this._done=!0,this.endTimer(),e(...t)},this.reject=e=>{this._done=!0,this.endTimer(),t(e)}})),this.doVerification&&!this.started&&(this.started=!0,this.resetTimer(),Promise.resolve(this.doVerification()).then(this.done.bind(this),this.cancel.bind(this)))),this.promise}async verifyKeys(e,t,n){const r=[];for(const[i,s]of Object.entries(t)){const t=i.split(":",2)[1],c=this.baseApis.getStoredDevice(e,t);if(c)n(i,c,s),r.push(t);else{const c=this.baseApis.crypto.deviceList.getStoredCrossSigningForUser(e);c&&c.getId()===t?(n(i,a.DeviceInfo.fromStorage({keys:{[i]:t}},t),s),r.push(t)):o.logger.warn(`verification: Could not find device ${t} to verify`)}}if(!r.length)throw new Error("No devices could be verified");o.logger.info("Verification completed! Marking devices verified: ",r);for(const t of r)await this.baseApis.setDeviceVerified(e,t)}get events(){}}t.VerificationBase=g},6702:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.errorFactory=s,t.errorFromEvent=function(e){const t=e.getContent();if(t){const{code:e,reason:n}=t;return{code:e,reason:n}}return{code:"Unknown error",reason:"m.unknown"}},t.newUserCancelledError=t.newUnknownMethodError=t.newUnexpectedMessageError=t.newTimeoutError=t.newKeyMismatchError=t.newInvalidMessageError=void 0,t.newVerificationError=i;var r=n(4369);function i(e,t,n){const i=Object.assign({},{code:e,reason:t},n);return new r.MatrixEvent({type:"m.key.verification.cancel",content:i})}function s(e,t){return function(n){return i(e,t,n)}}const o=s("m.user","Cancelled by user");t.newUserCancelledError=o;const a=s("m.timeout","Timed out");t.newTimeoutError=a;const c=s("m.unknown_method","Unknown method");t.newUnknownMethodError=c;const l=s("m.unexpected_message","Unexpected message");t.newUnexpectedMessageError=l;const d=s("m.key_mismatch","Key mismatch");t.newKeyMismatchError=d;const u=s("m.invalid_message","Invalid message");t.newInvalidMessageError=u},4028:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.IllegalMethod=void 0;var i=r(n(8416)),s=n(1631);class o extends s.VerificationBase{constructor(...e){super(...e),(0,i.default)(this,"doVerification",(async()=>{throw new Error("Verification is not possible with this method")}))}static factory(e,t,n,r,i,s){return new o(e,t,n,r,i,s)}static get NAME(){return"org.matrix.illegal_method"}}t.IllegalMethod=o},1696:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SHOW_QR_CODE_METHOD=t.SCAN_QR_CODE_METHOD=t.ReciprocateQRCode=t.QrCodeEvent=t.QRCodeData=void 0;var i=r(n(8416)),s=n(1631),o=n(6702),a=n(2772),c=n(7434);let l;t.SHOW_QR_CODE_METHOD="m.qr_code.show.v1",t.SCAN_QR_CODE_METHOD="m.qr_code.scan.v1",t.QrCodeEvent=l,function(e){e.ShowReciprocateQr="show_reciprocate_qr"}(l||(t.QrCodeEvent=l={}));class d extends s.VerificationBase{constructor(...e){super(...e),(0,i.default)(this,"reciprocateQREvent",void 0),(0,i.default)(this,"doVerification",(async()=>{if(!this.startEvent)throw new Error("It is not currently possible to start verificationwith this method yet.");const{qrCodeData:e}=this.request;if(this.startEvent.getContent().secret!==e.encodedSharedSecret)throw(0,o.newKeyMismatchError)();await new Promise(((e,t)=>{this.reciprocateQREvent={confirm:e,cancel:()=>t((0,o.newUserCancelledError)())},this.emit(l.ShowReciprocateQr,this.reciprocateQREvent)}));const t={};switch(e.mode){case u.VerifyOtherUser:{const n=e.otherUserMasterKey;t[`ed25519:${n}`]=n;break}case u.VerifySelfTrusted:{const n=this.request.targetDevice.deviceId;t[`ed25519:${n}`]=e.otherDeviceKey;break}case u.VerifySelfUntrusted:{const n=e.myMasterKey;t[`ed25519:${n}`]=n;break}}await this.verifyKeys(this.userId,t,((e,n,r)=>{const i=t[e];if(!i)throw(0,o.newKeyMismatchError)();if(r!==i)throw c.logger.error("key ID from key info does not match"),(0,o.newKeyMismatchError)();for(const e in n.keys){if(!e.startsWith("ed25519"))continue;const r=t[e];if(!r)throw(0,o.newKeyMismatchError)();if(n.keys[e]!==r)throw c.logger.error("master key does not match"),(0,o.newKeyMismatchError)()}}))}))}static factory(e,t,n,r,i,s){return new d(e,t,n,r,i,s)}static get NAME(){return"m.reciprocate.v1"}}var u;t.ReciprocateQRCode=d,function(e){e[e.VerifyOtherUser=0]="VerifyOtherUser",e[e.VerifySelfTrusted=1]="VerifySelfTrusted",e[e.VerifySelfUntrusted=2]="VerifySelfUntrusted"}(u||(u={}));class h{constructor(e,t,n,r,i,s){this.mode=e,this.sharedSecret=t,this.otherUserMasterKey=n,this.otherDeviceKey=r,this.myMasterKey=i,this.buffer=s}static async create(e,t){const n=h.generateSharedSecret(),r=h.determineMode(e,t);let i=null,s=null,o=null;if(r===u.VerifyOtherUser)i=t.getStoredCrossSigningForUser(e.otherUserId).getId("master");else if(r===u.VerifySelfTrusted)s=await h.getOtherDeviceKey(e,t);else if(r===u.VerifySelfUntrusted){const e=t.getUserId();o=t.getStoredCrossSigningForUser(e).getId("master")}const a=h.generateQrData(e,t,r,n,i,s,o),c=h.generateBuffer(a);return new h(r,n,i,s,o,c)}get encodedSharedSecret(){return this.sharedSecret}getBuffer(){return this.buffer}static generateSharedSecret(){const e=new Uint8Array(11);return n.g.crypto.getRandomValues(e),(0,a.encodeUnpaddedBase64)(e)}static async getOtherDeviceKey(e,t){const n=t.getUserId(),r=e.targetDevice,i=r?r.deviceId:null,s=t.getStoredDevice(n,i);if(!s)throw new Error("could not find device "+i);return s.getFingerprint()}static determineMode(e,t){const n=t.getUserId(),r=e.otherUserId;let i=u.VerifyOtherUser;return n===r&&(i=t.checkUserTrust(n).isCrossSigningVerified()?u.VerifySelfTrusted:u.VerifySelfUntrusted),i}static generateQrData(e,t,n,r,i,s,o){const a=t.getUserId(),c={prefix:"MATRIX",version:2,mode:n,transactionId:e.channel.transactionId,firstKeyB64:"",secondKeyB64:"",secretB64:r},l=t.getStoredCrossSigningForUser(a);return n===u.VerifyOtherUser?(c.firstKeyB64=l.getId("master"),c.secondKeyB64=i):n===u.VerifySelfTrusted?(c.firstKeyB64=l.getId("master"),c.secondKeyB64=s):n===u.VerifySelfUntrusted&&(c.firstKeyB64=t.getDeviceEd25519Key(),c.secondKeyB64=o),c}static generateBuffer(e){let t=Buffer.alloc(0);const n=e=>{const n=Buffer.from([e]);t=Buffer.concat([t,n])},r=(e,n,r=!0)=>{const i=Buffer.from(e,n);r&&(e=>{const n=Buffer.alloc(2);n.writeInt16BE(e,0),t=Buffer.concat([t,n])})(i.byteLength),t=Buffer.concat([t,i])},i=e=>{const n=(0,a.decodeBase64)(e),r=Buffer.from(n);t=Buffer.concat([t,r])};return r(e.prefix,"ascii",!1),n(e.version),n(e.mode),r(e.transactionId,"utf-8"),i(e.firstKeyB64),i(e.secondKeyB64),i(e.secretB64),t}}t.QRCodeData=h},6381:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SasEvent=t.SAS=void 0;var i=r(n(8416)),s=r(n(9141)),o=n(1631),a=n(6702),c=n(7434);const l="m.key.verification.start",d=["m.key.verification.accept","m.key.verification.key","m.key.verification.mac"];let u;const h=(0,a.errorFactory)("m.mismatched_sas","Mismatched short authentication string"),f=(0,a.errorFactory)("m.mismatched_commitment","Mismatched commitment"),g=[["🐶","dog"],["🐱","cat"],["🦁","lion"],["🐎","horse"],["🦄","unicorn"],["🐷","pig"],["🐘","elephant"],["🐰","rabbit"],["🐼","panda"],["🐓","rooster"],["🐧","penguin"],["🐢","turtle"],["🐟","fish"],["🐙","octopus"],["🦋","butterfly"],["🌷","flower"],["🌳","tree"],["🌵","cactus"],["🍄","mushroom"],["🌏","globe"],["🌙","moon"],["☁️","cloud"],["🔥","fire"],["🍌","banana"],["🍎","apple"],["🍓","strawberry"],["🌽","corn"],["🍕","pizza"],["🎂","cake"],["❤️","heart"],["🙂","smiley"],["🤖","robot"],["🎩","hat"],["👓","glasses"],["🔧","spanner"],["🎅","santa"],["👍","thumbs up"],["☂️","umbrella"],["⌛","hourglass"],["⏰","clock"],["🎁","gift"],["💡","light bulb"],["📕","book"],["✏️","pencil"],["📎","paperclip"],["✂️","scissors"],["🔒","lock"],["🔑","key"],["🔨","hammer"],["☎️","telephone"],["🏁","flag"],["🚂","train"],["🚲","bicycle"],["✈️","aeroplane"],["🚀","rocket"],["🏆","trophy"],["⚽","ball"],["🎸","guitar"],["🎺","trumpet"],["🔔","bell"],["⚓️","anchor"],["🎧","headphones"],["📁","folder"],["📌","pin"]],p={decimal:function(e){return[1e3+(e[0]<<5|e[1]>>3),1e3+((7&e[1])<<10|e[2]<<2|e[3]>>6),1e3+((63&e[3])<<7|e[4]>>1)]},emoji:function(e){return[e[0]>>2,(3&e[0])<<4|e[1]>>4,(15&e[1])<<2|e[2]>>6,63&e[2],e[3]>>2,(3&e[3])<<4|e[4]>>4,(15&e[4])<<2|e[5]>>6].map((e=>g[e]))}};function m(e,t){const n={};for(const r of t)r in p&&(n[r]=p[r](e));return n}const y={"hkdf-hmac-sha256":"calculate_mac","org.matrix.msc3783.hkdf-hmac-sha256":"calculate_mac_fixed_base64","hmac-sha256":"calculate_mac_long_kdf"};function v(e,t){return function(...n){const r=e[y[t]].apply(e,n);return c.logger.log("SAS calculateMAC:",t,n,r),r}}const b={"curve25519-hkdf-sha256":function(e,t,n){const r=`${e.baseApis.getUserId()}|${e.baseApis.deviceId}|${e.ourSASPubKey}|`,i=`${e.userId}|${e.deviceId}|${e.theirSASPubKey}|`,s="MATRIX_KEY_VERIFICATION_SAS|"+(e.initiatedByMe?r+i:i+r)+e.channel.transactionId;return t.generate_bytes(s,n)},curve25519:function(e,t,n){const r=`${e.baseApis.getUserId()}${e.baseApis.deviceId}`,i=`${e.userId}${e.deviceId}`,s="MATRIX_KEY_VERIFICATION_SAS"+(e.initiatedByMe?r+i:i+r)+e.channel.transactionId;return t.generate_bytes(s,n)}},_=["curve25519-hkdf-sha256","curve25519"],E=["sha256"],w=["org.matrix.msc3783.hkdf-hmac-sha256","hkdf-hmac-sha256","hmac-sha256"],S=Object.keys(p),C=new Set(_),T=new Set(E),R=new Set(w),I=new Set(S);function k(e,t){return e instanceof Array?e.filter((e=>t.has(e))):[]}let O;t.SasEvent=O,function(e){e.ShowSas="show_sas"}(O||(t.SasEvent=O={}));class A extends o.VerificationBase{constructor(...e){super(...e),(0,i.default)(this,"waitingForAccept",void 0),(0,i.default)(this,"ourSASPubKey",void 0),(0,i.default)(this,"theirSASPubKey",void 0),(0,i.default)(this,"sasEvent",void 0),(0,i.default)(this,"doVerification",(async()=>{await n.g.Olm.init(),u=u||new n.g.Olm.Utility,await this.baseApis.downloadKeys([this.userId]);let e=!1;do{try{return this.initiatedByMe?await this.doSendVerification():await this.doRespondVerification()}catch(t){if(!(t instanceof o.SwitchStartEventError))throw t;this.startEvent=t.startEvent,e=!0}}while(e)}))}static get NAME(){return"m.sas.v1"}get events(){return d}canSwitchStartEvent(e){if(e.getType()!==l)return!1;const t=e.getContent();return t&&t.method===A.NAME&&this.waitingForAccept}async sendStart(){const e=this.channel.completeContent(l,{method:A.NAME,from_device:this.baseApis.deviceId,key_agreement_protocols:_,hashes:E,message_authentication_codes:w,short_authentication_string:S});return await this.channel.sendCompleted(l,e),e}async doSendVerification(){let e,t;if(this.waitingForAccept=!0,e=this.startEvent?this.channel.completedContentFromEvent(this.startEvent):await this.sendStart(),!this.initiatedByMe)throw new o.SwitchStartEventError(this.startEvent);try{t=await this.waitForEvent("m.key.verification.accept")}finally{this.waitingForAccept=!1}let r=t.getContent();const i=k(r.short_authentication_string,I);if(!(C.has(r.key_agreement_protocol)&&T.has(r.hash)&&R.has(r.message_authentication_code)&&i.length))throw(0,a.newUnknownMethodError)();if("string"!=typeof r.commitment)throw(0,a.newInvalidMessageError)();const c=r.key_agreement_protocol,l=r.message_authentication_code,d=r.commitment,g=new n.g.Olm.SAS;try{this.ourSASPubKey=g.get_pubkey(),await this.send("m.key.verification.key",{key:this.ourSASPubKey}),t=await this.waitForEvent("m.key.verification.key"),r=t.getContent();const n=r.key+s.default.stringify(e);if(u.sha256(n)!==d)throw f();this.theirSASPubKey=r.key,g.set_their_key(r.key);const o=b[c](this,g,6),p=new Promise(((e,t)=>{this.sasEvent={sas:m(o,i),confirm:async()=>{try{await this.sendMAC(g,l),e()}catch(e){t(e)}},cancel:()=>t((0,a.newUserCancelledError)()),mismatch:()=>t(h())},this.emit(O.ShowSas,this.sasEvent)}));[t]=await Promise.all([this.waitForEvent("m.key.verification.mac").then((e=>(this.expectedEvent="m.key.verification.done",e))),p]),r=t.getContent(),await this.checkMAC(g,r,l)}finally{g.free()}}async doRespondVerification(){let e=this.channel.completedContentFromEvent(this.startEvent);const t=k(_,new Set(e.key_agreement_protocols))[0],r=k(E,new Set(e.hashes))[0],i=k(w,new Set(e.message_authentication_codes))[0],o=k(e.short_authentication_string,I);if(void 0===t||void 0===r||void 0===i||!o.length)throw(0,a.newUnknownMethodError)();const c=new n.g.Olm.SAS;try{const n=c.get_pubkey()+s.default.stringify(e);await this.send("m.key.verification.accept",{key_agreement_protocol:t,hash:r,message_authentication_code:i,short_authentication_string:o,commitment:u.sha256(n)});let l=await this.waitForEvent("m.key.verification.key");e=l.getContent(),this.theirSASPubKey=e.key,c.set_their_key(e.key),this.ourSASPubKey=c.get_pubkey(),await this.send("m.key.verification.key",{key:this.ourSASPubKey});const d=b[t](this,c,6),f=new Promise(((e,t)=>{this.sasEvent={sas:m(d,o),confirm:async()=>{try{await this.sendMAC(c,i),e()}catch(e){t(e)}},cancel:()=>t((0,a.newUserCancelledError)()),mismatch:()=>t(h())},this.emit(O.ShowSas,this.sasEvent)}));[l]=await Promise.all([this.waitForEvent("m.key.verification.mac").then((e=>(this.expectedEvent="m.key.verification.done",e))),f]),e=l.getContent(),await this.checkMAC(c,e,i)}finally{c.free()}}sendMAC(e,t){const n={},r=[],i="MATRIX_KEY_VERIFICATION_MAC"+this.baseApis.getUserId()+this.baseApis.deviceId+this.userId+this.deviceId+this.channel.transactionId,s=`ed25519:${this.baseApis.deviceId}`;n[s]=v(e,t)(this.baseApis.getDeviceEd25519Key(),i+s),r.push(s);const o=this.baseApis.getCrossSigningId();if(o){const s=`ed25519:${o}`;n[s]=v(e,t)(o,i+s),r.push(s)}const a=v(e,t)(r.sort().join(","),i+"KEY_IDS");return this.send("m.key.verification.mac",{mac:n,keys:a})}async checkMAC(e,t,n){const r="MATRIX_KEY_VERIFICATION_MAC"+this.userId+this.deviceId+this.baseApis.getUserId()+this.baseApis.deviceId+this.channel.transactionId;if(t.keys!==v(e,n)(Object.keys(t.mac).sort().join(","),r+"KEY_IDS"))throw(0,a.newKeyMismatchError)();await this.verifyKeys(this.userId,t.mac,((t,i,s)=>{if(s!==v(e,n)(i.keys[t],r+t))throw(0,a.newKeyMismatchError)()}))}}t.SAS=A},2842:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.InRoomRequests=t.InRoomChannel=void 0;var i=r(n(8416)),s=n(5279),o=n(7434);const a=n(2481).EventType.RoomMessage,c="m.reference",l="m.relates_to";class d{constructor(e,t,n=null){this.client=e,this.roomId=t,this.userId=n,(0,i.default)(this,"requestEventId",null)}get receiveStartFromOtherDevices(){return!0}get transactionId(){return this.requestEventId}static getOtherPartyUserId(e,t){if(d.getEventType(e)!==s.REQUEST_TYPE)return;const n=t.getUserId(),r=e.getSender(),i=e.getContent().to;return r===n?i:i===n?r:void 0}getTimestamp(e){return e.getTs()}static canCreateRequest(e){return e===s.REQUEST_TYPE}canCreateRequest(e){return d.canCreateRequest(e)}static getTransactionId(e){if(d.getEventType(e)===s.REQUEST_TYPE)return e.getId();{const t=e.getRelation();if(t&&t.rel_type===c)return t.event_id}}static validateEvent(e,t){const n=d.getTransactionId(e);if("string"!=typeof n||0===n.length)return!1;const r=d.getEventType(e),i=e.getContent();if(r===s.REQUEST_TYPE){if(!i||"string"!=typeof i.to||!i.to.length)return o.logger.log("InRoomChannel: validateEvent: no valid to "+(i&&i.to)),!1;if(!d.getOtherPartyUserId(e,t))return o.logger.log(`InRoomChannel: validateEvent: not directed to or sent by me: ${e.getSender()}, ${i&&i.to}`),!1}return s.VerificationRequest.validateEvent(r,e,t)}static getEventType(e){const t=e.getType();if(t===a){const t=e.getContent();if(t){const{msgtype:e}=t;if(e===s.REQUEST_TYPE)return s.REQUEST_TYPE}}return t&&t!==s.REQUEST_TYPE?t:""}handleEvent(e,t,n=!1){if(t.hasEventId(e.getId()))return;const r=d.getEventType(e);if(e.getRoomId()!==this.roomId)return;if(null===this.userId){const t=d.getOtherPartyUserId(e,this.client);t&&(this.userId=t)}const i=this.client.getUserId(),s=e.getSender();if(null!==this.userId&&s!==i&&s!==this.userId)return void o.logger.log(`InRoomChannel: ignoring verification event from non-participating sender ${s}`);null===this.requestEventId&&(this.requestEventId=d.getTransactionId(e));const a=!!e.getUnsigned().transaction_id,c=e.getSender()===this.client.getUserId();return t.handleEvent(r,e,n,a,c)}completedContentFromEvent(e){const t=Object.assign({},e.getContent());return t[l]=e.getRelation(),t}completeContent(e,t){return t=Object.assign({},t),e!==s.REQUEST_TYPE&&e!==s.READY_TYPE&&e!==s.START_TYPE||(t.from_device=this.client.getDeviceId()),e===s.REQUEST_TYPE?t={body:this.client.getUserId()+" is requesting to verify your key, but your client does not support in-chat key verification. You will need to use legacy key verification to verify keys.",msgtype:s.REQUEST_TYPE,to:this.userId,from_device:t.from_device,methods:t.methods}:t[l]={rel_type:c,event_id:this.transactionId},t}send(e,t){const n=this.completeContent(e,t);return this.sendCompleted(e,n)}async sendCompleted(e,t){let n=e;e===s.REQUEST_TYPE&&(n=a);const r=await this.client.sendEvent(this.roomId,n,t);e===s.REQUEST_TYPE&&(this.requestEventId=r.event_id)}}t.InRoomChannel=d,t.InRoomRequests=class{constructor(){(0,i.default)(this,"requestsByRoomId",new Map)}getRequest(e){const t=e.getRoomId(),n=d.getTransactionId(e);return this.getRequestByTxnId(t,n)}getRequestByChannel(e){return this.getRequestByTxnId(e.roomId,e.transactionId)}getRequestByTxnId(e,t){const n=this.requestsByRoomId.get(e);if(n)return n.get(t)}setRequest(e,t){this.doSetRequest(e.getRoomId(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.doSetRequest(e.roomId,e.transactionId,t)}doSetRequest(e,t,n){let r=this.requestsByRoomId.get(e);r||(r=new Map,this.requestsByRoomId.set(e,r)),r.set(t,n)}removeRequest(e){const t=e.getRoomId(),n=this.requestsByRoomId.get(t);n&&(n.delete(d.getTransactionId(e)),0===n.size&&this.requestsByRoomId.delete(t))}findRequestInProgress(e){const t=this.requestsByRoomId.get(e);if(t)for(const e of t.values())if(e.pending)return e}}},9588:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.ToDeviceRequests=t.ToDeviceChannel=void 0;var i=r(n(8416)),s=n(8401),o=n(7434),a=n(5279),c=n(6702),l=n(4369);class d{constructor(e,t,n,r=null,s=null){this.client=e,this.userId=t,this.devices=n,this.transactionId=r,this.deviceId=s,(0,i.default)(this,"request",void 0)}isToDevices(e){if(e.length===this.devices.length){for(const t of e)if(!this.devices.includes(t))return!1;return!0}return!1}static getEventType(e){return e.getType()}static getTransactionId(e){const t=e.getContent();return t&&t.transaction_id}static canCreateRequest(e){return e===a.REQUEST_TYPE||e===a.START_TYPE}canCreateRequest(e){return d.canCreateRequest(e)}static validateEvent(e,t){if(e.isCancelled())return o.logger.warn("Ignoring flagged verification request from "+e.getSender()),!1;const n=e.getContent();if(!n)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no content"),!1;if(!n.transaction_id)return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no transaction_id"),!1;const r=e.getType();if(r===a.REQUEST_TYPE){if(!Number.isFinite(n.timestamp))return o.logger.warn("ToDeviceChannel.validateEvent: invalid: no timestamp"),!1;if(e.getSender()===t.getUserId()&&n.from_device==t.getDeviceId())return o.logger.warn("ToDeviceChannel.validateEvent: invalid: from own device"),!1}return a.VerificationRequest.validateEvent(r,e,t)}getTimestamp(e){const t=e.getContent();return t&&t.timestamp}async handleEvent(e,t,n=!1){const r=e.getType(),i=e.getContent();if(r===a.REQUEST_TYPE||r===a.READY_TYPE||r===a.START_TYPE){this.transactionId||(this.transactionId=i.transaction_id);const e=i.from_device;if(!this.deviceId&&this.devices.includes(e)&&(this.deviceId=e),!this.deviceId||this.deviceId!==e){const t=this.completeContent(a.CANCEL_TYPE,(0,c.errorFromEvent)((0,c.newUnexpectedMessageError)()));return this.sendToDevices(a.CANCEL_TYPE,t,[e])}}const s=t.phase===a.PHASE_STARTED||t.phase===a.PHASE_READY;await t.handleEvent(e.getType(),e,n,!1,!1);const o=t.phase===a.PHASE_STARTED||t.phase===a.PHASE_READY;if((r===a.START_TYPE||r===a.READY_TYPE)&&!s&&o&&this.deviceId){const e=this.devices.filter((e=>e!==this.deviceId&&e!==this.client.getDeviceId()));if(e.length){const t=this.completeContent(a.CANCEL_TYPE,{code:"m.accepted",reason:"Verification request accepted by another device"});await this.sendToDevices(a.CANCEL_TYPE,t,e)}}}completedContentFromEvent(e){return e.getContent()}completeContent(e,t){return t=Object.assign({},t),this.transactionId&&(t.transaction_id=this.transactionId),e!==a.REQUEST_TYPE&&e!==a.READY_TYPE&&e!==a.START_TYPE||(t.from_device=this.client.getDeviceId()),e===a.REQUEST_TYPE&&(t.timestamp=Date.now()),t}send(e,t={}){e!==a.REQUEST_TYPE&&e!==a.START_TYPE||this.transactionId||(this.transactionId=d.makeTransactionId());const n=this.completeContent(e,t);return this.sendCompleted(e,n)}async sendCompleted(e,t){let n;n=e===a.REQUEST_TYPE||e===a.CANCEL_TYPE&&!this.deviceId?await this.sendToDevices(e,t,this.devices):await this.sendToDevices(e,t,[this.deviceId]);const r=new l.MatrixEvent({sender:this.client.getUserId(),content:t,type:e});return await this.request.handleEvent(e,r,!0,!0,!0),n}async sendToDevices(e,t,n){if(n.length){const r={};for(const e of n)r[e]=t;await this.client.sendToDevice(e,{[this.userId]:r})}}static makeTransactionId(){return(0,s.randomString)(32)}}t.ToDeviceChannel=d,t.ToDeviceRequests=class{constructor(){(0,i.default)(this,"requestsByUserId",new Map)}getRequest(e){return this.getRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e))}getRequestByChannel(e){return this.getRequestBySenderAndTxnId(e.userId,e.transactionId)}getRequestBySenderAndTxnId(e,t){const n=this.requestsByUserId.get(e);if(n)return n.get(t)}setRequest(e,t){this.setRequestBySenderAndTxnId(e.getSender(),d.getTransactionId(e),t)}setRequestByChannel(e,t){this.setRequestBySenderAndTxnId(e.userId,e.transactionId,t)}setRequestBySenderAndTxnId(e,t,n){let r=this.requestsByUserId.get(e);r||(r=new Map,this.requestsByUserId.set(e,r)),r.set(t,n)}removeRequest(e){const t=e.getSender(),n=this.requestsByUserId.get(t);n&&(n.delete(d.getTransactionId(e)),0===n.size&&this.requestsByUserId.delete(t))}findRequestInProgress(e,t){const n=this.requestsByUserId.get(e);if(n)for(const e of n.values())if(e.pending&&e.channel.isToDevices(t))return e}getRequestsInProgress(e){const t=this.requestsByUserId.get(e);return t?Array.from(t.values()).filter((e=>e.pending)):[]}}},5279:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.VerificationRequestEvent=t.VerificationRequest=t.START_TYPE=t.REQUEST_TYPE=t.READY_TYPE=t.Phase=t.PHASE_UNSENT=t.PHASE_STARTED=t.PHASE_REQUESTED=t.PHASE_READY=t.PHASE_DONE=t.PHASE_CANCELLED=t.EVENT_PREFIX=t.DONE_TYPE=t.CANCEL_TYPE=void 0;var i=r(n(8416)),s=n(7434),o=n(6702),a=n(1696),c=n(5861);const l="m.key.verification.";t.EVENT_PREFIX=l;const d=l+"request";t.REQUEST_TYPE=d;const u=l+"start";t.START_TYPE=u;const h=l+"cancel";t.CANCEL_TYPE=h;const f=l+"done";t.DONE_TYPE=f;const g=l+"ready";let p;t.READY_TYPE=g,t.Phase=p,function(e){e[e.Unsent=1]="Unsent",e[e.Requested=2]="Requested",e[e.Ready=3]="Ready",e[e.Started=4]="Started",e[e.Cancelled=5]="Cancelled",e[e.Done=6]="Done"}(p||(t.Phase=p={}));const m=p.Unsent;t.PHASE_UNSENT=m;const y=p.Requested;t.PHASE_REQUESTED=y;const v=p.Ready;t.PHASE_READY=v;const b=p.Started;t.PHASE_STARTED=b;const _=p.Cancelled;t.PHASE_CANCELLED=_;const E=p.Done;let w;t.PHASE_DONE=E,t.VerificationRequestEvent=w,function(e){e.Change="change"}(w||(t.VerificationRequestEvent=w={}));class S extends c.TypedEventEmitter{constructor(e,t,n){super(),this.channel=e,this.verificationMethods=t,this.client=n,(0,i.default)(this,"eventsByUs",new Map),(0,i.default)(this,"eventsByThem",new Map),(0,i.default)(this,"_observeOnly",!1),(0,i.default)(this,"timeoutTimer",null),(0,i.default)(this,"_accepting",!1),(0,i.default)(this,"_declining",!1),(0,i.default)(this,"verifierHasFinished",!1),(0,i.default)(this,"_cancelled",!1),(0,i.default)(this,"_chosenMethod",null),(0,i.default)(this,"_qrCodeData",null),(0,i.default)(this,"requestReceivedAt",null),(0,i.default)(this,"commonMethods",[]),(0,i.default)(this,"_phase",void 0),(0,i.default)(this,"_cancellingUserId",void 0),(0,i.default)(this,"_verifier",void 0),(0,i.default)(this,"cancelOnTimeout",(async()=>{try{this.initiatedByMe?await this.cancel({reason:"Other party didn't accept in time",code:"m.timeout"}):await this.cancel({reason:"User didn't accept in time",code:"m.timeout"})}catch(e){s.logger.error("Error while cancelling verification request",e)}})),this.channel.request=this,this.setPhase(m,!1)}static validateEvent(e,t,n){const r=t.getContent();return!(!e||!e.startsWith(l))&&(r?e!==d&&e!==g||Array.isArray(r.methods)?e!==d&&e!==g&&e!==u||"string"==typeof r.from_device&&0!==r.from_device.length||(s.logger.log("VerificationRequest: validateEvent: fail because from_device"),!1):(s.logger.log("VerificationRequest: validateEvent: fail because methods"),!1):(s.logger.log("VerificationRequest: validateEvent: no content"),!1))}get invalid(){return this.phase===m}get requested(){return this.phase===y}get cancelled(){return this.phase===_}get ready(){return this.phase===v}get started(){return this.phase===b}get done(){return this.phase===E}get methods(){return this.commonMethods}get chosenMethod(){return this._chosenMethod}calculateEventTimeout(e){let t=this.channel.getTimestamp(e)+6e5;if(this.requestReceivedAt&&!this.initiatedByMe&&this.phase<=y){const e=this.requestReceivedAt+12e4;t=Math.min(t,e)}return Math.max(0,t-Date.now())}get timeout(){const e=this.getEventByEither(d);return e?this.calculateEventTimeout(e):0}get requestEvent(){return this.getEventByEither(d)}get phase(){return this._phase}get verifier(){return this._verifier}get canAccept(){return this.phase<v&&!this._accepting&&!this._declining}get accepting(){return this._accepting}get declining(){return this._declining}get pending(){return!this.observeOnly&&this._phase!==E&&this._phase!==_}get qrCodeData(){return this._qrCodeData}otherPartySupportsMethod(e,t=!1){if(!t&&!this.ready&&!this.started)return!1;const n=this.eventsByThem.get(d)||this.eventsByThem.get(g);if(!n){if(this.started&&this.initiatedByMe){const t=this.eventsByUs.get(u),n=t&&t.getContent();return e==(n&&n.method)}return!1}const r=n.getContent();if(!r)return!1;const{methods:i}=r;return!!Array.isArray(i)&&i.includes(e)}get initiatedByMe(){const e=this.eventsByUs.size+this.eventsByThem.size===0;if(this._phase===m&&e)return!0;const t=this.eventsByUs.has(d),n=this.eventsByThem.has(d);if(t&&!n)return!0;if(!t&&n)return!1;const r=this.eventsByUs.has(u),i=this.eventsByThem.has(u);return!(!r||i)}get requestingUserId(){return this.initiatedByMe?this.client.getUserId():this.otherUserId}get receivingUserId(){return this.initiatedByMe?this.otherUserId:this.client.getUserId()}get otherUserId(){return this.channel.userId}get isSelfVerification(){return this.client.getUserId()===this.otherUserId}get cancellingUserId(){const e=this.eventsByUs.get(h),t=this.eventsByThem.get(h);return e&&(!t||e.getId()<t.getId())?e.getSender():t?t.getSender():void 0}get cancellationCode(){const e=this.getEventByEither(h);return e?e.getContent().code:null}get observeOnly(){return this._observeOnly}get targetDevice(){const e=(this.eventsByThem.get(d)||this.eventsByThem.get(g)||this.eventsByThem.get(u)).getContent().from_device;return{userId:this.otherUserId,deviceId:e}}beginKeyVerification(e,t=null){if(!this.observeOnly&&!this._verifier&&(this.phase===y||this.phase===v||this.phase===m&&this.channel.canCreateRequest(u))){if(this.commonMethods.length&&!this.commonMethods.includes(e))throw(0,o.newUnknownMethodError)();if(this._verifier=this.createVerifier(e,null,t),!this._verifier)throw(0,o.newUnknownMethodError)();this._chosenMethod=e}return this._verifier}async sendRequest(){if(!this.observeOnly&&this._phase===m){const e=[...this.verificationMethods.keys()];await this.channel.send(d,{methods:e})}}async cancel({reason:e="User declined",code:t="m.user"}={}){if(!this.observeOnly&&this._phase!==_){if(this._declining=!0,this.emit(w.Change),this._verifier)return this._verifier.cancel((0,o.errorFactory)(t,e)());this._cancellingUserId=this.client.getUserId(),await this.channel.send(h,{code:t,reason:e})}}async accept(){if(!this.observeOnly&&this.phase===y&&!this.initiatedByMe){const e=[...this.verificationMethods.keys()];this._accepting=!0,this.emit(w.Change),await this.channel.send(g,{methods:e})}}waitFor(e){return new Promise(((t,n)=>{const r=()=>{let i=!1;return e(this)?(t(this),i=!0):this.cancelled&&(n(new Error("cancelled")),i=!0),i&&this.off(w.Change,r),i};r()||this.on(w.Change,r)}))}setPhase(e,t=!0){this._phase=e,t&&this.emit(w.Change)}getEventByEither(e){return this.eventsByThem.get(e)||this.eventsByUs.get(e)}getEventBy(e,t=!1){return t?this.eventsByThem.get(e):this.eventsByUs.get(e)}calculatePhaseTransitions(){const e=[{phase:m}],t=()=>e[e.length-1].phase,n=this.eventsByThem.has(d),r=this.getEventBy(d,n);r&&e.push({phase:y,event:r});const i=r&&this.getEventBy(g,!n);let s;if(i&&t()===y&&e.push({phase:v,event:i}),i||!r){const e=this.eventsByThem.get(u),t=this.eventsByUs.get(u);s=e&&t?e.getSender()<t.getSender()?e:t:e||t}else s=this.getEventBy(u,!n);if(s){const n=t()===y&&r.getSender()!==s.getSender(),i=t()===m&&this.channel.canCreateRequest(u);(n||t()===v||i)&&e.push({phase:b,event:s})}const o=this.eventsByUs.get(f);(this.verifierHasFinished||o&&t()===b)&&e.push({phase:E});const a=this.getEventByEither(h);return(this._cancelled||a)&&t()!==E?(e.push({phase:_,event:a}),e):e}transitionToPhase(e){const{phase:t,event:n}=e;if((t===y||t===v)&&!this.wasSentByOwnDevice(n)){const e=n.getContent();this.commonMethods=e.methods.filter((e=>this.verificationMethods.has(e)))}if(this.observeOnly||t!==y&&t!==b&&t!==v||this.channel.receiveStartFromOtherDevices&&this.wasSentByOwnUser(n)&&!this.wasSentByOwnDevice(n)&&(this._observeOnly=!0),t===b){const{method:e}=n.getContent();this._verifier||this.observeOnly||(this._verifier=this.createVerifier(e,n),this._verifier?this._chosenMethod=e:this.cancel({code:"m.unknown_method",reason:`Unknown method: ${e}`}))}}applyPhaseTransitions(){const e=this.calculatePhaseTransitions(),t=e.findIndex((e=>e.phase===this.phase)),n=e.slice(t+1);for(const e of n)this.transitionToPhase(e);return n}isWinningStartRace(e){if(e.getType()!==u)return!1;const t=this._verifier.startEvent;let n,r;if(this.isSelfVerification)if(t){const e=t.getContent();n=e&&e.from_device}else n=this.client.getDeviceId();else n=t?t.getSender():this.client.getUserId();if(this.isSelfVerification){const t=e.getContent();r=t&&t.from_device}else r=e.getSender();return r<n}hasEventId(e){for(const t of this.eventsByUs.values())if(t.getId()===e)return!0;for(const t of this.eventsByThem.values())if(t.getId()===e)return!0;return!1}async handleEvent(e,t,n,r,i){if(this.done||this.cancelled)return;const o=this._observeOnly;if(this.adjustObserveOnly(t,n),!this.observeOnly&&!r&&await this.cancelOnError(e,t))return;if(i?this.eventsByUs.has(e):this.eventsByThem.has(e))return;const c=this.phase;this.addEvent(e,t,i);const l=this.applyPhaseTransitions();try{if(this._verifier&&!this.observeOnly){const n=this.isWinningStartRace(t);if(this._verifier.canSwitchStartEvent(t)&&n)this._verifier.switchStartEvent(t);else if(!r){var d;(e===h||null!==(d=this._verifier.events)&&void 0!==d&&d.includes(e))&&this._verifier.handleEvent(t)}}if(l.length){n&&l.some((e=>e.phase===v))&&this.otherPartySupportsMethod(a.SCAN_QR_CODE_METHOD,!0)&&(this._qrCodeData=await a.QRCodeData.create(this,this.client));const e=l[l.length-1],{phase:t}=e;this.setupTimeout(t),this.setPhase(t)}else this._observeOnly!==o&&this.emit(w.Change)}finally{s.logger.log(`Verification request ${this.channel.transactionId}: ${e} event with id:${t.getId()}, content:${JSON.stringify(t.getContent())} deviceId:${this.channel.deviceId}, sender:${t.getSender()}, isSentByUs:${i}, isLiveEvent:${n}, isRemoteEcho:${r}, phase:${c}=>${this.phase}, observeOnly:${o}=>${this._observeOnly}`)}}setupTimeout(e){!this.timeoutTimer&&!this.observeOnly&&e===y&&(this.timeoutTimer=setTimeout(this.cancelOnTimeout,this.timeout)),this.timeoutTimer&&(e===b||e===v||e===E||e===_)&&(clearTimeout(this.timeoutTimer),this.timeoutTimer=null)}async cancelOnError(e,t){if(e===u){const e=t.getContent().method;if(!this.verificationMethods.has(e))return await this.cancel((0,o.errorFromEvent)((0,o.newUnknownMethodError)())),!0}const n=e===d&&this.phase!==m,r=e===g&&this.phase!==y&&this.phase!==b;if(this.phase!==m&&(n||r)){s.logger.warn(`Cancelling, unexpected ${e} verification event from ${t.getSender()}`);const n=`Unexpected ${e} event in phase ${this.phase}`;return await this.cancel((0,o.errorFromEvent)((0,o.newUnexpectedMessageError)({reason:n}))),!0}return!1}adjustObserveOnly(e,t=!1){t||(this._observeOnly=!0),this.calculateEventTimeout(e)<3e3&&(this._observeOnly=!0)}addEvent(e,t,n=!1){if(n?this.eventsByUs.set(e,t):this.eventsByThem.set(e,t),e===d){for(const[e,t]of this.eventsByThem.entries())t.getSender()!==this.otherUserId&&this.eventsByThem.delete(e);this.requestReceivedAt=Date.now()}}createVerifier(e,t=null,n=null){n||(n=this.targetDevice);const{userId:r,deviceId:i}=n,o=this.verificationMethods.get(e);if(o)return new o(this.channel,this.client,r,i,t,this);s.logger.warn("could not find verifier constructor for method",e)}wasSentByOwnUser(e){return e.getSender()===this.client.getUserId()}wasSentByOwnDevice(e){if(!this.wasSentByOwnUser(e))return!1;const t=e.getContent();return!(!t||t.from_device!==this.client.getDeviceId())}onVerifierCancelled(){this._cancelled=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}onVerifierFinished(){this.channel.send("m.key.verification.done",{}),this.verifierHasFinished=!0;const e=this.applyPhaseTransitions();e.length&&this.setPhase(e[e.length-1].phase)}getEventFromOtherParty(e){return this.eventsByThem.get(e)}}t.VerificationRequest=S},9489:(e,t)=>{"use strict";function n(e,t){const n=`Store is invalid because ${e}, please stop the client, delete all data and start the client again`,r=Reflect.construct(Error,[n]);return Reflect.setPrototypeOf(r,Reflect.getPrototypeOf(this)),r.reason=e,r.value=t,r}function r(e){const t=`Crypto store is invalid because ${e}, please stop the client, delete all data and start the client again`,n=Reflect.construct(Error,[t]);return Reflect.setPrototypeOf(n,Reflect.getPrototypeOf(this)),n.reason=e,n.name="InvalidCryptoStoreError",n}Object.defineProperty(t,"__esModule",{value:!0}),t.InvalidCryptoStoreError=r,t.InvalidStoreError=n,t.KeySignatureUploadError=void 0,n.TOGGLED_LAZY_LOADING="TOGGLED_LAZY_LOADING",n.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Reflect.setPrototypeOf(n,Error),r.TOO_NEW="TOO_NEW",r.prototype=Object.create(Error.prototype,{constructor:{value:Error,enumerable:!1,writable:!0,configurable:!0}}),Reflect.setPrototypeOf(r,Error);class i extends Error{constructor(e,t){super(e),this.value=t}}t.KeySignatureUploadError=i},1166:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.eventMapperFor=function(e,t){let n=Boolean(t.preventReEmit);const r=!1!==t.decrypt;return function(t){const i=e.getRoom(t.room_id);let o;i&&void 0===t.state_key&&(o=i.findEventById(t.event_id)),!o||o.status?o=new s.MatrixEvent(t):(o.setUnsigned(a(a({},o.getUnsigned()),t.unsigned)),n=!0);const c=null==i?void 0:i.findThreadForEvent(o);return c&&o.setThread(c),o.isEncrypted()&&(n||e.reEmitter.reEmit(o,[s.MatrixEventEvent.Decrypted]),r&&e.decryptEventIfNeeded(o)),n||(e.reEmitter.reEmit(o,[s.MatrixEventEvent.Replaced,s.MatrixEventEvent.VisibilityChange]),null==i||i.reEmitter.reEmit(o,[s.MatrixEventEvent.BeforeRedaction])),o}};var i=r(n(8416)),s=n(4369);function o(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function a(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?o(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):o(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}},3564:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.FilterComponent=void 0;var r=n(6969);t.FilterComponent=class{constructor(e,t){this.filterJson=e,this.userId=t}check(e){var t,n;const i=(null===(t=e.getUnsigned())||void 0===t?void 0:t["m.relations"])||{},s=Object.keys(i),o=[];return this.userId&&null!=i&&null!==(n=i[r.THREAD_RELATION_TYPE.name])&&void 0!==n&&n.current_user_participated&&o.push(this.userId),this.checkFields(e.getRoomId(),e.getSender(),e.getType(),!!e.getContent()&&void 0!==e.getContent().url,s,o)}toJSON(){return{types:this.filterJson.types||null,not_types:this.filterJson.not_types||[],rooms:this.filterJson.rooms||null,not_rooms:this.filterJson.not_rooms||[],senders:this.filterJson.senders||null,not_senders:this.filterJson.not_senders||[],contains_url:this.filterJson.contains_url||null,[r.FILTER_RELATED_BY_SENDERS.name]:this.filterJson[r.FILTER_RELATED_BY_SENDERS.name]||[],[r.FILTER_RELATED_BY_REL_TYPES.name]:this.filterJson[r.FILTER_RELATED_BY_REL_TYPES.name]||[]}}checkFields(e,t,n,i,s,o){const a={rooms:function(t){return e===t},senders:function(e){return t===e},types:function(e){return function(e,t){if(t.endsWith("*")){const n=t.slice(0,-1);return e.slice(0,n.length)===n}return e===t}(n,e)}};for(let e=0;e<Object.keys(a).length;e++){const t=Object.keys(a)[e],n=a[t],r="not_"+t,i=this.filterJson[r];if(null!=i&&i.some(n))return!1;const s=this.filterJson[t];if(s&&!s.some(n))return!1}const c=this.filterJson.contains_url;if(void 0!==c&&c!==i)return!1;const l=this.filterJson[r.FILTER_RELATED_BY_REL_TYPES.name];if(void 0!==l&&!this.arrayMatchesFilter(l,s))return!1;const d=this.filterJson[r.FILTER_RELATED_BY_SENDERS.name];return!(void 0!==d&&!this.arrayMatchesFilter(d,o))}arrayMatchesFilter(e,t){return t.length>0&&e.every((e=>t.includes(e)))}filter(e){return e.filter(this.check,this)}limit(){return void 0!==this.filterJson.limit?this.filterJson.limit:10}}},7906:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.Filter=void 0;var i=r(n(8416)),s=n(3564);function o(e,t,n){const r=t.split(".");let i=e;for(let e=0;e<r.length-1;e++)i[r[e]]||(i[r[e]]={}),i=i[r[e]];i[r[r.length-1]]=n}class a{static fromJson(e,t,n){const r=new a(e,t);return r.setDefinition(n),r}constructor(e,t){this.userId=e,this.filterId=t,(0,i.default)(this,"definition",{}),(0,i.default)(this,"roomFilter",void 0),(0,i.default)(this,"roomTimelineFilter",void 0)}getFilterId(){return this.filterId}getDefinition(){return this.definition}setDefinition(e){this.definition=e;const t=e.room,n={};t&&(t.rooms&&(n.rooms=t.rooms),t.rooms&&(n.not_rooms=t.not_rooms)),this.roomFilter=new s.FilterComponent(n,this.userId),this.roomTimelineFilter=new s.FilterComponent((null==t?void 0:t.timeline)||{},this.userId)}getRoomTimelineFilterComponent(){return this.roomTimelineFilter}filterRoomTimeline(e){return this.roomTimelineFilter.filter(this.roomFilter.filter(e))}setTimelineLimit(e){o(this.definition,"room.timeline.limit",e)}setLazyLoadMembers(e){o(this.definition,"room.state.lazy_load_members",!!e)}setIncludeLeaveRooms(e){o(this.definition,"room.include_leave",e)}}t.Filter=a,(0,i.default)(a,"LAZY_LOADING_MESSAGES_FILTER",{lazy_load_members:!0})},7715:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.PREFIX_V3=t.PREFIX_V1=t.PREFIX_UNSTABLE=t.PREFIX_R0=t.PREFIX_MEDIA_R0=t.PREFIX_IDENTITY_V2=t.PREFIX_IDENTITY_V1=t.Method=t.MatrixHttpApi=t.MatrixError=t.HttpApiEvent=t.ConnectionError=t.AbortError=void 0,t.retryNetworkOperation=async function(e,t){let n=0,r=null;for(;n<e;)try{if(n>0){const e=1e3*Math.pow(2,n);c.logger.log(`network operation failed ${n} times, retrying in ${e}ms...`),await(0,a.sleep)(e)}return t()}catch(e){if(!(e instanceof v))throw e;n+=1,r=e}throw r};var i=r(n(8416)),s=n(7811),o=d(n(2731)),a=d(n(3102)),c=n(7434);function l(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(l=function(e){return e?n:t})(e)}function d(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=l(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let f,g;function p(e){return e.status||e.statusCode}function m(e,t,n=!1,r){return function(i,o,a){i&&("AbortError"===i.name||"aborted"===i||i instanceof y||(i=new v("request failed",i)));let c=a;if(!i)try{p(o)>=400?i=function(e,t){const n=p(e),r=function(e){let t;if(e.getResponseHeader?t=e.getResponseHeader("Content-Type"):e.headers&&(t=e.headers["content-type"]||null),!t)return null;try{return(0,s.parse)(t)}catch(e){throw new Error(`Error parsing Content-Type '${t}': ${e}`)}}(e);let i;if(r)if("application/json"===r.type){const e="object"==typeof t?t:JSON.parse(t);i=new y(e)}else"text/plain"===r.type&&(i=new Error(`Server returned ${n} error: ${t}`));return i||(i=new Error(`Server returned ${n} error`)),i.httpStatus=n,i}(o,a):r&&(c=r(a))}catch(e){i=new Error(`Error parsing server response: ${e}`)}if(i)e.reject(i),null==t||t(i);else if(n)e.resolve(c),null==t||t(null,c);else{const n={code:p(o),headers:o.headers,data:c};e.resolve(n),null==t||t(null,n)}}}t.PREFIX_R0="/_matrix/client/r0",t.PREFIX_V1="/_matrix/client/v1",t.PREFIX_V3="/_matrix/client/v3",t.PREFIX_UNSTABLE="/_matrix/client/unstable",t.PREFIX_IDENTITY_V1="/_matrix/identity/api/v1",t.PREFIX_IDENTITY_V2="/_matrix/identity/v2",t.PREFIX_MEDIA_R0="/_matrix/media/r0",t.Method=f,function(e){e.Get="GET",e.Put="PUT",e.Post="POST",e.Delete="DELETE"}(f||(t.Method=f={})),t.HttpApiEvent=g,function(e){e.SessionLoggedOut="Session.logged_out",e.NoConsent="no_consent"}(g||(t.HttpApiEvent=g={})),t.MatrixHttpApi=class{constructor(e,t){this.eventEmitter=e,this.opts=t,(0,i.default)(this,"uploads",[]),a.checkObjectHasKeys(t,["baseUrl","request","prefix"]),t.onlyData=!!t.onlyData,t.useAuthorizationHeader=!!t.useAuthorizationHeader}setIdBaseUrl(e){this.opts.idBaseUrl=e}getContentUri(){return{base:this.opts.baseUrl,path:"/_matrix/media/r0/upload",params:{access_token:this.opts.accessToken}}}uploadContent(e,t){a.isFunction(t)?t={callback:t}:t||(t={});const r=!1!==t.includeFilename,i=t.type||e.type||"application/octet-stream",s=t.name||e.name;let l=e;const d=l.stream;d&&"function"!=typeof d&&(c.logger.warn("Using `file.stream` as the content to upload. Future versions of the js-sdk will change this to expect `file` to be the content directly."),l=d);let u=t.rawResponse;void 0===u&&(n.g.XMLHttpRequest?u=!1:(c.logger.warn("Returning the raw JSON from uploadContent(). Future versions of the js-sdk will change this default, to return the parsed object. Set opts.rawResponse=false to change this behaviour now."),u=!0));let h=t.onlyContentUri;u||void 0!==h||(n.g.XMLHttpRequest?(c.logger.warn("Returning only the content-uri from uploadContent(). Future versions of the js-sdk will change this default, to return the whole response object. Set opts.onlyContentUri=false to change this behaviour now."),h=!0):h=!1);const g={loaded:0,total:0};let p,y=null;if(u||(y=function(e){let t=JSON.parse(e);if(h&&(t=t.content_uri,void 0===t))throw Error("Bad response");return t}),n.g.XMLHttpRequest){const e=a.defer(),c=new n.g.XMLHttpRequest,d=m(e,t.callback,this.opts.onlyData),u=function(){c.abort(),d(new Error("Timeout"))};let h=o.setTimeout(u,3e4);c.onreadystatechange=function(){let e;if(c.readyState===n.g.XMLHttpRequest.DONE){o.clearTimeout(h);try{if(0===c.status)throw new b;if(!c.responseText)throw new Error("No response body.");e=c.responseText,y&&(e=y(e))}catch(e){return e.httpStatus=c.status,void d(e)}d(void 0,c,e)}},c.upload.addEventListener("progress",(function(e){o.clearTimeout(h),g.loaded=e.loaded,g.total=e.total,h=o.setTimeout(u,3e4),t.progressHandler&&t.progressHandler({loaded:e.loaded,total:e.total})}));let f=this.opts.baseUrl+"/_matrix/media/r0/upload";const v=[];r&&s&&v.push("filename="+encodeURIComponent(s)),this.opts.useAuthorizationHeader||v.push("access_token="+encodeURIComponent(this.opts.accessToken)),v.length>0&&(f+="?"+v.join("&")),c.open("POST",f),this.opts.useAuthorizationHeader&&c.setRequestHeader("Authorization","Bearer "+this.opts.accessToken),c.setRequestHeader("Content-Type",i),c.send(l),p=e.promise,p.abort=c.abort.bind(c)}else{const e={};r&&s&&(e.filename=s);const n={"Content-Type":i};0===l.length&&(n["Content-Length"]="0"),p=this.authedRequest(t.callback,f.Post,"/upload",e,l,{prefix:"/_matrix/media/r0",headers:n,json:!1,bodyParser:y})}return g.promise=p.finally((()=>{for(let e=0;e<this.uploads.length;++e)if(this.uploads[e]===g)return void this.uploads.splice(e,1)})),g.promise.abort=p.abort,this.uploads.push(g),g.promise}cancelUpload(e){return!!e.abort&&(e.abort(),!0)}getCurrentUploads(){return this.uploads}idServerRequest(e,t,n,r,i,s){if(!this.opts.idBaseUrl)throw new Error("No identity server base URL set");const o=this.opts.idBaseUrl+i+n;if(void 0!==e&&!a.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);const c={uri:o,method:t,withCredentials:!1,json:!0,_matrix_opts:this.opts,headers:{}};t===f.Get?c.qs=r:"object"==typeof r&&(c.json=r),s&&(c.headers.Authorization=`Bearer ${s}`);const l=a.defer();return this.opts.request(c,m(l,e,this.opts.onlyData)),l.promise}authedRequest(e,t,n,r,i,s){r||(r={});let o=s||{};this.opts.useAuthorizationHeader?(isFinite(s)&&(o={localTimeoutMs:s}),o.headers||(o.headers={}),o.headers.Authorization||(o.headers.Authorization="Bearer "+this.opts.accessToken),r.access_token&&delete r.access_token):r.access_token||(r.access_token=this.opts.accessToken);const a=this.request(e,t,n,r,i,o);return a.catch((e=>{var t;"M_UNKNOWN_TOKEN"!=e.errcode||null!==(t=o)&&void 0!==t&&t.inhibitLogoutEmit?"M_CONSENT_NOT_GIVEN"==e.errcode&&this.eventEmitter.emit(g.NoConsent,e.message,e.data.consent_uri):this.eventEmitter.emit(g.SessionLoggedOut,e)})),a}request(e,t,n,r,i,s){var o,a;const c=null!==(o=null==s?void 0:s.prefix)&&void 0!==o?o:this.opts.prefix,l=(null!==(a=null==s?void 0:s.baseUrl)&&void 0!==a?a:this.opts.baseUrl)+c+n;return this.requestOtherUrl(e,t,l,r,i,s)}requestOtherUrl(e,t,n,r,i,s){let o=s||{};return isFinite(s)&&(o={localTimeoutMs:s}),this.doRequest(e,t,n,r,i,o)}getUrl(e,t,n){let r="";return t&&(r="?"+a.encodeParams(t)),this.opts.baseUrl+n+e+r}doRequest(e,t,n,r,i,s){var c;if(void 0!==e&&!a.isFunction(e))throw Error("Expected callback to be a function but got "+typeof e);this.opts.extraParams&&(r=h(h({},r||{}),this.opts.extraParams));const l=Object.assign({},s.headers||{});s||(s={});const d=null===(c=s.json)||void 0===c||c;let u=s.bodyParser;d&&(i&&(i=JSON.stringify(i),l["content-type"]="application/json"),l.accept||(l.accept="application/json"),void 0===u&&(u=function(e){return JSON.parse(e)}));const f=a.defer();let g,p,v=!1;const b=s.localTimeoutMs||this.opts.localTimeoutMs,_=()=>{b&&(g&&o.clearTimeout(g),g=o.setTimeout((function(){var e,t;v=!0,null===(e=p)||void 0===e||null===(t=e.abort)||void 0===t||t.call(e),f.reject(new y({error:"Locally timed out waiting for a response",errcode:"ORG.MATRIX.JSSDK_TIMEOUT",timeout:b}))}),b))};_();const E=f.promise;try{p=this.opts.request({uri:n,method:t,withCredentials:!1,qs:r,qsStringifyOptions:s.qsStringifyOptions,useQuerystring:!0,body:i,json:!1,timeout:b,headers:l||{},_matrix_opts:this.opts},((t,n,r)=>{b&&(o.clearTimeout(g),v)||m(f,e,this.opts.onlyData,u)(t,n,r)})),p&&("onprogress"in p&&(p.onprogress=e=>{_()}),p.abort&&(E.abort=p.abort.bind(p)))}catch(t){f.reject(t),e&&e(t)}return E}};class y extends Error{constructor(e={}){super(`MatrixError: ${e.errcode}`),(0,i.default)(this,"errcode",void 0),(0,i.default)(this,"data",void 0),(0,i.default)(this,"httpStatus",void 0),this.errcode=e.errcode,this.name=e.errcode||"Unknown error code",this.message=e.error||"Unknown message",this.data=e}}t.MatrixError=y;class v extends Error{constructor(e,t=void 0){super(e+(t?`: ${t.message}`:""))}get name(){return"ConnectionError"}}t.ConnectionError=v;class b extends Error{constructor(){super("Operation aborted")}get name(){return"AbortError"}}t.AbortError=b},3415:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.exists=function(e,t){return new Promise(((n,r)=>{let i=!0;const s=e.open(t);s.onupgradeneeded=()=>{i=!1},s.onblocked=()=>r(s.error),s.onsuccess=()=>{s.result.close(),i||e.deleteDatabase(t),n(i)},s.onerror=e=>r(s.error)}))}},8670:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.InteractiveAuth=t.AuthType=void 0;var i=r(n(8416)),s=n(7434),o=n(3102);const a="m.login.email.identity",c="m.login.msisdn";let l;t.AuthType=l,function(e){e.Password="m.login.password",e.Recaptcha="m.login.recaptcha",e.Terms="m.login.terms",e.Email="m.login.email.identity",e.Msisdn="m.login.msisdn",e.Sso="m.login.sso",e.SsoUnstable="org.matrix.login.sso",e.Dummy="m.login.dummy",e.RegistrationToken="m.login.registration_token",e.UnstableRegistrationToken="org.matrix.msc3231.login.registration_token"}(l||(t.AuthType=l={}));class d extends Error{constructor(e,t,n){super(e),this.required_stages=t,this.flows=n,(0,i.default)(this,"name","NoAuthFlowFoundError")}}t.InteractiveAuth=class{constructor(e){var t;(0,i.default)(this,"matrixClient",void 0),(0,i.default)(this,"inputs",void 0),(0,i.default)(this,"clientSecret",void 0),(0,i.default)(this,"requestCallback",void 0),(0,i.default)(this,"busyChangedCallback",void 0),(0,i.default)(this,"stateUpdatedCallback",void 0),(0,i.default)(this,"requestEmailTokenCallback",void 0),(0,i.default)(this,"data",void 0),(0,i.default)(this,"emailSid",void 0),(0,i.default)(this,"requestingEmailToken",!1),(0,i.default)(this,"attemptAuthDeferred",null),(0,i.default)(this,"chosenFlow",null),(0,i.default)(this,"currentStage",null),(0,i.default)(this,"emailAttempt",1),(0,i.default)(this,"submitPromise",null),(0,i.default)(this,"requestEmailToken",(async()=>{if(this.requestingEmailToken)s.logger.warn("Could not request email token: Already requesting");else{s.logger.trace("Requesting email token. Attempt: "+this.emailAttempt),this.requestingEmailToken=!0;try{const e=await this.requestEmailTokenCallback(this.inputs.emailAddress,this.clientSecret,this.emailAttempt++,this.data.session);this.emailSid=e.sid,s.logger.trace("Email token request succeeded")}finally{this.requestingEmailToken=!1}}})),this.matrixClient=e.matrixClient,this.data=e.authData||{},this.requestCallback=e.doRequest,this.busyChangedCallback=e.busyChanged,this.stateUpdatedCallback=e.stateUpdated||e.startAuthStage,this.requestEmailTokenCallback=e.requestEmailToken,this.inputs=e.inputs||{},e.sessionId&&(this.data.session=e.sessionId),this.clientSecret=e.clientSecret||this.matrixClient.generateClientSecret(),this.emailSid=null!==(t=e.emailSid)&&void 0!==t?t:null}attemptAuth(){var e;this.attemptAuthDeferred=(0,o.defer)();const t=this.attemptAuthDeferred.promise;if(null!==(e=this.data)&&void 0!==e&&e.flows)this.startNextAuthStage();else{var n;null===(n=this.busyChangedCallback)||void 0===n||n.call(this,!0);const e=this.data.session?{session:this.data.session}:null;this.doRequest(e).finally((()=>{var e;null===(e=this.busyChangedCallback)||void 0===e||e.call(this,!1)}))}return t}async poll(){if(!this.data.session)return;if(!this.attemptAuthDeferred)return;if(this.submitPromise)return;let e={};if(this.currentStage==a&&this.emailSid){const t={sid:this.emailSid,client_secret:this.clientSecret};if(await this.matrixClient.doesServerRequireIdServerParam()){const e=new URL(this.matrixClient.getIdentityServerUrl());t.id_server=e.host}e={type:a,threepid_creds:t,threepidCreds:t}}this.submitAuthDict(e,!0)}getSessionId(){var e;return null===(e=this.data)||void 0===e?void 0:e.session}getClientSecret(){return this.clientSecret}getStageParams(e){var t;return null===(t=this.data.params)||void 0===t?void 0:t[e]}getChosenFlow(){return this.chosenFlow}async submitAuthDict(e,t=!1){if(!this.attemptAuthDeferred)throw new Error("submitAuthDict() called before attemptAuth()");var n;for(t||null===(n=this.busyChangedCallback)||void 0===n||n.call(this,!0);this.submitPromise;)try{await this.submitPromise}catch(e){}let r;this.data.session?(r={session:this.data.session},Object.assign(r,e)):r=e;try{this.submitPromise=this.doRequest(r,t),await this.submitPromise}finally{var i;this.submitPromise=null,t||null===(i=this.busyChangedCallback)||void 0===i||i.call(this,!1)}}getEmailSid(){return this.emailSid}setEmailSid(e){this.emailSid=e}async doRequest(e,t=!1){try{const n=await this.requestCallback(e,t);this.attemptAuthDeferred.resolve(n),this.attemptAuthDeferred=null}catch(e){var n,r;const o=null!==(n=null===(r=e.data)||void 0===r?void 0:r.flows)&&void 0!==n?n:null,a=this.data.flows||Boolean(o);var i;401===e.httpStatus&&e.data&&a||(t?s.logger.log("Background poll request failed doing UI auth: ignoring",e):null===(i=this.attemptAuthDeferred)||void 0===i||i.reject(e)),e.data||(e.data={}),e.data.flows||e.data.completed||e.data.session||(e.data.flows=this.data.flows,e.data.completed=this.data.completed,e.data.session=this.data.session),this.data=e.data;try{this.startNextAuthStage()}catch(e){return this.attemptAuthDeferred.reject(e),void(this.attemptAuthDeferred=null)}if(!this.emailSid&&this.chosenFlow.stages.includes(l.Email))try{await this.requestEmailToken()}catch(e){this.attemptAuthDeferred.reject(e),this.attemptAuthDeferred=null}}}startNextAuthStage(){var e,t;const n=this.chooseStage();if(!n)throw new Error("No incomplete flows from the server");var r,i;this.currentStage=n,n!==l.Dummy?null!==(e=this.data)&&void 0!==e&&e.errcode||null!==(t=this.data)&&void 0!==t&&t.error?this.stateUpdatedCallback(n,{errcode:(null===(r=this.data)||void 0===r?void 0:r.errcode)||"",error:(null===(i=this.data)||void 0===i?void 0:i.error)||""}):this.stateUpdatedCallback(n,n===a?{emailSid:this.emailSid}:{}):this.submitAuthDict({type:"m.login.dummy"})}chooseStage(){null===this.chosenFlow&&(this.chosenFlow=this.chooseFlow()),s.logger.log("Active flow => %s",JSON.stringify(this.chosenFlow));const e=this.firstUncompletedStage(this.chosenFlow);return s.logger.log("Next stage: %s",e),e}chooseFlow(){const e=this.data.flows||[],t=Boolean(this.inputs.emailAddress)||Boolean(this.emailSid),n=Boolean(this.inputs.phoneCountry)&&Boolean(this.inputs.phoneNumber);for(const r of e){let e=!1,i=!1;for(const t of r.stages)t===a?e=!0:t==c&&(i=!0);if(e==t&&i==n)return r}const r=[];throw t&&r.push(a),n&&r.push(c),new d("No appropriate authentication flow found",r,e)}firstUncompletedStage(e){const t=this.data.completed||[];for(let n=0;n<e.stages.length;++n){const r=e.stages[n];if(-1===t.indexOf(r))return r}}}},7434:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.logger=void 0;var i=r(n(2043));const s="matrix";i.default.methodFactory=function(e,t,n){return function(...t){return this.prefix&&t.unshift(this.prefix),"error"===e||"warn"===e||"trace"===e||"info"===e?console[e](...t):console.log(...t)}};const o=i.default.getLogger(s);t.logger=o,o.setLevel(i.default.levels.DEBUG,!1),function e(t){t.withPrefix=function(t){return function(t){const n=i.default.getLogger(`${s}-${t}`);return n.prefix!==t&&(e(n),n.prefix=t,n.setLevel(i.default.levels.DEBUG,!1)),n}((this.prefix||"")+t)}}(o)},8070:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0});var r={request:!0,getRequest:!0,wrapRequest:!0,setCryptoStoreFactory:!0,createClient:!0,ContentHelpers:!0,createNewMatrixCall:!0};t.ContentHelpers=void 0,t.createClient=function(e){return"string"==typeof e&&(e={baseUrl:e}),e.request=e.request||N,e.store=e.store||new s.MemoryStore({localStorage:n.g.localStorage}),e.scheduler=e.scheduler||new o.MatrixScheduler,e.cryptoStore=e.cryptoStore||x(),new a.MatrixClient(e)},Object.defineProperty(t,"createNewMatrixCall",{enumerable:!0,get:function(){return U.createNewMatrixCall}}),t.getRequest=function(){return N},t.request=function(e){N=e},t.setCryptoStoreFactory=function(e){x=e},t.wrapRequest=function(e){const t=N;N=function(n,r){return e(t,n,r)}};var i=n(1045);Object.keys(i).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===i[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return i[e]}}))}));var s=n(1703);Object.keys(s).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===s[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return s[e]}}))}));var o=n(9443);Object.keys(o).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===o[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return o[e]}}))}));var a=n(2168);Object.keys(a).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===a[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return a[e]}}))}));var c=n(7715);Object.keys(c).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===c[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return c[e]}}))}));var l=n(9118);Object.keys(l).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===l[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return l[e]}}))}));var d=n(2741);Object.keys(d).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===d[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return d[e]}}))}));var u=n(9489);Object.keys(u).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===u[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return u[e]}}))}));var h=n(6320);Object.keys(h).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===h[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return h[e]}}))}));var f=n(4369);Object.keys(f).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===f[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return f[e]}}))}));var g=n(7366);Object.keys(g).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===g[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return g[e]}}))}));var p=n(8910);Object.keys(p).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===p[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return p[e]}}))}));var m=n(3705);Object.keys(m).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===m[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return m[e]}}))}));var y=n(2848);Object.keys(y).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===y[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return y[e]}}))}));var v=n(6860);Object.keys(v).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===v[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return v[e]}}))}));var b=n(3998);Object.keys(b).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===b[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return b[e]}}))}));var _=n(7906);Object.keys(_).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===_[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return _[e]}}))}));var E=n(4969);Object.keys(E).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===E[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return E[e]}}))}));var w=n(8670);Object.keys(w).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===w[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return w[e]}}))}));var S=n(1415);Object.keys(S).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===S[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return S[e]}}))}));var C=n(9789);Object.keys(C).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===C[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return C[e]}}))}));var T=n(7585);Object.keys(T).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===T[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return T[e]}}))}));var R=n(3667);Object.keys(R).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===R[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return R[e]}}))}));var I=n(2481);Object.keys(I).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===I[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return I[e]}}))}));var k=n(1470);Object.keys(k).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===k[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return k[e]}}))}));var O=n(4702);Object.keys(O).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===O[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return O[e]}}))}));var A=n(6513);Object.keys(A).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===A[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return A[e]}}))}));var D=n(9162);Object.keys(D).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===D[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return D[e]}}))}));var M=n(5205);Object.keys(M).forEach((function(e){"default"!==e&&"__esModule"!==e&&(Object.prototype.hasOwnProperty.call(r,e)||e in t&&t[e]===M[e]||Object.defineProperty(t,e,{enumerable:!0,get:function(){return M[e]}}))}));var P=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=L(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(4656));t.ContentHelpers=P;var U=n(9679);function L(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(L=function(e){return e?n:t})(e)}let N,x=()=>new i.MemoryCryptoStore},8807:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.MSC3089Branch=void 0;var i=r(n(8416)),s=n(2481),o=n(8910);function a(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function c(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?a(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):a(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}t.MSC3089Branch=class{constructor(e,t,n){this.client=e,this.indexEvent=t,this.directory=n}get id(){const e=this.indexEvent.getStateKey();if(!e)throw new Error("State key not found for branch");return e}get isActive(){return!0===this.indexEvent.getContent().active}get version(){var e;return null!==(e=this.indexEvent.getContent().version)&&void 0!==e?e:1}get roomId(){return this.indexEvent.getRoomId()}async delete(){await this.client.sendStateEvent(this.roomId,s.UNSTABLE_MSC3089_BRANCH.name,{},this.id),await this.client.redactEvent(this.roomId,this.id);const e=(await this.getVersionHistory())[1];e&&await e.delete()}getName(){return this.indexEvent.getContent().name||"Unnamed File"}async setName(e){await this.client.sendStateEvent(this.roomId,s.UNSTABLE_MSC3089_BRANCH.name,c(c({},this.indexEvent.getContent()),{},{name:e}),this.id)}isLocked(){return this.indexEvent.getContent().locked||!1}async setLocked(e){await this.client.sendStateEvent(this.roomId,s.UNSTABLE_MSC3089_BRANCH.name,c(c({},this.indexEvent.getContent()),{},{locked:e}),this.id)}async getFileInfo(){const e=(await this.getFileEvent()).getOriginalContent().file,t=this.client.mxcUrlToHttp(e.url);if(!t)throw new Error(`No HTTP URL available for ${e.url}`);return{info:e,httpUrl:t}}async getFileEvent(){const e=this.client.getRoom(this.roomId);if(!e)throw new Error("Unknown room");let t=e.getUnfilteredTimelineSet().findEventById(this.id);for(;!t&&e.getLiveTimeline().getState(o.EventTimeline.BACKWARDS).paginationToken;)await this.client.scrollback(e,100),t=e.getUnfilteredTimelineSet().findEventById(this.id);if(!t)throw new Error("Failed to find event");return await this.client.decryptEventIfNeeded(t,{emit:!0,isRetry:!0}),t}async createNewVersion(e,t,n,r){const i=await this.directory.createFile(e,t,n,c(c({},null!=r?r:{}),{},{"m.new_content":!0,"m.relates_to":{rel_type:s.RelationType.Replace,event_id:this.id}}));return await this.client.sendStateEvent(this.roomId,s.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:e,version:this.version+1},i.event_id),await this.client.sendStateEvent(this.roomId,s.UNSTABLE_MSC3089_BRANCH.name,c(c({},this.indexEvent.getContent()),{},{active:!1}),this.id),i}async getVersionHistory(){const e=[];e.push(this);const t=this.client.getRoom(this.roomId);if(!t)throw new Error("Invalid or unknown room");const n=[...t.getLiveTimeline().getEvents()].reverse();let r,i=await this.getFileEvent();do{if(r=n.find((e=>e.replacingEventId()===i.getId())),r){const t=this.directory.getFile(r.getId());if(!t)break;e.push(t),i=r}}while(r);return e}}},6170:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.TreePermissions=t.MSC3089TreeSpace=t.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=void 0;var i=r(n(8416)),s=r(n(2693)),o=n(2481),a=n(7434),c=n(3102),l=n(8807),d=n(7125);function u(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function h(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?u(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):u(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const f={invite:100,kick:100,ban:100,redact:50,state_default:50,events_default:50,users_default:0,events:{[o.EventType.RoomPowerLevels]:100,[o.EventType.RoomHistoryVisibility]:100,[o.EventType.RoomTombstone]:100,[o.EventType.RoomEncryption]:100,[o.EventType.RoomName]:50,[o.EventType.RoomMessage]:50,[o.EventType.RoomMessageEncrypted]:50,[o.EventType.Sticker]:50},users:{}};let g;t.DEFAULT_TREE_POWER_LEVELS_TEMPLATE=f,t.TreePermissions=g,function(e){e.Viewer="viewer",e.Editor="editor",e.Owner="owner"}(g||(t.TreePermissions=g={})),t.MSC3089TreeSpace=class{constructor(e,t){if(this.client=e,this.roomId=t,(0,i.default)(this,"room",void 0),this.room=this.client.getRoom(this.roomId),!this.room)throw new Error("Unknown room")}get id(){return this.roomId}get isTopLevel(){const e=this.room.currentState.getStateEvents(o.EventType.SpaceParent);return null==e||!e.length||e.every((e=>{var t;return!(null!==(t=e.getContent())&&void 0!==t&&t.via)}))}async setName(e){await this.client.sendStateEvent(this.roomId,o.EventType.RoomName,{name:e},"")}async invite(e,t=!0,n=!0){const r=[this.retryInvite(e)];return t&&r.push(...this.getDirectories().map((r=>r.invite(e,t,n)))),Promise.all(r).then((()=>{n&&(0,d.isRoomSharedHistory)(this.room)&&this.client.sendSharedHistoryKeys(this.roomId,[e])}))}retryInvite(e){return(0,c.simpleRetryOperation)((async()=>{await this.client.invite(this.roomId,e).catch((e=>{if("M_FORBIDDEN"===(null==e?void 0:e.errcode))throw new s.default.AbortError(e);throw e}))}))}async setPermissions(e,t){var n;const r=this.room.currentState.getStateEvents(o.EventType.RoomPowerLevels,"");if(Array.isArray(r))throw new Error("Unexpected return type for power levels");const i=r.getContent()||{},s=i.users_default||0,a=i.events_default||50,c=(null===(n=i.events)||void 0===n?void 0:n[o.EventType.RoomPowerLevels])||100,l=i.users||{};switch(t){case g.Viewer:l[e]=s;break;case g.Editor:l[e]=a;break;case g.Owner:l[e]=c;break;default:throw new Error("Invalid role: "+t)}i.users=l,await this.client.sendStateEvent(this.roomId,o.EventType.RoomPowerLevels,i,"")}getPermissions(e){var t,n;const r=this.room.currentState.getStateEvents(o.EventType.RoomPowerLevels,"");if(Array.isArray(r))throw new Error("Unexpected return type for power levels");const i=r.getContent()||{},s=i.users_default||0,a=i.events_default||50,c=(null===(t=i.events)||void 0===t?void 0:t[o.EventType.RoomPowerLevels])||100,l=(null===(n=i.users)||void 0===n?void 0:n[e])||s;return l>=c?g.Owner:l>=a?g.Editor:g.Viewer}async createDirectory(e){const t=await this.client.unstableCreateFileTree(e);return await this.client.sendStateEvent(this.roomId,o.EventType.SpaceChild,{via:[this.client.getDomain()]},t.roomId),await this.client.sendStateEvent(t.roomId,o.EventType.SpaceParent,{via:[this.client.getDomain()]},this.roomId),t}getDirectories(){const e=[],t=this.room.currentState.getStateEvents(o.EventType.SpaceChild);for(const n of t)try{const t=n.getStateKey();if(t){const n=this.client.unstableGetFileTreeSpace(t);n&&e.push(n)}}catch(e){a.logger.warn("Unable to create tree space instance for listing. Are we joined?",e)}return e}getDirectory(e){return this.getDirectories().find((t=>t.roomId===e))}async delete(){const e=this.getDirectories();for(const t of e)await t.delete();const t=["invite","knock","join"],n=this.room.currentState.getStateEvents(o.EventType.RoomMember);for(const e of n)if(e.getStateKey()!==this.client.getUserId()&&t.includes(e.getContent().membership)){const t=e.getStateKey();if(!t)throw new Error("State key not found for branch");await this.client.kick(this.roomId,t,"Room deleted")}await this.client.leave(this.roomId)}getOrderedChildren(e){const t=e.map((e=>({roomId:e.getStateKey(),order:e.getContent().order}))).filter((e=>e.roomId));return t.sort(((e,t)=>{if(e.order&&!t.order)return-1;if(!e.order&&t.order)return 1;if(e.order||t.order)return(0,c.lexicographicCompare)(e.order,t.order);{var n,r,i,s;const a=this.client.getRoom(e.roomId),l=this.client.getRoom(t.roomId);if(!a||!l)return(0,c.lexicographicCompare)(e.roomId,t.roomId);const d=null!==(n=null===(r=a.currentState.getStateEvents(o.EventType.RoomCreate,""))||void 0===r?void 0:r.getTs())&&void 0!==n?n:0,u=null!==(i=null===(s=l.currentState.getStateEvents(o.EventType.RoomCreate,""))||void 0===s?void 0:s.getTs())&&void 0!==i?i:0;return d===u?(0,c.lexicographicCompare)(e.roomId,t.roomId):d-u}})),t}getParentRoom(){const e=this.room.currentState.getStateEvents(o.EventType.SpaceParent)[0];if(!e)throw new Error("Expected to have a parent in a non-top level space");const t=e.getStateKey();if(!t)throw new Error("No state key found for parent");const n=this.client.getRoom(t);if(!n)throw new Error("Unable to locate room for parent");return n}getOrder(){if(this.isTopLevel)return-1;const e=this.getParentRoom().currentState.getStateEvents(o.EventType.SpaceChild);return this.getOrderedChildren(e).findIndex((e=>e.roomId===this.roomId))}async setOrder(e){var t;if(this.isTopLevel)throw new Error("Cannot set order of top level spaces currently");const n=this.getParentRoom(),r=n.currentState.getStateEvents(o.EventType.SpaceChild),i=this.getOrderedChildren(r);e=Math.max(Math.min(e,i.length-1),0);const s=this.getOrder()<e;s&&e===i.length-1?e--:s||0!==e||e++;const a=i[s?e:e-1],l=i[s?e+1:e];let d=c.DEFAULT_ALPHABET[0],u=!1;if(a)if(e===i.length-1)null!=l&&l.order&&(d=(0,c.nextString)(l.order));else{const e=null==a?void 0:a.order,t=null==l?void 0:l.order;e&&t?d=e===t?(0,c.nextString)(e):(0,c.averageBetweenStrings)(e,t):e?d=(0,c.nextString)(e):t?d=(0,c.prevString)(t):u=!0}else null!=l&&l.order&&(d=(0,c.prevString)(l.order));if(u){let t;for(let r=0;r<=e;r++){const e=i[r];if(0===r&&(t=e.order),e.order)t=e.order;else{var f;t=t?(0,c.nextString)(t):c.DEFAULT_ALPHABET[0];const r=n.currentState.getStateEvents(o.EventType.SpaceChild,e.roomId),i=null!==(f=null==r?void 0:r.getContent())&&void 0!==f?f:{via:[this.client.getDomain()]};await this.client.sendStateEvent(n.roomId,o.EventType.SpaceChild,h(h({},i),{},{order:t}),e.roomId)}}t&&(d=(0,c.nextString)(t))}const g=n.currentState.getStateEvents(o.EventType.SpaceChild,this.roomId),p=null!==(t=null==g?void 0:g.getContent())&&void 0!==t?t:{via:[this.client.getDomain()]};await this.client.sendStateEvent(n.roomId,o.EventType.SpaceChild,h(h({},p),{},{order:d}),this.roomId)}async createFile(e,t,n,r){var i;const s=await this.client.uploadContent(t,{includeFilename:!1,onlyContentUri:!0,rawResponse:!1});n.url=s;const a={msgtype:o.MsgType.File,body:e,url:s,file:n};(r=null!==(i=r)&&void 0!==i?i:{})["m.new_content"]&&(r["m.new_content"]=a);const c=await this.client.sendMessage(this.roomId,h(h(h({},r),a),{},{[o.UNSTABLE_MSC3089_LEAF.name]:{}}));return await this.client.sendStateEvent(this.roomId,o.UNSTABLE_MSC3089_BRANCH.name,{active:!0,name:e},c.event_id),c}getFile(e){const t=this.room.currentState.getStateEvents(o.UNSTABLE_MSC3089_BRANCH.name,e);return t?new l.MSC3089Branch(this.client,t,this):null}listFiles(){return this.listAllFiles().filter((e=>e.isActive))}listAllFiles(){var e;return(null!==(e=this.room.currentState.getStateEvents(o.UNSTABLE_MSC3089_BRANCH.name))&&void 0!==e?e:[]).map((e=>new l.MSC3089Branch(this.client,e,this)))}}},6320:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.isTimestampInDuration=t.getBeaconInfoIdentifier=t.BeaconEvent=t.Beacon=void 0;var i=r(n(8416)),s=n(6709),o=n(4656),a=n(3102),c=n(5861);let l;t.BeaconEvent=l,function(e){e.New="Beacon.new",e.Update="Beacon.update",e.LivenessChange="Beacon.LivenessChange",e.Destroy="Beacon.Destroy",e.LocationUpdate="Beacon.LocationUpdate"}(l||(t.BeaconEvent=l={}));const d=(e,t,n)=>n>=e&&e+t>=n;t.isTimestampInDuration=d;const u=e=>`${e.getRoomId()}_${e.getStateKey()}`;t.getBeaconInfoIdentifier=u;class h extends c.TypedEventEmitter{constructor(e){super(),this.rootEvent=e,(0,i.default)(this,"roomId",void 0),(0,i.default)(this,"_beaconInfo",void 0),(0,i.default)(this,"_isLive",void 0),(0,i.default)(this,"livenessWatchTimeout",void 0),(0,i.default)(this,"_latestLocationEvent",void 0),(0,i.default)(this,"clearLatestLocation",(()=>{this._latestLocationEvent=void 0,this.emit(l.LocationUpdate,this.latestLocationState)})),this.setBeaconInfo(this.rootEvent),this.roomId=this.rootEvent.getRoomId()}get isLive(){return this._isLive}get identifier(){return u(this.rootEvent)}get beaconInfoId(){return this.rootEvent.getId()}get beaconInfoOwner(){return this.rootEvent.getStateKey()}get beaconInfoEventType(){return this.rootEvent.getType()}get beaconInfo(){return this._beaconInfo}get latestLocationState(){return this._latestLocationEvent&&(0,o.parseBeaconContent)(this._latestLocationEvent.getContent())}get latestLocationEvent(){return this._latestLocationEvent}update(e){if(u(e)!==this.identifier)throw new Error("Invalid updating event");e.event.origin_server_ts<this.rootEvent.event.origin_server_ts||(this.rootEvent=e,this.setBeaconInfo(this.rootEvent),this.emit(l.Update,e,this),this.clearLatestLocation())}destroy(){this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this._isLive=!1,this.emit(l.Destroy,this.identifier)}monitorLiveness(){var e;if(this.livenessWatchTimeout&&clearTimeout(this.livenessWatchTimeout),this.checkLiveness(),this.isLive){var t,n;const e=(null===(t=this._beaconInfo)||void 0===t?void 0:t.timestamp)+(null===(n=this._beaconInfo)||void 0===n?void 0:n.timeout)-Date.now();e>1&&(this.livenessWatchTimeout=setTimeout((()=>{this.monitorLiveness()}),e))}else if((null===(e=this._beaconInfo)||void 0===e?void 0:e.timestamp)>Date.now()){var r;this.livenessWatchTimeout=setTimeout((()=>{this.monitorLiveness()}),(null===(r=this.beaconInfo)||void 0===r?void 0:r.timestamp)-Date.now())}}addLocations(e){var t;if(!this.isLive)return;const n=null===(t=e.filter((e=>{const t=e.getContent(),n=s.M_TIMESTAMP.findIn(t);return d(this._beaconInfo.timestamp,this._beaconInfo.timeout,n)&&(!this.latestLocationState||n>this.latestLocationState.timestamp)})).sort(a.sortEventsByLatestContentTimestamp))||void 0===t?void 0:t[0];n&&(this._latestLocationEvent=n,this.emit(l.LocationUpdate,this.latestLocationState))}setBeaconInfo(e){this._beaconInfo=(0,o.parseBeaconInfoContent)(e.getContent()),this.checkLiveness()}checkLiveness(){var e,t,n,r,i;const s=this.isLive,o=(null===(e=this._beaconInfo)||void 0===e?void 0:e.timestamp)>Date.now()?(null===(t=this._beaconInfo)||void 0===t?void 0:t.timestamp)-36e4:null===(n=this._beaconInfo)||void 0===n?void 0:n.timestamp;this._isLive=!(null===(r=this._beaconInfo)||void 0===r||!r.live)&&d(o,null===(i=this._beaconInfo)||void 0===i?void 0:i.timeout,Date.now()),s!==this.isLive&&this.emit(l.LivenessChange,this.isLive,this)}}t.Beacon=h},3558:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.EventContext=void 0;var i=r(n(8416)),s=n(8910);t.EventContext=class{constructor(e){this.ourEvent=e,(0,i.default)(this,"timeline",void 0),(0,i.default)(this,"ourEventIndex",0),(0,i.default)(this,"paginateTokens",{[s.Direction.Backward]:null,[s.Direction.Forward]:null}),this.timeline=[e]}getEvent(){return this.timeline[this.ourEventIndex]}getTimeline(){return this.timeline}getOurEventIndex(){return this.ourEventIndex}getPaginateToken(e=!1){return this.paginateTokens[e?s.Direction.Backward:s.Direction.Forward]}setPaginateToken(e,t=!1){this.paginateTokens[t?s.Direction.Backward:s.Direction.Forward]=e}addEvents(e,t=!1){t?(this.timeline=e.concat(this.timeline),this.ourEventIndex+=e.length):this.timeline=this.timeline.concat(e)}}},8881:(e,t)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),t.EventStatus=void 0,t.EventStatus=n,function(e){e.NOT_SENT="not_sent",e.ENCRYPTING="encrypting",e.SENDING="sending",e.QUEUED="queued",e.SENT="sent",e.CANCELLED="cancelled"}(n||(t.EventStatus=n={}))},3705:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.EventTimelineSet=t.DuplicateStrategy=void 0;var i=r(n(8416)),s=n(8910),o=n(7434),a=n(7366),c=n(5861),l=n(7286);let d,u;d=o.logger.log.bind(o.logger),t.DuplicateStrategy=u,function(e){e.Ignore="ignore",e.Replace="replace"}(u||(t.DuplicateStrategy=u={}));class h extends c.TypedEventEmitter{constructor(e,t={},n,r){var o,a,c;super(),this.room=e,this.thread=r,(0,i.default)(this,"relations",void 0),(0,i.default)(this,"timelineSupport",void 0),(0,i.default)(this,"displayPendingEvents",void 0),(0,i.default)(this,"liveTimeline",void 0),(0,i.default)(this,"timelines",void 0),(0,i.default)(this,"_eventIdToTimeline",new Map),(0,i.default)(this,"filter",void 0),this.timelineSupport=Boolean(t.timelineSupport),this.liveTimeline=new s.EventTimeline(this),this.displayPendingEvents=!1!==t.pendingEvents,this.timelines=[this.liveTimeline],this._eventIdToTimeline=new Map,this.filter=t.filter,this.relations=null!==(o=null===(a=this.room)||void 0===a?void 0:a.relations)&&void 0!==o?o:new l.RelationsContainer(null!==(c=null==e?void 0:e.client)&&void 0!==c?c:n)}getTimelines(){return this.timelines}getFilter(){return this.filter}setFilter(e){this.filter=e}getPendingEvents(){return this.room&&this.displayPendingEvents?this.room.getPendingEvents():[]}getLiveTimeline(){return this.liveTimeline}setLiveTimeline(e){this.liveTimeline=e}eventIdToTimeline(e){return this._eventIdToTimeline.get(e)}replaceEventId(e,t){const n=this._eventIdToTimeline.get(e);n&&(this._eventIdToTimeline.delete(e),this._eventIdToTimeline.set(t,n))}resetLiveTimeline(e,t){const n=!this.timelineSupport||!t,r=this.liveTimeline,i=n?r.forkLive(s.EventTimeline.FORWARDS):r.fork(s.EventTimeline.FORWARDS);n?(this.timelines=[i],this._eventIdToTimeline=new Map):this.timelines.push(i),t&&r.setPaginationToken(t,s.EventTimeline.FORWARDS),i.setPaginationToken(e,s.EventTimeline.BACKWARDS),this.liveTimeline=i,this.emit(a.RoomEvent.TimelineReset,this.room,this,n)}getTimelineForEvent(e){const t=this._eventIdToTimeline.get(e);return void 0===t?null:t}findEventById(e){const t=this.getTimelineForEvent(e);if(t)return t.getEvents().find((function(t){return t.getId()==e}))}addTimeline(){if(!this.timelineSupport)throw new Error("timeline support is disabled. Set the 'timelineSupport' parameter to true when creating MatrixClient to enable it.");const e=new s.EventTimeline(this);return this.timelines.push(e),e}addEventsToTimeline(e,t,n,r){if(!n)throw new Error("'timeline' not specified for EventTimelineSet.addEventsToTimeline");if(!t&&n==this.liveTimeline)throw new Error("EventTimelineSet.addEventsToTimeline cannot be used for adding events to the live timeline - use Room.addLiveEvents instead");if(this.filter&&!(e=this.filter.filterRoomTimeline(e)).length)return;const i=t?s.EventTimeline.BACKWARDS:s.EventTimeline.FORWARDS,a=t?s.EventTimeline.FORWARDS:s.EventTimeline.BACKWARDS;let c=!1,l=!1;for(let r=0;r<e.length;r++){const u=e[r],h=u.getId(),f=this._eventIdToTimeline.get(h);if(!f){this.addEventToTimeline(u,n,{toStartOfTimeline:t}),l=!0,c=!0;continue}if(l=!1,f==n){d("Event "+h+" already in timeline "+n);continue}const g=n.getNeighbouringTimeline(i);if(g){d(f==g?"Event "+h+" in neighbouring timeline - switching to "+f:"Event "+h+" already in a different timeline "+f),n=f;continue}o.logger.info("Already have timeline for "+h+" - joining timeline "+n+" to "+f);const p=f===this.liveTimeline,m=n===this.liveTimeline,y=i===s.EventTimeline.BACKWARDS&&p,v=i===s.EventTimeline.FORWARDS&&m;y||v?(y&&o.logger.warn("Refusing to set a preceding existingTimeLine on our timeline as the existingTimeLine is live ("+f+")"),v&&o.logger.warn("Refusing to set our preceding timeline on a existingTimeLine as our timeline is live ("+n+")")):(n.setNeighbouringTimeline(f,i),f.setNeighbouringTimeline(n,a),n=f,c=!0)}if(l||!c){if(i===s.EventTimeline.FORWARDS&&n===this.liveTimeline)return o.logger.warn({lastEventWasNew:l,didUpdate:c}),void o.logger.warn(`Refusing to set forwards pagination token of live timeline ${n} to ${r}`);n.setPaginationToken(r,i)}}addLiveEvent(e,t,n=!1,r){let i,a=t||u.Ignore;if("object"==typeof t?({duplicateStrategy:a=u.Ignore,fromCache:n=!1,roomState:r,timelineWasEmpty:i}=t):void 0!==t&&o.logger.warn("Overload deprecated: `EventTimelineSet.addLiveEvent(event, duplicateStrategy?, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addLiveEvent(event, IAddLiveEventOptions)`"),this.filter&&!this.filter.filterRoomTimeline([e]).length)return;const c=this._eventIdToTimeline.get(e.getId());if(c)if(a===u.Replace){d("EventTimelineSet.addLiveEvent: replacing duplicate event "+e.getId());const t=c.getEvents();for(let n=0;n<t.length;n++)if(t[n].getId()===e.getId()){r||(r=c.getState(s.EventTimeline.FORWARDS)),s.EventTimeline.setEventMetadata(e,r,!1),t[n]=e;break}}else d("EventTimelineSet.addLiveEvent: ignoring duplicate event "+e.getId());else this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1,fromCache:n,roomState:r,timelineWasEmpty:i})}addEventToTimeline(e,t,n,r=!1,i){let s,c=!!n;"object"==typeof n?({toStartOfTimeline:c,fromCache:r=!1,roomState:i,timelineWasEmpty:s}=n):void 0!==n&&o.logger.warn("Overload deprecated: `EventTimelineSet.addEventToTimeline(event, timeline, toStartOfTimeline, fromCache?, roomState?)` is deprecated in favor of the overload with `EventTimelineSet.addEventToTimeline(event, timeline, IAddEventToTimelineOptions)`");const l=e.getId();t.addEvent(e,{toStartOfTimeline:c,roomState:i,timelineWasEmpty:s}),this._eventIdToTimeline.set(l,t),this.relations.aggregateParentEvent(e),this.relations.aggregateChildEvent(e,this);const d={timeline:t,liveEvent:!c&&t==this.liveTimeline&&!r};this.emit(a.RoomEvent.Timeline,e,this.room,Boolean(c),!1,d)}handleRemoteEcho(e,t,n){const r=this._eventIdToTimeline.get(t);r?(this._eventIdToTimeline.delete(t),this._eventIdToTimeline.set(n,r)):this.filter?this.filter.filterRoomTimeline([e]).length&&this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1}):this.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:!1})}removeEvent(e){const t=this._eventIdToTimeline.get(e);if(!t)return null;const n=t.removeEvent(e);if(n){this._eventIdToTimeline.delete(e);const r={timeline:t};this.emit(a.RoomEvent.Timeline,n,this.room,void 0,!0,r)}return n}compareEventOrdering(e,t){if(e==t)return 0;const n=this._eventIdToTimeline.get(e),r=this._eventIdToTimeline.get(t);if(void 0===n)return null;if(void 0===r)return null;if(n===r){let r,i;const s=n.getEvents();for(let n=0;n<s.length&&(void 0===r||void 0===i);n++){const o=s[n].getId();o==e&&(r=n),o==t&&(i=n)}return r-i}let i=n;for(;i;){if(i===r)return-1;i=i.getNeighbouringTimeline(s.EventTimeline.FORWARDS)}for(i=n;i;){if(i===r)return 1;i=i.getNeighbouringTimeline(s.EventTimeline.BACKWARDS)}return null}canContain(e){if(!this.room)throw new Error("Cannot call `EventTimelineSet::canContain without a `room` set. Set the room when creating the EventTimelineSet to call this method.");const{threadId:t,shouldLiveInRoom:n}=this.room.eventShouldLiveIn(e);return this.thread?this.thread.id===t:n}}t.EventTimelineSet=h},8910:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.EventTimeline=t.Direction=void 0;var i=r(n(8416)),s=n(7434),o=n(6860),a=n(2481);let c;t.Direction=c,function(e){e.Backward="b",e.Forward="f"}(c||(t.Direction=c={}));class l{static setEventMetadata(e,t,n){var r,i,s,o;null!==(r=e.sender)&&void 0!==r&&null!==(i=r.events)&&void 0!==i&&i.member||(e.sender=t.getSentinelMember(e.getSender())),null!==(s=e.target)&&void 0!==s&&null!==(o=s.events)&&void 0!==o&&o.member||e.getType()!==a.EventType.RoomMember||(e.target=t.getSentinelMember(e.getStateKey())),e.isState()&&n&&(e.forwardLooking=!1)}constructor(e){var t,n;this.eventTimelineSet=e,(0,i.default)(this,"roomId",void 0),(0,i.default)(this,"name",void 0),(0,i.default)(this,"events",[]),(0,i.default)(this,"baseIndex",0),(0,i.default)(this,"startState",void 0),(0,i.default)(this,"endState",void 0),(0,i.default)(this,"prevTimeline",void 0),(0,i.default)(this,"nextTimeline",void 0),(0,i.default)(this,"paginationRequests",{[c.Backward]:null,[c.Forward]:null}),this.roomId=null!==(t=null===(n=e.room)||void 0===n?void 0:n.roomId)&&void 0!==t?t:null,this.startState=new o.RoomState(this.roomId),this.startState.paginationToken=null,this.endState=new o.RoomState(this.roomId),this.endState.paginationToken=null,this.prevTimeline=null,this.nextTimeline=null,this.paginationRequests={b:null,f:null},this.name=this.roomId+":"+(new Date).toISOString()}initialiseState(e,{timelineWasEmpty:t}={}){if(this.events.length>0)throw new Error("Cannot initialise state after events are added");for(const t of e)Object.freeze(t);this.startState.setStateEvents(e,{timelineWasEmpty:t}),this.endState.setStateEvents(e,{timelineWasEmpty:t})}forkLive(e){const t=this.getState(e),n=new l(this.eventTimelineSet);return n.startState=t.clone(),n.endState=t,this.endState=t.clone(),n}fork(e){const t=this.getState(e),n=new l(this.eventTimelineSet);return n.startState=t.clone(),n.endState=t.clone(),n}getRoomId(){return this.roomId}getFilter(){return this.eventTimelineSet.getFilter()}getTimelineSet(){return this.eventTimelineSet}getBaseIndex(){return this.baseIndex}getEvents(){return this.events}getState(e){if(e==l.BACKWARDS)return this.startState;if(e==l.FORWARDS)return this.endState;throw new Error("Invalid direction '"+e+"'")}getPaginationToken(e){return this.getState(e).paginationToken}setPaginationToken(e,t){this.getState(t).paginationToken=e}getNeighbouringTimeline(e){if(e==l.BACKWARDS)return this.prevTimeline;if(e==l.FORWARDS)return this.nextTimeline;throw new Error("Invalid direction '"+e+"'")}setNeighbouringTimeline(e,t){if(this.getNeighbouringTimeline(t))throw new Error("timeline already has a neighbouring timeline - cannot reset neighbour (direction: "+t+")");if(t==l.BACKWARDS)this.prevTimeline=e;else{if(t!=l.FORWARDS)throw new Error("Invalid direction '"+t+"'");this.nextTimeline=e}this.setPaginationToken(null,t)}addEvent(e,t,n){let r,i=!!t;"object"==typeof t?({toStartOfTimeline:i,roomState:n,timelineWasEmpty:r}=t):void 0!==t&&s.logger.warn("Overload deprecated: `EventTimeline.addEvent(event, toStartOfTimeline, roomState?)` is deprecated in favor of the overload with `EventTimeline.addEvent(event, IAddEventOptions)`"),n||(n=i?this.startState:this.endState);const o=this.getTimelineSet();let a;o.room&&(l.setEventMetadata(e,n,i),e.isState()&&o.room.getUnfilteredTimelineSet()===o&&(n.setStateEvents([e],{timelineWasEmpty:r}),e.sender&&("m.room.member"!==e.getType()||i)||l.setEventMetadata(e,n,i))),a=i?0:this.events.length,this.events.splice(a,0,e),i&&this.baseIndex++}removeEvent(e){for(let t=this.events.length-1;t>=0;t--){const n=this.events[t];if(n.getId()==e)return this.events.splice(t,1),t<this.baseIndex&&this.baseIndex--,n}return null}toString(){return this.name}}t.EventTimeline=l,(0,i.default)(l,"BACKWARDS",c.Backward),(0,i.default)(l,"FORWARDS",c.Forward)},4369:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),Object.defineProperty(t,"EventStatus",{enumerable:!0,get:function(){return h.EventStatus}}),t.MatrixEventEvent=t.MatrixEvent=void 0;var i=r(n(8416)),s=n(1333),o=n(7434),a=n(2481),c=n(3102),l=n(6969),d=n(771),u=n(5861),h=n(8881);const f=Object.freeze({visible:!0});let g;t.MatrixEventEvent=g,function(e){e.Decrypted="Event.decrypted",e.BeforeRedaction="Event.beforeRedaction",e.VisibilityChange="Event.visibilityChange",e.LocalEventIdReplaced="Event.localEventIdReplaced",e.Status="Event.status",e.Replaced="Event.replaced",e.RelationsCreated="Event.relationsCreated"}(g||(t.MatrixEventEvent=g={}));class p extends u.TypedEventEmitter{constructor(e={}){var t;super(),this.event=e,(0,i.default)(this,"pushActions",null),(0,i.default)(this,"_replacingEvent",null),(0,i.default)(this,"_localRedactionEvent",null),(0,i.default)(this,"_isCancelled",!1),(0,i.default)(this,"clearEvent",void 0),(0,i.default)(this,"visibility",f),(0,i.default)(this,"_hasCachedExtEv",!1),(0,i.default)(this,"_cachedExtEv",void 0),(0,i.default)(this,"senderCurve25519Key",null),(0,i.default)(this,"claimedEd25519Key",null),(0,i.default)(this,"forwardingCurve25519KeyChain",[]),(0,i.default)(this,"untrusted",null),(0,i.default)(this,"_decryptionPromise",null),(0,i.default)(this,"retryDecryption",!1),(0,i.default)(this,"txnId",null),(0,i.default)(this,"thread",null),(0,i.default)(this,"threadId",void 0),(0,i.default)(this,"localTimestamp",void 0),(0,i.default)(this,"sender",null),(0,i.default)(this,"target",null),(0,i.default)(this,"status",null),(0,i.default)(this,"error",null),(0,i.default)(this,"forwardLooking",!0),(0,i.default)(this,"verificationRequest",null),(0,i.default)(this,"reEmitter",void 0),["state_key","type","sender","room_id","membership"].forEach((t=>{"string"==typeof e[t]&&(e[t]=(0,c.internaliseString)(e[t]))})),["membership","avatar_url","displayname"].forEach((t=>{var n;"string"==typeof(null===(n=e.content)||void 0===n?void 0:n[t])&&(e.content[t]=(0,c.internaliseString)(e.content[t]))})),["rel_type"].forEach((t=>{var n,r;"string"==typeof(null===(n=e.content)||void 0===n||null===(r=n["m.relates_to"])||void 0===r?void 0:r[t])&&(e.content["m.relates_to"][t]=(0,c.internaliseString)(e.content["m.relates_to"][t]))})),this.txnId=e.txn_id||null,this.localTimestamp=Date.now()-(null!==(t=this.getAge())&&void 0!==t?t:0),this.reEmitter=new d.TypedReEmitter(this)}get unstableExtensibleEvent(){return this._hasCachedExtEv||(this._cachedExtEv=s.ExtensibleEvents.parse(this.getEffectiveEvent())),this._cachedExtEv}invalidateExtensibleEvent(){this._hasCachedExtEv=!1}getEffectiveEvent(){const e=Object.assign({},this.getContent());if(this.getWireType()===a.EventType.RoomMessageEncrypted)for(const[t,n]of Object.entries(this.getWireContent()))["algorithm","ciphertext","device_id","sender_key","session_id"].includes(t)||void 0===e[t]&&(e[t]=n);return Object.assign({},this.event,this.clearEvent,{content:e})}getId(){return this.event.event_id}getSender(){return this.event.sender||this.event.user_id}getType(){return this.clearEvent?this.clearEvent.type:this.event.type}getWireType(){return this.event.type}getRoomId(){return this.event.room_id}getTs(){return this.event.origin_server_ts}getDate(){return this.event.origin_server_ts?new Date(this.event.origin_server_ts):null}getOriginalContent(){return this._localRedactionEvent?{}:this.clearEvent?this.clearEvent.content||{}:this.event.content||{}}getContent(){return this._localRedactionEvent?{}:this._replacingEvent?this._replacingEvent.getContent()["m.new_content"]||{}:this.getOriginalContent()}getWireContent(){return this.event.content||{}}get threadRootId(){var e;const t=null===(e=this.getWireContent())||void 0===e?void 0:e["m.relates_to"];return(null==t?void 0:t.rel_type)===l.THREAD_RELATION_TYPE.name?t.event_id:(null===(n=this.getThread())||void 0===n?void 0:n.id)||this.threadId;var n}get isThreadRoot(){var e;return!!this.getServerAggregatedRelation(l.THREAD_RELATION_TYPE.name)||(null===(e=this.getThread())||void 0===e?void 0:e.id)===this.getId()}get replyEventId(){var e;const t=this.getContent()["m.relates_to"]||this.getWireContent()["m.relates_to"];return null==t||null===(e=t["m.in_reply_to"])||void 0===e?void 0:e.event_id}get relationEventId(){var e,t;return null===(e=this.getWireContent())||void 0===e||null===(t=e["m.relates_to"])||void 0===t?void 0:t.event_id}getPrevContent(){return this.getUnsigned().prev_content||this.event.prev_content||{}}getDirectionalContent(){return this.forwardLooking?this.getContent():this.getPrevContent()}getAge(){return this.getUnsigned().age||this.event.age}getLocalAge(){return Date.now()-this.localTimestamp}getStateKey(){return this.event.state_key}isState(){return void 0!==this.event.state_key}makeEncrypted(e,t,n,r){this.clearEvent={type:this.event.type,content:this.event.content},this.event.type=e,this.event.content=t,this.senderCurve25519Key=n,this.claimedEd25519Key=r}isBeingDecrypted(){return null!=this._decryptionPromise}getDecryptionPromise(){return this._decryptionPromise}isDecryptionFailure(){var e,t;return"m.bad.encrypted"===(null===(e=this.clearEvent)||void 0===e||null===(t=e.content)||void 0===t?void 0:t.msgtype)}shouldAttemptDecryption(){return!(this.isRedacted()||this.isBeingDecrypted()||this.clearEvent||!this.isEncrypted())}async attemptDecryption(e,t={}){if("boolean"==typeof t&&(t={isRetry:t}),!this.isEncrypted())throw new Error("Attempt to decrypt event which isn't encrypted");if(this.clearEvent&&!this.isDecryptionFailure())throw new Error("Attempt to decrypt event which has already been decrypted");return this._decryptionPromise?(o.logger.log(`Event ${this.getId()} already being decrypted; queueing a retry`),this.retryDecryption=!0,this._decryptionPromise):(this._decryptionPromise=this.decryptionLoop(e,t),this._decryptionPromise)}cancelAndResendKeyRequest(e,t){const n=this.getWireContent();return e.requestRoomKey({algorithm:n.algorithm,room_id:this.getRoomId(),session_id:n.session_id,sender_key:n.sender_key},this.getKeyRequestRecipients(t),!0)}getKeyRequestRecipients(e){const t=this.getWireContent(),n=[{userId:e,deviceId:"*"}],r=this.getSender();return r!==e&&n.push({userId:r,deviceId:t.device_id}),n}async decryptionLoop(e,t={}){for(await Promise.resolve();;){let n,r;this.retryDecryption=!1;try{e?(n=await e.decryptEvent(this),!0===t.isRetry&&o.logger.info(`Decrypted event on retry (id=${this.getId()})`)):n=this.badEncryptedMessage("Encryption not enabled")}catch(e){if("DecryptionError"!==e.name){const n=t.isRetry?"re":"";return o.logger.error(`Error ${n}decrypting event (id=${this.getId()}): ${e.stack||e}`),this._decryptionPromise=null,void(this.retryDecryption=!1)}if(r=e,this.retryDecryption){o.logger.log(`Got error decrypting event (id=${this.getId()}: ${e.detailedString}), but retrying`,e);continue}o.logger.warn(`Got error decrypting event (id=${this.getId()}: ${e.detailedString})`,e),n=this.badEncryptedMessage(e.message)}return this._decryptionPromise=null,this.retryDecryption=!1,this.setClearData(n),this.setPushActions(null),void(!1!==t.emit&&this.emit(g.Decrypted,this,r))}}badEncryptedMessage(e){return{clearEvent:{type:a.EventType.RoomMessage,content:{msgtype:"m.bad.encrypted",body:"** Unable to decrypt: "+e+" **"}}}}setClearData(e){this.clearEvent=e.clearEvent,this.senderCurve25519Key=e.senderCurve25519Key||null,this.claimedEd25519Key=e.claimedEd25519Key||null,this.forwardingCurve25519KeyChain=e.forwardingCurve25519KeyChain||[],this.untrusted=e.untrusted||!1,this.invalidateExtensibleEvent()}getClearContent(){return this.clearEvent?this.clearEvent.content:null}isEncrypted(){return!this.isState()&&this.event.type===a.EventType.RoomMessageEncrypted}getSenderKey(){return this.senderCurve25519Key}getKeysClaimed(){return{ed25519:this.claimedEd25519Key}}getClaimedEd25519Key(){return this.claimedEd25519Key}getForwardingCurve25519KeyChain(){return this.forwardingCurve25519KeyChain}isKeySourceUntrusted(){return this.untrusted}getUnsigned(){return this.event.unsigned||{}}setUnsigned(e){this.event.unsigned=e}unmarkLocallyRedacted(){const e=this._localRedactionEvent;return this._localRedactionEvent=null,this.event.unsigned&&(this.event.unsigned.redacted_because=null),!!e}markLocallyRedacted(e){this._localRedactionEvent||(this.emit(g.BeforeRedaction,this,e),this._localRedactionEvent=e,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event)}applyVisibilityEvent(e){const t=!e||e.visible,n=e?e.reason:null;let r=!1;this.visibility.visible!==e.visible?r=!0:this.visibility.visible||this.visibility.reason===n||(r=!0),r&&(this.visibility=t?f:Object.freeze({visible:!1,reason:n}),this.emit(g.VisibilityChange,this,t))}messageVisibility(){return this.visibility}makeRedacted(e){if(!e.event)throw new Error("invalid redactionEvent in makeRedacted");this._localRedactionEvent=null,this.emit(g.BeforeRedaction,this,e),this._replacingEvent=null,this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=e.event;for(const e in this.event)this.event.hasOwnProperty(e)&&!m.has(e)&&delete this.event[e];this.isEncrypted()&&(this.clearEvent=null);const t=y[this.getType()]||{},n=this.getContent();for(const e in n)n.hasOwnProperty(e)&&!t[e]&&delete n[e];this.invalidateExtensibleEvent()}isRedacted(){return Boolean(this.getUnsigned().redacted_because)}isRedaction(){return this.getType()===a.EventType.RoomRedaction}asVisibilityChange(){if(!a.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType()))return null;const e=this.getRelation();if(!e||"m.reference"!=e.rel_type)return null;const t=e.event_id;if(!t)return null;const n=this.getWireContent(),r=!!n.visible,i=n.reason;return i&&"string"!=typeof i?null:{visible:r,reason:i,eventId:t}}isVisibilityEvent(){return a.EVENT_VISIBILITY_CHANGE_TYPE.matches(this.getType())}getRedactionEvent(){var e,t;return this.isRedacted()?null!==(e=this.clearEvent)&&void 0!==e&&e.unsigned?null===(t=this.clearEvent)||void 0===t?void 0:t.unsigned.redacted_because:this.event.unsigned.redacted_because?this.event.unsigned.redacted_because:{}:null}getPushActions(){return this.pushActions}setPushActions(e){this.pushActions=e}handleRemoteEcho(e){const t=this.getUnsigned(),n=this.getId();this.event=e,t.redacted_because&&(this.event.unsigned||(this.event.unsigned={}),this.event.unsigned.redacted_because=t.redacted_because),this.setStatus(null),this.getId()!==n&&this.emit(g.LocalEventIdReplaced,this),this.localTimestamp=Date.now()-this.getAge()}isSending(){return!!this.status}setStatus(e){this.status=e,this.emit(g.Status,this,e)}replaceLocalEventId(e){this.event.event_id=e,this.emit(g.LocalEventIdReplaced,this)}isRelation(e=void 0){var t;const n=null===(t=this.getWireContent())||void 0===t?void 0:t["m.relates_to"];return(!this.isState()||(null==n?void 0:n.rel_type)!==a.RelationType.Replace)&&(null==n?void 0:n.rel_type)&&n.event_id&&(!e||n.rel_type===e)}getRelation(){return this.isRelation()?this.getWireContent()["m.relates_to"]:null}makeReplaced(e){this.isRedacted()&&e||this.isState()||this._replacingEvent!==e&&(this._replacingEvent=e,this.emit(g.Replaced,this),this.invalidateExtensibleEvent())}getAssociatedStatus(){return this._replacingEvent?this._replacingEvent.status:this._localRedactionEvent?this._localRedactionEvent.status:this.status}getServerAggregatedRelation(e){var t;return null===(t=this.getUnsigned()["m.relations"])||void 0===t?void 0:t[e]}replacingEventId(){const e=this.getServerAggregatedRelation(a.RelationType.Replace);return e?e.event_id:this._replacingEvent?this._replacingEvent.getId():void 0}replacingEvent(){return this._replacingEvent}replacingEventDate(){const e=this.getServerAggregatedRelation(a.RelationType.Replace);if(e){const t=e.origin_server_ts;if(Number.isFinite(t))return new Date(t)}else if(this._replacingEvent)return this._replacingEvent.getDate()}localRedactionEvent(){return this._localRedactionEvent}getAssociatedId(){const e=this.getRelation();return this.replyEventId?this.replyEventId:e?e.event_id:this.isRedaction()?this.event.redacts:void 0}hasAssocation(){return!!this.getAssociatedId()}updateAssociatedId(e){const t=this.getRelation();t?t.event_id=e:this.isRedaction()&&(this.event.redacts=e)}flagCancelled(e=!0){this._isCancelled=e}isCancelled(){return this._isCancelled}toSnapshot(){const e=new p(JSON.parse(JSON.stringify(this.event)));for(const[t,n]of Object.entries(this))"event"!==t&&(e[t]=n);return e}isEquivalentTo(e){if(!e)return!1;if(e===this)return!0;const t=(0,c.deepSortedObjectEntries)(this.event),n=(0,c.deepSortedObjectEntries)(e.event);return JSON.stringify(t)===JSON.stringify(n)}toJSON(){const e=this.getEffectiveEvent();return this.isEncrypted()?{decrypted:e,encrypted:this.event}:e}setVerificationRequest(e){this.verificationRequest=e}setTxnId(e){this.txnId=e}getTxnId(){return this.txnId}setThread(e){this.thread=e,this.setThreadId(e.id),this.reEmitter.reEmit(e,[l.ThreadEvent.Update])}getThread(){return this.thread}setThreadId(e){this.threadId=e}}t.MatrixEvent=p;const m=new Set(["event_id","type","room_id","user_id","sender","state_key","prev_state","content","unsigned","origin_server_ts"]),y={[a.EventType.RoomMember]:{membership:1},[a.EventType.RoomCreate]:{creator:1},[a.EventType.RoomJoinRules]:{join_rule:1},[a.EventType.RoomPowerLevels]:{ban:1,events:1,events_default:1,kick:1,redact:1,state_default:1,users:1,users_default:1},[a.EventType.RoomAliases]:{aliases:1}}},7286:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RelationsContainer=void 0;var i=r(n(8416)),s=n(9690),o=n(4369);t.RelationsContainer=class{constructor(e,t){this.client=e,this.room=t,(0,i.default)(this,"relations",new Map)}getChildEventsForEvent(e,t,n){var r,i;return null===(r=this.relations.get(e))||void 0===r||null===(i=r.get(t))||void 0===i?void 0:i.get(n)}getAllChildEventsForEvent(e){var t;const n=null!==(t=this.relations.get(e))&&void 0!==t?t:new Map,r=[];for(const e of n.values())for(const t of e.values())r.push(...t.getRelations());return r}aggregateParentEvent(e){const t=this.relations.get(e.getId());if(t)for(const n of t.values())for(const t of n.values())t.setTargetEvent(e)}aggregateChildEvent(e,t){if(e.isRedacted()||e.status===o.EventStatus.CANCELLED)return;const n=e.getRelation();if(!n)return;const r=()=>{e.isDecryptionFailure()?e.once(o.MatrixEventEvent.Decrypted,r):this.aggregateChildEvent(e,t)};if(e.isBeingDecrypted()||e.shouldAttemptDecryption())return void e.once(o.MatrixEventEvent.Decrypted,r);const{event_id:i,rel_type:a}=n,c=e.getType();let l=this.relations.get(i);l||(l=new Map,this.relations.set(i,l));let d=l.get(a);d||(d=new Map,l.set(a,d));let u=d.get(c);if(!u){var h,f,g;u=new s.Relations(a,c,this.client),d.set(c,u);const e=null!==(h=this.room)&&void 0!==h?h:null==t?void 0:t.room,n=null!==(f=null!==(g=null==t?void 0:t.findEventById(i))&&void 0!==g?g:null==e?void 0:e.findEventById(i))&&void 0!==f?f:null==e?void 0:e.getPendingEvent(i);n&&u.setTargetEvent(n)}u.addEvent(e)}}},9690:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RelationsEvent=t.Relations=void 0;var i=r(n(8416)),s=n(4369),o=n(7434),a=n(2481),c=n(5861),l=n(7366);let d;t.RelationsEvent=d,function(e){e.Add="Relations.add",e.Remove="Relations.remove",e.Redaction="Relations.redaction"}(d||(t.RelationsEvent=d={}));class u extends c.TypedEventEmitter{constructor(e,t,n){super(),this.relationType=e,this.eventType=t,(0,i.default)(this,"relationEventIds",new Set),(0,i.default)(this,"relations",new Set),(0,i.default)(this,"annotationsByKey",{}),(0,i.default)(this,"annotationsBySender",{}),(0,i.default)(this,"sortedAnnotationsByKey",[]),(0,i.default)(this,"targetEvent",null),(0,i.default)(this,"creationEmitted",!1),(0,i.default)(this,"client",void 0),(0,i.default)(this,"onEventStatus",((e,t)=>{e.isSending()?t===s.EventStatus.CANCELLED&&(e.removeListener(s.MatrixEventEvent.Status,this.onEventStatus),this.removeEvent(e)):e.removeListener(s.MatrixEventEvent.Status,this.onEventStatus)})),(0,i.default)(this,"onBeforeRedaction",(async e=>{if(this.relations.has(e)){if(this.relations.delete(e),this.relationType===a.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===a.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=await this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.removeListener(s.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(d.Redaction,e)}})),this.client=n instanceof l.Room?n.client:n}async addEvent(e){if(this.relationEventIds.has(e.getId()))return;const t=e.getRelation();if(!t)return void o.logger.error("Event must have relation info");const n=t.rel_type,r=e.getType();if(this.relationType===n&&this.eventType===r){if(e.isSending()&&e.on(s.MatrixEventEvent.Status,this.onEventStatus),this.relations.add(e),this.relationEventIds.add(e.getId()),this.relationType===a.RelationType.Annotation)this.addAnnotationToAggregation(e);else if(this.relationType===a.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=await this.getLastReplacement();this.targetEvent.makeReplaced(e)}e.on(s.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.emit(d.Add,e),this.maybeEmitCreated()}else o.logger.error("Event relation info doesn't match this container")}async removeEvent(e){if(!this.relations.has(e))return;const t=e.getRelation();if(!t)return void o.logger.error("Event must have relation info");const n=t.rel_type,r=e.getType();if(this.relationType===n&&this.eventType===r){if(this.relations.delete(e),this.relationType===a.RelationType.Annotation)this.removeAnnotationFromAggregation(e);else if(this.relationType===a.RelationType.Replace&&this.targetEvent&&!this.targetEvent.isState()){const e=await this.getLastReplacement();this.targetEvent.makeReplaced(e)}this.emit(d.Remove,e)}else o.logger.error("Event relation info doesn't match this container")}getRelations(){return[...this.relations]}addAnnotationToAggregation(e){const{key:t}=e.getRelation();if(!t)return;let n=this.annotationsByKey[t];n||(n=this.annotationsByKey[t]=new Set,this.sortedAnnotationsByKey.push([t,n])),n.add(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const n=e[1];return t[1].size-n.size}));const r=e.getSender();let i=this.annotationsBySender[r];i||(i=this.annotationsBySender[r]=new Set),i.add(e)}removeAnnotationFromAggregation(e){const{key:t}=e.getRelation();if(!t)return;const n=this.annotationsByKey[t];n&&(n.delete(e),this.sortedAnnotationsByKey.sort(((e,t)=>{const n=e[1];return t[1].size-n.size})));const r=e.getSender(),i=this.annotationsBySender[r];i&&i.delete(e)}getSortedAnnotationsByKey(){return this.relationType!==a.RelationType.Annotation?null:this.sortedAnnotationsByKey}getAnnotationsBySender(){return this.relationType!==a.RelationType.Annotation?null:this.annotationsBySender}async getLastReplacement(){if(this.relationType!==a.RelationType.Replace)return null;if(!this.targetEvent)return null;const e=this.targetEvent.getServerAggregatedRelation(a.RelationType.Replace),t=null==e?void 0:e.origin_server_ts,n=this.getRelations().reduce(((e,n)=>n.getSender()!==this.targetEvent.getSender()||t&&t>n.getTs()||e&&e.getTs()>n.getTs()?e:n),null);return null!=n&&n.shouldAttemptDecryption()?await n.attemptDecryption(this.client.crypto):null!=n&&n.isBeingDecrypted()&&await n.getDecryptionPromise(),n}async setTargetEvent(e){if(!this.targetEvent){if(this.targetEvent=e,this.relationType===a.RelationType.Replace&&!this.targetEvent.isState()){const e=await this.getLastReplacement();e&&this.targetEvent.makeReplaced(e)}this.maybeEmitCreated()}}maybeEmitCreated(){this.creationEmitted||this.targetEvent&&this.relations.size&&(this.creationEmitted=!0,this.targetEvent.emit(s.MatrixEventEvent.RelationsCreated,this.relationType,this.eventType))}}t.Relations=u},2848:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RoomMemberEvent=t.RoomMember=void 0;var i=r(n(8416)),s=n(3667),o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=d(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),a=n(7434),c=n(5861),l=n(2481);function d(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(d=function(e){return e?n:t})(e)}let u;t.RoomMemberEvent=u,function(e){e.Membership="RoomMember.membership",e.Name="RoomMember.name",e.PowerLevel="RoomMember.powerLevel",e.Typing="RoomMember.typing"}(u||(t.RoomMemberEvent=u={}));class h extends c.TypedEventEmitter{constructor(e,t){super(),this.roomId=e,this.userId=t,(0,i.default)(this,"_isOutOfBand",!1),(0,i.default)(this,"_modified",void 0),(0,i.default)(this,"_requestedProfileInfo",void 0),(0,i.default)(this,"typing",!1),(0,i.default)(this,"name",void 0),(0,i.default)(this,"rawDisplayName",void 0),(0,i.default)(this,"powerLevel",0),(0,i.default)(this,"powerLevelNorm",0),(0,i.default)(this,"user",null),(0,i.default)(this,"membership",null),(0,i.default)(this,"disambiguate",!1),(0,i.default)(this,"events",{member:null}),this.name=t,this.rawDisplayName=t,this.updateModifiedTime()}markOutOfBand(){this._isOutOfBand=!0}isOutOfBand(){return this._isOutOfBand}setMembershipEvent(e,t){const n=e.getDirectionalContent().displayname;if(e.getType()!==l.EventType.RoomMember)return;this._isOutOfBand=!1,this.events.member=e;const r=this.membership;this.membership=e.getDirectionalContent().membership,void 0===this.membership&&a.logger.trace(`membership event with membership undefined (forwardLooking: ${e.forwardLooking})!`,e.getContent(),"prevcontent is ",e.getPrevContent()),this.disambiguate=function(e,t,n){if(!t||t===e)return!1;if(!o.removeHiddenChars(t))return!1;if(!n)return!1;if(f.test(t))return!0;if(g.test(t))return!0;return!!n.getUserIdsWithDisplayName(t).some((t=>t!==e))}(this.userId,n,t);const i=this.name;this.name=function(e,t,n,r){return r?o.removeDirectionOverrideChars(t)+" ("+e+")":t&&t!==e&&o.removeHiddenChars(t)?o.removeDirectionOverrideChars(t):e}(this.userId,n,0,this.disambiguate),this.rawDisplayName=o.removeDirectionOverrideChars(e.getDirectionalContent().displayname),this.rawDisplayName&&o.removeHiddenChars(this.rawDisplayName)||(this.rawDisplayName=this.userId),r!==this.membership&&(this.updateModifiedTime(),this.emit(u.Membership,e,this,r)),i!==this.name&&(this.updateModifiedTime(),this.emit(u.Name,e,this,i))}setPowerLevelEvent(e){if("m.room.power_levels"!==e.getType())return;const t=e.getDirectionalContent();let n=t.users_default||0;const r=t.users||{};Object.values(r).forEach((function(e){n=Math.max(n,e)}));const i=this.powerLevel,s=this.powerLevelNorm;void 0!==r[this.userId]&&Number.isInteger(r[this.userId])?this.powerLevel=r[this.userId]:void 0!==t.users_default?this.powerLevel=t.users_default:this.powerLevel=0,this.powerLevelNorm=0,n>0&&(this.powerLevelNorm=100*this.powerLevel/n),i===this.powerLevel&&s===this.powerLevelNorm||(this.updateModifiedTime(),this.emit(u.PowerLevel,e,this))}setTypingEvent(e){if("m.typing"!==e.getType())return;const t=this.typing;this.typing=!1;const n=e.getContent().user_ids;Array.isArray(n)&&(-1!==n.indexOf(this.userId)&&(this.typing=!0),t!==this.typing&&(this.updateModifiedTime(),this.emit(u.Typing,e,this)))}updateModifiedTime(){this._modified=Date.now()}getLastModifiedTime(){return this._modified}isKicked(){return"leave"===this.membership&&this.events.member.getSender()!==this.events.member.getStateKey()}getDMInviter(){if(this.events.member){const e=this.events.member;let t=e.getContent(),n=e.getSender();if("join"===t.membership&&(t=e.getPrevContent(),n=e.getUnsigned().prev_sender),"invite"===t.membership&&t.is_direct)return n}}getAvatarUrl(e,t,n,r,i=!0,o){const a=this.getMxcAvatarUrl();if(!a&&!i)return null;return(0,s.getHttpUriForMxc)(e,a,t,n,r,o)||null}getMxcAvatarUrl(){return this.events.member?this.events.member.getDirectionalContent().avatar_url:this.user?this.user.avatarUrl:null}}t.RoomMember=h;const f=/@.+:.+/,g=/[\u200E\u200F\u202A-\u202F]/},6860:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RoomStateEvent=t.RoomState=void 0;var i,s=r(n(8416)),o=n(2848),a=n(7434),c=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=m(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),l=n(2481),d=n(4369),u=n(4702),h=n(5861),f=n(6320),g=n(771),p=n(5699);function m(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(m=function(e){return e?n:t})(e)}function y(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function v(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?y(Object(n),!0).forEach((function(t){(0,s.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):y(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let b;!function(e){e[e.NotStarted=0]="NotStarted",e[e.InProgress=1]="InProgress",e[e.Finished=2]="Finished"}(i||(i={})),t.RoomStateEvent=b,function(e){e.Events="RoomState.events",e.Members="RoomState.members",e.NewMember="RoomState.newMember",e.Update="RoomState.update",e.BeaconLiveness="RoomState.BeaconLiveness",e.Marker="RoomState.Marker"}(b||(t.RoomStateEvent=b={}));class _ extends h.TypedEventEmitter{constructor(e,t={status:i.NotStarted}){super(),this.roomId=e,this.oobMemberFlags=t,(0,s.default)(this,"reEmitter",new g.TypedReEmitter(this)),(0,s.default)(this,"sentinels",{}),(0,s.default)(this,"displayNameToUserIds",new Map),(0,s.default)(this,"userIdsToDisplayNames",{}),(0,s.default)(this,"tokenToInvite",{}),(0,s.default)(this,"joinedMemberCount",null),(0,s.default)(this,"summaryJoinedMemberCount",null),(0,s.default)(this,"invitedMemberCount",null),(0,s.default)(this,"summaryInvitedMemberCount",null),(0,s.default)(this,"modified",void 0),(0,s.default)(this,"members",{}),(0,s.default)(this,"events",new Map),(0,s.default)(this,"paginationToken",null),(0,s.default)(this,"beacons",new Map),(0,s.default)(this,"_liveBeaconIds",[]),this.updateModifiedTime()}getJoinedMemberCount(){return null!==this.summaryJoinedMemberCount?this.summaryJoinedMemberCount:(null===this.joinedMemberCount&&(this.joinedMemberCount=this.getMembers().reduce(((e,t)=>"join"===t.membership?e+1:e),0)),this.joinedMemberCount)}setJoinedMemberCount(e){this.summaryJoinedMemberCount=e}getInvitedMemberCount(){return null!==this.summaryInvitedMemberCount?this.summaryInvitedMemberCount:(null===this.invitedMemberCount&&(this.invitedMemberCount=this.getMembers().reduce(((e,t)=>"invite"===t.membership?e+1:e),0)),this.invitedMemberCount)}setInvitedMemberCount(e){this.summaryInvitedMemberCount=e}getMembers(){return Object.values(this.members)}getMembersExcept(e){return this.getMembers().filter((t=>!e.includes(t.userId)))}getMember(e){return this.members[e]||null}getSentinelMember(e){if(!e)return null;let t=this.sentinels[e];if(void 0===t){t=new o.RoomMember(this.roomId,e);const n=this.members[e];n&&t.setMembershipEvent(n.events.member,this),this.sentinels[e]=t}return t}getStateEvents(e,t){if(!this.events.has(e))return void 0===t?[]:null;if(void 0===t)return Array.from(this.events.get(e).values());return this.events.get(e).get(t)||null}get hasLiveBeacons(){var e;return!(null===(e=this.liveBeaconIds)||void 0===e||!e.length)}get liveBeaconIds(){return this._liveBeaconIds}clone(){const e=new _(this.roomId,this.oobMemberFlags),t=this.oobMemberFlags.status;return this.oobMemberFlags.status=i.NotStarted,Array.from(this.events.values()).forEach((t=>{e.setStateEvents(Array.from(t.values()))})),this.oobMemberFlags.status=t,null!==this.summaryInvitedMemberCount&&e.setInvitedMemberCount(this.getInvitedMemberCount()),null!==this.summaryJoinedMemberCount&&e.setJoinedMemberCount(this.getJoinedMemberCount()),this.oobMemberFlags.status==i.Finished&&this.getMembers().forEach((t=>{t.isOutOfBand()&&e.getMember(t.userId).markOutOfBand()})),e}setUnknownStateEvents(e){const t=e.filter((e=>!this.events.has(e.getType())||!this.events.get(e.getType()).has(e.getStateKey())));this.setStateEvents(t)}setStateEvents(e,t){this.updateModifiedTime(),e.forEach((e=>{if(e.getRoomId()!==this.roomId)return;if(!e.isState())return;p.M_BEACON_INFO.matches(e.getType())&&this.setBeacon(e);const t=this.getStateEventMatching(e);this.setStateEvent(e),e.getType()===l.EventType.RoomMember&&(this.updateDisplayNameCache(e.getStateKey(),e.getContent().displayname),this.updateThirdPartyTokenCache(e)),this.emit(b.Events,e,this,t)})),this.onBeaconLivenessChange(),e.forEach((e=>{if(e.getRoomId()===this.roomId&&e.isState())if(e.getType()===l.EventType.RoomMember){const t=e.getStateKey();"leave"!==e.getContent().membership&&"ban"!==e.getContent().membership||(e.getContent().avatar_url=e.getContent().avatar_url||e.getPrevContent().avatar_url,e.getContent().displayname=e.getContent().displayname||e.getPrevContent().displayname);const n=this.getOrCreateMember(t,e);n.setMembershipEvent(e,this),this.updateMember(n),this.emit(b.Members,e,this,n)}else if(e.getType()===l.EventType.RoomPowerLevels){if(""!==e.getStateKey())return;Object.values(this.members).forEach((t=>{const n=t.getLastModifiedTime();t.setPowerLevelEvent(e),n!==t.getLastModifiedTime()&&this.emit(b.Members,e,this,t)})),this.sentinels={}}else l.UNSTABLE_MSC2716_MARKER.matches(e.getType())&&this.emit(b.Marker,e,t)})),this.emit(b.Update,this)}processBeaconEvents(e,t){if(!e.length||!this.beacons.size)return;const n=[...this.beacons.values()].reduce(((e,t)=>v(v({},e),{},{[t.beaconInfoId]:t})),{}),r=(e,t)=>{if(!p.M_BEACON.matches(t.getType()))return;const r=n[e];r&&r.addLocations([t])};e.forEach((e=>{var i;const s=null===(i=e.getRelation())||void 0===i?void 0:i.event_id;n[s]&&(t.decryptEventIfNeeded(e),e.isBeingDecrypted()||e.isDecryptionFailure()?e.once(d.MatrixEventEvent.Decrypted,(async()=>{r(s,e)})):r(s,e))}))}getOrCreateMember(e,t){let n=this.members[e];return n||(n=new o.RoomMember(this.roomId,e),this.members[e]=n,this.emit(b.NewMember,t,this,n)),n}setStateEvent(e){this.events.has(e.getType())||this.events.set(e.getType(),new Map),this.events.get(e.getType()).set(e.getStateKey(),e)}setBeacon(e){const t=(0,f.getBeaconInfoIdentifier)(e);if(this.beacons.has(t)){const r=this.beacons.get(t);var n;return e.isRedacted()?void(r.beaconInfoId===(null===(n=e.getRedactionEvent())||void 0===n?void 0:n.redacts)&&(r.destroy(),this.beacons.delete(t))):r.update(e)}if(e.isRedacted())return;const r=new f.Beacon(e);this.reEmitter.reEmit(r,[f.BeaconEvent.New,f.BeaconEvent.Update,f.BeaconEvent.Destroy,f.BeaconEvent.LivenessChange]),this.emit(f.BeaconEvent.New,e,r),r.on(f.BeaconEvent.LivenessChange,this.onBeaconLivenessChange.bind(this)),r.on(f.BeaconEvent.Destroy,this.onBeaconLivenessChange.bind(this)),this.beacons.set(r.identifier,r)}onBeaconLivenessChange(){this._liveBeaconIds=Array.from(this.beacons.values()).filter((e=>e.isLive)).map((e=>e.identifier)),this.emit(b.BeaconLiveness,this,this.hasLiveBeacons)}getStateEventMatching(e){var t,n;return null!==(t=null===(n=this.events.get(e.getType()))||void 0===n?void 0:n.get(e.getStateKey()))&&void 0!==t?t:null}updateMember(e){const t=this.getStateEvents(l.EventType.RoomPowerLevels,"");t&&e.setPowerLevelEvent(t),delete this.sentinels[e.userId],this.members[e.userId]=e,this.joinedMemberCount=null,this.invitedMemberCount=null}needsOutOfBandMembers(){return this.oobMemberFlags.status===i.NotStarted}markOutOfBandMembersStarted(){this.oobMemberFlags.status===i.NotStarted&&(this.oobMemberFlags.status=i.InProgress)}markOutOfBandMembersFailed(){this.oobMemberFlags.status===i.InProgress&&(this.oobMemberFlags.status=i.NotStarted)}clearOutOfBandMembers(){let e=0;Object.keys(this.members).forEach((t=>{this.members[t].isOutOfBand()&&(++e,delete this.members[t])})),a.logger.log(`LL: RoomState removed ${e} members...`),this.oobMemberFlags.status=i.NotStarted}setOutOfBandMembers(e){a.logger.log(`LL: RoomState about to set ${e.length} OOB members ...`),this.oobMemberFlags.status===i.InProgress&&(a.logger.log("LL: RoomState put in finished state ..."),this.oobMemberFlags.status=i.Finished,e.forEach((e=>this.setOutOfBandMember(e))),this.emit(b.Update,this))}setOutOfBandMember(e){if(e.getType()!==l.EventType.RoomMember)return;const t=e.getStateKey(),n=this.getMember(t);if(n&&!n.isOutOfBand())return;const r=this.getOrCreateMember(t,e);r.setMembershipEvent(e,this),r.markOutOfBand(),this.updateDisplayNameCache(r.userId,r.name),this.setStateEvent(e),this.updateMember(r),this.emit(b.Members,e,this,r)}setTypingEvent(e){Object.values(this.members).forEach((function(t){t.setTypingEvent(e)}))}getInviteForThreePidToken(e){return this.tokenToInvite[e]||null}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getUserIdsWithDisplayName(e){var t;return null!==(t=this.displayNameToUserIds.get(c.removeHiddenChars(e)))&&void 0!==t?t:[]}maySendRedactionForEvent(e,t){const n=this.getMember(t);if(!n||"leave"===n.membership)return!1;if(e.status||e.isRedacted())return!1;const r=this.maySendEvent(l.EventType.RoomRedaction,t);return e.getSender()===t?r:this.hasSufficientPowerLevelFor("redact",n.powerLevel)}hasSufficientPowerLevelFor(e,t){const n=this.getStateEvents(l.EventType.RoomPowerLevels,"");let r={};n&&(r=n.getContent());let i=50;return c.isNumber(r[e])&&(i=r[e]),t>=i}maySendMessage(e){return this.maySendEventOfType(l.EventType.RoomMessage,e,!1)}maySendEvent(e,t){return this.maySendEventOfType(e,t,!1)}mayClientSendStateEvent(e,t){return!t.isGuest()&&this.maySendStateEvent(e,t.credentials.userId)}maySendStateEvent(e,t){return this.maySendEventOfType(e,t,!0)}maySendEventOfType(e,t,n){const r=this.getStateEvents(l.EventType.RoomPowerLevels,"");let i,s={},o=0,a=0,c=0;if(r){i=r.getContent(),s=i.events||{},o=Number.isSafeInteger(i.state_default)?i.state_default:50;const e=i.users&&i.users[t];Number.isSafeInteger(e)?c=e:Number.isSafeInteger(i.users_default)&&(c=i.users_default),Number.isSafeInteger(i.events_default)&&(a=i.events_default)}let d=n?o:a;return Number.isSafeInteger(s[e])&&(d=s[e]),c>=d}mayTriggerNotifOfType(e,t){const n=this.getMember(t);if(!n)return!1;const r=this.getStateEvents(l.EventType.RoomPowerLevels,"");let i=50;return r&&r.getContent()&&r.getContent().notifications&&c.isNumber(r.getContent().notifications[e])&&(i=r.getContent().notifications[e]),n.powerLevel>=i}getJoinRule(){var e;const t=this.getStateEvents(l.EventType.RoomJoinRules,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).join_rule||u.JoinRule.Invite}getHistoryVisibility(){var e;const t=this.getStateEvents(l.EventType.RoomHistoryVisibility,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).history_visibility||u.HistoryVisibility.Shared}getGuestAccess(){var e;const t=this.getStateEvents(l.EventType.RoomGuestAccess,"");return(null!==(e=null==t?void 0:t.getContent())&&void 0!==e?e:{}).guest_access||u.GuestAccess.Forbidden}updateThirdPartyTokenCache(e){if(!e.getContent().third_party_invite)return;const t=(e.getContent().third_party_invite.signed||{}).token;t&&this.getStateEvents(l.EventType.RoomThirdPartyInvite,t)&&(this.tokenToInvite[t]=e)}updateDisplayNameCache(e,t){const n=this.userIdsToDisplayNames[e];if(delete this.userIdsToDisplayNames[e],n){const t=c.removeHiddenChars(n),r=this.displayNameToUserIds.get(t);if(r){const n=r.filter((t=>t!==e));this.displayNameToUserIds.set(t,n)}}this.userIdsToDisplayNames[e]=t;const r=t&&c.removeHiddenChars(t);if(r){var i;const t=null!==(i=this.displayNameToUserIds.get(r))&&void 0!==i?i:[];t.push(e),this.displayNameToUserIds.set(r,t)}}}t.RoomState=_},5205:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.RoomSummary=void 0,t.RoomSummary=class{constructor(e,t){this.roomId=e}}},7366:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RoomNameType=t.RoomEvent=t.Room=t.NotificationCountType=t.KNOWN_SAFE_ROOM_VERSION=void 0;var i=r(n(8416)),s=n(3705),o=n(8910),a=n(3667),c=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=C(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),l=n(4369),d=n(8881),u=n(2848),h=n(5205),f=n(7434),g=n(771),p=n(2481),m=n(2168),y=n(7906),v=n(6860),b=n(6320),_=n(6969),E=n(5861),w=n(5550),S=n(7286);function C(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(C=function(e){return e?n:t})(e)}function T(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function R(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?T(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):T(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}t.KNOWN_SAFE_ROOM_VERSION="9";const I=["1","2","3","4","5","6","7","8","9"];function k(e,t,n){return new l.MatrixEvent({content:{[t.getId()]:{[n]:{[e]:{ts:t.getTs()}}}},type:p.EventType.Receipt,room_id:t.getRoomId()})}let O,A;t.NotificationCountType=O,function(e){e.Highlight="highlight",e.Total="total"}(O||(t.NotificationCountType=O={})),t.RoomEvent=A,function(e){e.MyMembership="Room.myMembership",e.Tags="Room.tags",e.AccountData="Room.accountData",e.Receipt="Room.receipt",e.Name="Room.name",e.Redaction="Room.redaction",e.RedactionCancelled="Room.redactionCancelled",e.LocalEchoUpdated="Room.localEchoUpdated",e.Timeline="Room.timeline",e.TimelineReset="Room.timelineReset",e.TimelineRefresh="Room.TimelineRefresh",e.OldStateUpdated="Room.OldStateUpdated",e.CurrentStateUpdated="Room.CurrentStateUpdated",e.HistoryImportedWithinTimeline="Room.historyImportedWithinTimeline"}(A||(t.RoomEvent=A={}));class D extends E.TypedEventEmitter{constructor(e,t,n,r={}){super(),this.roomId=e,this.client=t,this.myUserId=n,this.opts=r,(0,i.default)(this,"reEmitter",void 0),(0,i.default)(this,"txnToEvent",{}),(0,i.default)(this,"receipts",{}),(0,i.default)(this,"receiptCacheByEventId",{}),(0,i.default)(this,"notificationCounts",{}),(0,i.default)(this,"timelineSets",void 0),(0,i.default)(this,"threadsTimelineSets",[]),(0,i.default)(this,"filteredTimelineSets",{}),(0,i.default)(this,"timelineNeedsRefresh",!1),(0,i.default)(this,"pendingEventList",void 0),(0,i.default)(this,"blacklistUnverifiedDevices",null),(0,i.default)(this,"selfMembership",null),(0,i.default)(this,"summaryHeroes",null),(0,i.default)(this,"getTypeWarning",!1),(0,i.default)(this,"getVersionWarning",!1),(0,i.default)(this,"membersPromise",void 0),(0,i.default)(this,"name",void 0),(0,i.default)(this,"normalizedName",void 0),(0,i.default)(this,"tags",{}),(0,i.default)(this,"accountData",{}),(0,i.default)(this,"summary",null),(0,i.default)(this,"storageToken",void 0),(0,i.default)(this,"timeline",void 0),(0,i.default)(this,"oldState",void 0),(0,i.default)(this,"currentState",void 0),(0,i.default)(this,"relations",new S.RelationsContainer(this.client,this)),(0,i.default)(this,"threads",new Map),(0,i.default)(this,"lastThread",void 0),(0,i.default)(this,"visibilityEvents",new Map),(0,i.default)(this,"threadTimelineSetsPromise",null),(0,i.default)(this,"threadsReady",!1),(0,i.default)(this,"applyRedaction",(e=>{if(e.isRedaction()){const t=e.event.redacts,n=this.findEventById(t);n&&(n.makeRedacted(e),n.isState()&&this.currentState.getStateEvents(n.getType(),n.getStateKey()).getId()===n.getId()&&this.currentState.setStateEvents([n]),this.emit(A.Redaction,e,this),this.visibilityEvents.delete(t),n.isVisibilityEvent()&&this.redactVisibilityChangeEvent(e))}})),this.setMaxListeners(100),this.reEmitter=new g.TypedReEmitter(this),r.pendingEventOrdering=r.pendingEventOrdering||m.PendingEventOrdering.Chronological,this.name=e,this.timelineSets=[new s.EventTimelineSet(this,r)],this.reEmitter.reEmit(this.getUnfilteredTimelineSet(),[A.Timeline,A.TimelineReset]),this.fixUpLegacyTimelineFields(),this.opts.pendingEventOrdering===m.PendingEventOrdering.Detached&&(this.pendingEventList=[],this.client.store.getPendingEvents(this.roomId).then((e=>{e.forEach((async e=>{const t=new l.MatrixEvent(e);t.getType()===p.EventType.RoomMessageEncrypted&&await t.attemptDecryption(this.client.crypto),t.setStatus(d.EventStatus.NOT_SENT),this.addPendingEvent(t,t.getTxnId())}))}))),this.opts.lazyLoadMembers?this.membersPromise=null:this.membersPromise=Promise.resolve(!1)}async createThreadsTimelineSets(){var e;if(this.threadTimelineSetsPromise)return this.threadTimelineSetsPromise;if(null!==(e=this.client)&&void 0!==e&&e.supportsExperimentalThreads())try{this.threadTimelineSetsPromise=Promise.all([this.createThreadTimelineSet(),this.createThreadTimelineSet(_.ThreadFilterType.My)]);const e=await this.threadTimelineSetsPromise;this.threadsTimelineSets.push(...e)}catch(e){this.threadTimelineSetsPromise=null}}decryptCriticalEvents(){const e=this.getEventReadUpTo(this.client.getUserId(),!0),t=this.getLiveTimeline().getEvents(),n=t.findIndex((t=>t.event.event_id===e)),r=t.slice(n).filter((e=>e.shouldAttemptDecryption())).reverse().map((e=>e.attemptDecryption(this.client.crypto,{isRetry:!0})));return Promise.allSettled(r)}decryptAllEvents(){const e=this.getUnfilteredTimelineSet().getLiveTimeline().getEvents().filter((e=>e.shouldAttemptDecryption())).reverse().map((e=>e.attemptDecryption(this.client.crypto,{isRetry:!0})));return Promise.allSettled(e)}getCreator(){var e;const t=this.currentState.getStateEvents(p.EventType.RoomCreate,"");return null!==(e=null==t?void 0:t.getContent().creator)&&void 0!==e?e:null}getVersion(){const e=this.currentState.getStateEvents(p.EventType.RoomCreate,"");if(!e)return this.getVersionWarning||(f.logger.warn("[getVersion] Room "+this.roomId+" does not have an m.room.create event"),this.getVersionWarning=!0),"1";const t=e.getContent().room_version;return void 0===t?"1":t}shouldUpgradeToVersion(){return I.includes(this.getVersion())?null:"9"}async getRecommendedVersion(){let e=(await this.client.getCapabilities())["m.room_versions"];if(!e){e={default:"9",available:{}};for(const t of I)e.available[t]=m.RoomVersionStability.Stable}let t=this.checkVersionAgainstCapability(e);if(t.urgent&&t.needsUpgrade){if(f.logger.warn("Refreshing room version capability because the server looks to be supporting a newer room version we don't know about."),e=(await this.client.getCapabilities(!0))["m.room_versions"],!e)return f.logger.warn("No room version capability - assuming upgrade required."),t;t=this.checkVersionAgainstCapability(e)}return t}checkVersionAgainstCapability(e){const t=this.getVersion();f.logger.log(`[${this.roomId}] Current version: ${t}`),f.logger.log(`[${this.roomId}] Version capability: `,e);const n={version:t,needsUpgrade:!1,urgent:!1};return t===e.default||Object.keys(e.available).filter((t=>"stable"===e.available[t])).includes(t)||(n.version=e.default,n.needsUpgrade=!0,n.urgent=!!this.getVersion().match(/^[0-9]+[0-9.]*$/g),n.urgent?f.logger.warn(`URGENT upgrade required on ${this.roomId}`):f.logger.warn(`Non-urgent upgrade required on ${this.roomId}`)),n}userMayUpgradeRoom(e){return this.currentState.maySendStateEvent(p.EventType.RoomTombstone,e)}getPendingEvents(){if(this.opts.pendingEventOrdering!==m.PendingEventOrdering.Detached)throw new Error("Cannot call getPendingEvents with pendingEventOrdering == "+this.opts.pendingEventOrdering);return this.pendingEventList}removePendingEvent(e){if(this.opts.pendingEventOrdering!==m.PendingEventOrdering.Detached)throw new Error("Cannot call removePendingEvent with pendingEventOrdering == "+this.opts.pendingEventOrdering);const t=c.removeElement(this.pendingEventList,(function(t){return t.getId()==e}),!1);return this.savePendingEvents(),t}hasPendingEvent(e){return this.opts.pendingEventOrdering===m.PendingEventOrdering.Detached&&this.pendingEventList.some((t=>t.getId()===e))}getPendingEvent(e){return this.opts.pendingEventOrdering!==m.PendingEventOrdering.Detached?null:this.pendingEventList.find((t=>t.getId()===e))}getLiveTimeline(){return this.getUnfilteredTimelineSet().getLiveTimeline()}getLastActiveTimestamp(){const e=this.getLiveTimeline().getEvents();return e.length?e[e.length-1].getTs():Number.MIN_SAFE_INTEGER}getMyMembership(){return this.selfMembership}getDMInviter(){if(this.myUserId){const e=this.getMember(this.myUserId);if(e)return e.getDMInviter()}if("invite"===this.selfMembership&&2==this.getInvitedAndJoinedMemberCount()&&this.summaryHeroes.length)return this.summaryHeroes[0]}guessDMUserId(){const e=this.getMember(this.myUserId);if(e){const t=e.getDMInviter();if(t)return t}if(Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length)return this.summaryHeroes[0];const t=this.currentState.getMembers().find((e=>e.userId!==this.myUserId));return t?t.userId:this.myUserId}getAvatarFallbackMember(){if(this.getInvitedAndJoinedMemberCount()>2)return;const e=Array.isArray(this.summaryHeroes)&&this.summaryHeroes.length;if(e){const e=this.summaryHeroes.map((e=>this.getMember(e))).find((e=>!!e));if(e)return e}const t=this.currentState.getMembers();if(t.length<=2){const e=t.find((e=>e.userId!==this.myUserId));if(e)return e}if(e){const e=this.summaryHeroes.map((e=>this.client.getUser(e))).find((e=>!!e));if(e){const t=new u.RoomMember(this.roomId,e.userId);return t.user=e,t}}}updateMyMembership(e){const t=this.selfMembership;this.selfMembership=e,t!==e&&("leave"===e&&this.cleanupAfterLeaving(),this.emit(A.MyMembership,this,e,t))}async loadMembersFromServer(){const e=this.client.store.getSyncToken();return(await this.client.members(this.roomId,void 0,"leave",e)).chunk}async loadMembers(){let e=!1,t=await this.client.store.getOutOfBandMembers(this.roomId);return(null===t||this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId))&&(e=!0,t=await this.loadMembersFromServer(),f.logger.log(`LL: got ${t.length} members from server for room ${this.roomId}`)),{memberEvents:t.map(this.client.getEventMapper()),fromServer:e}}loadMembersIfNeeded(){if(this.membersPromise)return this.membersPromise;this.currentState.markOutOfBandMembersStarted();const e=this.loadMembers().then((e=>(this.currentState.setOutOfBandMembers(e.memberEvents),this.client.isCryptoEnabled()&&this.client.isRoomEncrypted(this.roomId)&&this.client.crypto.trackRoomDevices(this.roomId),e.fromServer))).catch((e=>{throw this.membersPromise=null,this.currentState.markOutOfBandMembersFailed(),e}));return e.then((e=>{if(e){const e=this.currentState.getMembers().filter((e=>e.isOutOfBand())).map((e=>e.events.member.event));return f.logger.log(`LL: telling store to write ${e.length} members for room ${this.roomId}`),this.client.store.setOutOfBandMembers(this.roomId,e).catch((e=>{f.logger.log("LL: storing OOB room members failed, oh well",e)}))}})).catch((e=>{f.logger.error(e)})),this.membersPromise=e,this.membersPromise}async clearLoadedMembersIfNeeded(){this.opts.lazyLoadMembers&&this.membersPromise&&(await this.loadMembersIfNeeded(),await this.client.store.clearOutOfBandMembers(this.roomId),this.currentState.clearOutOfBandMembers(),this.membersPromise=null)}cleanupAfterLeaving(){this.clearLoadedMembersIfNeeded().catch((e=>{f.logger.error(`error after clearing loaded members from room ${this.roomId} after leaving`),f.logger.log(e)}))}async refreshLiveTimeline(){const e=this.getLiveTimeline(),t=e.getPaginationToken(o.EventTimeline.FORWARDS),n=e.getPaginationToken(o.EventTimeline.BACKWARDS),r=e.getEvents(),i=r[r.length-1];f.logger.log(`[refreshLiveTimeline for ${this.roomId}] at mostRecentEventInTimeline=${i&&i.getId()} liveTimelineBefore=${e.toString()} forwardPaginationToken=${t} backwardPaginationToken=${n}`);const s=this.getUnfilteredTimelineSet();let a;i?(this.resetLiveTimeline(null,null),this.emit(A.TimelineRefresh,this,s),a=await this.client.getEventTimeline(s,i.getId())):a=await this.client.getLatestTimeline(s);const c=s.getLiveTimeline();!c||null===c.getPaginationToken(o.Direction.Forward)&&null===c.getPaginationToken(o.Direction.Backward)&&0===c.getEvents().length?(f.logger.log(`[refreshLiveTimeline for ${this.roomId}] using our new live timeline`),a.setPaginationToken(t,o.EventTimeline.FORWARDS),s.setLiveTimeline(a),this.fixUpLegacyTimelineFields()):f.logger.log(`[refreshLiveTimeline for ${this.roomId}] \`/sync\` or some other request beat us to creating a new live timeline after we reset it. We'll use that instead since any events in the scrollback from this timeline will include the history.`),this.setTimelineNeedsRefresh(!1),this.emit(A.TimelineRefresh,this,s)}resetLiveTimeline(e,t){for(let n=0;n<this.timelineSets.length;n++)this.timelineSets[n].resetLiveTimeline(e,t);this.fixUpLegacyTimelineFields()}fixUpLegacyTimelineFields(){const e=this.oldState,t=this.currentState;this.timeline=this.getLiveTimeline().getEvents(),this.oldState=this.getLiveTimeline().getState(o.EventTimeline.BACKWARDS),this.currentState=this.getLiveTimeline().getState(o.EventTimeline.FORWARDS),e!==this.oldState&&this.emit(A.OldStateUpdated,this,e,this.oldState),t!==this.currentState&&(this.emit(A.CurrentStateUpdated,this,t,this.currentState),this.reEmitter.stopReEmitting(t,[v.RoomStateEvent.Events,v.RoomStateEvent.Members,v.RoomStateEvent.NewMember,v.RoomStateEvent.Update,v.RoomStateEvent.Marker,b.BeaconEvent.New,b.BeaconEvent.Update,b.BeaconEvent.Destroy,b.BeaconEvent.LivenessChange]),this.reEmitter.reEmit(this.currentState,[v.RoomStateEvent.Events,v.RoomStateEvent.Members,v.RoomStateEvent.NewMember,v.RoomStateEvent.Update,v.RoomStateEvent.Marker,b.BeaconEvent.New,b.BeaconEvent.Update,b.BeaconEvent.Destroy,b.BeaconEvent.LivenessChange]))}async hasUnverifiedDevices(){if(!this.client.isRoomEncrypted(this.roomId))return!1;const e=await this.getEncryptionTargetMembers();for(const t of e)if(this.client.getStoredDevicesForUser(t.userId).some((e=>e.isUnverified())))return!0;return!1}getTimelineSets(){return this.timelineSets}getUnfilteredTimelineSet(){return this.timelineSets[0]}getTimelineForEvent(e){const t=this.findEventById(e),n=this.findThreadForEvent(t);return n?n.timelineSet.getLiveTimeline():this.getUnfilteredTimelineSet().getTimelineForEvent(e)}addTimeline(){return this.getUnfilteredTimelineSet().addTimeline()}setTimelineNeedsRefresh(e){this.timelineNeedsRefresh=e}getTimelineNeedsRefresh(){return this.timelineNeedsRefresh}findEventById(e){let t=this.getUnfilteredTimelineSet().findEventById(e);if(!t){const n=this.getThreads();for(let r=0;r<n.length;r++)if(t=n[r].findEventById(e),t)return t}return t}getUnreadNotificationCount(e=O.Total){return this.notificationCounts[e]}setUnreadNotificationCount(e,t){this.notificationCounts[e]=t}setSummary(e){const t=e["m.heroes"],n=e["m.joined_member_count"],r=e["m.invited_member_count"];Number.isInteger(n)&&this.currentState.setJoinedMemberCount(n),Number.isInteger(r)&&this.currentState.setInvitedMemberCount(r),Array.isArray(t)&&(this.summaryHeroes=t.filter((e=>e!==this.myUserId)))}setBlacklistUnverifiedDevices(e){this.blacklistUnverifiedDevices=e}getBlacklistUnverifiedDevices(){return this.blacklistUnverifiedDevices}getAvatarUrl(e,t,n,r,i=!0){const s=this.currentState.getStateEvents(p.EventType.RoomAvatar,"");if(!s&&!i)return null;const o=s?s.getContent().url:null;return o?(0,a.getHttpUriForMxc)(e,o,t,n,r):null}getMxcAvatarUrl(){var e,t;return(null===(e=this.currentState.getStateEvents(p.EventType.RoomAvatar,""))||void 0===e||null===(t=e.getContent())||void 0===t?void 0:t.url)||null}getAliases(){const e=[],t=this.currentState.getStateEvents(p.EventType.RoomAliases);if(t)for(const n of t)if(Array.isArray(n.getContent().aliases)){const t=n.getContent().aliases.filter((e=>"string"==typeof e&&"#"===e[0]&&!!e.endsWith(`:${n.getStateKey()}`)));e.push(...t)}return e}getCanonicalAlias(){const e=this.currentState.getStateEvents(p.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alias||null}getAltAliases(){const e=this.currentState.getStateEvents(p.EventType.RoomCanonicalAlias,"");return e&&e.getContent().alt_aliases||[]}addEventsToTimeline(e,t,n,r){n.getTimelineSet().addEventsToTimeline(e,t,n,r)}getThread(e){return this.threads.get(e)}getThreads(){return Array.from(this.threads.values())}getMember(e){return this.currentState.getMember(e)}getMembers(){return this.currentState.getMembers()}getJoinedMembers(){return this.getMembersWithMembership("join")}getJoinedMemberCount(){return this.currentState.getJoinedMemberCount()}getInvitedMemberCount(){return this.currentState.getInvitedMemberCount()}getInvitedAndJoinedMemberCount(){return this.getInvitedMemberCount()+this.getJoinedMemberCount()}getMembersWithMembership(e){return this.currentState.getMembers().filter((function(t){return t.membership===e}))}async getEncryptionTargetMembers(){await this.loadMembersIfNeeded();let e=this.getMembersWithMembership("join");return this.shouldEncryptForInvitedMembers()&&(e=e.concat(this.getMembersWithMembership("invite"))),e}shouldEncryptForInvitedMembers(){var e;const t=this.currentState.getStateEvents(p.EventType.RoomHistoryVisibility,"");return"joined"!==(null==t||null===(e=t.getContent())||void 0===e?void 0:e.history_visibility)}getDefaultRoomName(e){return this.calculateRoomName(e,!0)}hasMembershipState(e,t){const n=this.getMember(e);return!!n&&n.membership===t}getOrCreateFilteredTimelineSet(e,{prepopulateTimeline:t=!0,useSyncEvents:n=!0,pendingEvents:r=!0}={}){if(this.filteredTimelineSets[e.filterId])return this.filteredTimelineSets[e.filterId];const i=Object.assign({filter:e,pendingEvents:r},this.opts),a=new s.EventTimelineSet(this,i);this.reEmitter.reEmit(a,[A.Timeline,A.TimelineReset]),n&&(this.filteredTimelineSets[e.filterId]=a,this.timelineSets.push(a));const c=this.getLiveTimeline();if(t){c.getEvents().forEach((function(e){a.addLiveEvent(e)}));let e=c;for(;e.getNeighbouringTimeline(o.EventTimeline.BACKWARDS);)e=e.getNeighbouringTimeline(o.EventTimeline.BACKWARDS);a.getLiveTimeline().setPaginationToken(e.getPaginationToken(o.EventTimeline.BACKWARDS),o.EventTimeline.BACKWARDS)}else if(n){const e=c.getPaginationToken(o.Direction.Forward);a.getLiveTimeline().setPaginationToken(e,o.Direction.Backward)}return a}async getThreadListFilter(e=_.ThreadFilterType.All){const t=this.client.getUserId(),n=new y.Filter(t),r={room:{timeline:{[_.FILTER_RELATED_BY_REL_TYPES.name]:[_.THREAD_RELATION_TYPE.name]}}};e===_.ThreadFilterType.My&&(r.room.timeline[_.FILTER_RELATED_BY_SENDERS.name]=[t]),n.setDefinition(r);const i=await this.client.getOrCreateFilter(`THREAD_PANEL_${this.roomId}_${e}`,n);return n.filterId=i,n}async createThreadTimelineSet(e){let t;if(_.Thread.hasServerSideSupport){const n=await this.getThreadListFilter(e);t=this.getOrCreateFilteredTimelineSet(n,{prepopulateTimeline:!1,useSyncEvents:!1,pendingEvents:!1})}else t=new s.EventTimelineSet(this,{pendingEvents:!1}),Array.from(this.threads).forEach((([,n])=>{if(0===n.length)return;const r=n.events.some((e=>e.getSender()===this.client.getUserId()));(e!==_.ThreadFilterType.My||r)&&t.getLiveTimeline().addEvent(n.rootEvent,{toStartOfTimeline:!1})}));return t}async fetchRoomThreads(){if(this.threadsReady||!this.client.supportsExperimentalThreads())return;const e=await this.getThreadListFilter(),{chunk:t}=await this.client.createMessagesRequest(this.roomId,"",Number.MAX_SAFE_INTEGER,o.Direction.Backward,e);if(!t.length)return;const n=t.map(this.client.getEventMapper()).sort(((e,t)=>{const n=e.getServerAggregatedRelation(p.RelationType.Thread),r=t.getServerAggregatedRelation(p.RelationType.Thread);return n.latest_event.origin_server_ts-r.latest_event.origin_server_ts}));let r;const i=this.getLiveTimeline().getState(o.EventTimeline.FORWARDS);for(const e of n)this.threadsTimelineSets[0].addLiveEvent(e,{duplicateStrategy:s.DuplicateStrategy.Ignore,fromCache:!1,roomState:i}),e.getServerAggregatedRelation(p.RelationType.Thread).current_user_participated&&(this.threadsTimelineSets[1].addLiveEvent(e,{duplicateStrategy:s.DuplicateStrategy.Ignore,fromCache:!1,roomState:i}),r=e),this.getThread(e.getId())||this.createThread(e.getId(),e,[],!0);this.client.decryptEventIfNeeded(n[n.length-1]),r&&this.client.decryptEventIfNeeded(r),this.threadsReady=!0,this.on(_.ThreadEvent.NewReply,this.onThreadNewReply)}onThreadNewReply(e){for(const t of this.threadsTimelineSets)t.removeEvent(e.id),t.addLiveEvent(e.rootEvent)}removeFilteredTimelineSet(e){const t=this.filteredTimelineSets[e.filterId];delete this.filteredTimelineSets[e.filterId];const n=this.timelineSets.indexOf(t);n>-1&&this.timelineSets.splice(n,1)}eventShouldLiveIn(e,t,n){var r;if(!this.client.supportsExperimentalThreads())return{shouldLiveInRoom:!0,shouldLiveInThread:!1};if(e.isThreadRoot||null!=n&&n.has(e.getId()))return{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.getId()};if(e.isRelation(_.THREAD_RELATION_TYPE.name))return{shouldLiveInRoom:!1,shouldLiveInThread:!0,threadId:e.threadRootId};const i=e.getAssociatedId(),s=null!==(r=this.findEventById(i))&&void 0!==r?r:null==t?void 0:t.find((e=>e.getId()===i));return s&&(e.isRelation()||e.isRedaction())?this.eventShouldLiveIn(s,t,n):null!=n&&n.has(e.relationEventId)?{shouldLiveInRoom:!0,shouldLiveInThread:!0,threadId:e.relationEventId}:{shouldLiveInRoom:!0,shouldLiveInThread:!1}}findThreadForEvent(e){if(!e)return null;const{threadId:t}=this.eventShouldLiveIn(e);return t?this.getThread(t):null}addThreadedEvents(e,t,n=!1){let r=this.getThread(e);if(r)r.addEvents(t,n);else{var i;const s=null!==(i=this.findEventById(e))&&void 0!==i?i:t.find((t=>t.getId()===e));r=this.createThread(e,s,t,n),this.emit(_.ThreadEvent.Update,r)}}processThreadedEvents(e,t){e.forEach(this.applyRedaction);const n={};for(const t of e){var r;const{threadId:e,shouldLiveInThread:i}=this.eventShouldLiveIn(t);i&&!n[e]&&(n[e]=[]),null===(r=n[e])||void 0===r||r.push(t)}Object.entries(n).map((([e,n])=>this.addThreadedEvents(e,n,t)))}createThread(e,t,n=[],r){var i;if(t){const e=this.relations.getAllChildEventsForEvent(t.getId());null!=e&&e.length&&(n=n.concat(e.filter((e=>!e.isRelation(p.RelationType.Replace)))))}const s=new _.Thread(e,t,{initialEvents:n,room:this,client:this.client});return this.threads.set(s.id,s),this.reEmitter.reEmit(s,[_.ThreadEvent.Update,_.ThreadEvent.NewReply,A.Timeline,A.TimelineReset]),(!this.lastThread||(null===(i=this.lastThread.rootEvent)||void 0===i?void 0:i.localTimestamp)<(null==t?void 0:t.localTimestamp))&&(this.lastThread=s),this.emit(_.ThreadEvent.New,s,r),this.threadsReady&&this.threadsTimelineSets.forEach((e=>{s.rootEvent&&(_.Thread.hasServerSideSupport?e.addLiveEvent(s.rootEvent):e.addEventToTimeline(s.rootEvent,e.getLiveTimeline(),r))})),s}processLiveEvent(e){if(this.applyRedaction(e),e.isVisibilityEvent()&&this.applyNewVisibilityEvent(e),this.applyPendingVisibilityEvents(e),!e.getUnsigned().transaction_id&&e.getSender()===this.myUserId)for(const t in this.txnToEvent)if(this.txnToEvent[t].getId()===e.getId()){f.logger.debug("processLiveEvent: found sent event without txn ID: ",t,e.getId());const n=e.getUnsigned();n.transaction_id=t,e.setUnsigned(n);break}if(e.getUnsigned().transaction_id){const t=this.txnToEvent[e.getUnsigned().transaction_id];t&&this.handleRemoteEcho(e,t)}}addLiveEvent(e,t){const{duplicateStrategy:n,timelineWasEmpty:r,fromCache:i}=t;for(let t=0;t<this.timelineSets.length;t++)this.timelineSets[t].addLiveEvent(e,{duplicateStrategy:n,fromCache:i,timelineWasEmpty:r});e.sender&&e.getType()!==p.EventType.RoomRedaction&&this.addReceipt(k(e.sender.userId,e,w.ReceiptType.Read),!0)}addPendingEvent(e,t){if(e.status!==d.EventStatus.SENDING&&e.status!==d.EventStatus.NOT_SENT)throw new Error("addPendingEvent called on an event with status "+e.status);if(this.txnToEvent[t])throw new Error("addPendingEvent called on an event with known txnId "+t);if(o.EventTimeline.setEventMetadata(e,this.getLiveTimeline().getState(o.EventTimeline.FORWARDS),!1),this.txnToEvent[t]=e,this.opts.pendingEventOrdering===m.PendingEventOrdering.Detached){if(this.pendingEventList.some((e=>e.status===d.EventStatus.NOT_SENT))&&(f.logger.warn("Setting event as NOT_SENT due to messages in the same state"),e.setStatus(d.EventStatus.NOT_SENT)),this.pendingEventList.push(e),this.savePendingEvents(),e.isRelation()&&this.aggregateNonLiveRelation(e),e.isRedaction()){var n;const t=e.event.redacts;let r=null===(n=this.pendingEventList)||void 0===n?void 0:n.find((e=>e.getId()===t));r||(r=this.findEventById(t)),r&&(r.markLocallyRedacted(e),this.emit(A.Redaction,e,this))}}else for(let t=0;t<this.timelineSets.length;t++){const n=this.timelineSets[t];n.getFilter()?n.getFilter().filterRoomTimeline([e]).length&&n.addEventToTimeline(e,n.getLiveTimeline(),{toStartOfTimeline:!1}):n.addEventToTimeline(e,n.getLiveTimeline(),{toStartOfTimeline:!1})}this.emit(A.LocalEchoUpdated,e,this,null,null)}savePendingEvents(){if(this.pendingEventList){const e=this.pendingEventList.map((e=>R(R({},e.event),{},{txn_id:e.getTxnId()}))).filter((e=>{const t=e.type===p.EventType.RoomMessageEncrypted,n=this.client.isRoomEncrypted(this.roomId);return t||!n}));this.client.store.setPendingEvents(this.roomId,e)}}aggregateNonLiveRelation(e){this.relations.aggregateChildEvent(e)}getEventForTxnId(e){return this.txnToEvent[e]}handleRemoteEcho(e,t){const n=t.getId(),r=e.getId(),i=t.status;f.logger.debug(`Got remote echo for event ${n} -> ${r} old status ${i}`),delete this.txnToEvent[e.getUnsigned().transaction_id],this.pendingEventList&&this.removePendingEvent(n),t.handleRemoteEcho(e.event);const{shouldLiveInRoom:s,threadId:o}=this.eventShouldLiveIn(e),a=this.getThread(o);if(null==a||a.timelineSet.handleRemoteEcho(t,n,r),s)for(let e=0;e<this.timelineSets.length;e++)this.timelineSets[e].handleRemoteEcho(t,n,r);this.emit(A.LocalEchoUpdated,t,this,n,i)}updatePendingEvent(e,t,n){if(f.logger.log(`setting pendingEvent status to ${t} in ${e.getRoomId()} event ID ${e.getId()} -> ${n}`),t==d.EventStatus.SENT&&!n)throw new Error("updatePendingEvent called with status=SENT, but no new event id");if(t==d.EventStatus.SENT&&this.getTimelineForEvent(n)){const t=this.findEventById(n);if(!t.getUnsigned().transaction_id){const n=t.getUnsigned();n.transaction_id=e.getTxnId(),t.setUnsigned(n),this.removeEvent(t.getId()),this.handleRemoteEcho(t,e)}return}const r=e.status,i=e.getId();if(!r)throw new Error("updatePendingEventStatus called on an event which is not a local echo.");const s=M[r];if(!s||s.indexOf(t)<0)throw new Error("Invalid EventStatus transition "+r+"->"+t);if(e.setStatus(t),t==d.EventStatus.SENT){e.replaceLocalEventId(n);const{shouldLiveInRoom:t,threadId:r}=this.eventShouldLiveIn(e),s=this.getThread(r);if(null==s||s.timelineSet.replaceEventId(i,n),t)for(let e=0;e<this.timelineSets.length;e++)this.timelineSets[e].replaceEventId(i,n)}else if(t==d.EventStatus.CANCELLED){if(this.pendingEventList){const e=this.getPendingEvent(i);this.removePendingEvent(i),e.isRedaction()&&this.revertRedactionLocalEcho(e)}this.removeEvent(i)}this.savePendingEvents(),this.emit(A.LocalEchoUpdated,e,this,i,r)}revertRedactionLocalEcho(e){const t=e.event.redacts;if(!t)return;const n=this.getUnfilteredTimelineSet().findEventById(t);n&&(n.unmarkLocallyRedacted(),this.emit(A.RedactionCancelled,e,this),n.isRelation()&&this.aggregateNonLiveRelation(n))}addLiveEvents(e,t,n=!1){let r,i=t;if("object"==typeof t?({duplicateStrategy:i,fromCache:n=!1,timelineWasEmpty:r}=t):void 0!==t&&f.logger.warn("Overload deprecated: `Room.addLiveEvents(events, duplicateStrategy?, fromCache?)` is deprecated in favor of the overload with `Room.addLiveEvents(events, IAddLiveEventOptions)`"),i&&-1===["replace","ignore"].indexOf(i))throw new Error("duplicateStrategy MUST be either 'replace' or 'ignore'");for(let e=0;e<this.timelineSets.length;e++){const t=this.timelineSets[e].getLiveTimeline();if(t.getPaginationToken(o.EventTimeline.FORWARDS))throw new Error("live timeline "+e+" is no longer live - it has a pagination token ("+t.getPaginationToken(o.EventTimeline.FORWARDS)+")");if(t.getNeighbouringTimeline(o.EventTimeline.FORWARDS))throw new Error(`live timeline ${e} is no longer live - it has a neighbouring timeline`)}const s=this.findThreadRoots(e),a={};for(const t of e){var c;this.processLiveEvent(t);const{shouldLiveInRoom:o,shouldLiveInThread:l,threadId:d}=this.eventShouldLiveIn(t,e,s);l&&!a[d]&&(a[d]=[]),null===(c=a[d])||void 0===c||c.push(t),o&&this.addLiveEvent(t,{duplicateStrategy:i,fromCache:n,timelineWasEmpty:r})}Object.entries(a).forEach((([e,t])=>{this.addThreadedEvents(e,t,!1)}))}partitionThreadedEvents(e){if(this.client.supportsExperimentalThreads()){const t=this.findThreadRoots(e);return e.reduce(((n,r)=>{const{shouldLiveInRoom:i,shouldLiveInThread:s,threadId:o}=this.eventShouldLiveIn(r,e,t);return i&&n[0].push(r),s&&(r.setThreadId(o),n[1].push(r)),n}),[[],[]])}return[e,[]]}findThreadRoots(e){const t=new Set;for(const n of e)n.isRelation(_.THREAD_RELATION_TYPE.name)&&t.add(n.relationEventId);return t}addEphemeralEvents(e){for(const t of e)t.getType()===p.EventType.Typing?this.currentState.setTypingEvent(t):t.getType()===p.EventType.Receipt&&this.addReceipt(t)}removeEvents(e){for(let t=0;t<e.length;++t)this.removeEvent(e[t])}removeEvent(e){let t=!1;for(let n=0;n<this.timelineSets.length;n++){const r=this.timelineSets[n].removeEvent(e);r&&(r.isRedaction()&&this.revertRedactionLocalEcho(r),t=!0)}return t}recalculate(){const e=this.currentState.getStateEvents(p.EventType.RoomMember,this.myUserId);if(e){const t=e.getContent().membership;this.updateMyMembership(t),"invite"===t&&(e.getUnsigned().invite_room_state||[]).forEach((e=>{this.currentState.getStateEvents(e.type,e.state_key)||this.currentState.setStateEvents([new l.MatrixEvent({type:e.type,state_key:e.state_key,content:e.content,event_id:"$fake"+Date.now(),room_id:this.roomId,user_id:this.myUserId})])}))}const t=this.name;this.name=this.calculateRoomName(this.myUserId),this.normalizedName=(0,c.normalize)(this.name),this.summary=new h.RoomSummary(this.roomId,{title:this.name}),t!==this.name&&this.emit(A.Name,this)}getUsersReadUpTo(e){return this.getReceiptsForEvent(e).filter((function(e){return c.isSupportedReceiptType(e.type)})).map((function(e){return e.userId}))}getReadReceiptForUserId(e,t=!1,n=w.ReceiptType.Read){var r,i;const[s,o]=null!==(r=null===(i=this.receipts[n])||void 0===i?void 0:i[e])&&void 0!==r?r:[];return t?s:null!=o?o:s}getEventReadUpTo(e,t=!1){var n,r,i,s,o;const a=this.getUnfilteredTimelineSet(),c=this.getReadReceiptForUserId(e,t,w.ReceiptType.Read),l=this.getReadReceiptForUserId(e,t,w.ReceiptType.ReadPrivate),d=this.getReadReceiptForUserId(e,t,w.ReceiptType.UnstableReadPrivate);if(null!=c&&c.eventId&&null!=l&&l.eventId&&null!=d&&d.eventId){const e=a.compareEventOrdering(c.eventId,l.eventId),t=a.compareEventOrdering(c.eventId,d.eventId),n=a.compareEventOrdering(l.eventId,d.eventId);if(e&&t&&n)return e>0?t>0?c.eventId:d.eventId:n>0?l.eventId:d.eventId}let u=l;return[d,c].forEach((e=>{var t,n,r;((null==e||null===(t=e.data)||void 0===t?void 0:t.ts)>(null===(n=u)||void 0===n||null===(r=n.data)||void 0===r?void 0:r.ts)||!u)&&(u=e)})),null!==(n=u)&&void 0!==n&&n.eventId?null===(r=u)||void 0===r?void 0:r.eventId:null!==(i=null!==(s=null!==(o=null==l?void 0:l.eventId)&&void 0!==o?o:null==d?void 0:d.eventId)&&void 0!==s?s:null==c?void 0:c.eventId)&&void 0!==i?i:null}hasUserReadEvent(e,t){const n=this.getEventReadUpTo(e,!1);if(n===t)return!0;if(this.timeline.length&&this.timeline[this.timeline.length-1].getSender()&&this.timeline[this.timeline.length-1].getSender()===e)return!0;for(let e=this.timeline.length-1;e>=0;--e){const r=this.timeline[e];if(r.getId()===t)return!1;if(r.getId()===n)return!0}return!1}getReceiptsForEvent(e){return this.receiptCacheByEventId[e.getId()]||[]}addReceipt(e,t=!1){this.addReceiptsToStructure(e,t),this.emit(A.Receipt,e,this)}addReceiptsToStructure(e,t){const n=e.getContent();Object.keys(n).forEach((e=>{Object.keys(n[e]).forEach((r=>{Object.keys(n[e][r]).forEach((i=>{var s,o;const a=n[e][r][i];this.receipts[r]||(this.receipts[r]={}),this.receipts[r][i]||(this.receipts[r][i]=[null,null]);const c=this.receipts[r][i];let l=c[0];var d;if(t&&(l=null!==(d=c[1])&&void 0!==d?d:c[0]),l){const t=this.getUnfilteredTimelineSet().compareEventOrdering(l.eventId,e);if(null!==t&&t>=0)return}const u={eventId:e,data:a},h=t?c[0]:u,f=t?u:c[1];let g=null;h&&f&&(g=this.getUnfilteredTimelineSet().compareEventOrdering(h.eventId,f.eventId));const p=null===g||g<0,m=null!==(s=c[1])&&void 0!==s?s:c[0];if(t&&p?c[1]=u:t||(c[0]=u,p||(c[1]=null)),m!==(null!==(o=c[1])&&void 0!==o?o:c[0])){if(m&&this.receiptCacheByEventId[m.eventId]){const e=m.eventId;this.receiptCacheByEventId[e]=this.receiptCacheByEventId[e].filter((e=>e.type!==r||e.userId!==i)),this.receiptCacheByEventId[e].length<1&&delete this.receiptCacheByEventId[e]}this.receiptCacheByEventId[e]||(this.receiptCacheByEventId[e]=[]),this.receiptCacheByEventId[e].push({userId:i,type:r,data:a})}}))}))}))}addLocalEchoReceipt(e,t,n){this.addReceipt(k(e,t,n),!0)}addTags(e){this.tags=e.getContent().tags||{},this.emit(A.Tags,e,this)}addAccountData(e){for(let t=0;t<e.length;t++){const n=e[t];"m.tag"===n.getType()&&this.addTags(n);const r=this.accountData[n.getType()];this.accountData[n.getType()]=n,this.emit(A.AccountData,n,this,r)}}getAccountData(e){return this.accountData[e]}maySendMessage(){return"join"===this.getMyMembership()&&(this.client.isRoomEncrypted(this.roomId)?this.currentState.maySendEvent(p.EventType.RoomMessageEncrypted,this.myUserId):this.currentState.maySendEvent(p.EventType.RoomMessage,this.myUserId))}canInvite(e){let t="join"===this.getMyMembership();const n=this.currentState.getStateEvents(p.EventType.RoomPowerLevels,""),r=n&&n.getContent(),i=this.getMember(e);return r&&i&&r.invite>i.powerLevel&&(t=!1),t}getJoinRule(){return this.currentState.getJoinRule()}getHistoryVisibility(){return this.currentState.getHistoryVisibility()}getGuestAccess(){return this.currentState.getGuestAccess()}getType(){const e=this.currentState.getStateEvents(p.EventType.RoomCreate,"");if(e)return e.getContent()[p.RoomCreateTypeField];this.getTypeWarning||(f.logger.warn("[getType] Room "+this.roomId+" does not have an m.room.create event"),this.getTypeWarning=!0)}isSpaceRoom(){return this.getType()===p.RoomType.Space}isCallRoom(){return this.getType()===p.RoomType.UnstableCall}isElementVideoRoom(){return this.getType()===p.RoomType.ElementVideo}roomNameGenerator(e){if(this.client.roomNameGenerator){const t=this.client.roomNameGenerator(this.roomId,e);if(null!==t)return t}switch(e.type){case P.Actual:return e.name;case P.Generated:return"Inviting"===e.subtype?`Inviting ${U(e.names,e.count)}`:U(e.names,e.count);case P.EmptyRoom:return e.oldName?`Empty room (was ${e.oldName})`:"Empty room"}}calculateRoomName(e,t=!1){if(!t){const e=this.currentState.getStateEvents(p.EventType.RoomName,"");if(null!=e&&e.getContent().name)return this.roomNameGenerator({type:P.Actual,name:e.getContent().name})}const n=this.getCanonicalAlias();if(n)return this.roomNameGenerator({type:P.Actual,name:n});let r=this.currentState.getJoinedMemberCount()+this.currentState.getInvitedMemberCount()-1,i=[];const s=this.currentState.getStateEvents(p.UNSTABLE_ELEMENT_FUNCTIONAL_USERS.name,"");Array.isArray(null==s?void 0:s.getContent().service_members)&&(i=s.getContent().service_members);let o=null;if(this.summaryHeroes)o=[],this.summaryHeroes.forEach((e=>{if(i.includes(e))return void r--;const t=this.getMember(e);o.push(t?t.name:e)}));else{let t=this.currentState.getMembers().filter((t=>t.userId!==e&&("invite"===t.membership||"join"===t.membership)));t=t.filter((({userId:e})=>!i.includes(e)||(r--,!1))),t.sort(((e,t)=>c.compare(e.userId,t.userId))),t=t.slice(0,5),o=t.map((e=>e.name))}if(r)return this.roomNameGenerator({type:P.Generated,names:o,count:r});if("join"==this.getMyMembership()){const e=this.currentState.getStateEvents(p.EventType.RoomThirdPartyInvite);if(null!=e&&e.length){const t=e.map((e=>e.getContent().display_name));return this.roomNameGenerator({type:P.Generated,subtype:"Inviting",names:t,count:t.length+1})}}let a,l=o;return l.length||(l=this.currentState.getMembers().filter((t=>t.userId!==e&&"invite"!==t.membership&&"join"!==t.membership)).map((e=>e.name))),l.length&&(a=this.roomNameGenerator({type:P.Generated,names:l,count:l.length+1})),this.roomNameGenerator({type:P.EmptyRoom,oldName:a})}applyNewVisibilityEvent(e){const t=e.asVisibilityChange();if(!t)return;const n=e.getSender();if(!n)return;if(!(p.EVENT_VISIBILITY_CHANGE_TYPE.name&&this.currentState.maySendStateEvent(p.EVENT_VISIBILITY_CHANGE_TYPE.name,n)||p.EVENT_VISIBILITY_CHANGE_TYPE.altName&&this.currentState.maySendStateEvent(p.EVENT_VISIBILITY_CHANGE_TYPE.altName,n)))return;const r=this.visibilityEvents.get(t.eventId);if(r){let t=r.length-1;const n=Math.max(0,r.length-30);for(;t>=n&&!(r[t].getTs()<e.getTs());--t);-1===t?r.unshift(e):r.splice(t+1,0,e)}else this.visibilityEvents.set(t.eventId,[e]);const i=this.findEventById(t.eventId);i&&i.applyVisibilityEvent(t)}redactVisibilityChangeEvent(e){if(!e.isVisibilityEvent)throw new Error("expected a visibility change event");const t=e.getRelation().event_id,n=this.visibilityEvents.get(t);if(!n)return;const r=n.findIndex((t=>t.getId()===e.getId()));if(-1!==r&&(n.splice(r,1),r===n.length)){const e=this.findEventById(t);if(!e)return;if(0===r)this.visibilityEvents.delete(t),e.applyVisibilityEvent();else{const t=n[n.length-1].asVisibilityChange();if(!t)throw new Error("at this stage, visibility changes should be well-formed");e.applyVisibilityEvent(t)}}}applyPendingVisibilityEvents(e){const t=this.visibilityEvents.get(e.getId());if(!t||0==t.length)return;const n=t[t.length-1],r=n.asVisibilityChange();r&&(r.visible,n.getTs()<e.getTs()||e.applyVisibilityEvent(r))}}t.Room=D;const M={[d.EventStatus.ENCRYPTING]:[d.EventStatus.SENDING,d.EventStatus.NOT_SENT,d.EventStatus.CANCELLED],[d.EventStatus.SENDING]:[d.EventStatus.ENCRYPTING,d.EventStatus.QUEUED,d.EventStatus.NOT_SENT,d.EventStatus.SENT],[d.EventStatus.QUEUED]:[d.EventStatus.SENDING,d.EventStatus.CANCELLED],[d.EventStatus.SENT]:[],[d.EventStatus.NOT_SENT]:[d.EventStatus.SENDING,d.EventStatus.QUEUED,d.EventStatus.CANCELLED],[d.EventStatus.CANCELLED]:[]};let P;function U(e,t){const n=t-1;return e.length?1===e.length&&n<=1?e[0]:2===e.length&&n<=2?`${e[0]} and ${e[1]}`:n>1?`${e[0]} and ${n} others`:`${e[0]} and 1 other`:"Empty room"}t.RoomNameType=P,function(e){e[e.EmptyRoom=0]="EmptyRoom",e[e.Generated=1]="Generated",e[e.Actual=2]="Actual"}(P||(t.RoomNameType=P={}))},1398:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.SearchResult=void 0;var r=n(3558);class i{static fromJson(e,t){const n=e.context||{};let s=(n.events_before||[]).map(t),o=(n.events_after||[]).map(t);const a=new r.EventContext(t(e.result)),c=a.ourEvent.threadRootId;return s=s.filter((e=>e.threadRootId===c)),o=o.filter((e=>e.threadRootId===c)),a.setPaginateToken(n.start,!0),a.addEvents(s,!0),a.addEvents(o,!1),a.setPaginateToken(n.end,!1),new i(e.rank,a)}constructor(e,t){this.rank=e,this.context=t}}t.SearchResult=i},6969:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.ThreadFilterType=t.ThreadEvent=t.Thread=t.THREAD_RELATION_TYPE=t.FILTER_RELATED_BY_SENDERS=t.FILTER_RELATED_BY_REL_TYPES=void 0;var i=r(n(8416)),s=n(8070),o=n(771),a=n(4369),c=n(8910),l=n(3705),d=n(5861),u=n(7048),h=n(7434);function f(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}let g;t.ThreadEvent=g,function(e){e.New="Thread.new",e.Update="Thread.update",e.NewReply="Thread.newReply",e.ViewThread="Thread.viewThread"}(g||(t.ThreadEvent=g={}));class p extends d.TypedEventEmitter{constructor(e,t,n){var r;if(super(),this.id=e,this.rootEvent=t,(0,i.default)(this,"timelineSet",void 0),(0,i.default)(this,"_currentUserParticipated",!1),(0,i.default)(this,"reEmitter",void 0),(0,i.default)(this,"lastEvent",void 0),(0,i.default)(this,"replyCount",0),(0,i.default)(this,"room",void 0),(0,i.default)(this,"client",void 0),(0,i.default)(this,"initialEventsFetched",!p.hasServerSideSupport),(0,i.default)(this,"onBeforeRedaction",((e,t)=>{null!=e&&e.isRelation(v.name)&&this.room.eventShouldLiveIn(e).threadId===this.id&&e.getId()!==this.id&&!t.status&&(this.replyCount--,this.emit(g.Update,this))})),(0,i.default)(this,"onRedaction",(e=>{var t;if(e.threadRootId!==this.id)return;const n=[...this.timelineSet.getLiveTimeline().getEvents()].reverse();this.lastEvent=null!==(t=n.find((e=>!e.isRedacted()&&e.isRelation(v.name))))&&void 0!==t?t:this.rootEvent,this.emit(g.Update,this)})),(0,i.default)(this,"onEcho",(e=>{if(e.threadRootId!==this.id)return;if(this.lastEvent===e)return;if(!e.isRelation(v.name))return;const t=e.isRelation(v.name);(!this.lastEvent||this.lastEvent.isRedacted()||t&&e.getId()!==this.lastEvent.getId()&&e.localTimestamp>this.lastEvent.localTimestamp)&&(this.lastEvent=e,this.lastEvent.getId()!==this.id&&(p.hasServerSideSupport&&this.replyCount++,this.emit(g.NewReply,this,e))),this.emit(g.Update,this)})),null==n||!n.room)throw new Error("element-web#22141: A thread requires a room in order to function");this.room=n.room,this.client=n.client,this.timelineSet=new l.EventTimelineSet(this.room,{timelineSupport:!0,pendingEvents:!0},this.client,this),this.reEmitter=new o.TypedReEmitter(this),this.reEmitter.reEmit(this.timelineSet,[s.RoomEvent.Timeline,s.RoomEvent.TimelineReset]),this.room.on(s.MatrixEventEvent.BeforeRedaction,this.onBeforeRedaction),this.room.on(s.RoomEvent.Redaction,this.onRedaction),this.room.on(s.RoomEvent.LocalEchoUpdated,this.onEcho),this.timelineSet.on(s.RoomEvent.Timeline,this.onEcho),n.initialEvents&&this.addEvents(n.initialEvents,!1),this.initialiseThread(),null===(r=this.rootEvent)||void 0===r||r.setThread(this)}async fetchRootEvent(){var e;this.rootEvent=this.room.findEventById(this.id);try{const e=await this.client.fetchRoomEvent(this.roomId,this.id),t=this.client.getEventMapper();this.rootEvent=t(e)}catch(e){h.logger.error("Failed to fetch thread root to construct thread with",e)}null===(e=this.rootEvent)||void 0===e||e.setThread(this),this.emit(g.Update,this)}static setServerSideSupport(e,t){p.hasServerSideSupport=e,t||(m.setPreferUnstable(!0),y.setPreferUnstable(!0),v.setPreferUnstable(!0))}get roomState(){return this.room.getLiveTimeline().getState(c.EventTimeline.FORWARDS)}addEventToTimeline(e,t){this.findEventById(e.getId())||this.timelineSet.addEventToTimeline(e,this.liveTimeline,{toStartOfTimeline:t,fromCache:!1,roomState:this.roomState})}addEvents(e,t){e.forEach((e=>this.addEvent(e,t,!1))),this.emit(g.Update,this)}addEvent(e,t,n=!0){var r;if(e.setThread(this),this._currentUserParticipated||e.getSender()!==this.client.getUserId()||(this._currentUserParticipated=!0),p.hasServerSideSupport){if(!t&&this.initialEventsFetched&&e.localTimestamp>(null===(r=this.lastReply())||void 0===r?void 0:r.localTimestamp))this.fetchEditsWhereNeeded(e),this.addEventToTimeline(e,!1);else if(e.isRelation(s.RelationType.Annotation)||e.isRelation(s.RelationType.Replace))return this.timelineSet.relations.aggregateParentEvent(e),void this.timelineSet.relations.aggregateChildEvent(e,this.timelineSet)}else this.addEventToTimeline(e,t),this.client.decryptEventIfNeeded(e,{});p.hasServerSideSupport&&this.rootEvent||!e.isRelation(v.name)||this.replyCount++,n&&this.emit(g.Update,this)}getRootEventBundledRelationship(e=this.rootEvent){return null==e?void 0:e.getServerAggregatedRelation(v.name)}async initialiseThread(){let e=this.getRootEventBundledRelationship();if(p.hasServerSideSupport&&!e&&(await this.fetchRootEvent(),e=this.getRootEventBundledRelationship()),p.hasServerSideSupport&&e){this.replyCount=e.count,this._currentUserParticipated=e.current_user_participated;const t=new a.MatrixEvent(function(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?f(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):f(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}({room_id:this.rootEvent.getRoomId()},e.latest_event));this.setEventMetadata(t),t.setThread(this),this.lastEvent=t,this.fetchEditsWhereNeeded(t)}this.emit(g.Update,this)}async fetchEditsWhereNeeded(...e){return Promise.all(e.filter((e=>e.isEncrypted())).map((e=>{if(!e.isRelation())return this.client.relations(this.roomId,e.getId(),s.RelationType.Replace,e.getType(),{limit:1}).then((t=>{t.events.length&&e.makeReplaced(t.events[0])})).catch((e=>{h.logger.error("Failed to load edits for encrypted thread event",e)}))})))}async fetchInitialEvents(){this.initialEventsFetched||(await this.fetchEvents(),this.initialEventsFetched=!0)}setEventMetadata(e){c.EventTimeline.setEventMetadata(e,this.roomState,!1),e.setThread(this)}findEventById(e){var t;return(null===(t=this.lastEvent)||void 0===t?void 0:t.getId())===e?this.lastEvent:this.timelineSet.findEventById(e)}lastReply(e=(()=>!0)){for(let t=this.events.length-1;t>=0;t--){const n=this.events[t];if(e(n))return n}return null}get roomId(){return this.room.roomId}get length(){return this.replyCount}get replyToEvent(){var e;return null!==(e=this.lastEvent)&&void 0!==e?e:this.lastReply()}get events(){return this.liveTimeline.getEvents()}has(e){return this.timelineSet.findEventById(e)instanceof a.MatrixEvent}get hasCurrentUserParticipated(){return this._currentUserParticipated}get liveTimeline(){return this.timelineSet.getLiveTimeline()}async fetchEvents(e={limit:20,direction:c.Direction.Backward}){var t;let{originalEvent:n,events:r,prevBatch:i,nextBatch:s}=await this.client.relations(this.room.roomId,this.id,v.name,null,e);e.to||s||(r=[...r,n]),await this.fetchEditsWhereNeeded(...r),await Promise.all(r.map((e=>(this.setEventMetadata(e),this.client.decryptEventIfNeeded(e)))));const o=(null!==(t=e.direction)&&void 0!==t?t:c.Direction.Backward)===c.Direction.Backward;return this.timelineSet.addEventsToTimeline(r,o,this.liveTimeline,o?s:i),{originalEvent:n,events:r,prevBatch:i,nextBatch:s}}}t.Thread=p,(0,i.default)(p,"hasServerSideSupport",void 0);const m=new u.ServerControlledNamespacedValue("related_by_senders","io.element.relation_senders");t.FILTER_RELATED_BY_SENDERS=m;const y=new u.ServerControlledNamespacedValue("related_by_rel_types","io.element.relation_types");t.FILTER_RELATED_BY_REL_TYPES=y;const v=new u.ServerControlledNamespacedValue("m.thread","io.element.thread");let b;t.THREAD_RELATION_TYPE=v,t.ThreadFilterType=b,function(e){e[e.My=0]="My",e[e.All=1]="All"}(b||(t.ThreadFilterType=b={}))},5861:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.TypedEventEmitter=t.EventEmitterEvents=void 0;var r=n(7187);let i;t.EventEmitterEvents=i,function(e){e.NewListener="newListener",e.RemoveListener="removeListener",e.Error="error"}(i||(t.EventEmitterEvents=i={}));class s extends r.EventEmitter{addListener(e,t){return super.addListener(e,t)}emit(e,...t){return super.emit(e,...t)}eventNames(){return super.eventNames()}listenerCount(e){return super.listenerCount(e)}listeners(e){return super.listeners(e)}off(e,t){return super.off(e,t)}on(e,t){return super.on(e,t)}once(e,t){return super.once(e,t)}prependListener(e,t){return super.prependListener(e,t)}prependOnceListener(e,t){return super.prependOnceListener(e,t)}removeAllListeners(e){return super.removeAllListeners(e)}removeListener(e,t){return super.removeListener(e,t)}rawListeners(e){return super.rawListeners(e)}}t.TypedEventEmitter=s},3998:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.UserEvent=t.User=void 0;var i=r(n(8416)),s=n(5861);let o;t.UserEvent=o,function(e){e.DisplayName="User.displayName",e.AvatarUrl="User.avatarUrl",e.Presence="User.presence",e.CurrentlyActive="User.currentlyActive",e.LastPresenceTs="User.lastPresenceTs"}(o||(t.UserEvent=o={}));class a extends s.TypedEventEmitter{constructor(e){super(),this.userId=e,(0,i.default)(this,"modified",void 0),(0,i.default)(this,"displayName",void 0),(0,i.default)(this,"rawDisplayName",void 0),(0,i.default)(this,"avatarUrl",void 0),(0,i.default)(this,"presenceStatusMsg",null),(0,i.default)(this,"presence","offline"),(0,i.default)(this,"lastActiveAgo",0),(0,i.default)(this,"lastPresenceTs",0),(0,i.default)(this,"currentlyActive",!1),(0,i.default)(this,"events",{presence:null,profile:null}),this.displayName=e,this.rawDisplayName=e,this.avatarUrl=null,this.updateModifiedTime()}setPresenceEvent(e){if("m.presence"!==e.getType())return;const t=null===this.events.presence;this.events.presence=e;const n=[];(e.getContent().presence!==this.presence||t)&&n.push(o.Presence),e.getContent().avatar_url&&e.getContent().avatar_url!==this.avatarUrl&&n.push(o.AvatarUrl),e.getContent().displayname&&e.getContent().displayname!==this.displayName&&n.push(o.DisplayName),void 0!==e.getContent().currently_active&&e.getContent().currently_active!==this.currentlyActive&&n.push(o.CurrentlyActive),this.presence=e.getContent().presence,n.push(o.LastPresenceTs),e.getContent().status_msg&&(this.presenceStatusMsg=e.getContent().status_msg),e.getContent().displayname&&(this.displayName=e.getContent().displayname),e.getContent().avatar_url&&(this.avatarUrl=e.getContent().avatar_url),this.lastActiveAgo=e.getContent().last_active_ago,this.lastPresenceTs=Date.now(),this.currentlyActive=e.getContent().currently_active,this.updateModifiedTime();for(let t=0;t<n.length;t++)this.emit(n[t],e,this)}setDisplayName(e){const t=this.displayName;this.displayName="string"==typeof e?e:void 0,e!==t&&this.updateModifiedTime()}setRawDisplayName(e){this.rawDisplayName="string"==typeof e?e:void 0}setAvatarUrl(e){const t=this.avatarUrl;this.avatarUrl=e,e!==t&&this.updateModifiedTime()}updateModifiedTime(){this.modified=Date.now()}getLastModifiedTime(){return this.modified}getLastActiveTs(){return this.lastPresenceTs-this.lastActiveAgo}}t.User=a},1707:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.PushProcessor=void 0;var i=r(n(8416)),s=n(3102),o=n(7434),a=n(1470),c=n(2481);function l(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function d(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?l(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):l(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}const u=[a.PushRuleKind.Override,a.PushRuleKind.ContentSpecific,a.PushRuleKind.RoomSpecific,a.PushRuleKind.SenderSpecific,a.PushRuleKind.Underride],h=[{rule_id:".m.rule.reaction",default:!0,enabled:!0,conditions:[{kind:a.ConditionKind.EventMatch,key:"type",pattern:"m.reaction"}],actions:[a.PushRuleActionName.DontNotify]},{rule_id:".org.matrix.msc3786.rule.room.server_acl",default:!0,enabled:!0,conditions:[{kind:a.ConditionKind.EventMatch,key:"type",pattern:c.EventType.RoomServerAcl},{kind:a.ConditionKind.EventMatch,key:"state_key",pattern:""}],actions:[]}];class f{constructor(e){this.client=e}static actionListToActionsObject(e){const t={notify:!1,tweaks:{}};for(let n=0;n<e.length;++n){const r=e[n];r===a.PushRuleActionName.Notify?t.notify=!0:"object"==typeof r&&(void 0===r.value&&(r.value=!0),t.tweaks[r.set_tweak]=r.value)}return t}static rewriteDefaultRules(e){let t=JSON.parse(JSON.stringify(e));t||(t={}),t.global||(t.global={}),t.global.override||(t.global.override=[]);const n=t.global.override;for(const e of h){const t=n.find((t=>t.rule_id===e.rule_id));if(t)t.default=e.default,t.conditions=e.conditions,t.actions=e.actions;else{const t=e.rule_id;o.logger.warn(`Adding default global override for ${t}`),n.push(e)}}return t}matchingRuleFromKindSet(e,t){for(let n=0;n<u.length;++n){const r=u[n],i=t[r];if(i)for(let t=0;t<i.length;++t){const n=i[t];if(!n.enabled)continue;const s=this.templateRuleToRaw(r,n);if(s&&this.ruleMatchesEvent(s,e))return d(d({},n),{},{kind:r})}}return null}templateRuleToRaw(e,t){const n={rule_id:t.rule_id,actions:t.actions,conditions:[]};switch(e){case a.PushRuleKind.Underride:case a.PushRuleKind.Override:n.conditions=t.conditions;break;case a.PushRuleKind.RoomSpecific:if(!t.rule_id)return null;n.conditions.push({kind:a.ConditionKind.EventMatch,key:"room_id",value:t.rule_id});break;case a.PushRuleKind.SenderSpecific:if(!t.rule_id)return null;n.conditions.push({kind:a.ConditionKind.EventMatch,key:"user_id",value:t.rule_id});break;case a.PushRuleKind.ContentSpecific:if(!t.pattern)return null;n.conditions.push({kind:a.ConditionKind.EventMatch,key:"content.body",pattern:t.pattern})}return n}eventFulfillsCondition(e,t){switch(e.kind){case a.ConditionKind.EventMatch:return this.eventFulfillsEventMatchCondition(e,t);case a.ConditionKind.ContainsDisplayName:return this.eventFulfillsDisplayNameCondition(e,t);case a.ConditionKind.RoomMemberCount:return this.eventFulfillsRoomMemberCountCondition(e,t);case a.ConditionKind.SenderNotificationPermission:return this.eventFulfillsSenderNotifPermCondition(e,t)}return!1}eventFulfillsSenderNotifPermCondition(e,t){const n=e.key;if(!n)return!1;const r=this.client.getRoom(t.getRoomId());return!(null==r||!r.currentState)&&r.currentState.mayTriggerNotifOfType(n,t.getSender())}eventFulfillsRoomMemberCountCondition(e,t){if(!e.is)return!1;const n=this.client.getRoom(t.getRoomId());if(!n||!n.currentState||!n.currentState.members)return!1;const r=n.currentState.getJoinedMemberCount(),i=e.is.match(/^([=<>]*)(\d*)$/);if(!i)return!1;const s=i[1],o=parseInt(i[2]);if(isNaN(o))return!1;switch(s){case"":case"==":return r==o;case"<":return r<o;case">":return r>o;case"<=":return r<=o;case">=":return r>=o;default:return!1}}eventFulfillsDisplayNameCondition(e,t){let n=t.getContent();if(t.isEncrypted()&&t.getClearContent()&&(n=t.getClearContent()),!n||!n.body||"string"!=typeof n.body)return!1;const r=this.client.getRoom(t.getRoomId());if(!(r&&r.currentState&&r.currentState.members&&r.currentState.getMember(this.client.credentials.userId)))return!1;const i=r.currentState.getMember(this.client.credentials.userId).name,o=new RegExp("(^|\\W)"+(0,s.escapeRegExp)(i)+"(\\W|$)","i");return n.body.search(o)>-1}eventFulfillsEventMatchCondition(e,t){if(!e.key)return!1;const n=this.valueForDottedKey(e.key,t);if("string"!=typeof n)return!1;if(e.value)return e.value===n;if("string"!=typeof e.pattern)return!1;const r="content.body"===e.key?this.createCachedRegex("(^|\\W)",e.pattern,"(\\W|$)"):this.createCachedRegex("^",e.pattern,"$");return!!n.match(r)}createCachedRegex(e,t,n){return f.cachedGlobToRegex[t]||(f.cachedGlobToRegex[t]=new RegExp(e+(0,s.globToRegexp)(t)+n,"i")),f.cachedGlobToRegex[t]}valueForDottedKey(e,t){const n=e.split(".");let r;const i=n[0];for("content"===i?(r=t.getContent(),n.shift()):"type"===i?(r=t.getType(),n.shift()):r=t.event;n.length>0;){const e=n.shift();if((0,s.isNullOrUndefined)(r[e]))return null;r=r[e]}return r}matchingRuleForEventWithRulesets(e,t){return t?e.getSender()===this.client.credentials.userId?null:this.matchingRuleFromKindSet(e,t.global):null}pushActionsForEventAndRulesets(e,t){const n=this.matchingRuleForEventWithRulesets(e,t);if(!n)return{};const r=f.actionListToActionsObject(n.actions);return void 0===r.tweaks.highlight&&(r.tweaks.highlight=n.kind==a.PushRuleKind.ContentSpecific),r}ruleMatchesEvent(e,t){var n;if(null===(n=e.conditions)||void 0===n||!n.length)return!0;let r=!0;for(let n=0;n<e.conditions.length;++n){const i=e.conditions[n];r&=this.eventFulfillsCondition(i,t)}return r}actionsForEvent(e){return this.pushActionsForEventAndRulesets(e,this.client.pushRules)}getPushRuleById(e){for(const t of["global"])if(void 0!==this.client.pushRules[t])for(const n of u)if(void 0!==this.client.pushRules[t][n])for(const r of this.client.pushRules[t][n])if(r.rule_id===e)return r;return null}}t.PushProcessor=f,(0,i.default)(f,"cachedGlobToRegex",{})},8401:(e,t)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.randomLowercaseString=function(e){return s(e,n)},t.randomString=function(e){return s(e,r+n+i)},t.randomUppercaseString=function(e){return s(e,r)};const n="abcdefghijklmnopqrstuvwxyz",r="ABCDEFGHIJKLMNOPQRSTUVWXYZ",i="0123456789";function s(e,t){let n="";for(let r=0;r<e;++r)n+=t.charAt(Math.floor(Math.random()*t.length));return n}},2731:(e,t,n)=>{"use strict";Object.defineProperty(t,"__esModule",{value:!0}),t.clearTimeout=function(e){if(0===a.length)return;let t;for(t=0;t<a.length;t++)if(a[t].key==e){a.splice(t,1);break}0===t&&l()},t.setTimeout=function(e,t,...n){(t=t||0)<0&&(t=0);const r=Date.now()+t,i=o++;c("setTimeout: scheduling cb",i,"at",r,"(delay",t,")");const s={runAt:r,func:e,params:n,key:i},d=function(e,t){let n=0,i=e.length;for(;n<i;){const t=n+i>>1;e[t].runAt-r>0?i=t:n=t+1}return n}(a);return a.splice(d,0,s),l(),i};var r=n(7434);const i=1e3;let s,o=0;const a=[],c=function(...e){};function l(){s&&n.g.clearTimeout(s);const e=a[0];if(!e)return void c("scheduleRealCallback: no more callbacks, not rescheduling");const t=Date.now(),r=Math.min(e.runAt-t,i);c("scheduleRealCallback: now:",t,"delay:",r),s=n.g.setTimeout(d,r)}function d(){let e;const t=Date.now();c("runCallbacks: now:",t);const i=[];for(;;){const n=a[0];if(!n||n.runAt>t)break;e=a.shift(),c("runCallbacks: popping",e.key),i.push(e)}l();for(let t=0;t<i.length;t++){e=i[t];try{e.func.apply(n.g,e.params)}catch(e){r.logger.error("Uncaught exception in callback function",e.stack||e)}}}},9443:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.MatrixScheduler=void 0;var i=r(n(8416)),s=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=a(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),o=(n(7434),n(2481));function a(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(a=function(e){return e?n:t})(e)}class c{static RETRY_BACKOFF_RATELIMIT(e,t,n){if(400===n.httpStatus||403===n.httpStatus||401===n.httpStatus)return-1;if("rejected"===n.cors)return-1;if("M_TOO_LARGE"===n.name)return-1;if("M_LIMIT_EXCEEDED"===n.name){const e=n.data.retry_after_ms;if(e>0)return e}return t>4?-1:1e3*Math.pow(2,t)}static QUEUE_MESSAGES(e){return e.getType()===o.EventType.RoomMessage||e.hasAssocation()?"message":null}constructor(e=c.RETRY_BACKOFF_RATELIMIT,t=c.QUEUE_MESSAGES){this.retryAlgorithm=e,this.queueAlgorithm=t,(0,i.default)(this,"queues",{}),(0,i.default)(this,"activeQueues",[]),(0,i.default)(this,"procFn",null),(0,i.default)(this,"processQueue",(e=>{const t=this.peekNextEvent(e);if(!t){const t=this.activeQueues.indexOf(e);return t>=0&&this.activeQueues.splice(t,1),void l()}l(this.queues[e].length),Promise.resolve().then((()=>this.procFn(t.event))).then((n=>{this.removeNextEvent(e),l(t.event.getId()),t.defer.resolve(n),this.processQueue(e)}),(n=>{t.attempts+=1;const r=this.retryAlgorithm(t.event,t.attempts,n);l(t.attempts,t.event.getId()),-1===r?(l(t.event.getId()),this.removeNextEvent(e),t.defer.reject(n),this.processQueue(e)):setTimeout(this.processQueue,r,e)}))}))}getQueueForEvent(e){const t=this.queueAlgorithm(e);return t&&this.queues[t]?this.queues[t].map((function(e){return e.event})):null}removeEventFromQueue(e){const t=this.queueAlgorithm(e);if(!t||!this.queues[t])return!1;let n=!1;return s.removeElement(this.queues[t],(t=>{if(t.event.getId()===e.getId())return n=!0,!0})),n}setProcessFunction(e){this.procFn=e,this.startProcessingQueues()}queueEvent(e){const t=this.queueAlgorithm(e);if(!t)return null;this.queues[t]||(this.queues[t]=[]);const n=s.defer();return this.queues[t].push({event:e,defer:n,attempts:0}),l(e.getId()),this.startProcessingQueues(),n.promise}startProcessingQueues(){this.procFn&&Object.keys(this.queues).filter((e=>-1===this.activeQueues.indexOf(e)&&this.queues[e].length>0)).forEach((e=>{this.activeQueues.push(e),l(),this.processQueue(e)}))}peekNextEvent(e){const t=this.queues[e];return Array.isArray(t)?t[0]:null}removeNextEvent(e){const t=this.queues[e];return Array.isArray(t)?t.shift():null}}function l(...e){}t.MatrixScheduler=c},1415:(e,t)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),t.SERVICE_TYPES=void 0,t.SERVICE_TYPES=n,function(e){e.IS="SERVICE_TYPE_IS",e.IM="SERVICE_TYPE_IM"}(n||(t.SERVICE_TYPES=n={}))},11:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SlidingSyncSdk=void 0;var i=r(n(8416)),s=n(7366),o=n(7434),a=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=p(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),c=n(8910),l=n(2168),d=n(4551),u=n(7715),h=n(2443),f=n(8070),g=n(1707);function p(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(p=function(e){return e?n:t})(e)}class m{constructor(e){this.crypto=e}name(){return"e2ee"}when(){return h.ExtensionState.PreProcess}onRequest(e){if(e)return{enabled:!0}}async onResponse(e){if(e.device_lists&&await this.crypto.handleDeviceListChanges({oldSyncToken:"yep"},e.device_lists),e.device_one_time_keys_count){const t=e.device_one_time_keys_count.signed_curve25519||0;this.crypto.updateOneTimeKeyCount(t)}if(e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"]){const t=e.device_unused_fallback_key_types||e["org.matrix.msc2732.device_unused_fallback_key_types"];this.crypto.setNeedsNewFallback(t instanceof Array&&!t.includes("signed_curve25519"))}}}class y{constructor(e){this.client=e,(0,i.default)(this,"nextBatch",null)}name(){return"to_device"}when(){return h.ExtensionState.PreProcess}onRequest(e){const t={since:null!==this.nextBatch?this.nextBatch:void 0};return e&&(t.limit=100,t.enabled=!0),t}async onResponse(e){const t=[];e.events=e.events||[],e.events.map(this.client.getEventMapper()).map((e=>{if("m.key.verification.cancel"===e.getType()){const n=e.getContent().transaction_id;n&&t.push(n)}return e})).forEach((e=>{const n=e.getContent();if("m.room.message"!=e.getType()||"m.bad.encrypted"!=n.msgtype){if("m.key.verification.start"===e.getType()||"m.key.verification.request"===e.getType()){const r=n.transaction_id;t.includes(r)&&e.flagCancelled()}this.client.emit(l.ClientEvent.ToDeviceEvent,e)}else o.logger.log("Ignoring undecryptable to-device event from "+e.getSender())})),this.nextBatch=e.next_batch}}class v{constructor(e){this.client=e}name(){return"account_data"}when(){return h.ExtensionState.PostProcess}onRequest(e){if(e)return{enabled:!0}}onResponse(e){e.global&&e.global.length>0&&this.processGlobalAccountData(e.global);for(const t in e.rooms){const n=b(this.client,t,e.rooms[t]),r=this.client.getRoom(t);r?(r.addAccountData(n),n.forEach((e=>{this.client.emit(l.ClientEvent.Event,e)}))):o.logger.warn("got account data for room but room doesn't exist on client:",t)}}processGlobalAccountData(e){const t=b(this.client,void 0,e),n=t.reduce(((e,t)=>(e[t.getId()]=this.client.store.getAccountData(t.getType()),e)),{});this.client.store.storeAccountDataEvents(t),t.forEach((e=>{if(e.getType()===f.EventType.PushRules){const t=e.getContent();this.client.pushRules=g.PushProcessor.rewriteDefaultRules(t)}const t=n[e.getId()];return this.client.emit(l.ClientEvent.AccountData,e,t),e}))}}function b(e,t,n,r=!0){const i=e.getEventMapper({decrypt:r});return n.map((function(e){return e.room_id=t,i(e)}))}t.SlidingSyncSdk=class{constructor(e,t,n={}){var r;this.slidingSync=e,this.client=t,this.opts=n,(0,i.default)(this,"syncState",null),(0,i.default)(this,"syncStateData",void 0),(0,i.default)(this,"lastPos",null),(0,i.default)(this,"failCount",0),(0,i.default)(this,"notifEvents",[]),this.opts.initialSyncLimit=null!==(r=this.opts.initialSyncLimit)&&void 0!==r?r:8,this.opts.resolveInvitesToProfiles=this.opts.resolveInvitesToProfiles||!1,this.opts.pollTimeout=this.opts.pollTimeout||3e4,this.opts.pendingEventOrdering=this.opts.pendingEventOrdering||l.PendingEventOrdering.Chronological,this.opts.experimentalThreadSupport=!0===this.opts.experimentalThreadSupport,n.canResetEntireTimeline||(n.canResetEntireTimeline=e=>!1),t.getNotifTimelineSet()&&t.reEmitter.reEmit(t.getNotifTimelineSet(),[s.RoomEvent.Timeline,s.RoomEvent.TimelineReset]),this.slidingSync.on(h.SlidingSyncEvent.Lifecycle,this.onLifecycle.bind(this)),this.slidingSync.on(h.SlidingSyncEvent.RoomData,this.onRoomData.bind(this));const o=[new y(this.client),new v(this.client)];this.opts.crypto&&o.push(new m(this.opts.crypto)),o.forEach((e=>{this.slidingSync.registerExtension(e)}))}onRoomData(e,t){let n=this.client.store.getRoom(e);if(!n){if(!t.initial)return void o.logger.debug("initial flag not set but no stored room exists for room ",e,t);n=(0,d._createAndReEmitRoom)(this.client,e,this.opts)}this.processRoomData(this.client,n,t)}onLifecycle(e,t,n){switch(n&&o.logger.debug("onLifecycle",e,n),e){case h.SlidingSyncState.Complete:this.purgeNotifications(),this.lastPos||this.updateSyncState(d.SyncState.Prepared,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.updateSyncState(d.SyncState.Syncing,{oldSyncToken:this.lastPos,nextSyncToken:t.pos,catchingUp:!1,fromCache:!1}),this.lastPos=t.pos;break;case h.SlidingSyncState.RequestFinished:if(n){if(this.failCount+=1,this.updateSyncState(this.failCount>3?d.SyncState.Error:d.SyncState.Reconnecting,{error:new u.MatrixError(n)}),this.shouldAbortSync(new u.MatrixError(n)))return}else this.failCount=0}}async syncLeftRooms(){return[]}async peek(e){return null}stopPeeking(){}getSyncState(){return this.syncState}getSyncStateData(){return this.syncStateData}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(o.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(d.SyncState.Error,{error:e}),!0)}async processRoomData(e,t,n){n=function(e,t,n){if(!n.name)return n;for(const e of n.required_state)if(e.type===f.EventType.RoomName&&""===e.state_key)return e.content={name:n.name},n;return n.required_state.push({event_id:"$fake-sliding-sync-name-event-"+t,state_key:"",type:f.EventType.RoomName,content:{name:n.name},sender:e.getUserId(),origin_server_ts:(new Date).getTime()}),n}(e,t.roomId,n);const r=b(this.client,t.roomId,n.required_state);let i=b(this.client,t.roomId,n.timeline,!1);const o=[];if(n.initial){const e=new Set;t.getLiveTimeline().getEvents().forEach((t=>{e.add(t.getId())}));const r=[],s=[];let o=!1;for(let t=i.length-1;t>=0;t--){const n=i[t];e.has(n.getId())?o=!0:o?r.push(n):s.unshift(n)}i=s,r.length>0&&t.addEventsToTimeline(r,!0,t.getLiveTimeline(),n.prev_batch)}const d=this.client.isRoomEncrypted(t.roomId);if(null!=n.notification_count&&t.setUnreadNotificationCount(s.NotificationCountType.Total,n.notification_count),null!=n.highlight_count&&(!d||d&&t.getUnreadNotificationCount(s.NotificationCountType.Highlight)<=0)&&t.setUnreadNotificationCount(s.NotificationCountType.Highlight,n.highlight_count),n.invite_state){const e=b(this.client,t.roomId,n.invite_state);return this.processRoomEvents(t,e),n.initial&&(t.recalculate(),this.client.store.storeRoom(t),this.client.emit(l.ClientEvent.Room,t)),e.forEach((e=>{this.client.emit(l.ClientEvent.Event,e)})),void t.updateMyMembership("invite")}n.initial&&t.getLiveTimeline().setPaginationToken(n.prev_batch,c.EventTimeline.BACKWARDS),this.processRoomEvents(t,r,i,!1),t.addEphemeralEvents(o),t.recalculate(),n.initial&&(e.store.storeRoom(t),e.emit(l.ClientEvent.Room,t)),this.addNotifications(i);const u=async t=>{e.emit(l.ClientEvent.Event,t),t.isState()&&t.getType()==f.EventType.RoomEncryption&&this.opts.crypto&&await this.opts.crypto.onCryptoEvent(t)};await a.promiseMapSeries(r,u),await a.promiseMapSeries(i,u),o.forEach((function(t){e.emit(l.ClientEvent.Event,t)})),t.updateMyMembership("join"),t.decryptCriticalEvents()}processRoomEvents(e,t,n,r=!1){n=n||[],t=t||[];const i=e.getLiveTimeline(),s=0==i.getEvents().length;if(s){for(const e of t)this.client.getPushActionsForEvent(e);i.initialiseState(t)}s||(e.oldState.setStateEvents(t),e.currentState.setStateEvents(t)),e.addLiveEvents(n,{fromCache:r}),e.recalculate(),this.resolveInvites(e)}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(n){if(n._requestedProfileInfo)return;n._requestedProfileInfo=!0;const r=t.getUser(n.userId);let i;i=r?Promise.resolve({avatar_url:r.avatarUrl,displayname:r.displayName}):t.getProfileInfo(n.userId),i.then((function(t){const r=n.events.member;"invite"===r.getContent().membership&&(r.getContent().avatar_url=t.avatar_url,r.getContent().displayname=t.displayname,n.setMembershipEvent(r,e.currentState))}),(function(e){}))}))}retryImmediately(){return!0}async sync(){for(o.logger.debug("Sliding sync init loop");!this.client.isGuest();)try{o.logger.debug("Getting push rules...");const e=await this.client.getPushRules();o.logger.debug("Got push rules"),this.client.pushRules=e;break}catch(e){if(o.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return}await this.slidingSync.start()}stop(){o.logger.debug("SyncApi.stop"),this.slidingSync.stop()}updateSyncState(e,t){const n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(l.ClientEvent.Sync,this.syncState,n,t)}addNotifications(e){if(this.client.getNotifTimelineSet())for(const t of e){const e=this.client.getPushActionsForEvent(t);e&&e.notify&&e.tweaks&&e.tweaks.highlight&&this.notifEvents.push(t)}}purgeNotifications(){this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((e=>{this.client.getNotifTimelineSet().addLiveEvent(e)})),this.notifEvents=[]}}},2443:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SlidingSyncState=t.SlidingSyncEvent=t.SlidingSync=t.ExtensionState=void 0;var i=r(n(8416)),s=n(7434),o=n(5861),a=n(3102);function c(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function l(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?c(Object(n),!0).forEach((function(t){(0,i.default)(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):c(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}let d,u,h;t.SlidingSyncState=d,function(e){e.RequestFinished="FINISHED",e.Complete="COMPLETE"}(d||(t.SlidingSyncState=d={}));class f{constructor(e){(0,i.default)(this,"list",void 0),(0,i.default)(this,"isModified",void 0),(0,i.default)(this,"roomIndexToRoomId",void 0),(0,i.default)(this,"joinedCount",void 0),this.replaceList(e)}setModified(e){this.isModified=e}updateListRange(e){this.list.ranges=JSON.parse(JSON.stringify(e))}replaceList(e){e.filters=e.filters||{},e.ranges=e.ranges||[],this.list=JSON.parse(JSON.stringify(e)),this.isModified=!0,this.roomIndexToRoomId={},this.joinedCount=0}getList(e){let t={ranges:JSON.parse(JSON.stringify(this.list.ranges))};return(this.isModified||e)&&(t=JSON.parse(JSON.stringify(this.list))),t}isIndexInRange(e){for(const t of this.list.ranges)if(t[0]<=e&&e<=t[1])return!0;return!1}}t.ExtensionState=u,function(e){e.PreProcess="ExtState.PreProcess",e.PostProcess="ExtState.PostProcess"}(u||(t.ExtensionState=u={})),t.SlidingSyncEvent=h,function(e){e.RoomData="SlidingSync.RoomData",e.Lifecycle="SlidingSync.Lifecycle",e.List="SlidingSync.List"}(h||(t.SlidingSyncEvent=h={}));class g extends o.TypedEventEmitter{constructor(e,t,n,r,s){super(),this.proxyBaseUrl=e,this.roomSubscriptionInfo=n,this.client=r,this.timeoutMS=s,(0,i.default)(this,"lists",void 0),(0,i.default)(this,"listModifiedCount",0),(0,i.default)(this,"terminated",!1),(0,i.default)(this,"needsResend",!1),(0,i.default)(this,"txnId",null),(0,i.default)(this,"txnIdDefers",[]),(0,i.default)(this,"extensions",{}),(0,i.default)(this,"desiredRoomSubscriptions",new Set),(0,i.default)(this,"confirmedRoomSubscriptions",new Set),(0,i.default)(this,"pendingReq",void 0),this.lists=t.map((e=>new f(e)))}listLength(){return this.lists.length}getListData(e){return this.lists[e]?{joinedCount:this.lists[e].joinedCount,roomIndexToRoomId:Object.assign({},this.lists[e].roomIndexToRoomId)}:null}getList(e){return this.lists[e]?this.lists[e].getList(!0):null}setListRanges(e,t){return this.lists[e].updateListRange(t),this.resend()}setList(e,t){return this.lists[e]?this.lists[e].replaceList(t):this.lists[e]=new f(t),this.listModifiedCount+=1,this.resend()}getRoomSubscriptions(){return new Set(Array.from(this.desiredRoomSubscriptions))}modifyRoomSubscriptions(e){return this.desiredRoomSubscriptions=e,this.resend()}modifyRoomSubscriptionInfo(e){return this.roomSubscriptionInfo=e,this.confirmedRoomSubscriptions=new Set,this.resend()}registerExtension(e){if(this.extensions[e.name()])throw new Error(`registerExtension: ${e.name()} already exists as an extension`);this.extensions[e.name()]=e}getExtensionRequest(e){const t={};return Object.keys(this.extensions).forEach((n=>{t[n]=this.extensions[n].onRequest(e)})),t}onPreExtensionsResponse(e){Object.keys(e).forEach((t=>{this.extensions[t].when()==u.PreProcess&&this.extensions[t].onResponse(e[t])}))}onPostExtensionsResponse(e){Object.keys(e).forEach((t=>{this.extensions[t].when()==u.PostProcess&&this.extensions[t].onResponse(e[t])}))}invokeRoomDataListeners(e,t){t.required_state||(t.required_state=[]),t.timeline||(t.timeline=[]),this.emit(h.RoomData,e,t)}invokeLifecycleListeners(e,t,n){this.emit(h.Lifecycle,e,t,n)}shiftRight(e,t,n){for(let r=t;r>n;r--)this.lists[e].isIndexInRange(r)&&(this.lists[e].roomIndexToRoomId[r]=this.lists[e].roomIndexToRoomId[r-1])}shiftLeft(e,t,n){for(let r=n;r<t;r++)this.lists[e].isIndexInRange(r)&&(this.lists[e].roomIndexToRoomId[r]=this.lists[e].roomIndexToRoomId[r+1])}removeEntry(e,t){let n=-1;for(const t in this.lists[e].roomIndexToRoomId)Number(t)>n&&(n=Number(t));n<0||t>n||(this.shiftLeft(e,n,t),delete this.lists[e].roomIndexToRoomId[n])}addEntry(e,t){let n=-1;for(const t in this.lists[e].roomIndexToRoomId)Number(t)>n&&(n=Number(t));n<0||t>n||this.shiftRight(e,n+1,t)}processListOps(e,t){let n=-1;e.ops.forEach((e=>{switch(e.op){case"DELETE":s.logger.debug("DELETE",t,e.index,";"),delete this.lists[t].roomIndexToRoomId[e.index],-1!==n&&this.removeEntry(t,n),n=e.index;break;case"INSERT":s.logger.debug("INSERT",t,e.index,e.room_id,";"),this.lists[t].roomIndexToRoomId[e.index]&&(n<0?this.addEntry(t,e.index):n>e.index?this.shiftRight(t,n,e.index):n<e.index&&this.shiftLeft(t,e.index,n),n=-1),this.lists[t].roomIndexToRoomId[e.index]=e.room_id;break;case"INVALIDATE":for(let n=e.range[0];n<=e.range[1];n++)delete this.lists[t].roomIndexToRoomId[n];s.logger.debug("INVALIDATE",t,e.range[0],e.range[1],";");break;case"SYNC":{const n=e.range[0];for(let r=n;r<=e.range[1];r++){const i=e.room_ids[r-n];if(!i)break;this.lists[t].roomIndexToRoomId[r]=i}s.logger.debug("SYNC",t,e.range[0],e.range[1],(e.room_ids||[]).join(" "),";");break}}})),-1!==n&&this.removeEntry(t,n)}resend(){var e;if(this.needsResend&&this.txnIdDefers.length>0)return this.txnIdDefers[this.txnIdDefers.length-1].promise;this.needsResend=!0,this.txnId=this.client.makeTxnId();const t=(0,a.defer)();return this.txnIdDefers.push(l(l({},t),{},{txnId:this.txnId})),null===(e=this.pendingReq)||void 0===e||e.abort(),t.promise}resolveTransactionDefers(e){if(!e)return;let t=-1;for(let n=0;n<this.txnIdDefers.length;n++)if(this.txnIdDefers[n].txnId===e){t=n;break}if(-1!==t){for(let e=0;e<t;e++)this.txnIdDefers[e].reject(this.txnIdDefers[e].txnId);this.txnIdDefers[t].resolve(e),this.txnIdDefers=this.txnIdDefers.slice(t+1)}else s.logger.warn(`resolveTransactionDefers: seen ${e} but it isn't a pending txn, ignoring.`)}stop(){var e;this.terminated=!0,null===(e=this.pendingReq)||void 0===e||e.abort(),this.removeAllListeners(h.Lifecycle),this.removeAllListeners(h.List),this.removeAllListeners(h.RoomData)}async start(){let e;for(;!this.terminated;){this.needsResend=!1;let t,n=!1;try{const r=this.listModifiedCount,i={lists:this.lists.map((e=>e.getList(!1))),pos:e,timeout:this.timeoutMS,clientTimeout:this.timeoutMS+1e4,extensions:this.getExtensionRequest(void 0===e)},o=p(this.desiredRoomSubscriptions,this.confirmedRoomSubscriptions),a=p(this.confirmedRoomSubscriptions,this.desiredRoomSubscriptions);if(a.size>0&&(i.unsubscribe_rooms=Array.from(a)),o.size>0){i.room_subscriptions={};for(const e of o)i.room_subscriptions[e]=this.roomSubscriptionInfo}this.txnId&&(i.txn_id=this.txnId,this.txnId=null),this.pendingReq=this.client.slidingSync(i,this.proxyBaseUrl),t=await this.pendingReq,s.logger.debug(t),e=t.pos;for(const e of o)this.confirmedRoomSubscriptions.add(e);for(const e of a)this.confirmedRoomSubscriptions.delete(e);r!==this.listModifiedCount&&(s.logger.debug("list modified during await call, not updating list"),n=!0),this.lists.forEach((e=>{e.setModified(!1)})),t.lists=t.lists||[],t.rooms=t.rooms||{},t.extensions=t.extensions||{},t.lists.forEach(((e,t)=>{this.lists[t].joinedCount=e.count})),this.invokeLifecycleListeners(d.RequestFinished,t)}catch(e){if(e.httpStatus)this.invokeLifecycleListeners(d.RequestFinished,null,e),await(0,a.sleep)(3e3);else{if(this.needsResend||"aborted"===e)continue;s.logger.error(e),await(0,a.sleep)(3e3)}}if(!t)continue;this.onPreExtensionsResponse(t.extensions),Object.keys(t.rooms).forEach((e=>{this.invokeRoomDataListeners(e,t.rooms[e])}));const r=new Set;n||t.lists.forEach(((e,t)=>{e.ops=e.ops||[],e.ops.length>0&&r.add(t),this.processListOps(e,t)})),this.invokeLifecycleListeners(d.Complete,t),this.onPostExtensionsResponse(t.extensions),r.forEach((e=>{this.emit(h.List,e,this.lists[e].joinedCount,Object.assign({},this.lists[e].roomIndexToRoomId))})),this.resolveTransactionDefers(t.txn_id)}}}t.SlidingSync=g;const p=(e,t)=>{const n=new Set(e);for(const e of t)n.delete(e);return n}},3861:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.LocalIndexedDBStoreBackend=void 0;var i=r(n(8416)),s=n(2741),o=d(n(3102)),a=d(n(3415)),c=n(7434);function l(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(l=function(e){return e?n:t})(e)}function d(e,t){if(!t&&e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=l(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}function u(e,t,n){const r=e.openCursor(t);return new Promise(((e,t)=>{const i=[];r.onerror=()=>{t(new Error("Query failed: "+r.error))},r.onsuccess=()=>{const t=r.result;t?(i.push(n(t)),t.continue()):e(i)}}))}function h(e){return new Promise(((t,n)=>{e.oncomplete=function(e){t(e)},e.onerror=function(){n(e.error)}}))}function f(e){return new Promise(((t,n)=>{e.onsuccess=function(e){t(e)},e.onerror=function(){n(e.error)}}))}function g(e){return f(e).then((t=>e.result))}t.LocalIndexedDBStoreBackend=class{static exists(e,t){return t="matrix-js-sdk:"+(t||"default"),a.exists(e,t)}constructor(e,t){this.indexedDB=e,(0,i.default)(this,"dbName",void 0),(0,i.default)(this,"syncAccumulator",void 0),(0,i.default)(this,"db",null),(0,i.default)(this,"disconnected",!0),(0,i.default)(this,"_isNewlyCreated",!1),(0,i.default)(this,"isPersisting",!1),(0,i.default)(this,"pendingUserPresenceData",[]),this.dbName="matrix-js-sdk:"+(t||"default"),this.syncAccumulator=new s.SyncAccumulator}connect(){if(!this.disconnected)return c.logger.log("LocalIndexedDBStoreBackend.connect: already connected or connecting"),Promise.resolve();this.disconnected=!1,c.logger.log("LocalIndexedDBStoreBackend.connect: connecting...");const e=this.indexedDB.open(this.dbName,4);return e.onupgradeneeded=t=>{const n=e.result,r=t.oldVersion;c.logger.log(`LocalIndexedDBStoreBackend.connect: upgrading from ${r}`),r<1&&(this._isNewlyCreated=!0,function(e){e.createObjectStore("users",{keyPath:["userId"]}),e.createObjectStore("accountData",{keyPath:["type"]}),e.createObjectStore("sync",{keyPath:["clobber"]})}(n)),r<2&&function(e){e.createObjectStore("oob_membership_events",{keyPath:["room_id","state_key"]}).createIndex("room","room_id")}(n),r<3&&function(e){e.createObjectStore("client_options",{keyPath:["clobber"]})}(n),r<4&&function(e){e.createObjectStore("to_device_queue",{autoIncrement:!0})}(n)},e.onblocked=()=>{c.logger.log("can't yet open LocalIndexedDBStoreBackend because it is open elsewhere")},c.logger.log("LocalIndexedDBStoreBackend.connect: awaiting connection..."),f(e).then((()=>(c.logger.log("LocalIndexedDBStoreBackend.connect: connected"),this.db=e.result,this.db.onversionchange=()=>{this.db.close()},this.init())))}isNewlyCreated(){return Promise.resolve(this._isNewlyCreated)}init(){return Promise.all([this.loadAccountData(),this.loadSyncData()]).then((([e,t])=>{c.logger.log("LocalIndexedDBStoreBackend: loaded initial data"),this.syncAccumulator.accumulate({next_batch:t.nextBatch,rooms:t.roomsData,account_data:{events:e}},!0)}))}getOutOfBandMembers(e){return new Promise(((t,n)=>{const r=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),i=IDBKeyRange.only(e),s=r.openCursor(i),o=[];let a=!1;s.onsuccess=()=>{const e=s.result;if(!e)return o.length||a?t(o):t(null);const n=e.value;n.oob_written?a=!0:o.push(n),e.continue()},s.onerror=e=>{n(e)}})).then((t=>(c.logger.log(`LL: got ${null==t?void 0:t.length} membershipEvents from storage for room ${e} ...`),t)))}async setOutOfBandMembers(e,t){c.logger.log(`LL: backend about to store ${t.length} members for ${e}`);const n=this.db.transaction(["oob_membership_events"],"readwrite"),r=n.objectStore("oob_membership_events");t.forEach((e=>{r.put(e)}));const i={room_id:e,oob_written:!0,state_key:0};r.put(i),await h(n),c.logger.log(`LL: backend done storing for ${e}!`)}async clearOutOfBandMembers(e){const t=this.db.transaction(["oob_membership_events"],"readonly").objectStore("oob_membership_events").index("room"),n=IDBKeyRange.only(e),r=g(t.openKeyCursor(n,"next")).then((e=>e&&e.primaryKey[1])),i=g(t.openKeyCursor(n,"prev")).then((e=>e&&e.primaryKey[1])),[s,o]=await Promise.all([r,i]),a=this.db.transaction(["oob_membership_events"],"readwrite").objectStore("oob_membership_events"),l=IDBKeyRange.bound([e,s],[e,o]);var d;c.logger.log(`LL: Deleting all users + marker in storage for room ${e}, with key range:`,[e,s],[e,o]),await(d=a.delete(l),new Promise(((e,t)=>{d.onsuccess=()=>e(d),d.onerror=e=>t(e)})))}clearDatabase(){return new Promise((e=>{c.logger.log(`Removing indexeddb instance: ${this.dbName}`);const t=this.indexedDB.deleteDatabase(this.dbName);t.onblocked=()=>{c.logger.log(`can't yet delete indexeddb ${this.dbName} because it is open elsewhere`)},t.onerror=()=>{c.logger.warn(`unable to delete js-sdk store indexeddb: ${t.error}`),e()},t.onsuccess=()=>{c.logger.log(`Removed indexeddb instance: ${this.dbName}`),e()}}))}getSavedSync(e=!0){const t=this.syncAccumulator.getJSON();return t.nextBatch?e?Promise.resolve(o.deepCopy(t)):Promise.resolve(t):Promise.resolve(null)}getNextBatchToken(){return Promise.resolve(this.syncAccumulator.getNextBatchToken())}setSyncData(e){return Promise.resolve().then((()=>{this.syncAccumulator.accumulate(e)}))}async syncToDatabase(e){if(this.isPersisting)return c.logger.warn("Skipping syncToDatabase() as persist already in flight"),void this.pendingUserPresenceData.push(...e);e.unshift(...this.pendingUserPresenceData),this.isPersisting=!0;try{const t=this.syncAccumulator.getJSON(!0);await Promise.all([this.persistUserPresenceEvents(e),this.persistAccountData(t.accountData),this.persistSyncData(t.nextBatch,t.roomsData)])}finally{this.isPersisting=!1}}persistSyncData(e,t){return c.logger.log("Persisting sync data up to",e),o.promiseTry((()=>{const n=this.db.transaction(["sync"],"readwrite");return n.objectStore("sync").put({clobber:"-",nextBatch:e,roomsData:t}),h(n).then((()=>{c.logger.log("Persisted sync data up to",e)}))}))}persistAccountData(e){return o.promiseTry((()=>{const t=this.db.transaction(["accountData"],"readwrite"),n=t.objectStore("accountData");for(let t=0;t<e.length;t++)n.put(e[t]);return h(t).then()}))}persistUserPresenceEvents(e){return o.promiseTry((()=>{const t=this.db.transaction(["users"],"readwrite"),n=t.objectStore("users");for(const t of e)n.put({userId:t[0],event:t[1]});return h(t).then()}))}getUserPresenceEvents(){return o.promiseTry((()=>u(this.db.transaction(["users"],"readonly").objectStore("users"),void 0,(e=>[e.value.userId,e.value.event]))))}loadAccountData(){return c.logger.log("LocalIndexedDBStoreBackend: loading account data..."),o.promiseTry((()=>u(this.db.transaction(["accountData"],"readonly").objectStore("accountData"),void 0,(e=>e.value)).then((e=>(c.logger.log("LocalIndexedDBStoreBackend: loaded account data"),e)))))}loadSyncData(){return c.logger.log("LocalIndexedDBStoreBackend: loading sync data..."),o.promiseTry((()=>u(this.db.transaction(["sync"],"readonly").objectStore("sync"),void 0,(e=>e.value)).then((e=>(c.logger.log("LocalIndexedDBStoreBackend: loaded sync data"),e.length>1&&c.logger.warn("loadSyncData: More than 1 sync row found."),e.length>0?e[0]:{})))))}getClientOptions(){return Promise.resolve().then((()=>u(this.db.transaction(["client_options"],"readonly").objectStore("client_options"),void 0,(e=>{var t;return null===(t=e.value)||void 0===t?void 0:t.options})).then((e=>e[0]))))}async storeClientOptions(e){const t=this.db.transaction(["client_options"],"readwrite");t.objectStore("client_options").put({clobber:"-",options:e}),await h(t)}async saveToDeviceBatches(e){const t=this.db.transaction(["to_device_queue"],"readwrite"),n=t.objectStore("to_device_queue");for(const t of e)n.add(t);await h(t)}async getOldestToDeviceBatch(){const e=this.db.transaction(["to_device_queue"],"readonly").objectStore("to_device_queue"),t=await g(e.openCursor());if(!t)return null;const n=t.value;return{id:t.key,txnId:n.txnId,eventType:n.eventType,batch:n.batch}}async removeToDeviceBatch(e){const t=this.db.transaction(["to_device_queue"],"readwrite");t.objectStore("to_device_queue").delete(e),await h(t)}}},4215:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteIndexedDBStoreBackend=void 0;var i=r(n(8416)),s=n(7434),o=n(3102);t.RemoteIndexedDBStoreBackend=class{constructor(e,t){this.workerFactory=e,this.dbName=t,(0,i.default)(this,"worker",void 0),(0,i.default)(this,"nextSeq",0),(0,i.default)(this,"inFlight",{}),(0,i.default)(this,"startPromise",null),(0,i.default)(this,"onWorkerMessage",(e=>{const t=e.data;if("cmd_success"==t.command||"cmd_fail"==t.command){if(void 0===t.seq)return void s.logger.error("Got reply from worker with no seq");const e=this.inFlight[t.seq];if(void 0===e)return void s.logger.error("Got reply for unknown seq "+t.seq);if(delete this.inFlight[t.seq],"cmd_success"==t.command)e.resolve(t.result);else{const n=new Error(t.error.message);n.name=t.error.name,e.reject(n)}}else s.logger.warn("Unrecognised message from worker: ",t)}))}connect(){return this.ensureStarted().then((()=>this.doCmd("connect")))}clearDatabase(){return this.ensureStarted().then((()=>this.doCmd("clearDatabase")))}isNewlyCreated(){return this.doCmd("isNewlyCreated")}getSavedSync(){return this.doCmd("getSavedSync")}getNextBatchToken(){return this.doCmd("getNextBatchToken")}setSyncData(e){return this.doCmd("setSyncData",[e])}syncToDatabase(e){return this.doCmd("syncToDatabase",[e])}getOutOfBandMembers(e){return this.doCmd("getOutOfBandMembers",[e])}setOutOfBandMembers(e,t){return this.doCmd("setOutOfBandMembers",[e,t])}clearOutOfBandMembers(e){return this.doCmd("clearOutOfBandMembers",[e])}getClientOptions(){return this.doCmd("getClientOptions")}storeClientOptions(e){return this.doCmd("storeClientOptions",[e])}getUserPresenceEvents(){return this.doCmd("getUserPresenceEvents")}async saveToDeviceBatches(e){return this.doCmd("saveToDeviceBatches",[e])}async getOldestToDeviceBatch(){return this.doCmd("getOldestToDeviceBatch")}async removeToDeviceBatch(e){return this.doCmd("removeToDeviceBatch",[e])}ensureStarted(){return null===this.startPromise&&(this.worker=this.workerFactory(),this.worker.onmessage=this.onWorkerMessage,this.startPromise=this.doCmd("_setupWorker",[this.dbName]).then((()=>{s.logger.log("IndexedDB worker is ready")}))),this.startPromise}doCmd(e,t){return Promise.resolve().then((()=>{const n=this.nextSeq++,r=(0,o.defer)();return this.inFlight[n]=r,this.worker.postMessage({command:e,seq:n,args:t}),r.promise}))}}},9789:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.IndexedDBStore=void 0;var i=r(n(8416)),s=n(1703),o=n(3861),a=n(4215),c=n(3998),l=n(4369),d=n(7434),u=n(5861);class h extends s.MemoryStore{static exists(e,t){return o.LocalIndexedDBStoreBackend.exists(e,t)}constructor(e){if(super(e),(0,i.default)(this,"backend",void 0),(0,i.default)(this,"startedUp",!1),(0,i.default)(this,"syncTs",0),(0,i.default)(this,"userModifiedMap",{}),(0,i.default)(this,"emitter",new u.TypedEventEmitter),(0,i.default)(this,"on",this.emitter.on.bind(this.emitter)),(0,i.default)(this,"getSavedSync",this.degradable((()=>this.backend.getSavedSync()),"getSavedSync")),(0,i.default)(this,"isNewlyCreated",this.degradable((()=>this.backend.isNewlyCreated()),"isNewlyCreated")),(0,i.default)(this,"getSavedSyncToken",this.degradable((()=>this.backend.getNextBatchToken()),"getSavedSyncToken")),(0,i.default)(this,"deleteAllData",this.degradable((()=>(super.deleteAllData(),this.backend.clearDatabase().then((()=>{d.logger.log("Deleted indexeddb data.")}),(e=>{throw d.logger.error(`Failed to delete indexeddb data: ${e}`),e})))))),(0,i.default)(this,"reallySave",this.degradable((()=>{this.syncTs=Date.now();const e=[];for(const t of this.getUsers())this.userModifiedMap[t.userId]!==t.getLastModifiedTime()&&t.events.presence&&(e.push([t.userId,t.events.presence.event]),this.userModifiedMap[t.userId]=t.getLastModifiedTime());return this.backend.syncToDatabase(e)}))),(0,i.default)(this,"setSyncData",this.degradable((e=>this.backend.setSyncData(e)),"setSyncData")),(0,i.default)(this,"getOutOfBandMembers",this.degradable((e=>this.backend.getOutOfBandMembers(e)),"getOutOfBandMembers")),(0,i.default)(this,"setOutOfBandMembers",this.degradable(((e,t)=>(super.setOutOfBandMembers(e,t),this.backend.setOutOfBandMembers(e,t))),"setOutOfBandMembers")),(0,i.default)(this,"clearOutOfBandMembers",this.degradable((e=>(super.clearOutOfBandMembers(e),this.backend.clearOutOfBandMembers(e))),"clearOutOfBandMembers")),(0,i.default)(this,"getClientOptions",this.degradable((()=>this.backend.getClientOptions()),"getClientOptions")),(0,i.default)(this,"storeClientOptions",this.degradable((e=>(super.storeClientOptions(e),this.backend.storeClientOptions(e))),"storeClientOptions")),!e.indexedDB)throw new Error("Missing required option: indexedDB");e.workerFactory?this.backend=new a.RemoteIndexedDBStoreBackend(e.workerFactory,e.dbName):this.backend=new o.LocalIndexedDBStoreBackend(e.indexedDB,e.dbName)}startup(){return this.startedUp?(d.logger.log("IndexedDBStore.startup: already started"),Promise.resolve()):(d.logger.log("IndexedDBStore.startup: connecting to backend"),this.backend.connect().then((()=>(d.logger.log("IndexedDBStore.startup: loading presence events"),this.backend.getUserPresenceEvents()))).then((e=>{d.logger.log("IndexedDBStore.startup: processing presence events"),e.forEach((([e,t])=>{const n=new c.User(e);t&&n.setPresenceEvent(new l.MatrixEvent(t)),this.userModifiedMap[n.userId]=n.getLastModifiedTime(),this.storeUser(n)}))})))}wantsSave(){return Date.now()-this.syncTs>3e5}save(e=!1){return e||this.wantsSave()?this.reallySave():Promise.resolve()}degradable(e,t){const n=super[t];return async(...t)=>{try{return await e.call(this,...t)}catch(e){d.logger.error("IndexedDBStore failure, degrading to MemoryStore",e),this.emitter.emit("degraded",e);try{d.logger.log("IndexedDBStore trying to delete degraded data"),await this.backend.clearDatabase(),d.logger.log("IndexedDBStore delete after degrading succeeded")}catch(e){d.logger.warn("IndexedDBStore delete after degrading failed",e)}if(n)return n.call(this,...t)}}}async getPendingEvents(e){if(!this.localStorage)return super.getPendingEvents(e);const t=this.localStorage.getItem(f(e));if(t)try{return JSON.parse(t)}catch(e){d.logger.error("Could not parse persisted pending events",e)}return[]}async setPendingEvents(e,t){if(!this.localStorage)return super.setPendingEvents(e,t);t.length>0?this.localStorage.setItem(f(e),JSON.stringify(t)):this.localStorage.removeItem(f(e))}saveToDeviceBatches(e){return this.backend.saveToDeviceBatches(e)}getOldestToDeviceBatch(){return this.backend.getOldestToDeviceBatch()}removeToDeviceBatch(e){return this.backend.removeToDeviceBatch(e)}}function f(e){return`mx_pending_events_${e}`}t.IndexedDBStore=h},1703:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.MemoryStore=void 0;var i=r(n(8416)),s=n(3998),o=n(6860);function a(e){return"string"==typeof e&&!!e&&"undefined"!==e&&"null"!==e||"number"==typeof e}t.MemoryStore=class{constructor(e={}){(0,i.default)(this,"rooms",{}),(0,i.default)(this,"users",{}),(0,i.default)(this,"syncToken",null),(0,i.default)(this,"filters",{}),(0,i.default)(this,"accountData",{}),(0,i.default)(this,"localStorage",void 0),(0,i.default)(this,"oobMembers",{}),(0,i.default)(this,"pendingEvents",{}),(0,i.default)(this,"clientOptions",{}),(0,i.default)(this,"pendingToDeviceBatches",[]),(0,i.default)(this,"nextToDeviceBatchId",0),(0,i.default)(this,"onRoomMember",((e,t,n)=>{if("invite"===n.membership)return;const r=this.users[n.userId]||new s.User(n.userId);n.name&&(r.setDisplayName(n.name),n.events.member&&r.setRawDisplayName(n.events.member.getDirectionalContent().displayname)),n.events.member&&n.events.member.getContent().avatar_url&&r.setAvatarUrl(n.events.member.getContent().avatar_url),this.users[r.userId]=r})),this.localStorage=e.localStorage}getSyncToken(){return this.syncToken}isNewlyCreated(){return Promise.resolve(!0)}setSyncToken(e){this.syncToken=e}storeRoom(e){this.rooms[e.roomId]=e,e.currentState.on(o.RoomStateEvent.Members,this.onRoomMember),e.currentState.getMembers().forEach((t=>{this.onRoomMember(null,e.currentState,t)}))}getRoom(e){return this.rooms[e]||null}getRooms(){return Object.values(this.rooms)}removeRoom(e){this.rooms[e]&&this.rooms[e].currentState.removeListener(o.RoomStateEvent.Members,this.onRoomMember),delete this.rooms[e]}getRoomSummaries(){return Object.values(this.rooms).map((function(e){return e.summary}))}storeUser(e){this.users[e.userId]=e}getUser(e){return this.users[e]||null}getUsers(){return Object.values(this.users)}scrollback(e,t){return[]}storeEvents(e,t,n,r){}storeFilter(e){e&&(this.filters[e.userId]||(this.filters[e.userId]={}),this.filters[e.userId][e.filterId]=e)}getFilter(e,t){return this.filters[e]&&this.filters[e][t]?this.filters[e][t]:null}getFilterIdByName(e){if(!this.localStorage)return null;const t="mxjssdk_memory_filter_"+e;try{const e=this.localStorage.getItem(t);if(a(e))return e}catch(e){}return null}setFilterIdByName(e,t){if(!this.localStorage)return;const n="mxjssdk_memory_filter_"+e;try{a(t)?this.localStorage.setItem(n,t):this.localStorage.removeItem(n)}catch(e){}}storeAccountDataEvents(e){e.forEach((e=>{this.accountData[e.getType()]=e}))}getAccountData(e){return this.accountData[e]}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(e){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return this.rooms={},this.users={},this.syncToken=null,this.filters={},this.accountData={},Promise.resolve()}getOutOfBandMembers(e){return Promise.resolve(this.oobMembers[e]||null)}setOutOfBandMembers(e,t){return this.oobMembers[e]=t,Promise.resolve()}clearOutOfBandMembers(e){return this.oobMembers={},Promise.resolve()}getClientOptions(){return Promise.resolve(this.clientOptions)}storeClientOptions(e){return this.clientOptions=Object.assign({},e),Promise.resolve()}async getPendingEvents(e){var t;return null!==(t=this.pendingEvents[e])&&void 0!==t?t:[]}async setPendingEvents(e,t){this.pendingEvents[e]=t}saveToDeviceBatches(e){for(const t of e)this.pendingToDeviceBatches.push({id:this.nextToDeviceBatchId++,eventType:t.eventType,txnId:t.txnId,batch:t.batch});return Promise.resolve()}async getOldestToDeviceBatch(){return 0===this.pendingToDeviceBatches.length?null:this.pendingToDeviceBatches[0]}removeToDeviceBatch(e){return this.pendingToDeviceBatches=this.pendingToDeviceBatches.filter((t=>t.id!==e)),Promise.resolve()}}},5641:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.StubStore=void 0;var i=r(n(8416));t.StubStore=class{constructor(){(0,i.default)(this,"accountData",{}),(0,i.default)(this,"fromToken",null)}isNewlyCreated(){return Promise.resolve(!0)}getSyncToken(){return this.fromToken}setSyncToken(e){this.fromToken=e}storeRoom(e){}getRoom(e){return null}getRooms(){return[]}removeRoom(e){}getRoomSummaries(){return[]}storeUser(e){}getUser(e){return null}getUsers(){return[]}scrollback(e,t){return[]}storeEvents(e,t,n,r){}storeFilter(e){}getFilter(e,t){return null}getFilterIdByName(e){return null}setFilterIdByName(e,t){}storeAccountDataEvents(e){}getAccountData(e){}setSyncData(e){return Promise.resolve()}wantsSave(){return!1}save(){}startup(){return Promise.resolve()}getSavedSync(){return Promise.resolve(null)}getSavedSyncToken(){return Promise.resolve(null)}deleteAllData(){return Promise.resolve()}getOutOfBandMembers(){return Promise.resolve(null)}setOutOfBandMembers(e,t){return Promise.resolve()}clearOutOfBandMembers(){return Promise.resolve()}getClientOptions(){return Promise.resolve({})}storeClientOptions(e){return Promise.resolve()}async getPendingEvents(e){return[]}setPendingEvents(e,t){return Promise.resolve()}async saveToDeviceBatches(e){return Promise.resolve()}getOldestToDeviceBatch(){return Promise.resolve(null)}async removeToDeviceBatch(e){return Promise.resolve()}}},2741:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SyncAccumulator=t.Category=void 0;var i=r(n(8416)),s=n(7434),o=n(3102);let a;function c(e,t){null!==t.state_key&&void 0!==t.state_key&&t.type&&(e[t.type]||(e[t.type]=Object.create(null)),e[t.type][t.state_key]=t)}t.Category=a,function(e){e.Invite="invite",e.Leave="leave",e.Join="join"}(a||(t.Category=a={})),t.SyncAccumulator=class{constructor(e={}){this.opts=e,(0,i.default)(this,"accountData",{}),(0,i.default)(this,"inviteRooms",{}),(0,i.default)(this,"joinRooms",{}),(0,i.default)(this,"nextBatch",null),this.opts.maxTimelineEntries=this.opts.maxTimelineEntries||50}accumulate(e,t=!1){this.accumulateRooms(e,t),this.accumulateAccountData(e),this.nextBatch=e.next_batch}accumulateAccountData(e){e.account_data&&e.account_data.events&&e.account_data.events.forEach((e=>{this.accountData[e.type]=e}))}accumulateRooms(e,t=!1){e.rooms&&(e.rooms.invite&&Object.keys(e.rooms.invite).forEach((n=>{this.accumulateRoom(n,a.Invite,e.rooms.invite[n],t)})),e.rooms.join&&Object.keys(e.rooms.join).forEach((n=>{this.accumulateRoom(n,a.Join,e.rooms.join[n],t)})),e.rooms.leave&&Object.keys(e.rooms.leave).forEach((n=>{this.accumulateRoom(n,a.Leave,e.rooms.leave[n],t)})))}accumulateRoom(e,t,n,r=!1){switch(t){case a.Invite:this.accumulateInviteState(e,n);break;case a.Join:this.inviteRooms[e]&&delete this.inviteRooms[e],this.accumulateJoinState(e,n,r);break;case a.Leave:this.inviteRooms[e]?delete this.inviteRooms[e]:delete this.joinRooms[e];break;default:s.logger.error("Unknown cateogory: ",t)}}accumulateInviteState(e,t){if(!t.invite_state||!t.invite_state.events)return;if(!this.inviteRooms[e])return void(this.inviteRooms[e]={invite_state:t.invite_state});const n=this.inviteRooms[e];t.invite_state.events.forEach((e=>{let t=!1;for(let r=0;r<n.invite_state.events.length;r++){const i=n.invite_state.events[r];i.type===e.type&&i.state_key==e.state_key&&(n.invite_state.events[r]=e,t=!0)}t||n.invite_state.events.push(e)}))}accumulateJoinState(e,t,n=!1){this.joinRooms[e]||(this.joinRooms[e]={_currentState:Object.create(null),_timeline:[],_accountData:Object.create(null),_unreadNotifications:{},_summary:{},_readReceipts:{}});const r=this.joinRooms[e];if(t.account_data&&t.account_data.events&&t.account_data.events.forEach((e=>{r._accountData[e.type]=e})),t.unread_notifications&&(r._unreadNotifications=t.unread_notifications),t.summary){const e="m.heroes",n="m.invited_member_count",i="m.joined_member_count",s=r._summary,o=t.summary;s[e]=o[e]||s[e],s[i]=o[i]||s[i],s[n]=o[n]||s[n]}if(t.ephemeral&&t.ephemeral.events&&t.ephemeral.events.forEach((e=>{"m.receipt"===e.type&&e.content&&Object.keys(e.content).forEach((t=>{Object.entries(e.content[t]).forEach((([n,i])=>{(0,o.isSupportedReceiptType)(n)&&Object.keys(i).forEach((i=>{r._readReceipts[i]={data:e.content[t][n][i],type:n,eventId:t}}))}))}))})),t.timeline&&t.timeline.limited&&(r._timeline=[]),t.state&&t.state.events&&t.state.events.forEach((e=>{c(r._currentState,e)})),t.timeline&&t.timeline.events&&t.timeline.events.forEach(((e,i)=>{let s;if(c(r._currentState,e),n)s=e;else{s=Object.assign({},e),void 0!==s.unsigned&&(s.unsigned=Object.assign({},s.unsigned));const t=e.unsigned?e.unsigned.age:e.age;void 0!==t&&(s._localTs=Date.now()-t)}r._timeline.push({event:s,token:0===i?t.timeline.prev_batch:null})})),r._timeline.length>this.opts.maxTimelineEntries)for(let e=r._timeline.length-this.opts.maxTimelineEntries;e<r._timeline.length;e++)if(r._timeline[e].token){r._timeline=r._timeline.slice(e,r._timeline.length);break}}getJSON(e=!1){const t={join:{},invite:{},leave:{}};Object.keys(this.inviteRooms).forEach((e=>{t.invite[e]=this.inviteRooms[e]})),Object.keys(this.joinRooms).forEach((n=>{const r=this.joinRooms[n],i={ephemeral:{events:[]},account_data:{events:[]},state:{events:[]},timeline:{events:[],prev_batch:null},unread_notifications:r._unreadNotifications,summary:r._summary};Object.keys(r._accountData).forEach((e=>{i.account_data.events.push(r._accountData[e])}));const s={type:"m.receipt",room_id:n,content:{}};Object.keys(r._readReceipts).forEach((e=>{const t=r._readReceipts[e];s.content[t.eventId]||(s.content[t.eventId]={}),s.content[t.eventId][t.type]||(s.content[t.eventId][t.type]={}),s.content[t.eventId][t.type][e]=t.data})),Object.keys(s.content).length>0&&i.ephemeral.events.push(s),r._timeline.forEach((t=>{if(!i.timeline.prev_batch){if(!t.token)return;i.timeline.prev_batch=t.token}let n;!e&&t.event._localTs?(n=Object.assign({},t.event),void 0!==n.unsigned&&(n.unsigned=Object.assign({},n.unsigned)),delete n._localTs,n.unsigned=n.unsigned||{},n.unsigned.age=Date.now()-t.event._localTs):n=t.event,i.timeline.events.push(n)}));const a=Object.create(null);for(let e=i.timeline.events.length-1;e>=0;e--){const t=i.timeline.events[e];if(null===t.state_key||void 0===t.state_key)continue;const n=(0,o.deepCopy)(t);n.unsigned&&(n.unsigned.prev_content&&(n.content=n.unsigned.prev_content),n.unsigned.prev_sender&&(n.sender=n.unsigned.prev_sender)),c(a,n)}Object.keys(r._currentState).forEach((e=>{Object.keys(r._currentState[e]).forEach((t=>{let n=r._currentState[e][t];a[e]&&a[e][t]&&(n=a[e][t]),i.state.events.push(n)}))})),t.join[n]=i}));const n=[];return Object.keys(this.accountData).forEach((e=>{n.push(this.accountData[e])})),{nextBatch:this.nextBatch,roomsData:t,accountData:n}}getNextBatchToken(){return this.nextBatch}}},4551:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SyncState=t.SyncApi=void 0,t._createAndReEmitRoom=R;var i=r(n(8416)),s=n(3998),o=n(7366),a=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=b(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),c=n(7906),l=n(8910),d=n(1707),u=n(7434),h=n(9489),f=n(2168),g=n(7715),p=n(2481),m=n(6860),y=n(2848),v=n(6320);function b(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(b=function(e){return e?n:t})(e)}let _;t.SyncState=_,function(e){e.Error="ERROR",e.Prepared="PREPARED",e.Stopped="STOPPED",e.Syncing="SYNCING",e.Catchup="CATCHUP",e.Reconnecting="RECONNECTING"}(_||(t.SyncState=_={}));const E=["org.matrix.msc2716v3"];function w(e,t){return"FILTER_SYNC_"+e+(t?"_"+t:"")}function S(...e){u.logger.log(...e)}var C;function T(e,t){const n=new s.User(t);return e.reEmitter.reEmit(n,[s.UserEvent.AvatarUrl,s.UserEvent.DisplayName,s.UserEvent.Presence,s.UserEvent.CurrentlyActive,s.UserEvent.LastPresenceTs]),n}function R(e,t,n){const{timelineSupport:r}=e,i=new o.Room(t,e,e.getUserId(),{lazyLoadMembers:n.lazyLoadMembers,pendingEventOrdering:n.pendingEventOrdering,timelineSupport:r});return e.reEmitter.reEmit(i,[o.RoomEvent.Name,o.RoomEvent.Redaction,o.RoomEvent.RedactionCancelled,o.RoomEvent.Receipt,o.RoomEvent.Tags,o.RoomEvent.LocalEchoUpdated,o.RoomEvent.AccountData,o.RoomEvent.MyMembership,o.RoomEvent.Timeline,o.RoomEvent.TimelineReset,m.RoomStateEvent.Events,m.RoomStateEvent.Members,m.RoomStateEvent.NewMember,m.RoomStateEvent.Update,v.BeaconEvent.New,v.BeaconEvent.Update,v.BeaconEvent.Destroy,v.BeaconEvent.LivenessChange]),i.on(m.RoomStateEvent.NewMember,((t,n,r)=>{r.user=e.getUser(r.userId),e.reEmitter.reEmit(r,[y.RoomMemberEvent.Name,y.RoomMemberEvent.Typing,y.RoomMemberEvent.PowerLevel,y.RoomMemberEvent.Membership])})),i}!function(e){e.Offline="offline",e.Online="online",e.Unavailable="unavailable"}(C||(C={})),t.SyncApi=class{constructor(e,t={}){var n;this.client=e,this.opts=t,(0,i.default)(this,"_peekRoom",null),(0,i.default)(this,"currentSyncRequest",null),(0,i.default)(this,"syncState",null),(0,i.default)(this,"syncStateData",null),(0,i.default)(this,"catchingUp",!1),(0,i.default)(this,"running",!1),(0,i.default)(this,"keepAliveTimer",null),(0,i.default)(this,"connectionReturnedDefer",null),(0,i.default)(this,"notifEvents",[]),(0,i.default)(this,"failedSyncCount",0),(0,i.default)(this,"storeIsInvalid",!1),(0,i.default)(this,"onOnline",(()=>{S("Browser thinks we are back online"),this.startKeepAlives(0)})),this.opts.initialSyncLimit=null!==(n=this.opts.initialSyncLimit)&&void 0!==n?n:8,this.opts.resolveInvitesToProfiles=this.opts.resolveInvitesToProfiles||!1,this.opts.pollTimeout=this.opts.pollTimeout||3e4,this.opts.pendingEventOrdering=this.opts.pendingEventOrdering||f.PendingEventOrdering.Chronological,this.opts.experimentalThreadSupport=!0===this.opts.experimentalThreadSupport,t.canResetEntireTimeline||(t.canResetEntireTimeline=e=>!1),e.getNotifTimelineSet()&&e.reEmitter.reEmit(e.getNotifTimelineSet(),[o.RoomEvent.Timeline,o.RoomEvent.TimelineReset])}createRoom(e){const t=R(this.client,e,this.opts);return t.on(m.RoomStateEvent.Marker,((e,n)=>{this.onMarkerStateEvent(t,e,n)})),t}onMarkerStateEvent(e,t,{timelineWasEmpty:n}={}){n?u.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because the timeline was empty before the marker arrived which means there is nothing to refresh.`):E.includes(e.getVersion())||t.getSender()===e.getCreator()?(u.logger.debug(`MarkerState: Timeline needs to be refreshed because a new markerEventId=${t.getId()} was sent in roomId=${e.roomId}`),e.setTimelineNeedsRefresh(!0),e.emit(o.RoomEvent.HistoryImportedWithinTimeline,t,e)):u.logger.debug(`MarkerState: Ignoring markerEventId=${t.getId()} in roomId=${e.roomId} because MSC2716 is not supported in the room version or for any room version, the marker wasn't sent by the room creator.`)}syncLeftRooms(){const e=this.client,t=new c.Filter(this.client.credentials.userId);t.setTimelineLimit(1),t.setIncludeLeaveRooms(!0);const n=this.opts.pollTimeout+8e4,r={timeout:0};return e.getOrCreateFilter(w(e.credentials.userId,"LEFT_ROOMS"),t).then((function(t){return r.filter=t,e.http.authedRequest(void 0,g.Method.Get,"/sync",r,void 0,n)})).then((async t=>{var n;let r=[];return null!==(n=t.rooms)&&void 0!==n&&n.leave&&(r=this.mapSyncResponseToRoomArray(t.rooms.leave)),Promise.all(r.map((async t=>{const n=t.room;if(!t.isBrandNewRoom)return;t.timeline=t.timeline||{};const r=this.mapSyncEventsFormat(t.timeline,n),i=this.mapSyncEventsFormat(t.state,n);return n.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,l.EventTimeline.BACKWARDS),await this.processRoomEvents(n,i,r),n.recalculate(),e.store.storeRoom(n),e.emit(f.ClientEvent.Room,n),this.processEventsForNotifs(n,r),n})))}))}peek(e){if(this._peekRoom&&this._peekRoom.roomId===e)return Promise.resolve(this._peekRoom);const t=this.client;return this._peekRoom=this.createRoom(e),this.client.roomInitialSync(e,20).then((e=>{e.messages=e.messages||{chunk:[]},e.messages.chunk=e.messages.chunk||[],e.state=e.state||[];const n=a.deepCopy(e.state).map(t.getEventMapper()),r=e.state.map(t.getEventMapper()),i=e.messages.chunk.map(t.getEventMapper());return e.presence&&Array.isArray(e.presence)&&e.presence.map(t.getEventMapper()).forEach((function(e){let n=t.store.getUser(e.getContent().user_id);n?n.setPresenceEvent(e):(n=T(t,e.getContent().user_id),n.setPresenceEvent(e),t.store.storeUser(n)),t.emit(f.ClientEvent.Event,e)})),e.messages.start&&(this._peekRoom.oldState.paginationToken=e.messages.start),this._peekRoom.oldState.setStateEvents(n),this._peekRoom.currentState.setStateEvents(r),this.resolveInvites(this._peekRoom),this._peekRoom.recalculate(),this._peekRoom.addEventsToTimeline(i.reverse(),!0,this._peekRoom.getLiveTimeline(),e.messages.start),t.store.storeRoom(this._peekRoom),t.emit(f.ClientEvent.Room,this._peekRoom),this.peekPoll(this._peekRoom),this._peekRoom}))}stopPeeking(){this._peekRoom=null}peekPoll(e,t){this._peekRoom===e?this.client.http.authedRequest(void 0,g.Method.Get,"/events",{room_id:e.roomId,timeout:String(3e4),from:t},void 0,5e4).then((t=>{if(this._peekRoom!==e)return void S("Stopped peeking in room %s",e.roomId);t.chunk.filter((function(e){return"m.presence"===e.type})).map(this.client.getEventMapper()).forEach((e=>{let t=this.client.store.getUser(e.getContent().user_id);t?t.setPresenceEvent(e):(t=T(this.client,e.getContent().user_id),t.setPresenceEvent(e),this.client.store.storeUser(t)),this.client.emit(f.ClientEvent.Event,e)}));const n=t.chunk.filter((function(t){return t.room_id===e.roomId&&t.event_id})).map(this.client.getEventMapper());e.addLiveEvents(n),this.peekPoll(e,t.end)}),(n=>{u.logger.error("[%s] Peek poll failed: %s",e.roomId,n),setTimeout((()=>{this.peekPoll(e,t)}),3e4)})):S("Stopped peeking in room %s",e.roomId)}getSyncState(){return this.syncState}getSyncStateData(){return this.syncStateData}async recoverFromSyncStartupError(e,t){await e;const n=this.startKeepAlives();this.updateSyncState(_.Error,{error:t}),await n}async wasLazyLoadingToggled(e=!1){let t=!1;if(!await this.client.store.isNewlyCreated()){const n=await this.client.store.getClientOptions();return n&&(t=!!n.lazyLoadMembers),t!==e}return!1}shouldAbortSync(e){return"M_UNKNOWN_TOKEN"===e.errcode&&(u.logger.warn("Token no longer valid - assuming logout"),this.stop(),this.updateSyncState(_.Error,{error:e}),!0)}sync(){const e=this.client;this.running=!0,n.g.window&&n.g.window.addEventListener&&n.g.window.addEventListener("online",this.onOnline,!1);let t=Promise.resolve(),r=null;const i=async()=>{try{S("Getting push rules...");const t=await e.getPushRules();S("Got push rules"),e.pushRules=t}catch(e){if(u.logger.error("Getting push rules failed",e),this.shouldAbortSync(e))return;return S("Waiting for saved sync before retrying push rules..."),await this.recoverFromSyncStartupError(t,e),void i()}o()},s=()=>{const t=new c.Filter(e.credentials.userId);return t.setTimelineLimit(this.opts.initialSyncLimit),t},o=async()=>{if(S("Checking lazy load status..."),this.opts.lazyLoadMembers&&e.isGuest()&&(this.opts.lazyLoadMembers=!1),this.opts.lazyLoadMembers&&(S("Checking server lazy load support..."),await e.doesServerSupportLazyLoading()?(S("Enabling lazy load on sync filter..."),this.opts.filter||(this.opts.filter=s()),this.opts.filter.setLazyLoadMembers(!0)):(S("LL: lazy loading requested but not supported by server, so disabling"),this.opts.lazyLoadMembers=!1)),S("Checking whether lazy loading has changed in store..."),await this.wasLazyLoadingToggled(this.opts.lazyLoadMembers)){this.storeIsInvalid=!0;const e=h.InvalidStoreError.TOGGLED_LAZY_LOADING,t=new h.InvalidStoreError(e,!!this.opts.lazyLoadMembers);return this.updateSyncState(_.Error,{error:t}),void u.logger.warn("InvalidStoreError: store is not usable: stopping sync.")}this.opts.lazyLoadMembers&&this.opts.crypto&&this.opts.crypto.enableLazyLoading();try{S("Storing client options..."),await this.client.storeClientOptions(),S("Stored client options")}catch(e){throw u.logger.error("Storing client options failed",e),e}a()},a=async()=>{let n,i;S("Getting filter..."),n=this.opts.filter?this.opts.filter:s();try{i=await e.getOrCreateFilter(w(e.credentials.userId),n)}catch(e){if(u.logger.error("Getting filter failed",e),this.shouldAbortSync(e))return;return S("Waiting for saved sync before retrying filter..."),await this.recoverFromSyncStartupError(t,e),void a()}e.resetNotifTimelineSet(),null===this.currentSyncRequest&&(S("Sending first sync request..."),this.currentSyncRequest=this.doSyncRequest({filterId:i},r)),S("Waiting for saved sync before starting sync processing..."),await t,this.doSync({filterId:i})};e.isGuest()?this.doSync({}):(S("Getting saved sync token..."),t=e.store.getSavedSyncToken().then((t=>(S("Got saved sync token"),r=t,S("Getting saved sync..."),e.store.getSavedSync()))).then((e=>{if(S(`Got reply from saved sync, exists? ${!!e}`),e)return this.syncFromCache(e)})).catch((e=>{u.logger.error("Getting saved sync failed",e)})),i())}stop(){var e;S("SyncApi.stop"),n.g.window&&n.g.window.removeEventListener&&n.g.window.removeEventListener("online",this.onOnline,!1),this.running=!1,null===(e=this.currentSyncRequest)||void 0===e||e.abort(),this.keepAliveTimer&&(clearTimeout(this.keepAliveTimer),this.keepAliveTimer=null)}retryImmediately(){return!!this.connectionReturnedDefer&&(this.startKeepAlives(0),!0)}async syncFromCache(e){S("sync(): not doing HTTP hit, instead returning stored /sync data");const t=e.nextBatch;this.client.store.setSyncToken(t);const n={oldSyncToken:null,nextSyncToken:t,catchingUp:!1,fromCache:!0},r={next_batch:t,rooms:e.roomsData,account_data:{events:e.accountData}};try{await this.processSyncResponse(n,r)}catch(e){u.logger.error("Error processing cached sync",e)}this.storeIsInvalid||this.updateSyncState(_.Prepared,n)}async doSync(e){const t=this.client;if(!this.running)return S("Sync no longer running: exiting."),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=null),void this.updateSyncState(_.Stopped);const n=t.store.getSyncToken();let r;try{null===this.currentSyncRequest&&(this.currentSyncRequest=this.doSyncRequest(e,n)),r=await this.currentSyncRequest}catch(t){return void this.onSyncError(t,e)}finally{this.currentSyncRequest=null}t.store.setSyncToken(r.next_batch),this.failedSyncCount=0,await t.store.setSyncData(r);const i={oldSyncToken:n,nextSyncToken:r.next_batch,catchingUp:this.catchingUp};this.opts.crypto&&await this.opts.crypto.onSyncWillProcess(i);try{await this.processSyncResponse(i,r)}catch(e){u.logger.error("Caught /sync error",e),this.client.emit(f.ClientEvent.SyncUnexpectedError,e)}i.catchingUp=this.catchingUp,e.hasSyncedBefore||(this.updateSyncState(_.Prepared,i),e.hasSyncedBefore=!0),this.opts.crypto&&await this.opts.crypto.onSyncCompleted(i),this.updateSyncState(_.Syncing,i),t.store.wantsSave()&&(this.opts.crypto&&await this.opts.crypto.saveDeviceList(0),t.store.save()),this.doSync(e)}doSyncRequest(e,t){const n=this.getSyncParams(e,t);return this.client.http.authedRequest(void 0,g.Method.Get,"/sync",n,void 0,n.timeout+8e4)}getSyncParams(e,t){let n=this.opts.pollTimeout;("SYNCING"!==this.getSyncState()||this.catchingUp)&&(this.catchingUp=!0,n=0);let r=e.filterId;this.client.isGuest()&&!r&&(r=this.getGuestFilter());const i={filter:r,timeout:n};return this.opts.disablePresence&&(i.set_presence=C.Offline),t?i.since=t:i._cacheBuster=Date.now(),"ERROR"!=this.getSyncState()&&"RECONNECTING"!=this.getSyncState()||(i.timeout=0),i}onSyncError(e,t){if(!this.running)return S("Sync no longer running: exiting"),this.connectionReturnedDefer&&(this.connectionReturnedDefer.reject(),this.connectionReturnedDefer=null),void this.updateSyncState(_.Stopped);u.logger.error("/sync error %s",e),u.logger.error(e),this.shouldAbortSync(e)||(this.failedSyncCount++,u.logger.log("Number of consecutive failed sync requests:",this.failedSyncCount),S("Starting keep-alive"),this.startKeepAlives().then((e=>{e&&this.getSyncState()===_.Error&&this.updateSyncState(_.Catchup,{oldSyncToken:null,nextSyncToken:null,catchingUp:!0}),this.doSync(t)})),this.currentSyncRequest=null,this.updateSyncState(this.failedSyncCount>=3?_.Error:_.Reconnecting,{error:e}))}async processSyncResponse(e,t){var n;const r=this.client;if(t.presence&&Array.isArray(t.presence.events)&&t.presence.events.map(r.getEventMapper()).forEach((function(e){let t=r.store.getUser(e.getSender());t?t.setPresenceEvent(e):(t=T(r,e.getSender()),t.setPresenceEvent(e),r.store.storeUser(t)),r.emit(f.ClientEvent.Event,e)})),t.account_data&&Array.isArray(t.account_data.events)){const e=t.account_data.events.map(r.getEventMapper()),n=e.reduce(((e,t)=>(e[t.getId()]=r.store.getAccountData(t.getType()),e)),{});r.store.storeAccountDataEvents(e),e.forEach((function(e){if(e.getType()===p.EventType.PushRules){const t=e.getContent();r.pushRules=d.PushProcessor.rewriteDefaultRules(t)}const t=n[e.getId()];return r.emit(f.ClientEvent.AccountData,e,t),e}))}if(Array.isArray(null===(n=t.to_device)||void 0===n?void 0:n.events)&&t.to_device.events.length>0){const e=[];t.to_device.events.map(r.getEventMapper()).map((t=>{if("m.key.verification.cancel"===t.getType()){const n=t.getContent().transaction_id;n&&e.push(n)}return t})).forEach((function(t){const n=t.getContent();if("m.room.message"!=t.getType()||"m.bad.encrypted"!=n.msgtype){if("m.key.verification.start"===t.getType()||"m.key.verification.request"===t.getType()){const r=n.transaction_id;e.includes(r)&&t.flagCancelled()}r.emit(f.ClientEvent.ToDeviceEvent,t)}else u.logger.log("Ignoring undecryptable to-device event from "+t.getSender())}))}else this.catchingUp=!1;let i=[],s=[],c=[];if(t.rooms&&(t.rooms.invite&&(i=this.mapSyncResponseToRoomArray(t.rooms.invite)),t.rooms.join&&(s=this.mapSyncResponseToRoomArray(t.rooms.join)),t.rooms.leave&&(c=this.mapSyncResponseToRoomArray(t.rooms.leave))),this.notifEvents=[],await a.promiseMapSeries(i,(async e=>{const t=e.room,n=this.mapSyncEventsFormat(e.invite_state,t);await this.processRoomEvents(t,n),e.isBrandNewRoom?(t.recalculate(),r.store.storeRoom(t),r.emit(f.ClientEvent.Room,t)):t.recalculate(),n.forEach((function(e){r.emit(f.ClientEvent.Event,e)}))})),await a.promiseMapSeries(s,(async t=>{const n=t.room,i=this.mapSyncEventsFormat(t.state,n),s=this.mapSyncEventsFormat(t.timeline,n,!1),c=this.mapSyncEventsFormat(t.ephemeral),d=this.mapSyncEventsFormat(t.account_data),u=r.isRoomEncrypted(n.roomId);if(t.unread_notifications&&(n.setUnreadNotificationCount(o.NotificationCountType.Total,t.unread_notifications.notification_count),(!u||u&&n.getUnreadNotificationCount(o.NotificationCountType.Highlight)<=0)&&n.setUnreadNotificationCount(o.NotificationCountType.Highlight,t.unread_notifications.highlight_count)),t.timeline=t.timeline||{},t.isBrandNewRoom)n.getLiveTimeline().setPaginationToken(t.timeline.prev_batch,l.EventTimeline.BACKWARDS);else if(t.timeline.limited){let i=!0;for(let e=s.length-1;e>=0;e--){const t=s[e].getId();if(n.getTimelineForEvent(t)){S("Already have event "+t+" in limited sync - not resetting"),i=!1,s.splice(0,e);break}}i&&(n.resetLiveTimeline(t.timeline.prev_batch,this.opts.canResetEntireTimeline(n.roomId)?null:e.oldSyncToken),r.resetNotifTimelineSet())}await this.processRoomEvents(n,i,s,e.fromCache),t.summary&&n.setSummary(t.summary),n.addEphemeralEvents(c),n.addAccountData(d),n.recalculate(),t.isBrandNewRoom&&(r.store.storeRoom(n),r.emit(f.ClientEvent.Room,n)),this.processEventsForNotifs(n,s);const h=async e=>{r.emit(f.ClientEvent.Event,e),e.isState()&&"m.room.encryption"==e.getType()&&this.opts.crypto&&await this.opts.crypto.onCryptoEvent(e)};await a.promiseMapSeries(i,h),await a.promiseMapSeries(s,h),c.forEach((function(e){r.emit(f.ClientEvent.Event,e)})),d.forEach((function(e){r.emit(f.ClientEvent.Event,e)})),n.decryptCriticalEvents()})),await a.promiseMapSeries(c,(async e=>{const t=e.room,n=this.mapSyncEventsFormat(e.state,t),i=this.mapSyncEventsFormat(e.timeline,t),s=this.mapSyncEventsFormat(e.account_data);await this.processRoomEvents(t,n,i),t.addAccountData(s),t.recalculate(),e.isBrandNewRoom&&(r.store.storeRoom(t),r.emit(f.ClientEvent.Room,t)),this.processEventsForNotifs(t,i),n.forEach((function(e){r.emit(f.ClientEvent.Event,e)})),i.forEach((function(e){r.emit(f.ClientEvent.Event,e)})),s.forEach((function(e){r.emit(f.ClientEvent.Event,e)}))})),e.oldSyncToken&&this.notifEvents.length&&(this.notifEvents.sort((function(e,t){return e.getTs()-t.getTs()})),this.notifEvents.forEach((function(e){r.getNotifTimelineSet().addLiveEvent(e)}))),t.device_lists&&this.opts.crypto&&await this.opts.crypto.handleDeviceListChanges(e,t.device_lists),this.opts.crypto&&t.device_one_time_keys_count){const e=t.device_one_time_keys_count.signed_curve25519||0;this.opts.crypto.updateOneTimeKeyCount(e)}if(this.opts.crypto&&(t.device_unused_fallback_key_types||t["org.matrix.msc2732.device_unused_fallback_key_types"])){const e=t.device_unused_fallback_key_types||t["org.matrix.msc2732.device_unused_fallback_key_types"];this.opts.crypto.setNeedsNewFallback(e instanceof Array&&!e.includes("signed_curve25519"))}}startKeepAlives(e){return void 0===e&&(e=2e3+Math.floor(5e3*Math.random())),null!==this.keepAliveTimer&&clearTimeout(this.keepAliveTimer),e>0?this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this),e):this.pokeKeepAlive(),this.connectionReturnedDefer||(this.connectionReturnedDefer=a.defer()),this.connectionReturnedDefer.promise}pokeKeepAlive(e=!1){const t=()=>{clearTimeout(this.keepAliveTimer),this.connectionReturnedDefer&&(this.connectionReturnedDefer.resolve(e),this.connectionReturnedDefer=null)};this.client.http.request(void 0,g.Method.Get,"/_matrix/client/versions",void 0,void 0,{prefix:"",localTimeoutMs:15e3}).then((()=>{t()}),(n=>{400==n.httpStatus||404==n.httpStatus?this.keepAliveTimer=setTimeout(t,2e3):(e=!0,this.keepAliveTimer=setTimeout(this.pokeKeepAlive.bind(this,e),5e3+Math.floor(5e3*Math.random())),this.updateSyncState(_.Error,{error:n}))}))}mapSyncResponseToRoomArray(e){const t=this.client;return Object.keys(e).map((n=>{const r=e[n];let i=t.store.getRoom(n),s=!1;return i||(i=this.createRoom(n),s=!0),r.room=i,r.isBrandNewRoom=s,r}))}mapSyncEventsFormat(e,t,n=!0){if(!e||!Array.isArray(e.events))return[];const r=this.client.getEventMapper({decrypt:n});return e.events.map((function(e){return t&&(e.room_id=t.roomId),r(e)}))}resolveInvites(e){if(!e||!this.opts.resolveInvitesToProfiles)return;const t=this.client;e.getMembersWithMembership("invite").forEach((function(n){if(n._requestedProfileInfo)return;n._requestedProfileInfo=!0;const r=t.getUser(n.userId);let i;i=r?Promise.resolve({avatar_url:r.avatarUrl,displayname:r.displayName}):t.getProfileInfo(n.userId),i.then((function(t){const r=n.events.member;"invite"===r.getContent().membership&&(r.getContent().avatar_url=t.avatar_url,r.getContent().displayname=t.displayname,n.setMembershipEvent(r,e.currentState))}),(function(e){}))}))}async processRoomEvents(e,t,n,r=!1){const i=e.getLiveTimeline(),s=0==i.getEvents().length;if(s){for(const e of t)this.client.getPushActionsForEvent(e);i.initialiseState(t,{timelineWasEmpty:s})}this.resolveInvites(e),e.recalculate(),s||(e.oldState.setStateEvents(t||[]),e.currentState.setStateEvents(t||[])),e.addLiveEvents(n||[],{fromCache:r,timelineWasEmpty:s}),this.client.processBeaconEvents(e,n)}processEventsForNotifs(e,t){if(this.client.getNotifTimelineSet())for(let e=0;e<t.length;e++){const n=this.client.getPushActionsForEvent(t[e]);n&&n.notify&&n.tweaks&&n.tweaks.highlight&&this.notifEvents.push(t[e])}}getGuestFilter(){return"{}"}updateSyncState(e,t){const n=this.syncState;this.syncState=e,this.syncStateData=t,this.client.emit(f.ClientEvent.Sync,this.syncState,n,t)}}},4969:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.TimelineWindow=t.TimelineIndex=void 0;var i=r(n(8416)),s=n(8910);n(7434);t.TimelineWindow=class{constructor(e,t,n={}){this.client=e,this.timelineSet=t,(0,i.default)(this,"windowLimit",void 0),(0,i.default)(this,"start",null),(0,i.default)(this,"end",null),(0,i.default)(this,"eventCount",0),this.windowLimit=n.windowLimit||1e3}load(e,t=20){const n=n=>{let r;const i=n.getEvents();if(e){if(r=i.findIndex((t=>t.getId()===e)),r<0)throw new Error("getEventTimeline result didn't include requested event")}else r=i.length;const s=Math.min(i.length,r+Math.ceil(t/2)),a=Math.max(0,s-t);this.start=new o(n,a-n.getBaseIndex()),this.end=new o(n,s-n.getBaseIndex()),this.eventCount=s-a};if(e){const t=this.timelineSet.getTimelineForEvent(e);return t?(n(t),Promise.resolve()):this.client.getEventTimeline(this.timelineSet,e).then(n)}return n(this.timelineSet.getLiveTimeline()),Promise.resolve()}getTimelineIndex(e){if(e==s.EventTimeline.BACKWARDS)return this.start;if(e==s.EventTimeline.FORWARDS)return this.end;throw new Error("Invalid direction '"+e+"'")}extend(e,t){const n=this.getTimelineIndex(e);if(!n)return!1;const r=e==s.EventTimeline.BACKWARDS?n.retreat(t):n.advance(t);if(r){this.eventCount+=r,this.eventCount;const t=this.eventCount-this.windowLimit;return t>0&&this.unpaginate(t,e!=s.EventTimeline.BACKWARDS),!0}return!1}canPaginate(e){const t=this.getTimelineIndex(e);if(!t)return!1;if(e==s.EventTimeline.BACKWARDS){if(t.index>t.minIndex())return!0}else if(t.index<t.maxIndex())return!0;return Boolean(t.timeline.getNeighbouringTimeline(e)||null!==t.timeline.getPaginationToken(e))}paginate(e,t,n=!0,r=5){const i=this.getTimelineIndex(e);if(!i)return Promise.resolve(!1);if(i.pendingPaginate)return i.pendingPaginate;if(this.extend(e,t))return Promise.resolve(!0);if(!n||0===r)return Promise.resolve(!1);if(null===i.timeline.getPaginationToken(e))return Promise.resolve(!1);const o=this.client.paginateEventTimeline(i.timeline,{backwards:e==s.EventTimeline.BACKWARDS,limit:t}).finally((function(){i.pendingPaginate=null})).then((n=>!!n&&this.paginate(e,t,!0,r-1)));return i.pendingPaginate=o,o}unpaginate(e,t){const n=t?this.start:this.end;if(e>this.eventCount||e<0)throw new Error("Attemting to unpaginate "+e+" events, but only have "+this.eventCount+" in the timeline");for(;e>0;){const r=t?n.advance(e):n.retreat(e);if(r<=0)throw new Error("Unable to unpaginate any further, but still have "+this.eventCount+" events");e-=r,this.eventCount-=r,this.eventCount}}getEvents(){if(!this.start)return[];const e=[];let t=this.start.timeline;for(;;){const n=t.getEvents();let r=0,i=n.length;t===this.start.timeline&&(r=this.start.index+t.getBaseIndex()),t===this.end.timeline&&(i=this.end.index+t.getBaseIndex());for(let t=r;t<i;t++)e.push(n[t]);if(t===this.end.timeline)break;t=t.getNeighbouringTimeline(s.EventTimeline.FORWARDS)}return e}};class o{constructor(e,t){this.timeline=e,this.index=t,(0,i.default)(this,"pendingPaginate",void 0)}minIndex(){return-1*this.timeline.getBaseIndex()}maxIndex(){return this.timeline.getEvents().length-this.timeline.getBaseIndex()}advance(e){if(!e)return 0;let t;if(e<0){if(t=Math.max(e,this.minIndex()-this.index),t<0)return this.index+=t,t}else if(t=Math.min(e,this.maxIndex()-this.index),t>0)return this.index+=t,t;const n=this.timeline.getNeighbouringTimeline(e<0?s.EventTimeline.BACKWARDS:s.EventTimeline.FORWARDS);return n?(this.timeline=n,this.index=e<0?this.maxIndex():this.minIndex(),this.advance(e)):0}retreat(e){return-1*this.advance(-1*e)}}t.TimelineIndex=o},3102:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.DEFAULT_ALPHABET=void 0,t.alphabetPad=g,t.averageBetweenStrings=function(e,t,n=f){const r=Math.max(e.length,t.length),i=m(g(e,r,n),n),s=m(g(t,r,n),n),o=(i+s)/BigInt(2);return o===i||o==s?p(o,n)+n[0]:p(o,n)},t.baseToString=p,t.checkObjectHasKeys=function(e,t){for(let n=0;n<t.length;n++)if(!e.hasOwnProperty(t[n]))throw new Error("Missing required key: "+t[n])},t.chunkPromises=async function(e,t){const n=[];for(let r=0;r<e.length;r+=t)n.push(...await Promise.all(e.slice(r,r+t).map((e=>e()))));return n},t.compare=function(e,t){return v.compare(e,t)},t.decodeParams=function(e){const t={},n=new URLSearchParams(e);for(const e of n.keys()){const r=n.getAll(e);t[e]=1===r.length?r[0]:r}return t},t.deepCompare=function e(t,n){if(t===n)return!0;if(typeof t!=typeof n)return!1;if("number"==typeof t&&isNaN(t)&&isNaN(n))return!0;if(null===t||null===n)return t===n;if(!(t instanceof Object))return!1;if(t.constructor!==n.constructor||t.prototype!==n.prototype)return!1;if(t instanceof RegExp||t instanceof Date)return t.toString()===n.toString();if(t instanceof Array){if(t.length!==n.length)return!1;for(let r=0;r<t.length;r++)if(!e(t[r],n[r]))return!1}else{let r;for(r in n)if(n.hasOwnProperty(r)!==t.hasOwnProperty(r))return!1;for(r in n){if(n.hasOwnProperty(r)!==t.hasOwnProperty(r))return!1;if(!e(t[r],n[r]))return!1}}return!0},t.deepCopy=function(e){return JSON.parse(JSON.stringify(e))},t.deepSortedObjectEntries=function e(t){if("object"!=typeof t)return t;if(null==t||Array.isArray(t))return t;const n=[];for(const[r,i]of Object.entries(t))n.push([r,e(i)]);return n.sort(((e,t)=>y(e[0],t[0]))),n},t.defer=function(){let e,t;const n=new Promise(((n,r)=>{e=n,t=r}));return{resolve:e,reject:t,promise:n}},t.encodeParams=function(e){const t=new URLSearchParams;for(const[n,r]of Object.entries(e))null!=r&&t.set(n,String(r));return t.toString()},t.encodeUri=function(e,t){for(const n in t)t.hasOwnProperty(n)&&(e=e.replace(n,encodeURIComponent(t[n])));return e},t.ensureNoTrailingSlash=function(e){return e&&e.endsWith("/")?e.slice(0,-1):e},t.escapeRegExp=u,t.getCrypto=function(){return h},t.getPrivateReadReceiptField=async function(e){return await e.doesServerSupportUnstableFeature("org.matrix.msc2285.stable")?a.ReceiptType.ReadPrivate:await e.doesServerSupportUnstableFeature("org.matrix.msc2285")?a.ReceiptType.UnstableReadPrivate:null},t.globToRegexp=function(e,t){return[[/\\\*/g,".*"],[/\?/g,"."],!1!==t&&[/\\\[(!|)(.*)\\]/g,(e,t,n)=>["[",t?"^":"",n.replace(/\\-/,"-"),"]"].join("")]].reduce(((e,t)=>t?e.replace(t[0],t[1]):e),u(e))},t.internaliseString=function(e){return e instanceof String&&(e=e.toString()),c.has(e)||c.set(e,e),c.get(e)},t.isFunction=function(e){return"[object Function]"===Object.prototype.toString.call(e)},t.isNullOrUndefined=function(e){return null==e},t.isNumber=function(e){return"number"==typeof e&&isFinite(e)},t.isSupportedReceiptType=function(e){return[a.ReceiptType.Read,a.ReceiptType.ReadPrivate,a.ReceiptType.UnstableReadPrivate].includes(e)},t.lexicographicCompare=y,t.nextString=function(e,t=f){return p(m(e,t)+BigInt(1),t)},t.normalize=function(e){return l(e.toLowerCase()).replace(/[\\'!"#$%&()*+,\-./:;<=>?@[\]^_`{|}~\u2000-\u206f\u2e00-\u2e7f]/g,"").toLowerCase()},t.prevString=function(e,t=f){return p(m(e,t)-BigInt(1),t)},t.promiseMapSeries=async function(e,t){for(const n of e)await t(await n)},t.promiseTry=function(e){return Promise.resolve(e())},t.recursivelyAssign=function e(t,n,r=!1){for(const[i,s]of Object.entries(n))t[i]instanceof Object&&s?e(t[i],s):null==s&&r||(t[i]=s);return t},t.removeDirectionOverrideChars=function(e){return"string"==typeof e?e.replace(/[\u202d-\u202e]/g,""):""},t.removeElement=function(e,t,n){let r;if(n){for(r=e.length-1;r>=0;r--)if(t(e[r],r,e))return e.splice(r,1),!0}else for(r=0;r<e.length;r++)if(t(e[r],r,e))return e.splice(r,1),!0;return!1},t.removeHiddenChars=l,t.setCrypto=function(e){h=e},t.simpleRetryOperation=function(e){return(0,s.default)((t=>e(t)),{forever:!0,factor:2,minTimeout:3e3,maxTimeout:15e3})},t.sleep=function(e,t){return new Promise((n=>{setTimeout(n,e,t)}))},t.sortEventsByLatestContentTimestamp=function(e,t){return b(t)-b(e)},t.stringToBase=m;var i=r(n(5067)),s=r(n(2693)),o=n(6709),a=n(5550);const c=new Map;function l(e){return"string"==typeof e?(0,i.default)(e.normalize("NFD").replace(d,"")):""}const d=/[\u2000-\u200F\u202A-\u202F\u0300-\u036F\uFEFF\u061C\s]/g;function u(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}let h;const f=(()=>{let e="";for(let t=32;t<=126;t++)e+=String.fromCharCode(t);return e})();function g(e,t,n=f){return e.padEnd(t,n[0])}function p(e,t=f){const n=BigInt(t.length);var r;if(e<=n)return null!==(r=t[Number(e)-1])&&void 0!==r?r:"";let i=e/n,s=Number(e%n)-1;return s<0&&(i-=BigInt(Math.abs(s)),s=Number(n)-1),p(i,t)+t[s]}function m(e,t=f){const n=BigInt(t.length);let r=BigInt(0);for(let i=e.length-1,s=BigInt(0);i>=0;i--,s++){const o=e.charCodeAt(i)-t.charCodeAt(0);r+=BigInt(1+o)*n**s}return r}function y(e,t){return e<t?-1:e>t?1:0}t.DEFAULT_ALPHABET=f;const v=new Intl.Collator;function b(e){var t;return null!==(t=o.M_TIMESTAMP.findIn(e.getContent()))&&void 0!==t?t:-1}},9679:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.MatrixCall=t.CallType=t.CallState=t.CallParty=t.CallEvent=t.CallErrorCode=t.CallError=t.CallDirection=void 0,t.createNewMatrixCall=function(e,t,n){if(!S())return null;const r=!!n&&n.forceTURN,i={client:e,roomId:t,turnServers:e.getTurnServers(),forceTURN:e.forceTURN||r},s=new E(i);return e.reEmitter.reEmit(s,Object.values(y)),s},t.supportsMatrixCall=S;var i=r(n(8416)),s=n(7434),o=function(e,t){if(e&&e.__esModule)return e;if(null===e||"object"!=typeof e&&"function"!=typeof e)return{default:e};var n=h(t);if(n&&n.has(e))return n.get(e);var r={},i=Object.defineProperty&&Object.getOwnPropertyDescriptor;for(var s in e)if("default"!==s&&Object.prototype.hasOwnProperty.call(e,s)){var o=i?Object.getOwnPropertyDescriptor(e,s):null;o&&(o.get||o.set)?Object.defineProperty(r,s,o):r[s]=e[s]}return r.default=e,n&&n.set(e,r),r}(n(3102)),a=n(2481),c=n(8401),l=n(5964),d=n(9704),u=n(5861);function h(e){if("function"!=typeof WeakMap)return null;var t=new WeakMap,n=new WeakMap;return(h=function(e){return e?n:t})(e)}let f,g,p,m,y,v;t.CallState=f,function(e){e.Fledgling="fledgling",e.InviteSent="invite_sent",e.WaitLocalMedia="wait_local_media",e.CreateOffer="create_offer",e.CreateAnswer="create_answer",e.Connecting="connecting",e.Connected="connected",e.Ringing="ringing",e.Ended="ended"}(f||(t.CallState=f={})),t.CallType=g,function(e){e.Voice="voice",e.Video="video"}(g||(t.CallType=g={})),t.CallDirection=p,function(e){e.Inbound="inbound",e.Outbound="outbound"}(p||(t.CallDirection=p={})),t.CallParty=m,function(e){e.Local="local",e.Remote="remote"}(m||(t.CallParty=m={})),t.CallEvent=y,function(e){e.Hangup="hangup",e.State="state",e.Error="error",e.Replaced="replaced",e.LocalHoldUnhold="local_hold_unhold",e.RemoteHoldUnhold="remote_hold_unhold",e.HoldUnhold="hold_unhold",e.FeedsChanged="feeds_changed",e.AssertedIdentityChanged="asserted_identity_changed",e.LengthChanged="length_changed",e.DataChannel="datachannel"}(y||(t.CallEvent=y={})),t.CallErrorCode=v,function(e){e.UserHangup="user_hangup",e.LocalOfferFailed="local_offer_failed",e.NoUserMedia="no_user_media",e.UnknownDevices="unknown_devices",e.SendInvite="send_invite",e.CreateAnswer="create_answer",e.SendAnswer="send_answer",e.SetRemoteDescription="set_remote_description",e.SetLocalDescription="set_local_description",e.AnsweredElsewhere="answered_elsewhere",e.IceFailed="ice_failed",e.InviteTimeout="invite_timeout",e.Replaced="replaced",e.SignallingFailed="signalling_timeout",e.UserBusy="user_busy",e.Transfered="transferred"}(v||(t.CallErrorCode=v={}));class b extends Error{constructor(e,t,n){super(t+": "+n),(0,i.default)(this,"code",void 0),this.code=e}}function _(){return Date.now().toString()+(0,c.randomString)(16)}t.CallError=b;class E extends u.TypedEventEmitter{constructor(e){super(),(0,i.default)(this,"roomId",void 0),(0,i.default)(this,"callId",void 0),(0,i.default)(this,"state",f.Fledgling),(0,i.default)(this,"hangupParty",void 0),(0,i.default)(this,"hangupReason",void 0),(0,i.default)(this,"direction",void 0),(0,i.default)(this,"ourPartyId",void 0),(0,i.default)(this,"client",void 0),(0,i.default)(this,"forceTURN",void 0),(0,i.default)(this,"turnServers",void 0),(0,i.default)(this,"candidateSendQueue",[]),(0,i.default)(this,"candidateSendTries",0),(0,i.default)(this,"sentEndOfCandidates",!1),(0,i.default)(this,"peerConn",void 0),(0,i.default)(this,"feeds",[]),(0,i.default)(this,"usermediaSenders",[]),(0,i.default)(this,"screensharingSenders",[]),(0,i.default)(this,"inviteOrAnswerSent",!1),(0,i.default)(this,"waitForLocalAVStream",void 0),(0,i.default)(this,"successor",void 0),(0,i.default)(this,"opponentMember",void 0),(0,i.default)(this,"opponentVersion",void 0),(0,i.default)(this,"opponentPartyId",void 0),(0,i.default)(this,"opponentCaps",void 0),(0,i.default)(this,"inviteTimeout",void 0),(0,i.default)(this,"remoteOnHold",!1),(0,i.default)(this,"callStatsAtEnd",void 0),(0,i.default)(this,"makingOffer",!1),(0,i.default)(this,"ignoreOffer",void 0),(0,i.default)(this,"remoteCandidateBuffer",new Map),(0,i.default)(this,"remoteAssertedIdentity",void 0),(0,i.default)(this,"remoteSDPStreamMetadata",void 0),(0,i.default)(this,"callLengthInterval",void 0),(0,i.default)(this,"callLength",0),(0,i.default)(this,"gotLocalIceCandidate",(e=>{if(e.candidate){if(s.logger.debug("Call "+this.callId+" got local ICE "+e.candidate.sdpMid+" candidate: "+e.candidate.candidate),this.callHasEnded())return;""===e.candidate.candidate&&this.sentEndOfCandidates||(this.queueCandidate(e.candidate),""===e.candidate.candidate&&(this.sentEndOfCandidates=!0))}})),(0,i.default)(this,"onIceGatheringStateChange",(e=>{if(s.logger.debug("ice gathering state changed to "+this.peerConn.iceGatheringState),"complete"===this.peerConn.iceGatheringState&&!this.sentEndOfCandidates){const e={candidate:""};this.queueCandidate(e),this.sentEndOfCandidates=!0}})),(0,i.default)(this,"gotLocalOffer",(async e=>{if(s.logger.debug("Created offer: ",e),this.callHasEnded())return void s.logger.debug("Ignoring newly created offer on call ID "+this.callId+" because the call has ended");try{await this.peerConn.setLocalDescription(e)}catch(e){return s.logger.debug("Error setting local description!",e),void this.terminate(m.Local,v.SetLocalDescription,!0)}if("gathering"===this.peerConn.iceGatheringState&&await new Promise((e=>{setTimeout(e,200)})),this.callHasEnded())return;const t=this.state===f.CreateOffer?a.EventType.CallInvite:a.EventType.CallNegotiate,n={lifetime:6e4};this.state===f.CreateOffer?n.offer=this.peerConn.localDescription:n.description=this.peerConn.localDescription,n.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},n[l.SDPStreamMetadataKey]=this.getLocalSDPStreamMetadata(),s.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in offer`),this.candidateSendQueue=[];try{await this.sendVoipEvent(t,n)}catch(e){s.logger.error("Failed to send invite",e),e.event&&this.client.cancelPendingEvent(e.event);let t=v.SignallingFailed,n="Signalling failed";return this.state===f.CreateOffer&&(t=v.SendInvite,n="Failed to send invite"),"UnknownDeviceError"==e.name&&(t=v.UnknownDevices,n="Unknown devices present in the room"),this.emit(y.Error,new b(t,n,e)),void this.terminate(m.Local,t,!1)}this.sendCandidateQueue(),this.state===f.CreateOffer&&(this.inviteOrAnswerSent=!0,this.setState(f.InviteSent),this.inviteTimeout=setTimeout((()=>{this.inviteTimeout=null,this.state===f.InviteSent&&this.hangup(v.InviteTimeout,!1)}),6e4))})),(0,i.default)(this,"getLocalOfferFailed",(e=>{s.logger.error("Failed to get local offer",e),this.emit(y.Error,new b(v.LocalOfferFailed,"Failed to get local offer!",e)),this.terminate(m.Local,v.LocalOfferFailed,!1)})),(0,i.default)(this,"getUserMediaFailed",(e=>{this.successor?this.successor.getUserMediaFailed(e):(s.logger.warn("Failed to get user media - ending call",e),this.emit(y.Error,new b(v.NoUserMedia,"Couldn't start capturing media! Is your microphone set up and does this app have permission?",e)),this.terminate(m.Local,v.NoUserMedia,!1))})),(0,i.default)(this,"onIceConnectionStateChanged",(()=>{this.callHasEnded()||(s.logger.debug("Call ID "+this.callId+": ICE connection state changed to: "+this.peerConn.iceConnectionState),"connected"==this.peerConn.iceConnectionState?(this.setState(f.Connected),this.callLengthInterval||(this.callLengthInterval=setInterval((()=>{this.callLength++,this.emit(y.LengthChanged,this.callLength)}),1e3))):"failed"==this.peerConn.iceConnectionState&&this.hangup(v.IceFailed,!1))})),(0,i.default)(this,"onSignallingStateChanged",(()=>{s.logger.debug("call "+this.callId+": Signalling state changed to: "+this.peerConn.signalingState)})),(0,i.default)(this,"onTrack",(e=>{if(0===e.streams.length)return void s.logger.warn(`Streamless ${e.track.kind} found: ignoring.`);const t=e.streams[0];this.pushRemoteFeed(t),t.addEventListener("removetrack",(()=>{0===t.getTracks().length&&(s.logger.info(`Stream ID ${t.id} has no tracks remaining - removing`),this.deleteFeedByStream(t))}))})),(0,i.default)(this,"onDataChannel",(e=>{this.emit(y.DataChannel,e.channel)})),(0,i.default)(this,"onNegotiationNeeded",(async()=>{if(s.logger.info("Negotiation is needed!"),this.state===f.CreateOffer||0!==this.opponentVersion){this.makingOffer=!0;try{this.getRidOfRTXCodecs();const e=await this.peerConn.createOffer();await this.gotLocalOffer(e)}catch(e){return void this.getLocalOfferFailed(e)}finally{this.makingOffer=!1}}else s.logger.info("Opponent does not support renegotiation: ignoring negotiationneeded event")})),(0,i.default)(this,"onHangupReceived",(e=>{s.logger.debug("Hangup received for call ID "+this.callId),this.partyIdMatches(e)||this.state===f.Ringing?this.terminate(m.Remote,e.reason||v.UserHangup,!0):s.logger.info(`Ignoring message from party ID ${e.party_id}: our partner is ${this.opponentPartyId}`)})),(0,i.default)(this,"onRejectReceived",(e=>{s.logger.debug("Reject received for call ID "+this.callId),[f.InviteSent,f.Ringing].includes(this.state)||this.state===f.Fledgling&&this.direction===p.Inbound?this.terminate(m.Remote,e.reason||v.UserHangup,!0):s.logger.debug(`Call is in state: ${this.state}: ignoring reject`)})),(0,i.default)(this,"onAnsweredElsewhere",(e=>{s.logger.debug("Call ID "+this.callId+" answered elsewhere"),this.terminate(m.Remote,v.AnsweredElsewhere,!0)})),this.roomId=e.roomId,this.client=e.client,this.forceTURN=e.forceTURN,this.ourPartyId=this.client.deviceId,this.turnServers=e.turnServers||[],0===this.turnServers.length&&this.client.isFallbackICEServerAllowed()&&this.turnServers.push({urls:["stun:turn.matrix.org"]});for(const e of this.turnServers)o.checkObjectHasKeys(e,["urls"]);this.callId=_()}async placeVoiceCall(){await this.placeCall(!0,!1)}async placeVideoCall(){await this.placeCall(!0,!0)}createDataChannel(e,t){const n=this.peerConn.createDataChannel(e,t);return this.emit(y.DataChannel,n),s.logger.debug("created data channel"),n}getOpponentMember(){return this.opponentMember}opponentCanBeTransferred(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.transferee"])}opponentSupportsDTMF(){return Boolean(this.opponentCaps&&this.opponentCaps["m.call.dtmf"])}getRemoteAssertedIdentity(){return this.remoteAssertedIdentity}get type(){return this.hasLocalUserMediaVideoTrack||this.hasRemoteUserMediaVideoTrack?g.Video:g.Voice}get hasLocalUserMediaVideoTrack(){var e;return(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getVideoTracks().length)>0}get hasRemoteUserMediaVideoTrack(){return this.getRemoteFeeds().some((e=>e.purpose===l.SDPStreamMetadataPurpose.Usermedia&&e.stream.getVideoTracks().length>0))}get hasLocalUserMediaAudioTrack(){var e;return(null===(e=this.localUsermediaStream)||void 0===e?void 0:e.getAudioTracks().length)>0}get hasRemoteUserMediaAudioTrack(){return this.getRemoteFeeds().some((e=>e.purpose===l.SDPStreamMetadataPurpose.Usermedia&&e.stream.getAudioTracks().length>0))}get localUsermediaFeed(){return this.getLocalFeeds().find((e=>e.purpose===l.SDPStreamMetadataPurpose.Usermedia))}get localScreensharingFeed(){return this.getLocalFeeds().find((e=>e.purpose===l.SDPStreamMetadataPurpose.Screenshare))}get localUsermediaStream(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.stream}get localScreensharingStream(){var e;return null===(e=this.localScreensharingFeed)||void 0===e?void 0:e.stream}get remoteUsermediaFeed(){return this.getRemoteFeeds().find((e=>e.purpose===l.SDPStreamMetadataPurpose.Usermedia))}get remoteScreensharingFeed(){return this.getRemoteFeeds().find((e=>e.purpose===l.SDPStreamMetadataPurpose.Screenshare))}get remoteUsermediaStream(){var e;return null===(e=this.remoteUsermediaFeed)||void 0===e?void 0:e.stream}get remoteScreensharingStream(){var e;return null===(e=this.remoteScreensharingFeed)||void 0===e?void 0:e.stream}getFeedByStreamId(e){return this.getFeeds().find((t=>t.stream.id===e))}getFeeds(){return this.feeds}getLocalFeeds(){return this.feeds.filter((e=>e.isLocal()))}getRemoteFeeds(){return this.feeds.filter((e=>!e.isLocal()))}getLocalSDPStreamMetadata(){const e={};for(const t of this.getLocalFeeds())e[t.stream.id]={purpose:t.purpose,audio_muted:t.isAudioMuted(),video_muted:t.isVideoMuted()};return s.logger.debug("Got local SDPStreamMetadata",e),e}noIncomingFeeds(){return!this.feeds.some((e=>!e.isLocal()))}pushRemoteFeed(e){if(!this.opponentSupportsSDPStreamMetadata())return void this.pushRemoteFeedWithoutMetadata(e);const t=this.getOpponentMember().userId,n=this.remoteSDPStreamMetadata[e.id].purpose,r=this.remoteSDPStreamMetadata[e.id].audio_muted,i=this.remoteSDPStreamMetadata[e.id].video_muted;n?this.getFeedByStreamId(e.id)?s.logger.warn(`Ignoring stream with id ${e.id} because we already have a feed for it`):(this.feeds.push(new d.CallFeed({client:this.client,roomId:this.roomId,userId:t,stream:e,purpose:n,audioMuted:r,videoMuted:i})),this.emit(y.FeedsChanged,this.feeds),s.logger.info(`Pushed remote stream (id="${e.id}", active="${e.active}", purpose=${n})`)):s.logger.warn(`Ignoring stream with id ${e.id} because we didn't get any metadata about it`)}pushRemoteFeedWithoutMetadata(e){var t;const n=this.getOpponentMember().userId,r=l.SDPStreamMetadataPurpose.Usermedia,i=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;i&&e.id!==i.id?s.logger.warn(`Ignoring new stream ID ${e.id}: we already have stream ID ${i.id}`):this.getFeedByStreamId(e.id)?s.logger.warn(`Ignoring stream with id ${e.id} because we already have a feed for it`):(this.feeds.push(new d.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:n,stream:e,purpose:r})),this.emit(y.FeedsChanged,this.feeds),s.logger.info(`Pushed remote stream (id="${e.id}", active="${e.active}")`))}pushNewLocalFeed(e,t,n=!0){const r=this.client.getUserId();w(e.getAudioTracks(),!0),w(e.getVideoTracks(),!0),this.getFeedByStreamId(e.id)?s.logger.warn(`Ignoring stream with id ${e.id} because we already have a feed for it`):this.pushLocalFeed(new d.CallFeed({client:this.client,roomId:this.roomId,audioMuted:!1,videoMuted:!1,userId:r,stream:e,purpose:t}),n)}pushLocalFeed(e,t=!0){if(this.feeds.push(e),t){const t=e.purpose===l.SDPStreamMetadataPurpose.Usermedia?this.usermediaSenders:this.screensharingSenders;t.splice(0,t.length);for(const n of e.stream.getTracks())s.logger.info(`Adding track (id="${n.id}", kind="${n.kind}", streamId="${e.stream.id}", streamPurpose="${e.purpose}", enabled=${n.enabled}) to peer connection`),t.push(this.peerConn.addTrack(n,e.stream))}s.logger.info(`Pushed local stream (id="${e.stream.id}", active="${e.stream.active}", purpose="${e.purpose}")`),this.emit(y.FeedsChanged,this.feeds)}removeLocalFeed(e){const t=e.purpose===l.SDPStreamMetadataPurpose.Usermedia?this.usermediaSenders:this.screensharingSenders;for(const e of t)this.peerConn.removeTrack(e);t.splice(0,t.length),this.deleteFeedByStream(e.stream)}deleteAllFeeds(){for(const e of this.feeds)e.dispose();this.feeds=[],this.emit(y.FeedsChanged,this.feeds)}deleteFeedByStream(e){s.logger.debug(`Removing feed with stream id ${e.id}`);const t=this.getFeedByStreamId(e.id);t?(t.dispose(),this.feeds.splice(this.feeds.indexOf(t),1),this.emit(y.FeedsChanged,this.feeds)):s.logger.warn(`Didn't find the feed with stream id ${e.id} to delete`)}async getCurrentCallStats(){return this.callHasEnded()?this.callStatsAtEnd:this.collectCallStats()}async collectCallStats(){if(!this.peerConn)return;const e=await this.peerConn.getStats(),t=[];return e.forEach((e=>{t.push(e)})),t}async initWithInvite(e){var t;const n=e.getContent();this.direction=p.Inbound,await this.client.checkTurnServers()||s.logger.warn("Failed to get TURN credentials! Proceeding with call anyway...");const r=n[l.SDPStreamMetadataKey];r?this.updateRemoteSDPStreamMetadata(r):s.logger.debug("Did not get any SDPStreamMetadata! Can not send/receive multiple streams"),this.peerConn=this.createPeerConnection(),this.chooseOpponent(e);try{await this.peerConn.setRemoteDescription(n.offer),await this.addBufferedIceCandidates()}catch(e){return s.logger.debug("Failed to set remote description",e),void this.terminate(m.Local,v.SetRemoteDescription,!1)}const i=null===(t=this.feeds.find((e=>!e.isLocal())))||void 0===t?void 0:t.stream;if(!i||0===i.getTracks().length)return s.logger.error("No remote stream or no tracks after setting remote description!"),void this.terminate(m.Local,v.SetRemoteDescription,!1);this.setState(f.Ringing),e.getLocalAge()&&setTimeout((()=>{this.state==f.Ringing&&(s.logger.debug("Call invite has expired. Hanging up."),this.hangupParty=m.Remote,this.setState(f.Ended),this.stopAllMedia(),"closed"!=this.peerConn.signalingState&&this.peerConn.close(),this.emit(y.Hangup))}),n.lifetime-e.getLocalAge())}initWithHangup(e){this.setState(f.Ended)}shouldAnswerWithMediaType(e,t,n){return e&&!t?(s.logger.warn(`Unable to answer with ${n} because the other side isn't sending it either.`),!1):o.isNullOrUndefined(e)||e===t||this.opponentSupportsSDPStreamMetadata()?null!=e?e:t:(s.logger.warn(`Unable to answer with ${n}=${e} because the other side doesn't support it. Answering with ${n}=${t}.`),t)}async answer(e,t){if(!this.inviteOrAnswerSent){if(!1===e&&!1===t)throw new Error("You CANNOT answer a call without media");if(s.logger.debug(`Answering call ${this.callId}`),this.localUsermediaStream||this.waitForLocalAVStream)this.waitForLocalAVStream&&this.setState(f.WaitLocalMedia);else{const n=this.state,r=this.shouldAnswerWithMediaType(e,this.hasRemoteUserMediaAudioTrack,"audio"),i=this.shouldAnswerWithMediaType(t,this.hasRemoteUserMediaVideoTrack,"video");this.setState(f.WaitLocalMedia),this.waitForLocalAVStream=!0;try{const e=await this.client.getMediaHandler().getUserMediaStream(r,i);this.waitForLocalAVStream=!1;const t=[new d.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),stream:e,purpose:l.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1})];this.localScreensharingFeed&&t.push(this.localScreensharingFeed),this.answerWithCallFeeds(t)}catch(e){if(!i)return void this.getUserMediaFailed(e);s.logger.warn("Failed to getUserMedia(), trying to getUserMedia() without video"),this.setState(n),this.waitForLocalAVStream=!1,await this.answer(r,!1)}}}}answerWithCallFeeds(e){this.inviteOrAnswerSent||this.gotCallFeedsForAnswer(e)}replacedBy(e){this.state===f.WaitLocalMedia?(s.logger.debug("Telling new call to wait for local media"),e.waitForLocalAVStream=!0):[f.CreateOffer,f.InviteSent].includes(this.state)&&(s.logger.debug("Handing local stream to new call"),e.gotCallFeedsForAnswer(this.getLocalFeeds())),this.successor=e,this.emit(y.Replaced,e),this.hangup(v.Replaced,!0)}hangup(e,t){if(this.callHasEnded())return;if(s.logger.debug("Ending call "+this.callId),this.terminate(m.Local,e,!t),this.state===f.WaitLocalMedia)return;const n={};(this.opponentVersion&&0!==this.opponentVersion||e!==v.UserHangup)&&(n.reason=e),this.sendVoipEvent(a.EventType.CallHangup,n)}reject(){if(this.state!==f.Ringing)throw Error("Call must be in 'ringing' state to reject!");if(0===this.opponentVersion)return s.logger.info(`Opponent version is less than 1 (${this.opponentVersion}): sending hangup instead of reject`),void this.hangup(v.UserHangup,!0);s.logger.debug("Rejecting call: "+this.callId),this.terminate(m.Local,v.UserHangup,!0),this.sendVoipEvent(a.EventType.CallReject,{})}async upgradeCall(e,t){if((e||t)&&this.opponentSupportsSDPStreamMetadata())try{const n=e||this.hasLocalUserMediaAudioTrack,r=t||this.hasLocalUserMediaVideoTrack,i=await this.client.getMediaHandler().getUserMediaStream(n,r,!1);await this.updateLocalUsermediaStream(i,e,t)}catch(e){s.logger.error("Failed to upgrade the call",e),this.emit(y.Error,new b(v.NoUserMedia,"Failed to get camera access: ",e))}}opponentSupportsSDPStreamMetadata(){return Boolean(this.remoteSDPStreamMetadata)}isScreensharing(){return Boolean(this.localScreensharingStream)}async setScreensharingEnabled(e,t){if(e&&this.isScreensharing())return s.logger.warn("There is already a screensharing stream - there is nothing to do!"),!0;if(!e&&!this.isScreensharing())return s.logger.warn("There already isn't a screensharing stream - there is nothing to do!"),!1;if(!this.opponentSupportsSDPStreamMetadata())return this.setScreensharingEnabledWithoutMetadataSupport(e,t);if(s.logger.debug(`Set screensharing enabled? ${e}`),!e){for(const e of this.screensharingSenders)this.peerConn.removeTrack(e);return this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=await this.client.getMediaHandler().getScreensharingStream(t);return!!e&&(this.pushNewLocalFeed(e,l.SDPStreamMetadataPurpose.Screenshare),!0)}catch(e){return s.logger.error("Failed to get screen-sharing stream:",e),!1}}async setScreensharingEnabledWithoutMetadataSupport(e,t){if(s.logger.debug(`Set screensharing enabled? ${e} using replaceTrack()`),!e){const e=this.localUsermediaStream.getTracks().find((e=>"video"===e.kind));return this.usermediaSenders.find((e=>{var t;return"video"===(null===(t=e.track)||void 0===t?void 0:t.kind)})).replaceTrack(e),this.client.getMediaHandler().stopScreensharingStream(this.localScreensharingStream),this.deleteFeedByStream(this.localScreensharingStream),!1}try{const e=await this.client.getMediaHandler().getScreensharingStream(t);if(!e)return!1;const n=e.getTracks().find((e=>"video"===e.kind));return this.usermediaSenders.find((e=>{var t;return"video"===(null===(t=e.track)||void 0===t?void 0:t.kind)})).replaceTrack(n),this.pushNewLocalFeed(e,l.SDPStreamMetadataPurpose.Screenshare,!1),!0}catch(e){return s.logger.error("Failed to get screen-sharing stream:",e),!1}}async updateLocalUsermediaStream(e,t=!1,n=!1){const r=this.localUsermediaFeed,i=t||!r.isAudioMuted()&&!this.remoteOnHold,o=n||!r.isVideoMuted()&&!this.remoteOnHold;w(e.getAudioTracks(),i),w(e.getVideoTracks(),o);for(const e of this.localUsermediaStream.getTracks())this.localUsermediaStream.removeTrack(e),e.stop();for(const t of e.getTracks())this.localUsermediaStream.addTrack(t);const a=[];for(const t of e.getTracks()){const n=this.usermediaSenders.find((e=>{var n;return(null===(n=e.track)||void 0===n?void 0:n.kind)===t.kind}));let i;n?(s.logger.info(`Replacing track (id="${t.id}", kind="${t.kind}", streamId="${e.id}", streamPurpose="${r.purpose}") to peer connection`),await n.replaceTrack(t),i=n):(s.logger.info(`Adding track (id="${t.id}", kind="${t.kind}", streamId="${e.id}", streamPurpose="${r.purpose}") to peer connection`),i=this.peerConn.addTrack(t,this.localUsermediaStream)),a.push(i)}this.usermediaSenders=a}async setLocalVideoMuted(e){var t;return await this.client.getMediaHandler().hasVideoDevice()?this.hasLocalUserMediaVideoTrack||e?(null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(null,e),this.updateMuteStatus(),this.isLocalVideoMuted()):(await this.upgradeCall(!1,!0),this.isLocalVideoMuted()):this.isLocalVideoMuted()}isLocalVideoMuted(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isVideoMuted()}async setMicrophoneMuted(e){var t;return await this.client.getMediaHandler().hasAudioDevice()?this.hasLocalUserMediaAudioTrack||e?(null===(t=this.localUsermediaFeed)||void 0===t||t.setAudioVideoMuted(e,null),this.updateMuteStatus(),this.isMicrophoneMuted()):(await this.upgradeCall(!0,!1),this.isMicrophoneMuted()):this.isMicrophoneMuted()}isMicrophoneMuted(){var e;return null===(e=this.localUsermediaFeed)||void 0===e?void 0:e.isAudioMuted()}isRemoteOnHold(){return this.remoteOnHold}setRemoteOnHold(e){if(this.isRemoteOnHold()!==e){this.remoteOnHold=e;for(const t of this.peerConn.getTransceivers())t.direction=e?"sendonly":"sendrecv";this.updateMuteStatus(),this.emit(y.RemoteHoldUnhold,this.remoteOnHold)}}isLocalOnHold(){if(this.state!==f.Connected)return!1;let e=!0;for(const t of this.peerConn.getTransceivers())["inactive","recvonly"].includes(t.currentDirection)||(e=!1);return e}sendDtmfDigit(e){for(const t of this.peerConn.getSenders())if("audio"===t.track.kind&&t.dtmf)return void t.dtmf.insertDTMF(e);throw new Error("Unable to find a track to send DTMF on")}updateMuteStatus(){this.sendVoipEvent(a.EventType.CallSDPStreamMetadataChangedPrefix,{[l.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()});const e=this.isMicrophoneMuted()||this.remoteOnHold,t=this.isLocalVideoMuted()||this.remoteOnHold;w(this.localUsermediaStream.getAudioTracks(),!e),w(this.localUsermediaStream.getVideoTracks(),!t)}gotCallFeedsForInvite(e){if(this.successor)this.successor.gotCallFeedsForAnswer(e);else if(this.callHasEnded())this.stopAllMedia();else{for(const t of e)this.pushLocalFeed(t);this.setState(f.CreateOffer),s.logger.debug("gotUserMediaForInvite")}}async sendAnswer(){const e={answer:{sdp:this.peerConn.localDescription.sdp,type:this.peerConn.localDescription.type},[l.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()};e.capabilities={"m.call.transferee":this.client.supportsCallTransfer,"m.call.dtmf":!1},s.logger.info(`Discarding ${this.candidateSendQueue.length} candidates that will be sent in answer`),this.candidateSendQueue=[];try{await this.sendVoipEvent(a.EventType.CallAnswer,e),this.inviteOrAnswerSent=!0}catch(e){this.setState(f.Ringing),this.client.cancelPendingEvent(e.event);let t=v.SendAnswer,n="Failed to send answer";throw"UnknownDeviceError"==e.name&&(t=v.UnknownDevices,n="Unknown devices present in the room"),this.emit(y.Error,new b(t,n,e)),e}this.sendCandidateQueue()}async gotCallFeedsForAnswer(e){if(this.callHasEnded())return;this.waitForLocalAVStream=!1;for(const t of e)this.pushLocalFeed(t);let t;this.setState(f.CreateAnswer);try{this.getRidOfRTXCodecs(),t=await this.peerConn.createAnswer()}catch(e){return s.logger.debug("Failed to create answer: ",e),void this.terminate(m.Local,v.CreateAnswer,!0)}try{await this.peerConn.setLocalDescription(t),this.setState(f.Connecting),await new Promise((e=>{setTimeout(e,200)})),this.sendAnswer()}catch(e){return s.logger.debug("Error setting local description!",e),void this.terminate(m.Local,v.SetLocalDescription,!0)}}async onRemoteIceCandidatesReceived(e){if(this.callHasEnded())return;const t=e.getContent(),n=t.candidates;if(!n)return void s.logger.info("Ignoring candidates event with no candidates!");const r=0===t.version?null:t.party_id||null;if(void 0===this.opponentPartyId){s.logger.info(`Buffering ${n.length} candidates until we pick an opponent`);const e=this.remoteCandidateBuffer.get(r)||[];return e.push(...n),void this.remoteCandidateBuffer.set(r,e)}this.partyIdMatches(t)?await this.addIceCandidates(n):s.logger.info(`Ignoring candidates from party ID ${t.party_id}: we have chosen party ID ${this.opponentPartyId}`)}async onAnswerReceived(e){const t=e.getContent();if(s.logger.debug(`Got answer for call ID ${this.callId} from party ID ${t.party_id}`),this.callHasEnded())return void s.logger.debug(`Ignoring answer because call ID ${this.callId} has ended`);if(void 0!==this.opponentPartyId)return void s.logger.info(`Ignoring answer from party ID ${t.party_id}: we already have an answer/reject from ${this.opponentPartyId}`);this.chooseOpponent(e),await this.addBufferedIceCandidates(),this.setState(f.Connecting);const n=t[l.SDPStreamMetadataKey];n?this.updateRemoteSDPStreamMetadata(n):s.logger.warn("Did not get any SDPStreamMetadata! Can not send/receive multiple streams");try{await this.peerConn.setRemoteDescription(t.answer)}catch(e){return s.logger.debug("Failed to set remote description",e),void this.terminate(m.Local,v.SetRemoteDescription,!1)}if(null!==this.opponentPartyId)try{await this.sendVoipEvent(a.EventType.CallSelectAnswer,{selected_party_id:this.opponentPartyId})}catch(e){s.logger.warn("Failed to send select_answer event",e)}}async onSelectAnswerReceived(e){if(this.direction!==p.Inbound)return void s.logger.warn("Got select_answer for an outbound call: ignoring");const t=e.getContent().selected_party_id;null!=t?t!==this.ourPartyId&&(s.logger.info(`Got select_answer for party ID ${t}: we are party ID ${this.ourPartyId}.`),await this.terminate(m.Remote,v.AnsweredElsewhere,!0)):s.logger.warn("Got nonsensical select_answer with null/undefined selected_party_id: ignoring")}async onNegotiateReceived(e){const t=e.getContent(),n=t.description;if(!n||!n.sdp||!n.type)return void s.logger.info("Ignoring invalid m.call.negotiate event");const r=this.direction===p.Inbound,i="offer"===n.type&&(this.makingOffer||"stable"!==this.peerConn.signalingState);if(this.ignoreOffer=!r&&i,this.ignoreOffer)return void s.logger.info("Ignoring colliding negotiate event because we're impolite");const o=this.isLocalOnHold(),c=t[l.SDPStreamMetadataKey];c?this.updateRemoteSDPStreamMetadata(c):s.logger.warn("Received negotiation event without SDPStreamMetadata!");try{if(await this.peerConn.setRemoteDescription(n),"offer"===n.type){this.getRidOfRTXCodecs();const e=await this.peerConn.createAnswer();await this.peerConn.setLocalDescription(e),this.sendVoipEvent(a.EventType.CallNegotiate,{description:this.peerConn.localDescription,[l.SDPStreamMetadataKey]:this.getLocalSDPStreamMetadata()})}}catch(e){s.logger.warn("Failed to complete negotiation",e)}const d=this.isLocalOnHold();o!==d&&(this.emit(y.LocalHoldUnhold,d),this.emit(y.HoldUnhold,d))}updateRemoteSDPStreamMetadata(e){this.remoteSDPStreamMetadata=o.recursivelyAssign(this.remoteSDPStreamMetadata||{},e,!0);for(const e of this.getRemoteFeeds()){var t;const n=e.stream.id,r=this.remoteSDPStreamMetadata[n];e.setAudioVideoMuted(null==r?void 0:r.audio_muted,null==r?void 0:r.video_muted),e.purpose=null===(t=this.remoteSDPStreamMetadata[n])||void 0===t?void 0:t.purpose}}onSDPStreamMetadataChangedReceived(e){const t=e.getContent()[l.SDPStreamMetadataKey];this.updateRemoteSDPStreamMetadata(t)}async onAssertedIdentityReceived(e){const t=e.getContent();t.asserted_identity&&(this.remoteAssertedIdentity={id:t.asserted_identity.id,displayName:t.asserted_identity.display_name},this.emit(y.AssertedIdentityChanged))}callHasEnded(){return this.state===f.Ended}getRidOfRTXCodecs(){if(!RTCRtpReceiver.getCapabilities||!RTCRtpSender.getCapabilities)return;const e=RTCRtpReceiver.getCapabilities("video").codecs,t=[...RTCRtpSender.getCapabilities("video").codecs,...e];for(const e of t)if("video/rtx"===e.mimeType){const n=t.indexOf(e);t.splice(n,1)}for(const e of this.peerConn.getTransceivers()){var n,r;!this.screensharingSenders.includes(e.sender)||"video"!==(null===(n=e.sender.track)||void 0===n?void 0:n.kind)&&"video"!==(null===(r=e.receiver.track)||void 0===r?void 0:r.kind)||e.setCodecPreferences(t)}}setState(e){const t=this.state;this.state=e,this.emit(y.State,e,t)}sendVoipEvent(e,t){return this.client.sendEvent(this.roomId,e,Object.assign({},t,{version:"1",call_id:this.callId,party_id:this.ourPartyId}))}queueCandidate(e){if(this.candidateSendQueue.push(e),this.state===f.Ringing||!this.inviteOrAnswerSent)return;const t=this.direction===p.Inbound?500:2e3;0===this.candidateSendTries&&setTimeout((()=>{this.sendCandidateQueue()}),t)}async transfer(e){const t=await this.client.getProfileInfo(e),n=_(),r={replacement_id:_(),target_user:{id:e,display_name:t.displayname,avatar_url:t.avatar_url},create_call:n};await this.sendVoipEvent(a.EventType.CallReplaces,r),await this.terminate(m.Local,v.Transfered,!0)}async transferToCall(e){const t=await this.client.getProfileInfo(e.getOpponentMember().userId),n=await this.client.getProfileInfo(this.getOpponentMember().userId),r=_(),i={replacement_id:_(),target_user:{id:this.getOpponentMember().userId,display_name:n.displayname,avatar_url:n.avatar_url},await_call:r};await e.sendVoipEvent(a.EventType.CallReplaces,i);const s={replacement_id:_(),target_user:{id:e.getOpponentMember().userId,display_name:t.displayname,avatar_url:t.avatar_url},create_call:r};await this.sendVoipEvent(a.EventType.CallReplaces,s),await this.terminate(m.Local,v.Transfered,!0),await e.terminate(m.Local,v.Transfered,!0)}async terminate(e,t,n){this.callHasEnded()||(this.callStatsAtEnd=await this.collectCallStats(),this.inviteTimeout&&(clearTimeout(this.inviteTimeout),this.inviteTimeout=null),this.callLengthInterval&&(clearInterval(this.callLengthInterval),this.callLengthInterval=null),t!==v.Replaced&&this.stopAllMedia(),this.deleteAllFeeds(),this.hangupParty=e,this.hangupReason=t,this.setState(f.Ended),this.peerConn&&"closed"!==this.peerConn.signalingState&&this.peerConn.close(),n&&this.emit(y.Hangup))}stopAllMedia(){s.logger.debug("Stopping all media for call",this.callId);for(const e of this.feeds)if(e.isLocal()&&e.purpose===l.SDPStreamMetadataPurpose.Usermedia)this.client.getMediaHandler().stopUserMediaStream(e.stream);else if(e.isLocal()&&e.purpose===l.SDPStreamMetadataPurpose.Screenshare)this.client.getMediaHandler().stopScreensharingStream(e.stream);else{s.logger.debug("Stopping remote stream",e.stream.id);for(const t of e.stream.getTracks())t.stop()}}checkForErrorListener(){if(0===this.listeners(u.EventEmitterEvents.Error).length)throw new Error("You MUST attach an error listener using call.on('error', function() {})")}async sendCandidateQueue(){if(0===this.candidateSendQueue.length)return;const e=this.candidateSendQueue;this.candidateSendQueue=[],++this.candidateSendTries;const t={candidates:e};s.logger.debug("Attempting to send "+e.length+" candidates");try{await this.sendVoipEvent(a.EventType.CallCandidates,t),this.candidateSendTries=0}catch(t){if(t.event&&this.client.cancelPendingEvent(t.event),this.candidateSendQueue.push(...e),this.candidateSendTries>5){s.logger.debug("Failed to send candidates on attempt "+this.candidateSendTries+". Giving up on this call.",t);const e=v.SignallingFailed,n="Signalling failed";return this.emit(y.Error,new b(e,n,t)),void this.hangup(e,!1)}const n=500*Math.pow(2,this.candidateSendTries);++this.candidateSendTries,s.logger.debug("Failed to send candidates. Retrying in "+n+"ms",t),setTimeout((()=>{this.sendCandidateQueue()}),n)}}async placeCall(e,t){if(!e)throw new Error("You CANNOT start a call without audio");this.setState(f.WaitLocalMedia);try{const n=await this.client.getMediaHandler().getUserMediaStream(e,t);w(n.getAudioTracks(),!0),w(n.getVideoTracks(),!0);const r=new d.CallFeed({client:this.client,roomId:this.roomId,userId:this.client.getUserId(),stream:n,purpose:l.SDPStreamMetadataPurpose.Usermedia,audioMuted:!1,videoMuted:!1});await this.placeCallWithCallFeeds([r])}catch(e){return void this.getUserMediaFailed(e)}}async placeCallWithCallFeeds(e){this.checkForErrorListener(),this.direction=p.Outbound,this.client.callEventHandler.calls.set(this.callId,this),await this.client.checkTurnServers()||s.logger.warn("Failed to get TURN credentials! Proceeding with call anyway..."),this.peerConn=this.createPeerConnection(),this.gotCallFeedsForInvite(e)}createPeerConnection(){const e=new window.RTCPeerConnection({iceTransportPolicy:this.forceTURN?"relay":void 0,iceServers:this.turnServers,iceCandidatePoolSize:this.client.iceCandidatePoolSize});return e.addEventListener("iceconnectionstatechange",this.onIceConnectionStateChanged),e.addEventListener("signalingstatechange",this.onSignallingStateChanged),e.addEventListener("icecandidate",this.gotLocalIceCandidate),e.addEventListener("icegatheringstatechange",this.onIceGatheringStateChange),e.addEventListener("track",this.onTrack),e.addEventListener("negotiationneeded",this.onNegotiationNeeded),e.addEventListener("datachannel",this.onDataChannel),e}partyIdMatches(e){return(0===e.version?null:e.party_id||null)===this.opponentPartyId}chooseOpponent(e){const t=e.getContent();s.logger.debug(`Choosing party ID ${t.party_id} for call ID ${this.callId}`),this.opponentVersion=t.version,0===this.opponentVersion?this.opponentPartyId=null:this.opponentPartyId=t.party_id||null,this.opponentCaps=t.capabilities||{},this.opponentMember=e.sender}async addBufferedIceCandidates(){const e=this.remoteCandidateBuffer.get(this.opponentPartyId);e&&(s.logger.info(`Adding ${e.length} buffered candidates for opponent ${this.opponentPartyId}`),await this.addIceCandidates(e)),this.remoteCandidateBuffer=null}async addIceCandidates(e){for(const t of e)if(null!==t.sdpMid&&void 0!==t.sdpMid||null!==t.sdpMLineIndex&&void 0!==t.sdpMLineIndex){s.logger.debug("Call "+this.callId+" got remote ICE "+t.sdpMid+" candidate: "+t.candidate);try{await this.peerConn.addIceCandidate(t)}catch(e){this.ignoreOffer||s.logger.info("Failed to add remote ICE candidate",e)}}else s.logger.debug("Ignoring remote ICE candidate with no sdpMid or sdpMLineIndex")}get hasPeerConnection(){return Boolean(this.peerConn)}}function w(e,t){for(let n=0;n<e.length;n++)e[n].enabled=t}function S(){if("undefined"==typeof window||"undefined"==typeof document)return!1;try{if(!Boolean(window.RTCPeerConnection||window.RTCSessionDescription||window.RTCIceCandidate||navigator.mediaDevices))return s.logger.error("WebRTC is not supported in this browser / environment"),!1}catch(e){return s.logger.error("Exception thrown when trying to access WebRTC",e),!1}return!0}t.MatrixCall=E},2931:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.CallEventHandlerEvent=t.CallEventHandler=void 0;var i=r(n(8416)),s=n(4369),o=n(7434),a=n(9679),c=n(2481),l=n(2168),d=n(4551),u=n(7366);let h;t.CallEventHandlerEvent=h,function(e){e.Incoming="Call.incoming"}(h||(t.CallEventHandlerEvent=h={})),t.CallEventHandler=class{constructor(e){(0,i.default)(this,"client",void 0),(0,i.default)(this,"calls",void 0),(0,i.default)(this,"callEventBuffer",void 0),(0,i.default)(this,"candidateEventsByCall",void 0),(0,i.default)(this,"evaluateEventBuffer",(async()=>{if(this.client.getSyncState()===d.SyncState.Syncing){await Promise.all(this.callEventBuffer.map((e=>{this.client.decryptEventIfNeeded(e)})));const e=new Set;for(const t of this.callEventBuffer)t.getType()!==c.EventType.CallAnswer&&t.getType()!==c.EventType.CallHangup||e.add(t.getContent().call_id);for(const t of this.callEventBuffer)if(t.getType()!==c.EventType.CallInvite||!e.has(t.getContent().call_id))try{await this.handleCallEvent(t)}catch(e){o.logger.error("Caught exception handling call event",e)}this.callEventBuffer=[]}})),(0,i.default)(this,"onRoomTimeline",(e=>{this.client.decryptEventIfNeeded(e),(this.eventIsACall(e)||e.isBeingDecrypted())&&this.callEventBuffer.push(e),(e.isBeingDecrypted()||e.isDecryptionFailure())&&e.once(s.MatrixEventEvent.Decrypted,(async()=>{if(this.eventIsACall(e))if(this.callEventBuffer.includes(e))this.evaluateEventBuffer();else try{await this.handleCallEvent(e)}catch(e){o.logger.error("Caught exception handling call event",e)}}))})),this.client=e,this.calls=new Map,this.callEventBuffer=[],this.candidateEventsByCall=new Map}start(){this.client.on(l.ClientEvent.Sync,this.evaluateEventBuffer),this.client.on(u.RoomEvent.Timeline,this.onRoomTimeline)}stop(){this.client.removeListener(l.ClientEvent.Sync,this.evaluateEventBuffer),this.client.removeListener(u.RoomEvent.Timeline,this.onRoomTimeline)}eventIsACall(e){const t=e.getType();return t.startsWith("m.call.")||t.startsWith("org.matrix.call.")}async handleCallEvent(e){const t=e.getContent(),n=e.getType(),r=e.getSender()===this.client.credentials.userId;let i=t.call_id?this.calls.get(t.call_id):void 0;if(n!==c.EventType.CallInvite)if(n!==c.EventType.CallCandidates)if([c.EventType.CallHangup,c.EventType.CallReject].includes(n))i?i.state!==a.CallState.Ended&&(n===c.EventType.CallHangup?i.onHangupReceived(t):i.onRejectReceived(t),i.state===a.CallState.Ended&&this.calls.delete(t.call_id)):(i=(0,a.createNewMatrixCall)(this.client,e.getRoomId()),i&&(i.callId=t.call_id,i.initWithHangup(e),this.calls.set(t.call_id,i)));else if(i&&i.hasPeerConnection){if(e.getContent().party_id!==i.ourPartyId)switch(n){case c.EventType.CallAnswer:r?i.state===a.CallState.Ringing&&i.onAnsweredElsewhere(t):i.onAnswerReceived(e);break;case c.EventType.CallSelectAnswer:i.onSelectAnswerReceived(e);break;case c.EventType.CallNegotiate:i.onNegotiateReceived(e);break;case c.EventType.CallAssertedIdentity:case c.EventType.CallAssertedIdentityPrefix:i.onAssertedIdentityReceived(e);break;case c.EventType.CallSDPStreamMetadataChanged:case c.EventType.CallSDPStreamMetadataChangedPrefix:i.onSDPStreamMetadataChangedReceived(e)}}else o.logger.info(`Discarding possible call event ${e.getId()} as we don't have a call/peerConn`,n);else{if(r)return;i?i.onRemoteIceCandidatesReceived(e):(this.candidateEventsByCall.has(t.call_id)||this.candidateEventsByCall.set(t.call_id,[]),this.candidateEventsByCall.get(t.call_id).push(e))}else{if(r)return;if(e.getLocalAge()>t.lifetime-3e3)return;if(i&&i.state===a.CallState.Ended)return;i&&o.logger.log(`WARN: Already have a MatrixCall with id ${t.call_id} but got an invite. Clobbering.`);const n=this.client.getTurnServersExpiry()-Date.now();if(o.logger.info("Current turn creds expire in "+n+" ms"),i=(0,a.createNewMatrixCall)(this.client,e.getRoomId(),{forceTURN:this.client.forceTURN}),!i)return void o.logger.log("Incoming call ID "+t.call_id+" but this client doesn't support WebRTC");if(i.callId=t.call_id,await i.initWithInvite(e),this.calls.set(i.callId,i),this.candidateEventsByCall.get(i.callId))for(const e of this.candidateEventsByCall.get(i.callId))i.onRemoteIceCandidatesReceived(e);let s;for(const e of this.calls.values()){const t=[a.CallState.WaitLocalMedia,a.CallState.CreateOffer,a.CallState.InviteSent].includes(e.state);if(i.roomId===e.roomId&&e.direction===a.CallDirection.Outbound&&t){s=e;break}}s?s.state===a.CallState.WaitLocalMedia||s.state===a.CallState.CreateOffer||s.callId>i.callId?(o.logger.log("Glare detected: answering incoming call "+i.callId+" and canceling outgoing call "+s.callId),s.replacedBy(i),i.answer()):(o.logger.log("Glare detected: rejecting incoming call "+i.callId+" and keeping outgoing call "+s.callId),i.hangup(a.CallErrorCode.Replaced,!0)):this.client.emit(h.Incoming,i)}}}},5964:(e,t)=>{"use strict";let n;Object.defineProperty(t,"__esModule",{value:!0}),t.SDPStreamMetadataPurpose=t.SDPStreamMetadataKey=void 0,t.SDPStreamMetadataKey="org.matrix.msc3077.sdp_stream_metadata",t.SDPStreamMetadataPurpose=n,function(e){e.Usermedia="m.usermedia",e.Screenshare="m.screenshare"}(n||(t.SDPStreamMetadataPurpose=n={}))},9704:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.SPEAKING_THRESHOLD=t.CallFeedEvent=t.CallFeed=void 0;var i=r(n(8416)),s=n(5861);let o;t.SPEAKING_THRESHOLD=-60,t.CallFeedEvent=o,function(e){e.NewStream="new_stream",e.MuteStateChanged="mute_state_changed",e.VolumeChanged="volume_changed",e.Speaking="speaking"}(o||(t.CallFeedEvent=o={}));class a extends s.TypedEventEmitter{constructor(e){super(),(0,i.default)(this,"stream",void 0),(0,i.default)(this,"userId",void 0),(0,i.default)(this,"purpose",void 0),(0,i.default)(this,"speakingVolumeSamples",void 0),(0,i.default)(this,"client",void 0),(0,i.default)(this,"roomId",void 0),(0,i.default)(this,"audioMuted",void 0),(0,i.default)(this,"videoMuted",void 0),(0,i.default)(this,"measuringVolumeActivity",!1),(0,i.default)(this,"audioContext",void 0),(0,i.default)(this,"analyser",void 0),(0,i.default)(this,"frequencyBinCount",void 0),(0,i.default)(this,"speakingThreshold",-60),(0,i.default)(this,"speaking",!1),(0,i.default)(this,"volumeLooperTimeout",void 0),(0,i.default)(this,"onAddTrack",(()=>{this.emit(o.NewStream,this.stream)})),(0,i.default)(this,"volumeLooper",(()=>{if(!this.analyser)return;if(!this.measuringVolumeActivity)return;this.analyser.getFloatFrequencyData(this.frequencyBinCount);let e=-1/0;for(let t=0;t<this.frequencyBinCount.length;t++)this.frequencyBinCount[t]>e&&(e=this.frequencyBinCount[t]);this.speakingVolumeSamples.shift(),this.speakingVolumeSamples.push(e),this.emit(o.VolumeChanged,e);let t=!1;for(let e=0;e<this.speakingVolumeSamples.length;e++)if(this.speakingVolumeSamples[e]>this.speakingThreshold){t=!0;break}this.speaking!==t&&(this.speaking=t,this.emit(o.Speaking,this.speaking)),this.volumeLooperTimeout=setTimeout(this.volumeLooper,200)})),this.client=e.client,this.roomId=e.roomId,this.userId=e.userId,this.purpose=e.purpose,this.audioMuted=e.audioMuted,this.videoMuted=e.videoMuted,this.speakingVolumeSamples=new Array(8).fill(-1/0),this.updateStream(null,e.stream),this.hasAudioTrack&&this.initVolumeMeasuring()}get hasAudioTrack(){return this.stream.getAudioTracks().length>0}updateStream(e,t){t!==e&&(e&&(e.removeEventListener("addtrack",this.onAddTrack),this.measureVolumeActivity(!1)),t&&(this.stream=t,t.addEventListener("addtrack",this.onAddTrack),this.hasAudioTrack?this.initVolumeMeasuring():this.measureVolumeActivity(!1)),this.emit(o.NewStream,this.stream))}initVolumeMeasuring(){const e=window.AudioContext||window.webkitAudioContext;this.hasAudioTrack&&e&&(this.audioContext=new e,this.analyser=this.audioContext.createAnalyser(),this.analyser.fftSize=512,this.analyser.smoothingTimeConstant=.1,this.audioContext.createMediaStreamSource(this.stream).connect(this.analyser),this.frequencyBinCount=new Float32Array(this.analyser.frequencyBinCount))}getMember(){return this.client.getRoom(this.roomId).getMember(this.userId)}isLocal(){return this.userId===this.client.getUserId()}isAudioMuted(){return 0===this.stream.getAudioTracks().length||this.audioMuted}isVideoMuted(){return 0===this.stream.getVideoTracks().length||this.videoMuted}isSpeaking(){return this.speaking}setAudioVideoMuted(e,t){null!==e&&(this.audioMuted!==e&&this.speakingVolumeSamples.fill(-1/0),this.audioMuted=e),null!==t&&(this.videoMuted=t),this.emit(o.MuteStateChanged,this.audioMuted,this.videoMuted)}measureVolumeActivity(e){if(e){if(!(this.audioContext&&this.analyser&&this.frequencyBinCount&&this.hasAudioTrack))return;this.measuringVolumeActivity=!0,this.volumeLooper()}else this.measuringVolumeActivity=!1,this.speakingVolumeSamples.fill(-1/0),this.emit(o.VolumeChanged,-1/0)}setSpeakingThreshold(e){this.speakingThreshold=e}dispose(){clearTimeout(this.volumeLooperTimeout)}}t.CallFeed=a},7626:(e,t,n)=>{"use strict";var r=n(4836);Object.defineProperty(t,"__esModule",{value:!0}),t.MediaHandler=void 0;var i=r(n(8416)),s=n(7434),o=n(9679);t.MediaHandler=class{constructor(e){this.client=e,(0,i.default)(this,"audioInput",void 0),(0,i.default)(this,"videoInput",void 0),(0,i.default)(this,"localUserMediaStream",void 0),(0,i.default)(this,"userMediaStreams",[]),(0,i.default)(this,"screensharingStreams",[])}async setAudioInput(e){s.logger.info("LOG setting audio input to",e),this.audioInput!==e&&(this.audioInput=e,await this.updateLocalUsermediaStreams())}async setVideoInput(e){s.logger.info("LOG setting video input to",e),this.videoInput!==e&&(this.videoInput=e,await this.updateLocalUsermediaStreams())}async updateLocalUsermediaStreams(){if(0===this.userMediaStreams.length)return;const e=new Map;for(const t of this.client.callEventHandler.calls.values())e.set(t.callId,{audio:t.hasLocalUserMediaAudioTrack,video:t.hasLocalUserMediaVideoTrack});for(const t of this.client.callEventHandler.calls.values()){if(t.state===o.CallState.Ended||!e.has(t.callId))continue;const{audio:n,video:r}=e.get(t.callId),i=await this.getUserMediaStream(n,r,!1);await t.updateLocalUsermediaStream(i)}}async hasAudioDevice(){return(await navigator.mediaDevices.enumerateDevices()).filter((e=>"audioinput"===e.kind)).length>0}async hasVideoDevice(){return(await navigator.mediaDevices.enumerateDevices()).filter((e=>"videoinput"===e.kind)).length>0}async getUserMediaStream(e,t,n=!0){var r,i,o,a;const c=e&&await this.hasAudioDevice(),l=t&&await this.hasVideoDevice();let d;if(!this.localUserMediaStream||0===this.localUserMediaStream.getAudioTracks().length&&c||0===this.localUserMediaStream.getVideoTracks().length&&l||(null===(r=this.localUserMediaStream.getAudioTracks()[0])||void 0===r||null===(i=r.getSettings())||void 0===i?void 0:i.deviceId)!==this.audioInput||(null===(o=this.localUserMediaStream.getVideoTracks()[0])||void 0===o||null===(a=o.getSettings())||void 0===a?void 0:a.deviceId)!==this.videoInput){const e=this.getUserMediaContraints(c,l);s.logger.log("Getting user media with constraints",e),d=await navigator.mediaDevices.getUserMedia(e);for(const e of d.getTracks()){const t=e.getSettings();"audio"===e.kind?this.audioInput=t.deviceId:"video"===e.kind&&(this.videoInput=t.deviceId)}n&&(this.localUserMediaStream=d)}else{if(d=this.localUserMediaStream.clone(),!c)for(const e of d.getAudioTracks())d.removeTrack(e);if(!l)for(const e of d.getVideoTracks())d.removeTrack(e)}return n&&this.userMediaStreams.push(d),d}stopUserMediaStream(e){s.logger.debug("Stopping usermedia stream",e.id);for(const t of e.getTracks())t.stop();const t=this.userMediaStreams.indexOf(e);-1!==t&&(s.logger.debug("Splicing usermedia stream out stream array",e.id),this.userMediaStreams.splice(t,1)),this.localUserMediaStream===e&&(this.localUserMediaStream=void 0)}async getScreensharingStream(e,t=!0){let n;if(0===this.screensharingStreams.length){const t=this.getScreenshareContraints(e);if(!t)return null;e?(s.logger.debug("Getting screensharing stream using getUserMedia()",e),n=await navigator.mediaDevices.getUserMedia(t)):(s.logger.debug("Getting screensharing stream using getDisplayMedia()"),n=await navigator.mediaDevices.getDisplayMedia(t))}else{const e=this.screensharingStreams[this.screensharingStreams.length-1];s.logger.log("Cloning screensharing stream",e.id),n=e.clone()}return t&&this.screensharingStreams.push(n),n}stopScreensharingStream(e){s.logger.debug("Stopping screensharing stream",e.id);for(const t of e.getTracks())t.stop();const t=this.screensharingStreams.indexOf(e);-1!==t&&(s.logger.debug("Splicing screensharing stream out stream array",e.id),this.screensharingStreams.splice(t,1))}stopAllStreams(){for(const e of this.userMediaStreams)for(const t of e.getTracks())t.stop();for(const e of this.screensharingStreams)for(const t of e.getTracks())t.stop();this.userMediaStreams=[],this.screensharingStreams=[],this.localUserMediaStream=void 0}getUserMediaContraints(e,t){const n=!!navigator.webkitGetUserMedia;return{audio:!!e&&{deviceId:this.audioInput?{ideal:this.audioInput}:void 0},video:!!t&&{deviceId:this.videoInput?{ideal:this.videoInput}:void 0,width:n?{exact:640}:{ideal:640},height:n?{exact:360}:{ideal:360}}}}getScreenshareContraints(e){return e?(s.logger.debug("Using desktop capturer source",e),{audio:!1,video:{mandatory:{chromeMediaSource:"desktop",chromeMediaSourceId:e}}}):(s.logger.debug("Not using desktop capturer source"),{audio:!1,video:!0})}}},7824:e=>{var t=1e3,n=60*t,r=60*n,i=24*r;function s(e,t,n,r){var i=t>=1.5*n;return Math.round(e/n)+" "+r+(i?"s":"")}e.exports=function(e,o){o=o||{};var a,c,l=typeof e;if("string"===l&&e.length>0)return function(e){if(!((e=String(e)).length>100)){var s=/^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec(e);if(s){var o=parseFloat(s[1]);switch((s[2]||"ms").toLowerCase()){case"years":case"year":case"yrs":case"yr":case"y":return 315576e5*o;case"weeks":case"week":case"w":return 6048e5*o;case"days":case"day":case"d":return o*i;case"hours":case"hour":case"hrs":case"hr":case"h":return o*r;case"minutes":case"minute":case"mins":case"min":case"m":return o*n;case"seconds":case"second":case"secs":case"sec":case"s":return o*t;case"milliseconds":case"millisecond":case"msecs":case"msec":case"ms":return o;default:return}}}}(e);if("number"===l&&isFinite(e))return o.long?(a=e,(c=Math.abs(a))>=i?s(a,c,i,"day"):c>=r?s(a,c,r,"hour"):c>=n?s(a,c,n,"minute"):c>=t?s(a,c,t,"second"):a+" ms"):function(e){var s=Math.abs(e);return s>=i?Math.round(e/i)+"d":s>=r?Math.round(e/r)+"h":s>=n?Math.round(e/n)+"m":s>=t?Math.round(e/t)+"s":e+"ms"}(e);throw new Error("val is not a non-empty string or a valid number. val="+JSON.stringify(e))}},631:(e,t,n)=>{var r="function"==typeof Map&&Map.prototype,i=Object.getOwnPropertyDescriptor&&r?Object.getOwnPropertyDescriptor(Map.prototype,"size"):null,s=r&&i&&"function"==typeof i.get?i.get:null,o=r&&Map.prototype.forEach,a="function"==typeof Set&&Set.prototype,c=Object.getOwnPropertyDescriptor&&a?Object.getOwnPropertyDescriptor(Set.prototype,"size"):null,l=a&&c&&"function"==typeof c.get?c.get:null,d=a&&Set.prototype.forEach,u="function"==typeof WeakMap&&WeakMap.prototype?WeakMap.prototype.has:null,h="function"==typeof WeakSet&&WeakSet.prototype?WeakSet.prototype.has:null,f="function"==typeof WeakRef&&WeakRef.prototype?WeakRef.prototype.deref:null,g=Boolean.prototype.valueOf,p=Object.prototype.toString,m=Function.prototype.toString,y=String.prototype.match,v=String.prototype.slice,b=String.prototype.replace,_=String.prototype.toUpperCase,E=String.prototype.toLowerCase,w=RegExp.prototype.test,S=Array.prototype.concat,C=Array.prototype.join,T=Array.prototype.slice,R=Math.floor,I="function"==typeof BigInt?BigInt.prototype.valueOf:null,k=Object.getOwnPropertySymbols,O="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?Symbol.prototype.toString:null,A="function"==typeof Symbol&&"object"==typeof Symbol.iterator,D="function"==typeof Symbol&&Symbol.toStringTag&&(Symbol.toStringTag,1)?Symbol.toStringTag:null,M=Object.prototype.propertyIsEnumerable,P=("function"==typeof Reflect?Reflect.getPrototypeOf:Object.getPrototypeOf)||([].__proto__===Array.prototype?function(e){return e.__proto__}:null);function U(e,t){if(e===1/0||e===-1/0||e!=e||e&&e>-1e3&&e<1e3||w.call(/e/,t))return t;var n=/[0-9](?=(?:[0-9]{3})+(?![0-9]))/g;if("number"==typeof e){var r=e<0?-R(-e):R(e);if(r!==e){var i=String(r),s=v.call(t,i.length+1);return b.call(i,n,"$&_")+"."+b.call(b.call(s,/([0-9]{3})/g,"$&_"),/_$/,"")}}return b.call(t,n,"$&_")}var L=n(4654),N=L.custom,x=q(N)?N:null;function B(e,t,n){var r="double"===(n.quoteStyle||t)?'"':"'";return r+e+r}function j(e){return b.call(String(e),/"/g,""")}function F(e){return!("[object Array]"!==G(e)||D&&"object"==typeof e&&D in e)}function K(e){return!("[object RegExp]"!==G(e)||D&&"object"==typeof e&&D in e)}function q(e){if(A)return e&&"object"==typeof e&&e instanceof Symbol;if("symbol"==typeof e)return!0;if(!e||"object"!=typeof e||!O)return!1;try{return O.call(e),!0}catch(e){}return!1}e.exports=function e(t,r,i,a){var c=r||{};if(V(c,"quoteStyle")&&"single"!==c.quoteStyle&&"double"!==c.quoteStyle)throw new TypeError('option "quoteStyle" must be "single" or "double"');if(V(c,"maxStringLength")&&("number"==typeof c.maxStringLength?c.maxStringLength<0&&c.maxStringLength!==1/0:null!==c.maxStringLength))throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`');var p=!V(c,"customInspect")||c.customInspect;if("boolean"!=typeof p&&"symbol"!==p)throw new TypeError("option \"customInspect\", if provided, must be `true`, `false`, or `'symbol'`");if(V(c,"indent")&&null!==c.indent&&"\t"!==c.indent&&!(parseInt(c.indent,10)===c.indent&&c.indent>0))throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`');if(V(c,"numericSeparator")&&"boolean"!=typeof c.numericSeparator)throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`');var _=c.numericSeparator;if(void 0===t)return"undefined";if(null===t)return"null";if("boolean"==typeof t)return t?"true":"false";if("string"==typeof t)return H(t,c);if("number"==typeof t){if(0===t)return 1/0/t>0?"0":"-0";var w=String(t);return _?U(t,w):w}if("bigint"==typeof t){var R=String(t)+"n";return _?U(t,R):R}var k=void 0===c.depth?5:c.depth;if(void 0===i&&(i=0),i>=k&&k>0&&"object"==typeof t)return F(t)?"[Array]":"[Object]";var N,$=function(e,t){var n;if("\t"===e.indent)n="\t";else{if(!("number"==typeof e.indent&&e.indent>0))return null;n=C.call(Array(e.indent+1)," ")}return{base:n,prev:C.call(Array(t+1),n)}}(c,i);if(void 0===a)a=[];else if(W(a,t)>=0)return"[Circular]";function Y(t,n,r){if(n&&(a=T.call(a)).push(n),r){var s={depth:c.depth};return V(c,"quoteStyle")&&(s.quoteStyle=c.quoteStyle),e(t,s,i+1,a)}return e(t,c,i+1,a)}if("function"==typeof t&&!K(t)){var ee=function(e){if(e.name)return e.name;var t=y.call(m.call(e),/^function\s*([\w$]+)/);return t?t[1]:null}(t),te=Z(t,Y);return"[Function"+(ee?": "+ee:" (anonymous)")+"]"+(te.length>0?" { "+C.call(te,", ")+" }":"")}if(q(t)){var ne=A?b.call(String(t),/^(Symbol\(.*\))_[^)]*$/,"$1"):O.call(t);return"object"!=typeof t||A?ne:z(ne)}if((N=t)&&"object"==typeof N&&("undefined"!=typeof HTMLElement&&N instanceof HTMLElement||"string"==typeof N.nodeName&&"function"==typeof N.getAttribute)){for(var re="<"+E.call(String(t.nodeName)),ie=t.attributes||[],se=0;se<ie.length;se++)re+=" "+ie[se].name+"="+B(j(ie[se].value),"double",c);return re+=">",t.childNodes&&t.childNodes.length&&(re+="..."),re+"</"+E.call(String(t.nodeName))+">"}if(F(t)){if(0===t.length)return"[]";var oe=Z(t,Y);return $&&!function(e){for(var t=0;t<e.length;t++)if(W(e[t],"\n")>=0)return!1;return!0}(oe)?"["+X(oe,$)+"]":"[ "+C.call(oe,", ")+" ]"}if(function(e){return!("[object Error]"!==G(e)||D&&"object"==typeof e&&D in e)}(t)){var ae=Z(t,Y);return"cause"in Error.prototype||!("cause"in t)||M.call(t,"cause")?0===ae.length?"["+String(t)+"]":"{ ["+String(t)+"] "+C.call(ae,", ")+" }":"{ ["+String(t)+"] "+C.call(S.call("[cause]: "+Y(t.cause),ae),", ")+" }"}if("object"==typeof t&&p){if(x&&"function"==typeof t[x]&&L)return L(t,{depth:k-i});if("symbol"!==p&&"function"==typeof t.inspect)return t.inspect()}if(function(e){if(!s||!e||"object"!=typeof e)return!1;try{s.call(e);try{l.call(e)}catch(e){return!0}return e instanceof Map}catch(e){}return!1}(t)){var ce=[];return o&&o.call(t,(function(e,n){ce.push(Y(n,t,!0)+" => "+Y(e,t))})),Q("Map",s.call(t),ce,$)}if(function(e){if(!l||!e||"object"!=typeof e)return!1;try{l.call(e);try{s.call(e)}catch(e){return!0}return e instanceof Set}catch(e){}return!1}(t)){var le=[];return d&&d.call(t,(function(e){le.push(Y(e,t))})),Q("Set",l.call(t),le,$)}if(function(e){if(!u||!e||"object"!=typeof e)return!1;try{u.call(e,u);try{h.call(e,h)}catch(e){return!0}return e instanceof WeakMap}catch(e){}return!1}(t))return J("WeakMap");if(function(e){if(!h||!e||"object"!=typeof e)return!1;try{h.call(e,h);try{u.call(e,u)}catch(e){return!0}return e instanceof WeakSet}catch(e){}return!1}(t))return J("WeakSet");if(function(e){if(!f||!e||"object"!=typeof e)return!1;try{return f.call(e),!0}catch(e){}return!1}(t))return J("WeakRef");if(function(e){return!("[object Number]"!==G(e)||D&&"object"==typeof e&&D in e)}(t))return z(Y(Number(t)));if(function(e){if(!e||"object"!=typeof e||!I)return!1;try{return I.call(e),!0}catch(e){}return!1}(t))return z(Y(I.call(t)));if(function(e){return!("[object Boolean]"!==G(e)||D&&"object"==typeof e&&D in e)}(t))return z(g.call(t));if(function(e){return!("[object String]"!==G(e)||D&&"object"==typeof e&&D in e)}(t))return z(Y(String(t)));if("undefined"!=typeof window&&t===window)return"{ [object Window] }";if(t===n.g)return"{ [object globalThis] }";if(!function(e){return!("[object Date]"!==G(e)||D&&"object"==typeof e&&D in e)}(t)&&!K(t)){var de=Z(t,Y),ue=P?P(t)===Object.prototype:t instanceof Object||t.constructor===Object,he=t instanceof Object?"":"null prototype",fe=!ue&&D&&Object(t)===t&&D in t?v.call(G(t),8,-1):he?"Object":"",ge=(ue||"function"!=typeof t.constructor?"":t.constructor.name?t.constructor.name+" ":"")+(fe||he?"["+C.call(S.call([],fe||[],he||[]),": ")+"] ":"");return 0===de.length?ge+"{}":$?ge+"{"+X(de,$)+"}":ge+"{ "+C.call(de,", ")+" }"}return String(t)};var $=Object.prototype.hasOwnProperty||function(e){return e in this};function V(e,t){return $.call(e,t)}function G(e){return p.call(e)}function W(e,t){if(e.indexOf)return e.indexOf(t);for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}function H(e,t){if(e.length>t.maxStringLength){var n=e.length-t.maxStringLength,r="... "+n+" more character"+(n>1?"s":"");return H(v.call(e,0,t.maxStringLength),t)+r}return B(b.call(b.call(e,/(['\\])/g,"\\$1"),/[\x00-\x1f]/g,Y),"single",t)}function Y(e){var t=e.charCodeAt(0),n={8:"b",9:"t",10:"n",12:"f",13:"r"}[t];return n?"\\"+n:"\\x"+(t<16?"0":"")+_.call(t.toString(16))}function z(e){return"Object("+e+")"}function J(e){return e+" { ? }"}function Q(e,t,n,r){return e+" ("+t+") {"+(r?X(n,r):C.call(n,", "))+"}"}function X(e,t){if(0===e.length)return"";var n="\n"+t.prev+t.base;return n+C.call(e,","+n)+"\n"+t.prev}function Z(e,t){var n=F(e),r=[];if(n){r.length=e.length;for(var i=0;i<e.length;i++)r[i]=V(e,i)?t(e[i],e):""}var s,o="function"==typeof k?k(e):[];if(A){s={};for(var a=0;a<o.length;a++)s["$"+o[a]]=o[a]}for(var c in e)V(e,c)&&(n&&String(Number(c))===c&&c<e.length||A&&s["$"+c]instanceof Symbol||(w.call(/[^\w$]/,c)?r.push(t(c,e)+": "+t(e[c],e)):r.push(c+": "+t(e[c],e))));if("function"==typeof k)for(var l=0;l<o.length;l++)M.call(e,o[l])&&r.push("["+t(o[l])+"]: "+t(e[o[l]],e));return r}},2693:(e,t,n)=>{"use strict";const r=n(9353),i=["Failed to fetch","NetworkError when attempting to fetch resource.","The Internet connection appears to be offline.","Network request failed"];class s extends Error{constructor(e){super(),e instanceof Error?(this.originalError=e,({message:e}=e)):(this.originalError=new Error(e),this.originalError.stack=this.stack),this.name="AbortError",this.message=e}}const o=(e,t)=>new Promise(((n,o)=>{t={onFailedAttempt:()=>{},retries:10,...t};const a=r.operation(t);a.attempt((async r=>{try{n(await e(r))}catch(e){if(!(e instanceof Error))return void o(new TypeError(`Non-error was thrown: "${e}". You should only throw errors.`));if(e instanceof s)a.stop(),o(e.originalError);else if(e instanceof TypeError&&(c=e.message,!i.includes(c)))a.stop(),o(e);else{((e,t,n)=>{const r=n.retries-(t-1);e.attemptNumber=t,e.retriesLeft=r})(e,r,t);try{await t.onFailedAttempt(e)}catch(e){return void o(e)}a.retry(e)||o(a.mainError())}}var c}))}));e.exports=o,e.exports.default=o,e.exports.AbortError=s},5798:e=>{"use strict";var t=String.prototype.replace,n=/%20/g,r="RFC3986";e.exports={default:r,formatters:{RFC1738:function(e){return t.call(e,n,"+")},RFC3986:function(e){return String(e)}},RFC1738:"RFC1738",RFC3986:r}},129:(e,t,n)=>{"use strict";var r=n(8261),i=n(5235),s=n(5798);e.exports={formats:s,parse:i,stringify:r}},5235:(e,t,n)=>{"use strict";var r=n(2769),i=Object.prototype.hasOwnProperty,s=Array.isArray,o={allowDots:!1,allowPrototypes:!1,allowSparse:!1,arrayLimit:20,charset:"utf-8",charsetSentinel:!1,comma:!1,decoder:r.decode,delimiter:"&",depth:5,ignoreQueryPrefix:!1,interpretNumericEntities:!1,parameterLimit:1e3,parseArrays:!0,plainObjects:!1,strictNullHandling:!1},a=function(e){return e.replace(/&#(\d+);/g,(function(e,t){return String.fromCharCode(parseInt(t,10))}))},c=function(e,t){return e&&"string"==typeof e&&t.comma&&e.indexOf(",")>-1?e.split(","):e},l=function(e,t,n,r){if(e){var s=n.allowDots?e.replace(/\.([^.[]+)/g,"[$1]"):e,o=/(\[[^[\]]*])/g,a=n.depth>0&&/(\[[^[\]]*])/.exec(s),l=a?s.slice(0,a.index):s,d=[];if(l){if(!n.plainObjects&&i.call(Object.prototype,l)&&!n.allowPrototypes)return;d.push(l)}for(var u=0;n.depth>0&&null!==(a=o.exec(s))&&u<n.depth;){if(u+=1,!n.plainObjects&&i.call(Object.prototype,a[1].slice(1,-1))&&!n.allowPrototypes)return;d.push(a[1])}return a&&d.push("["+s.slice(a.index)+"]"),function(e,t,n,r){for(var i=r?t:c(t,n),s=e.length-1;s>=0;--s){var o,a=e[s];if("[]"===a&&n.parseArrays)o=[].concat(i);else{o=n.plainObjects?Object.create(null):{};var l="["===a.charAt(0)&&"]"===a.charAt(a.length-1)?a.slice(1,-1):a,d=parseInt(l,10);n.parseArrays||""!==l?!isNaN(d)&&a!==l&&String(d)===l&&d>=0&&n.parseArrays&&d<=n.arrayLimit?(o=[])[d]=i:"__proto__"!==l&&(o[l]=i):o={0:i}}i=o}return i}(d,t,n,r)}};e.exports=function(e,t){var n=function(e){if(!e)return o;if(null!==e.decoder&&void 0!==e.decoder&&"function"!=typeof e.decoder)throw new TypeError("Decoder has to be a function.");if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var t=void 0===e.charset?o.charset:e.charset;return{allowDots:void 0===e.allowDots?o.allowDots:!!e.allowDots,allowPrototypes:"boolean"==typeof e.allowPrototypes?e.allowPrototypes:o.allowPrototypes,allowSparse:"boolean"==typeof e.allowSparse?e.allowSparse:o.allowSparse,arrayLimit:"number"==typeof e.arrayLimit?e.arrayLimit:o.arrayLimit,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:o.charsetSentinel,comma:"boolean"==typeof e.comma?e.comma:o.comma,decoder:"function"==typeof e.decoder?e.decoder:o.decoder,delimiter:"string"==typeof e.delimiter||r.isRegExp(e.delimiter)?e.delimiter:o.delimiter,depth:"number"==typeof e.depth||!1===e.depth?+e.depth:o.depth,ignoreQueryPrefix:!0===e.ignoreQueryPrefix,interpretNumericEntities:"boolean"==typeof e.interpretNumericEntities?e.interpretNumericEntities:o.interpretNumericEntities,parameterLimit:"number"==typeof e.parameterLimit?e.parameterLimit:o.parameterLimit,parseArrays:!1!==e.parseArrays,plainObjects:"boolean"==typeof e.plainObjects?e.plainObjects:o.plainObjects,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:o.strictNullHandling}}(t);if(""===e||null==e)return n.plainObjects?Object.create(null):{};for(var d="string"==typeof e?function(e,t){var n,l={__proto__:null},d=t.ignoreQueryPrefix?e.replace(/^\?/,""):e,u=t.parameterLimit===1/0?void 0:t.parameterLimit,h=d.split(t.delimiter,u),f=-1,g=t.charset;if(t.charsetSentinel)for(n=0;n<h.length;++n)0===h[n].indexOf("utf8=")&&("utf8=%E2%9C%93"===h[n]?g="utf-8":"utf8=%26%2310003%3B"===h[n]&&(g="iso-8859-1"),f=n,n=h.length);for(n=0;n<h.length;++n)if(n!==f){var p,m,y=h[n],v=y.indexOf("]="),b=-1===v?y.indexOf("="):v+1;-1===b?(p=t.decoder(y,o.decoder,g,"key"),m=t.strictNullHandling?null:""):(p=t.decoder(y.slice(0,b),o.decoder,g,"key"),m=r.maybeMap(c(y.slice(b+1),t),(function(e){return t.decoder(e,o.decoder,g,"value")}))),m&&t.interpretNumericEntities&&"iso-8859-1"===g&&(m=a(m)),y.indexOf("[]=")>-1&&(m=s(m)?[m]:m),i.call(l,p)?l[p]=r.combine(l[p],m):l[p]=m}return l}(e,n):e,u=n.plainObjects?Object.create(null):{},h=Object.keys(d),f=0;f<h.length;++f){var g=h[f],p=l(g,d[g],n,"string"==typeof e);u=r.merge(u,p,n)}return!0===n.allowSparse?u:r.compact(u)}},8261:(e,t,n)=>{"use strict";var r=n(7478),i=n(2769),s=n(5798),o=Object.prototype.hasOwnProperty,a={brackets:function(e){return e+"[]"},comma:"comma",indices:function(e,t){return e+"["+t+"]"},repeat:function(e){return e}},c=Array.isArray,l=Array.prototype.push,d=function(e,t){l.apply(e,c(t)?t:[t])},u=Date.prototype.toISOString,h=s.default,f={addQueryPrefix:!1,allowDots:!1,charset:"utf-8",charsetSentinel:!1,delimiter:"&",encode:!0,encoder:i.encode,encodeValuesOnly:!1,format:h,formatter:s.formatters[h],indices:!1,serializeDate:function(e){return u.call(e)},skipNulls:!1,strictNullHandling:!1},g={},p=function e(t,n,s,o,a,l,u,h,p,m,y,v,b,_,E,w){for(var S,C=t,T=w,R=0,I=!1;void 0!==(T=T.get(g))&&!I;){var k=T.get(t);if(R+=1,void 0!==k){if(k===R)throw new RangeError("Cyclic object value");I=!0}void 0===T.get(g)&&(R=0)}if("function"==typeof h?C=h(n,C):C instanceof Date?C=y(C):"comma"===s&&c(C)&&(C=i.maybeMap(C,(function(e){return e instanceof Date?y(e):e}))),null===C){if(a)return u&&!_?u(n,f.encoder,E,"key",v):n;C=""}if("string"==typeof(S=C)||"number"==typeof S||"boolean"==typeof S||"symbol"==typeof S||"bigint"==typeof S||i.isBuffer(C))return u?[b(_?n:u(n,f.encoder,E,"key",v))+"="+b(u(C,f.encoder,E,"value",v))]:[b(n)+"="+b(String(C))];var O,A=[];if(void 0===C)return A;if("comma"===s&&c(C))_&&u&&(C=i.maybeMap(C,u)),O=[{value:C.length>0?C.join(",")||null:void 0}];else if(c(h))O=h;else{var D=Object.keys(C);O=p?D.sort(p):D}for(var M=o&&c(C)&&1===C.length?n+"[]":n,P=0;P<O.length;++P){var U=O[P],L="object"==typeof U&&void 0!==U.value?U.value:C[U];if(!l||null!==L){var N=c(C)?"function"==typeof s?s(M,U):M:M+(m?"."+U:"["+U+"]");w.set(t,R);var x=r();x.set(g,w),d(A,e(L,N,s,o,a,l,"comma"===s&&_&&c(C)?null:u,h,p,m,y,v,b,_,E,x))}}return A};e.exports=function(e,t){var n,i=e,l=function(e){if(!e)return f;if(null!==e.encoder&&void 0!==e.encoder&&"function"!=typeof e.encoder)throw new TypeError("Encoder has to be a function.");var t=e.charset||f.charset;if(void 0!==e.charset&&"utf-8"!==e.charset&&"iso-8859-1"!==e.charset)throw new TypeError("The charset option must be either utf-8, iso-8859-1, or undefined");var n=s.default;if(void 0!==e.format){if(!o.call(s.formatters,e.format))throw new TypeError("Unknown format option provided.");n=e.format}var r=s.formatters[n],i=f.filter;return("function"==typeof e.filter||c(e.filter))&&(i=e.filter),{addQueryPrefix:"boolean"==typeof e.addQueryPrefix?e.addQueryPrefix:f.addQueryPrefix,allowDots:void 0===e.allowDots?f.allowDots:!!e.allowDots,charset:t,charsetSentinel:"boolean"==typeof e.charsetSentinel?e.charsetSentinel:f.charsetSentinel,delimiter:void 0===e.delimiter?f.delimiter:e.delimiter,encode:"boolean"==typeof e.encode?e.encode:f.encode,encoder:"function"==typeof e.encoder?e.encoder:f.encoder,encodeValuesOnly:"boolean"==typeof e.encodeValuesOnly?e.encodeValuesOnly:f.encodeValuesOnly,filter:i,format:n,formatter:r,serializeDate:"function"==typeof e.serializeDate?e.serializeDate:f.serializeDate,skipNulls:"boolean"==typeof e.skipNulls?e.skipNulls:f.skipNulls,sort:"function"==typeof e.sort?e.sort:null,strictNullHandling:"boolean"==typeof e.strictNullHandling?e.strictNullHandling:f.strictNullHandling}}(t);"function"==typeof l.filter?i=(0,l.filter)("",i):c(l.filter)&&(n=l.filter);var u,h=[];if("object"!=typeof i||null===i)return"";u=t&&t.arrayFormat in a?t.arrayFormat:t&&"indices"in t?t.indices?"indices":"repeat":"indices";var g=a[u];if(t&&"commaRoundTrip"in t&&"boolean"!=typeof t.commaRoundTrip)throw new TypeError("`commaRoundTrip` must be a boolean, or absent");var m="comma"===g&&t&&t.commaRoundTrip;n||(n=Object.keys(i)),l.sort&&n.sort(l.sort);for(var y=r(),v=0;v<n.length;++v){var b=n[v];l.skipNulls&&null===i[b]||d(h,p(i[b],b,g,m,l.strictNullHandling,l.skipNulls,l.encode?l.encoder:null,l.filter,l.sort,l.allowDots,l.serializeDate,l.format,l.formatter,l.encodeValuesOnly,l.charset,y))}var _=h.join(l.delimiter),E=!0===l.addQueryPrefix?"?":"";return l.charsetSentinel&&("iso-8859-1"===l.charset?E+="utf8=%26%2310003%3B&":E+="utf8=%E2%9C%93&"),_.length>0?E+_:""}},2769:(e,t,n)=>{"use strict";var r=n(5798),i=Object.prototype.hasOwnProperty,s=Array.isArray,o=function(){for(var e=[],t=0;t<256;++t)e.push("%"+((t<16?"0":"")+t.toString(16)).toUpperCase());return e}(),a=function(e,t){for(var n=t&&t.plainObjects?Object.create(null):{},r=0;r<e.length;++r)void 0!==e[r]&&(n[r]=e[r]);return n};e.exports={arrayToObject:a,assign:function(e,t){return Object.keys(t).reduce((function(e,n){return e[n]=t[n],e}),e)},combine:function(e,t){return[].concat(e,t)},compact:function(e){for(var t=[{obj:{o:e},prop:"o"}],n=[],r=0;r<t.length;++r)for(var i=t[r],o=i.obj[i.prop],a=Object.keys(o),c=0;c<a.length;++c){var l=a[c],d=o[l];"object"==typeof d&&null!==d&&-1===n.indexOf(d)&&(t.push({obj:o,prop:l}),n.push(d))}return function(e){for(;e.length>1;){var t=e.pop(),n=t.obj[t.prop];if(s(n)){for(var r=[],i=0;i<n.length;++i)void 0!==n[i]&&r.push(n[i]);t.obj[t.prop]=r}}}(t),e},decode:function(e,t,n){var r=e.replace(/\+/g," ");if("iso-8859-1"===n)return r.replace(/%[0-9a-f]{2}/gi,unescape);try{return decodeURIComponent(r)}catch(e){return r}},encode:function(e,t,n,i,s){if(0===e.length)return e;var a=e;if("symbol"==typeof e?a=Symbol.prototype.toString.call(e):"string"!=typeof e&&(a=String(e)),"iso-8859-1"===n)return escape(a).replace(/%u[0-9a-f]{4}/gi,(function(e){return"%26%23"+parseInt(e.slice(2),16)+"%3B"}));for(var c="",l=0;l<a.length;++l){var d=a.charCodeAt(l);45===d||46===d||95===d||126===d||d>=48&&d<=57||d>=65&&d<=90||d>=97&&d<=122||s===r.RFC1738&&(40===d||41===d)?c+=a.charAt(l):d<128?c+=o[d]:d<2048?c+=o[192|d>>6]+o[128|63&d]:d<55296||d>=57344?c+=o[224|d>>12]+o[128|d>>6&63]+o[128|63&d]:(l+=1,d=65536+((1023&d)<<10|1023&a.charCodeAt(l)),c+=o[240|d>>18]+o[128|d>>12&63]+o[128|d>>6&63]+o[128|63&d])}return c},isBuffer:function(e){return!(!e||"object"!=typeof e||!(e.constructor&&e.constructor.isBuffer&&e.constructor.isBuffer(e)))},isRegExp:function(e){return"[object RegExp]"===Object.prototype.toString.call(e)},maybeMap:function(e,t){if(s(e)){for(var n=[],r=0;r<e.length;r+=1)n.push(t(e[r]));return n}return t(e)},merge:function e(t,n,r){if(!n)return t;if("object"!=typeof n){if(s(t))t.push(n);else{if(!t||"object"!=typeof t)return[t,n];(r&&(r.plainObjects||r.allowPrototypes)||!i.call(Object.prototype,n))&&(t[n]=!0)}return t}if(!t||"object"!=typeof t)return[t].concat(n);var o=t;return s(t)&&!s(n)&&(o=a(t,r)),s(t)&&s(n)?(n.forEach((function(n,s){if(i.call(t,s)){var o=t[s];o&&"object"==typeof o&&n&&"object"==typeof n?t[s]=e(o,n,r):t.push(n)}else t[s]=n})),t):Object.keys(n).reduce((function(t,s){var o=n[s];return i.call(t,s)?t[s]=e(t[s],o,r):t[s]=o,t}),o)}}},4375:(e,t,n)=>{let r;e.exports="function"==typeof queueMicrotask?queueMicrotask.bind("undefined"!=typeof window?window:n.g):e=>(r||(r=Promise.resolve())).then(e).catch((e=>setTimeout((()=>{throw e}),0)))},1798:(e,t,n)=>{"use strict";var r=65536,i=n(9509).Buffer,s=n.g.crypto||n.g.msCrypto;s&&s.getRandomValues?e.exports=function(e,t){if(e>4294967295)throw new RangeError("requested too many random bytes");var n=i.allocUnsafe(e);if(e>0)if(e>r)for(var o=0;o<e;o+=r)s.getRandomValues(n.slice(o,o+r));else s.getRandomValues(n);return"function"==typeof t?process.nextTick((function(){t(null,n)})):n}:e.exports=function(){throw new Error("Secure random number generation is not supported by this browser.\nUse Chrome, Firefox or Internet Explorer 11")}},4281:e=>{"use strict";var t={};function n(e,n,r){r||(r=Error);var i=function(e){var t,r;function i(t,r,i){return e.call(this,function(e,t,r){return"string"==typeof n?n:n(e,t,r)}(t,r,i))||this}return r=e,(t=i).prototype=Object.create(r.prototype),t.prototype.constructor=t,t.__proto__=r,i}(r);i.prototype.name=r.name,i.prototype.code=e,t[e]=i}function r(e,t){if(Array.isArray(e)){var n=e.length;return e=e.map((function(e){return String(e)})),n>2?"one of ".concat(t," ").concat(e.slice(0,n-1).join(", "),", or ")+e[n-1]:2===n?"one of ".concat(t," ").concat(e[0]," or ").concat(e[1]):"of ".concat(t," ").concat(e[0])}return"of ".concat(t," ").concat(String(e))}n("ERR_INVALID_OPT_VALUE",(function(e,t){return'The value "'+t+'" is invalid for option "'+e+'"'}),TypeError),n("ERR_INVALID_ARG_TYPE",(function(e,t,n){var i,s,o,a,c;if("string"==typeof t&&(s="not ",t.substr(0,4)===s)?(i="must not be",t=t.replace(/^not /,"")):i="must be",function(e,t,n){return(void 0===n||n>e.length)&&(n=e.length),e.substring(n-9,n)===t}(e," argument"))o="The ".concat(e," ").concat(i," ").concat(r(t,"type"));else{var l=("number"!=typeof c&&(c=0),c+1>(a=e).length||-1===a.indexOf(".",c)?"argument":"property");o='The "'.concat(e,'" ').concat(l," ").concat(i," ").concat(r(t,"type"))}return o+". Received type ".concat(typeof n)}),TypeError),n("ERR_STREAM_PUSH_AFTER_EOF","stream.push() after EOF"),n("ERR_METHOD_NOT_IMPLEMENTED",(function(e){return"The "+e+" method is not implemented"})),n("ERR_STREAM_PREMATURE_CLOSE","Premature close"),n("ERR_STREAM_DESTROYED",(function(e){return"Cannot call "+e+" after a stream was destroyed"})),n("ERR_MULTIPLE_CALLBACK","Callback called multiple times"),n("ERR_STREAM_CANNOT_PIPE","Cannot pipe, not readable"),n("ERR_STREAM_WRITE_AFTER_END","write after end"),n("ERR_STREAM_NULL_VALUES","May not write null values to stream",TypeError),n("ERR_UNKNOWN_ENCODING",(function(e){return"Unknown encoding: "+e}),TypeError),n("ERR_STREAM_UNSHIFT_AFTER_END_EVENT","stream.unshift() after end event"),e.exports.q=t},6753:(e,t,n)=>{"use strict";var r=Object.keys||function(e){var t=[];for(var n in e)t.push(n);return t};e.exports=l;var i=n(9481),s=n(4229);n(5717)(l,i);for(var o=r(s.prototype),a=0;a<o.length;a++){var c=o[a];l.prototype[c]||(l.prototype[c]=s.prototype[c])}function l(e){if(!(this instanceof l))return new l(e);i.call(this,e),s.call(this,e),this.allowHalfOpen=!0,e&&(!1===e.readable&&(this.readable=!1),!1===e.writable&&(this.writable=!1),!1===e.allowHalfOpen&&(this.allowHalfOpen=!1,this.once("end",d)))}function d(){this._writableState.ended||process.nextTick(u,this)}function u(e){e.end()}Object.defineProperty(l.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),Object.defineProperty(l.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(l.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(l.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&void 0!==this._writableState&&this._readableState.destroyed&&this._writableState.destroyed},set:function(e){void 0!==this._readableState&&void 0!==this._writableState&&(this._readableState.destroyed=e,this._writableState.destroyed=e)}})},2725:(e,t,n)=>{"use strict";e.exports=i;var r=n(4605);function i(e){if(!(this instanceof i))return new i(e);r.call(this,e)}n(5717)(i,r),i.prototype._transform=function(e,t,n){n(null,e)}},9481:(e,t,n)=>{"use strict";var r;e.exports=C,C.ReadableState=S,n(7187).EventEmitter;var i,s=function(e,t){return e.listeners(t).length},o=n(2503),a=n(8764).Buffer,c=(void 0!==n.g?n.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},l=n(4616);i=l&&l.debuglog?l.debuglog("stream"):function(){};var d,u,h,f=n(7327),g=n(1195),p=n(2457).getHighWaterMark,m=n(4281).q,y=m.ERR_INVALID_ARG_TYPE,v=m.ERR_STREAM_PUSH_AFTER_EOF,b=m.ERR_METHOD_NOT_IMPLEMENTED,_=m.ERR_STREAM_UNSHIFT_AFTER_END_EVENT;n(5717)(C,o);var E=g.errorOrDestroy,w=["error","close","destroy","pause","resume"];function S(e,t,i){r=r||n(6753),e=e||{},"boolean"!=typeof i&&(i=t instanceof r),this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode),this.highWaterMark=p(this,e,"readableHighWaterMark",i),this.buffer=new f,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.paused=!0,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(d||(d=n(2553).s),this.decoder=new d(e.encoding),this.encoding=e.encoding)}function C(e){if(r=r||n(6753),!(this instanceof C))return new C(e);var t=this instanceof r;this._readableState=new S(e,this,t),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),o.call(this)}function T(e,t,n,r,s){i("readableAddChunk",t);var o,l=e._readableState;if(null===t)l.reading=!1,function(e,t){if(i("onEofChunk"),!t.ended){if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,t.sync?O(e):(t.needReadable=!1,t.emittedReadable||(t.emittedReadable=!0,A(e)))}}(e,l);else if(s||(o=function(e,t){var n,r;return r=t,a.isBuffer(r)||r instanceof c||"string"==typeof t||void 0===t||e.objectMode||(n=new y("chunk",["string","Buffer","Uint8Array"],t)),n}(l,t)),o)E(e,o);else if(l.objectMode||t&&t.length>0)if("string"==typeof t||l.objectMode||Object.getPrototypeOf(t)===a.prototype||(t=function(e){return a.from(e)}(t)),r)l.endEmitted?E(e,new _):R(e,l,t,!0);else if(l.ended)E(e,new v);else{if(l.destroyed)return!1;l.reading=!1,l.decoder&&!n?(t=l.decoder.write(t),l.objectMode||0!==t.length?R(e,l,t,!1):D(e,l)):R(e,l,t,!1)}else r||(l.reading=!1,D(e,l));return!l.ended&&(l.length<l.highWaterMark||0===l.length)}function R(e,t,n,r){t.flowing&&0===t.length&&!t.sync?(t.awaitDrain=0,e.emit("data",n)):(t.length+=t.objectMode?1:n.length,r?t.buffer.unshift(n):t.buffer.push(n),t.needReadable&&O(e)),D(e,t)}Object.defineProperty(C.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._readableState&&this._readableState.destroyed},set:function(e){this._readableState&&(this._readableState.destroyed=e)}}),C.prototype.destroy=g.destroy,C.prototype._undestroy=g.undestroy,C.prototype._destroy=function(e,t){t(e)},C.prototype.push=function(e,t){var n,r=this._readableState;return r.objectMode?n=!0:"string"==typeof e&&((t=t||r.defaultEncoding)!==r.encoding&&(e=a.from(e,t),t=""),n=!0),T(this,e,t,!1,n)},C.prototype.unshift=function(e){return T(this,e,null,!0,!1)},C.prototype.isPaused=function(){return!1===this._readableState.flowing},C.prototype.setEncoding=function(e){d||(d=n(2553).s);var t=new d(e);this._readableState.decoder=t,this._readableState.encoding=this._readableState.decoder.encoding;for(var r=this._readableState.buffer.head,i="";null!==r;)i+=t.write(r.data),r=r.next;return this._readableState.buffer.clear(),""!==i&&this._readableState.buffer.push(i),this._readableState.length=i.length,this};var I=1073741824;function k(e,t){return e<=0||0===t.length&&t.ended?0:t.objectMode?1:e!=e?t.flowing&&t.length?t.buffer.head.data.length:t.length:(e>t.highWaterMark&&(t.highWaterMark=function(e){return e>=I?e=I:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function O(e){var t=e._readableState;i("emitReadable",t.needReadable,t.emittedReadable),t.needReadable=!1,t.emittedReadable||(i("emitReadable",t.flowing),t.emittedReadable=!0,process.nextTick(A,e))}function A(e){var t=e._readableState;i("emitReadable_",t.destroyed,t.length,t.ended),t.destroyed||!t.length&&!t.ended||(e.emit("readable"),t.emittedReadable=!1),t.needReadable=!t.flowing&&!t.ended&&t.length<=t.highWaterMark,N(e)}function D(e,t){t.readingMore||(t.readingMore=!0,process.nextTick(M,e,t))}function M(e,t){for(;!t.reading&&!t.ended&&(t.length<t.highWaterMark||t.flowing&&0===t.length);){var n=t.length;if(i("maybeReadMore read 0"),e.read(0),n===t.length)break}t.readingMore=!1}function P(e){var t=e._readableState;t.readableListening=e.listenerCount("readable")>0,t.resumeScheduled&&!t.paused?t.flowing=!0:e.listenerCount("data")>0&&e.resume()}function U(e){i("readable nexttick read 0"),e.read(0)}function L(e,t){i("resume",t.reading),t.reading||e.read(0),t.resumeScheduled=!1,e.emit("resume"),N(e),t.flowing&&!t.reading&&e.read(0)}function N(e){var t=e._readableState;for(i("flow",t.flowing);t.flowing&&null!==e.read(););}function x(e,t){return 0===t.length?null:(t.objectMode?n=t.buffer.shift():!e||e>=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.first():t.buffer.concat(t.length),t.buffer.clear()):n=t.buffer.consume(e,t.decoder),n);var n}function B(e){var t=e._readableState;i("endReadable",t.endEmitted),t.endEmitted||(t.ended=!0,process.nextTick(j,t,e))}function j(e,t){if(i("endReadableNT",e.endEmitted,e.length),!e.endEmitted&&0===e.length&&(e.endEmitted=!0,t.readable=!1,t.emit("end"),e.autoDestroy)){var n=t._writableState;(!n||n.autoDestroy&&n.finished)&&t.destroy()}}function F(e,t){for(var n=0,r=e.length;n<r;n++)if(e[n]===t)return n;return-1}C.prototype.read=function(e){i("read",e),e=parseInt(e,10);var t=this._readableState,n=e;if(0!==e&&(t.emittedReadable=!1),0===e&&t.needReadable&&((0!==t.highWaterMark?t.length>=t.highWaterMark:t.length>0)||t.ended))return i("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?B(this):O(this),null;if(0===(e=k(e,t))&&t.ended)return 0===t.length&&B(this),null;var r,s=t.needReadable;return i("need readable",s),(0===t.length||t.length-e<t.highWaterMark)&&i("length less than watermark",s=!0),t.ended||t.reading?i("reading or ended",s=!1):s&&(i("do read"),t.reading=!0,t.sync=!0,0===t.length&&(t.needReadable=!0),this._read(t.highWaterMark),t.sync=!1,t.reading||(e=k(n,t))),null===(r=e>0?x(e,t):null)?(t.needReadable=t.length<=t.highWaterMark,e=0):(t.length-=e,t.awaitDrain=0),0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&B(this)),null!==r&&this.emit("data",r),r},C.prototype._read=function(e){E(this,new b("_read()"))},C.prototype.pipe=function(e,t){var n=this,r=this._readableState;switch(r.pipesCount){case 0:r.pipes=e;break;case 1:r.pipes=[r.pipes,e];break;default:r.pipes.push(e)}r.pipesCount+=1,i("pipe count=%d opts=%j",r.pipesCount,t);var o=t&&!1===t.end||e===process.stdout||e===process.stderr?g:a;function a(){i("onend"),e.end()}r.endEmitted?process.nextTick(o):n.once("end",o),e.on("unpipe",(function t(s,o){i("onunpipe"),s===n&&o&&!1===o.hasUnpiped&&(o.hasUnpiped=!0,i("cleanup"),e.removeListener("close",h),e.removeListener("finish",f),e.removeListener("drain",c),e.removeListener("error",u),e.removeListener("unpipe",t),n.removeListener("end",a),n.removeListener("end",g),n.removeListener("data",d),l=!0,!r.awaitDrain||e._writableState&&!e._writableState.needDrain||c())}));var c=function(e){return function(){var t=e._readableState;i("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&s(e,"data")&&(t.flowing=!0,N(e))}}(n);e.on("drain",c);var l=!1;function d(t){i("ondata");var s=e.write(t);i("dest.write",s),!1===s&&((1===r.pipesCount&&r.pipes===e||r.pipesCount>1&&-1!==F(r.pipes,e))&&!l&&(i("false write response, pause",r.awaitDrain),r.awaitDrain++),n.pause())}function u(t){i("onerror",t),g(),e.removeListener("error",u),0===s(e,"error")&&E(e,t)}function h(){e.removeListener("finish",f),g()}function f(){i("onfinish"),e.removeListener("close",h),g()}function g(){i("unpipe"),n.unpipe(e)}return n.on("data",d),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?Array.isArray(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",u),e.once("close",h),e.once("finish",f),e.emit("pipe",n),r.flowing||(i("pipe resume"),n.resume()),e},C.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes||(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n)),this;if(!e){var r=t.pipes,i=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var s=0;s<i;s++)r[s].emit("unpipe",this,{hasUnpiped:!1});return this}var o=F(t.pipes,e);return-1===o||(t.pipes.splice(o,1),t.pipesCount-=1,1===t.pipesCount&&(t.pipes=t.pipes[0]),e.emit("unpipe",this,n)),this},C.prototype.on=function(e,t){var n=o.prototype.on.call(this,e,t),r=this._readableState;return"data"===e?(r.readableListening=this.listenerCount("readable")>0,!1!==r.flowing&&this.resume()):"readable"===e&&(r.endEmitted||r.readableListening||(r.readableListening=r.needReadable=!0,r.flowing=!1,r.emittedReadable=!1,i("on readable",r.length,r.reading),r.length?O(this):r.reading||process.nextTick(U,this))),n},C.prototype.addListener=C.prototype.on,C.prototype.removeListener=function(e,t){var n=o.prototype.removeListener.call(this,e,t);return"readable"===e&&process.nextTick(P,this),n},C.prototype.removeAllListeners=function(e){var t=o.prototype.removeAllListeners.apply(this,arguments);return"readable"!==e&&void 0!==e||process.nextTick(P,this),t},C.prototype.resume=function(){var e=this._readableState;return e.flowing||(i("resume"),e.flowing=!e.readableListening,function(e,t){t.resumeScheduled||(t.resumeScheduled=!0,process.nextTick(L,e,t))}(this,e)),e.paused=!1,this},C.prototype.pause=function(){return i("call pause flowing=%j",this._readableState.flowing),!1!==this._readableState.flowing&&(i("pause"),this._readableState.flowing=!1,this.emit("pause")),this._readableState.paused=!0,this},C.prototype.wrap=function(e){var t=this,n=this._readableState,r=!1;for(var s in e.on("end",(function(){if(i("wrapped end"),n.decoder&&!n.ended){var e=n.decoder.end();e&&e.length&&t.push(e)}t.push(null)})),e.on("data",(function(s){i("wrapped data"),n.decoder&&(s=n.decoder.write(s)),n.objectMode&&null==s||(n.objectMode||s&&s.length)&&(t.push(s)||(r=!0,e.pause()))})),e)void 0===this[s]&&"function"==typeof e[s]&&(this[s]=function(t){return function(){return e[t].apply(e,arguments)}}(s));for(var o=0;o<w.length;o++)e.on(w[o],this.emit.bind(this,w[o]));return this._read=function(t){i("wrapped _read",t),r&&(r=!1,e.resume())},this},"function"==typeof Symbol&&(C.prototype[Symbol.asyncIterator]=function(){return void 0===u&&(u=n(5850)),u(this)}),Object.defineProperty(C.prototype,"readableHighWaterMark",{enumerable:!1,get:function(){return this._readableState.highWaterMark}}),Object.defineProperty(C.prototype,"readableBuffer",{enumerable:!1,get:function(){return this._readableState&&this._readableState.buffer}}),Object.defineProperty(C.prototype,"readableFlowing",{enumerable:!1,get:function(){return this._readableState.flowing},set:function(e){this._readableState&&(this._readableState.flowing=e)}}),C._fromList=x,Object.defineProperty(C.prototype,"readableLength",{enumerable:!1,get:function(){return this._readableState.length}}),"function"==typeof Symbol&&(C.from=function(e,t){return void 0===h&&(h=n(5167)),h(C,e,t)})},4605:(e,t,n)=>{"use strict";e.exports=d;var r=n(4281).q,i=r.ERR_METHOD_NOT_IMPLEMENTED,s=r.ERR_MULTIPLE_CALLBACK,o=r.ERR_TRANSFORM_ALREADY_TRANSFORMING,a=r.ERR_TRANSFORM_WITH_LENGTH_0,c=n(6753);function l(e,t){var n=this._transformState;n.transforming=!1;var r=n.writecb;if(null===r)return this.emit("error",new s);n.writechunk=null,n.writecb=null,null!=t&&this.push(t),r(e);var i=this._readableState;i.reading=!1,(i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}function d(e){if(!(this instanceof d))return new d(e);c.call(this,e),this._transformState={afterTransform:l.bind(this),needTransform:!1,transforming:!1,writecb:null,writechunk:null,writeencoding:null},this._readableState.needReadable=!0,this._readableState.sync=!1,e&&("function"==typeof e.transform&&(this._transform=e.transform),"function"==typeof e.flush&&(this._flush=e.flush)),this.on("prefinish",u)}function u(){var e=this;"function"!=typeof this._flush||this._readableState.destroyed?h(this,null,null):this._flush((function(t,n){h(e,t,n)}))}function h(e,t,n){if(t)return e.emit("error",t);if(null!=n&&e.push(n),e._writableState.length)throw new a;if(e._transformState.transforming)throw new o;return e.push(null)}n(5717)(d,c),d.prototype.push=function(e,t){return this._transformState.needTransform=!1,c.prototype.push.call(this,e,t)},d.prototype._transform=function(e,t,n){n(new i("_transform()"))},d.prototype._write=function(e,t,n){var r=this._transformState;if(r.writecb=n,r.writechunk=e,r.writeencoding=t,!r.transforming){var i=this._readableState;(r.needTransform||i.needReadable||i.length<i.highWaterMark)&&this._read(i.highWaterMark)}},d.prototype._read=function(e){var t=this._transformState;null===t.writechunk||t.transforming?t.needTransform=!0:(t.transforming=!0,this._transform(t.writechunk,t.writeencoding,t.afterTransform))},d.prototype._destroy=function(e,t){c.prototype._destroy.call(this,e,(function(e){t(e)}))}},4229:(e,t,n)=>{"use strict";function r(e){var t=this;this.next=null,this.entry=null,this.finish=function(){!function(e,t,n){var r=e.entry;for(e.entry=null;r;){var i=r.callback;t.pendingcb--,i(undefined),r=r.next}t.corkedRequestsFree.next=e}(t,e)}}var i;e.exports=C,C.WritableState=S;var s,o={deprecate:n(4927)},a=n(2503),c=n(8764).Buffer,l=(void 0!==n.g?n.g:"undefined"!=typeof window?window:"undefined"!=typeof self?self:{}).Uint8Array||function(){},d=n(1195),u=n(2457).getHighWaterMark,h=n(4281).q,f=h.ERR_INVALID_ARG_TYPE,g=h.ERR_METHOD_NOT_IMPLEMENTED,p=h.ERR_MULTIPLE_CALLBACK,m=h.ERR_STREAM_CANNOT_PIPE,y=h.ERR_STREAM_DESTROYED,v=h.ERR_STREAM_NULL_VALUES,b=h.ERR_STREAM_WRITE_AFTER_END,_=h.ERR_UNKNOWN_ENCODING,E=d.errorOrDestroy;function w(){}function S(e,t,s){i=i||n(6753),e=e||{},"boolean"!=typeof s&&(s=t instanceof i),this.objectMode=!!e.objectMode,s&&(this.objectMode=this.objectMode||!!e.writableObjectMode),this.highWaterMark=u(this,e,"writableHighWaterMark",s),this.finalCalled=!1,this.needDrain=!1,this.ending=!1,this.ended=!1,this.finished=!1,this.destroyed=!1;var o=!1===e.decodeStrings;this.decodeStrings=!o,this.defaultEncoding=e.defaultEncoding||"utf8",this.length=0,this.writing=!1,this.corked=0,this.sync=!0,this.bufferProcessing=!1,this.onwrite=function(e){!function(e,t){var n=e._writableState,r=n.sync,i=n.writecb;if("function"!=typeof i)throw new p;if(function(e){e.writing=!1,e.writecb=null,e.length-=e.writelen,e.writelen=0}(n),t)!function(e,t,n,r,i){--t.pendingcb,n?(process.nextTick(i,r),process.nextTick(A,e,t),e._writableState.errorEmitted=!0,E(e,r)):(i(r),e._writableState.errorEmitted=!0,E(e,r),A(e,t))}(e,n,r,t,i);else{var s=k(n)||e.destroyed;s||n.corked||n.bufferProcessing||!n.bufferedRequest||I(e,n),r?process.nextTick(R,e,n,s,i):R(e,n,s,i)}}(t,e)},this.writecb=null,this.writelen=0,this.bufferedRequest=null,this.lastBufferedRequest=null,this.pendingcb=0,this.prefinished=!1,this.errorEmitted=!1,this.emitClose=!1!==e.emitClose,this.autoDestroy=!!e.autoDestroy,this.bufferedRequestCount=0,this.corkedRequestsFree=new r(this)}function C(e){var t=this instanceof(i=i||n(6753));if(!t&&!s.call(C,this))return new C(e);this._writableState=new S(e,this,t),this.writable=!0,e&&("function"==typeof e.write&&(this._write=e.write),"function"==typeof e.writev&&(this._writev=e.writev),"function"==typeof e.destroy&&(this._destroy=e.destroy),"function"==typeof e.final&&(this._final=e.final)),a.call(this)}function T(e,t,n,r,i,s,o){t.writelen=r,t.writecb=o,t.writing=!0,t.sync=!0,t.destroyed?t.onwrite(new y("write")):n?e._writev(i,t.onwrite):e._write(i,s,t.onwrite),t.sync=!1}function R(e,t,n,r){n||function(e,t){0===t.length&&t.needDrain&&(t.needDrain=!1,e.emit("drain"))}(e,t),t.pendingcb--,r(),A(e,t)}function I(e,t){t.bufferProcessing=!0;var n=t.bufferedRequest;if(e._writev&&n&&n.next){var i=t.bufferedRequestCount,s=new Array(i),o=t.corkedRequestsFree;o.entry=n;for(var a=0,c=!0;n;)s[a]=n,n.isBuf||(c=!1),n=n.next,a+=1;s.allBuffers=c,T(e,t,!0,t.length,s,"",o.finish),t.pendingcb++,t.lastBufferedRequest=null,o.next?(t.corkedRequestsFree=o.next,o.next=null):t.corkedRequestsFree=new r(t),t.bufferedRequestCount=0}else{for(;n;){var l=n.chunk,d=n.encoding,u=n.callback;if(T(e,t,!1,t.objectMode?1:l.length,l,d,u),n=n.next,t.bufferedRequestCount--,t.writing)break}null===n&&(t.lastBufferedRequest=null)}t.bufferedRequest=n,t.bufferProcessing=!1}function k(e){return e.ending&&0===e.length&&null===e.bufferedRequest&&!e.finished&&!e.writing}function O(e,t){e._final((function(n){t.pendingcb--,n&&E(e,n),t.prefinished=!0,e.emit("prefinish"),A(e,t)}))}function A(e,t){var n=k(t);if(n&&(function(e,t){t.prefinished||t.finalCalled||("function"!=typeof e._final||t.destroyed?(t.prefinished=!0,e.emit("prefinish")):(t.pendingcb++,t.finalCalled=!0,process.nextTick(O,e,t)))}(e,t),0===t.pendingcb&&(t.finished=!0,e.emit("finish"),t.autoDestroy))){var r=e._readableState;(!r||r.autoDestroy&&r.endEmitted)&&e.destroy()}return n}n(5717)(C,a),S.prototype.getBuffer=function(){for(var e=this.bufferedRequest,t=[];e;)t.push(e),e=e.next;return t},function(){try{Object.defineProperty(S.prototype,"buffer",{get:o.deprecate((function(){return this.getBuffer()}),"_writableState.buffer is deprecated. Use _writableState.getBuffer instead.","DEP0003")})}catch(e){}}(),"function"==typeof Symbol&&Symbol.hasInstance&&"function"==typeof Function.prototype[Symbol.hasInstance]?(s=Function.prototype[Symbol.hasInstance],Object.defineProperty(C,Symbol.hasInstance,{value:function(e){return!!s.call(this,e)||this===C&&e&&e._writableState instanceof S}})):s=function(e){return e instanceof this},C.prototype.pipe=function(){E(this,new m)},C.prototype.write=function(e,t,n){var r,i=this._writableState,s=!1,o=!i.objectMode&&(r=e,c.isBuffer(r)||r instanceof l);return o&&!c.isBuffer(e)&&(e=function(e){return c.from(e)}(e)),"function"==typeof t&&(n=t,t=null),o?t="buffer":t||(t=i.defaultEncoding),"function"!=typeof n&&(n=w),i.ending?function(e,t){var n=new b;E(e,n),process.nextTick(t,n)}(this,n):(o||function(e,t,n,r){var i;return null===n?i=new v:"string"==typeof n||t.objectMode||(i=new f("chunk",["string","Buffer"],n)),!i||(E(e,i),process.nextTick(r,i),!1)}(this,i,e,n))&&(i.pendingcb++,s=function(e,t,n,r,i,s){if(!n){var o=function(e,t,n){return e.objectMode||!1===e.decodeStrings||"string"!=typeof t||(t=c.from(t,n)),t}(t,r,i);r!==o&&(n=!0,i="buffer",r=o)}var a=t.objectMode?1:r.length;t.length+=a;var l=t.length<t.highWaterMark;if(l||(t.needDrain=!0),t.writing||t.corked){var d=t.lastBufferedRequest;t.lastBufferedRequest={chunk:r,encoding:i,isBuf:n,callback:s,next:null},d?d.next=t.lastBufferedRequest:t.bufferedRequest=t.lastBufferedRequest,t.bufferedRequestCount+=1}else T(e,t,!1,a,r,i,s);return l}(this,i,o,e,t,n)),s},C.prototype.cork=function(){this._writableState.corked++},C.prototype.uncork=function(){var e=this._writableState;e.corked&&(e.corked--,e.writing||e.corked||e.bufferProcessing||!e.bufferedRequest||I(this,e))},C.prototype.setDefaultEncoding=function(e){if("string"==typeof e&&(e=e.toLowerCase()),!(["hex","utf8","utf-8","ascii","binary","base64","ucs2","ucs-2","utf16le","utf-16le","raw"].indexOf((e+"").toLowerCase())>-1))throw new _(e);return this._writableState.defaultEncoding=e,this},Object.defineProperty(C.prototype,"writableBuffer",{enumerable:!1,get:function(){return this._writableState&&this._writableState.getBuffer()}}),Object.defineProperty(C.prototype,"writableHighWaterMark",{enumerable:!1,get:function(){return this._writableState.highWaterMark}}),C.prototype._write=function(e,t,n){n(new g("_write()"))},C.prototype._writev=null,C.prototype.end=function(e,t,n){var r=this._writableState;return"function"==typeof e?(n=e,e=null,t=null):"function"==typeof t&&(n=t,t=null),null!=e&&this.write(e,t),r.corked&&(r.corked=1,this.uncork()),r.ending||function(e,t,n){t.ending=!0,A(e,t),n&&(t.finished?process.nextTick(n):e.once("finish",n)),t.ended=!0,e.writable=!1}(this,r,n),this},Object.defineProperty(C.prototype,"writableLength",{enumerable:!1,get:function(){return this._writableState.length}}),Object.defineProperty(C.prototype,"destroyed",{enumerable:!1,get:function(){return void 0!==this._writableState&&this._writableState.destroyed},set:function(e){this._writableState&&(this._writableState.destroyed=e)}}),C.prototype.destroy=d.destroy,C.prototype._undestroy=d.undestroy,C.prototype._destroy=function(e,t){t(e)}},5850:(e,t,n)=>{"use strict";var r;function i(e,t,n){return(t=function(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}var s=n(8610),o=Symbol("lastResolve"),a=Symbol("lastReject"),c=Symbol("error"),l=Symbol("ended"),d=Symbol("lastPromise"),u=Symbol("handlePromise"),h=Symbol("stream");function f(e,t){return{value:e,done:t}}function g(e){var t=e[o];if(null!==t){var n=e[h].read();null!==n&&(e[d]=null,e[o]=null,e[a]=null,t(f(n,!1)))}}function p(e){process.nextTick(g,e)}var m=Object.getPrototypeOf((function(){})),y=Object.setPrototypeOf((i(r={get stream(){return this[h]},next:function(){var e=this,t=this[c];if(null!==t)return Promise.reject(t);if(this[l])return Promise.resolve(f(void 0,!0));if(this[h].destroyed)return new Promise((function(t,n){process.nextTick((function(){e[c]?n(e[c]):t(f(void 0,!0))}))}));var n,r=this[d];if(r)n=new Promise(function(e,t){return function(n,r){e.then((function(){t[l]?n(f(void 0,!0)):t[u](n,r)}),r)}}(r,this));else{var i=this[h].read();if(null!==i)return Promise.resolve(f(i,!1));n=new Promise(this[u])}return this[d]=n,n}},Symbol.asyncIterator,(function(){return this})),i(r,"return",(function(){var e=this;return new Promise((function(t,n){e[h].destroy(null,(function(e){e?n(e):t(f(void 0,!0))}))}))})),r),m);e.exports=function(e){var t,n=Object.create(y,(i(t={},h,{value:e,writable:!0}),i(t,o,{value:null,writable:!0}),i(t,a,{value:null,writable:!0}),i(t,c,{value:null,writable:!0}),i(t,l,{value:e._readableState.endEmitted,writable:!0}),i(t,u,{value:function(e,t){var r=n[h].read();r?(n[d]=null,n[o]=null,n[a]=null,e(f(r,!1))):(n[o]=e,n[a]=t)},writable:!0}),t));return n[d]=null,s(e,(function(e){if(e&&"ERR_STREAM_PREMATURE_CLOSE"!==e.code){var t=n[a];return null!==t&&(n[d]=null,n[o]=null,n[a]=null,t(e)),void(n[c]=e)}var r=n[o];null!==r&&(n[d]=null,n[o]=null,n[a]=null,r(f(void 0,!0))),n[l]=!0})),e.on("readable",p.bind(null,n)),n}},7327:(e,t,n)=>{"use strict";function r(e,t){var n=Object.keys(e);if(Object.getOwnPropertySymbols){var r=Object.getOwnPropertySymbols(e);t&&(r=r.filter((function(t){return Object.getOwnPropertyDescriptor(e,t).enumerable}))),n.push.apply(n,r)}return n}function i(e){for(var t=1;t<arguments.length;t++){var n=null!=arguments[t]?arguments[t]:{};t%2?r(Object(n),!0).forEach((function(t){s(e,t,n[t])})):Object.getOwnPropertyDescriptors?Object.defineProperties(e,Object.getOwnPropertyDescriptors(n)):r(Object(n)).forEach((function(t){Object.defineProperty(e,t,Object.getOwnPropertyDescriptor(n,t))}))}return e}function s(e,t,n){return(t=a(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e}function o(e,t){for(var n=0;n<t.length;n++){var r=t[n];r.enumerable=r.enumerable||!1,r.configurable=!0,"value"in r&&(r.writable=!0),Object.defineProperty(e,a(r.key),r)}}function a(e){var t=function(e,t){if("object"!=typeof e||null===e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var r=n.call(e,"string");if("object"!=typeof r)return r;throw new TypeError("@@toPrimitive must return a primitive value.")}return String(e)}(e);return"symbol"==typeof t?t:String(t)}var c=n(8764).Buffer,l=n(2361).inspect,d=l&&l.custom||"inspect";e.exports=function(){function e(){!function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}(this,e),this.head=null,this.tail=null,this.length=0}var t,n;return t=e,(n=[{key:"push",value:function(e){var t={data:e,next:null};this.length>0?this.tail.next=t:this.head=t,this.tail=t,++this.length}},{key:"unshift",value:function(e){var t={data:e,next:this.head};0===this.length&&(this.tail=t),this.head=t,++this.length}},{key:"shift",value:function(){if(0!==this.length){var e=this.head.data;return 1===this.length?this.head=this.tail=null:this.head=this.head.next,--this.length,e}}},{key:"clear",value:function(){this.head=this.tail=null,this.length=0}},{key:"join",value:function(e){if(0===this.length)return"";for(var t=this.head,n=""+t.data;t=t.next;)n+=e+t.data;return n}},{key:"concat",value:function(e){if(0===this.length)return c.alloc(0);for(var t,n,r,i=c.allocUnsafe(e>>>0),s=this.head,o=0;s;)t=s.data,n=i,r=o,c.prototype.copy.call(t,n,r),o+=s.data.length,s=s.next;return i}},{key:"consume",value:function(e,t){var n;return e<this.head.data.length?(n=this.head.data.slice(0,e),this.head.data=this.head.data.slice(e)):n=e===this.head.data.length?this.shift():t?this._getString(e):this._getBuffer(e),n}},{key:"first",value:function(){return this.head.data}},{key:"_getString",value:function(e){var t=this.head,n=1,r=t.data;for(e-=r.length;t=t.next;){var i=t.data,s=e>i.length?i.length:e;if(s===i.length?r+=i:r+=i.slice(0,e),0==(e-=s)){s===i.length?(++n,t.next?this.head=t.next:this.head=this.tail=null):(this.head=t,t.data=i.slice(s));break}++n}return this.length-=n,r}},{key:"_getBuffer",value:function(e){var t=c.allocUnsafe(e),n=this.head,r=1;for(n.data.copy(t),e-=n.data.length;n=n.next;){var i=n.data,s=e>i.length?i.length:e;if(i.copy(t,t.length-e,0,s),0==(e-=s)){s===i.length?(++r,n.next?this.head=n.next:this.head=this.tail=null):(this.head=n,n.data=i.slice(s));break}++r}return this.length-=r,t}},{key:d,value:function(e,t){return l(this,i(i({},t),{},{depth:0,customInspect:!1}))}}])&&o(t.prototype,n),Object.defineProperty(t,"prototype",{writable:!1}),e}()},1195:e=>{"use strict";function t(e,t){r(e,t),n(e)}function n(e){e._writableState&&!e._writableState.emitClose||e._readableState&&!e._readableState.emitClose||e.emit("close")}function r(e,t){e.emit("error",t)}e.exports={destroy:function(e,i){var s=this,o=this._readableState&&this._readableState.destroyed,a=this._writableState&&this._writableState.destroyed;return o||a?(i?i(e):e&&(this._writableState?this._writableState.errorEmitted||(this._writableState.errorEmitted=!0,process.nextTick(r,this,e)):process.nextTick(r,this,e)),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,(function(e){!i&&e?s._writableState?s._writableState.errorEmitted?process.nextTick(n,s):(s._writableState.errorEmitted=!0,process.nextTick(t,s,e)):process.nextTick(t,s,e):i?(process.nextTick(n,s),i(e)):process.nextTick(n,s)})),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finalCalled=!1,this._writableState.prefinished=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)},errorOrDestroy:function(e,t){var n=e._readableState,r=e._writableState;n&&n.autoDestroy||r&&r.autoDestroy?e.destroy(t):e.emit("error",t)}}},8610:(e,t,n)=>{"use strict";var r=n(4281).q.ERR_STREAM_PREMATURE_CLOSE;function i(){}e.exports=function e(t,n,s){if("function"==typeof n)return e(t,null,n);n||(n={}),s=function(e){var t=!1;return function(){if(!t){t=!0;for(var n=arguments.length,r=new Array(n),i=0;i<n;i++)r[i]=arguments[i];e.apply(this,r)}}}(s||i);var o=n.readable||!1!==n.readable&&t.readable,a=n.writable||!1!==n.writable&&t.writable,c=function(){t.writable||d()},l=t._writableState&&t._writableState.finished,d=function(){a=!1,l=!0,o||s.call(t)},u=t._readableState&&t._readableState.endEmitted,h=function(){o=!1,u=!0,a||s.call(t)},f=function(e){s.call(t,e)},g=function(){var e;return o&&!u?(t._readableState&&t._readableState.ended||(e=new r),s.call(t,e)):a&&!l?(t._writableState&&t._writableState.ended||(e=new r),s.call(t,e)):void 0},p=function(){t.req.on("finish",d)};return function(e){return e.setHeader&&"function"==typeof e.abort}(t)?(t.on("complete",d),t.on("abort",g),t.req?p():t.on("request",p)):a&&!t._writableState&&(t.on("end",c),t.on("close",c)),t.on("end",h),t.on("finish",d),!1!==n.error&&t.on("error",f),t.on("close",g),function(){t.removeListener("complete",d),t.removeListener("abort",g),t.removeListener("request",p),t.req&&t.req.removeListener("finish",d),t.removeListener("end",c),t.removeListener("close",c),t.removeListener("finish",d),t.removeListener("end",h),t.removeListener("error",f),t.removeListener("close",g)}}},5167:e=>{e.exports=function(){throw new Error("Readable.from is not available in the browser")}},9946:(e,t,n)=>{"use strict";var r,i=n(4281).q,s=i.ERR_MISSING_ARGS,o=i.ERR_STREAM_DESTROYED;function a(e){if(e)throw e}function c(e){e()}function l(e,t){return e.pipe(t)}e.exports=function(){for(var e=arguments.length,t=new Array(e),i=0;i<e;i++)t[i]=arguments[i];var d,u=function(e){return e.length?"function"!=typeof e[e.length-1]?a:e.pop():a}(t);if(Array.isArray(t[0])&&(t=t[0]),t.length<2)throw new s("streams");var h=t.map((function(e,i){var s=i<t.length-1;return function(e,t,i,s){s=function(e){var t=!1;return function(){t||(t=!0,e.apply(void 0,arguments))}}(s);var a=!1;e.on("close",(function(){a=!0})),void 0===r&&(r=n(8610)),r(e,{readable:t,writable:i},(function(e){if(e)return s(e);a=!0,s()}));var c=!1;return function(t){if(!a&&!c)return c=!0,function(e){return e.setHeader&&"function"==typeof e.abort}(e)?e.abort():"function"==typeof e.destroy?e.destroy():void s(t||new o("pipe"))}}(e,s,i>0,(function(e){d||(d=e),e&&h.forEach(c),s||(h.forEach(c),u(d))}))}));return t.reduce(l)}},2457:(e,t,n)=>{"use strict";var r=n(4281).q.ERR_INVALID_OPT_VALUE;e.exports={getHighWaterMark:function(e,t,n,i){var s=function(e,t,n){return null!=e.highWaterMark?e.highWaterMark:t?e[n]:null}(t,i,n);if(null!=s){if(!isFinite(s)||Math.floor(s)!==s||s<0)throw new r(i?n:"highWaterMark",s);return Math.floor(s)}return e.objectMode?16:16384}}},2503:(e,t,n)=>{e.exports=n(7187).EventEmitter},8473:(e,t,n)=>{(t=e.exports=n(9481)).Stream=t,t.Readable=t,t.Writable=n(4229),t.Duplex=n(6753),t.Transform=n(4605),t.PassThrough=n(2725),t.finished=n(8610),t.pipeline=n(9946)},9353:(e,t,n)=>{e.exports=n(1846)},1846:(e,t,n)=>{var r=n(1960);t.operation=function(e){var n=t.timeouts(e);return new r(n,{forever:e&&(e.forever||e.retries===1/0),unref:e&&e.unref,maxRetryTime:e&&e.maxRetryTime})},t.timeouts=function(e){if(e instanceof Array)return[].concat(e);var t={retries:10,factor:2,minTimeout:1e3,maxTimeout:1/0,randomize:!1};for(var n in e)t[n]=e[n];if(t.minTimeout>t.maxTimeout)throw new Error("minTimeout is greater than maxTimeout");for(var r=[],i=0;i<t.retries;i++)r.push(this.createTimeout(i,t));return e&&e.forever&&!r.length&&r.push(this.createTimeout(i,t)),r.sort((function(e,t){return e-t})),r},t.createTimeout=function(e,t){var n=t.randomize?Math.random()+1:1,r=Math.round(n*Math.max(t.minTimeout,1)*Math.pow(t.factor,e));return Math.min(r,t.maxTimeout)},t.wrap=function(e,n,r){if(n instanceof Array&&(r=n,n=null),!r)for(var i in r=[],e)"function"==typeof e[i]&&r.push(i);for(var s=0;s<r.length;s++){var o=r[s],a=e[o];e[o]=function(r){var i=t.operation(n),s=Array.prototype.slice.call(arguments,1),o=s.pop();s.push((function(e){i.retry(e)||(e&&(arguments[0]=i.mainError()),o.apply(this,arguments))})),i.attempt((function(){r.apply(e,s)}))}.bind(e,a),e[o].options=n}}},1960:e=>{function t(e,t){"boolean"==typeof t&&(t={forever:t}),this._originalTimeouts=JSON.parse(JSON.stringify(e)),this._timeouts=e,this._options=t||{},this._maxRetryTime=t&&t.maxRetryTime||1/0,this._fn=null,this._errors=[],this._attempts=1,this._operationTimeout=null,this._operationTimeoutCb=null,this._timeout=null,this._operationStart=null,this._timer=null,this._options.forever&&(this._cachedTimeouts=this._timeouts.slice(0))}e.exports=t,t.prototype.reset=function(){this._attempts=1,this._timeouts=this._originalTimeouts.slice(0)},t.prototype.stop=function(){this._timeout&&clearTimeout(this._timeout),this._timer&&clearTimeout(this._timer),this._timeouts=[],this._cachedTimeouts=null},t.prototype.retry=function(e){if(this._timeout&&clearTimeout(this._timeout),!e)return!1;var t=(new Date).getTime();if(e&&t-this._operationStart>=this._maxRetryTime)return this._errors.push(e),this._errors.unshift(new Error("RetryOperation timeout occurred")),!1;this._errors.push(e);var n=this._timeouts.shift();if(void 0===n){if(!this._cachedTimeouts)return!1;this._errors.splice(0,this._errors.length-1),n=this._cachedTimeouts.slice(-1)}var r=this;return this._timer=setTimeout((function(){r._attempts++,r._operationTimeoutCb&&(r._timeout=setTimeout((function(){r._operationTimeoutCb(r._attempts)}),r._operationTimeout),r._options.unref&&r._timeout.unref()),r._fn(r._attempts)}),n),this._options.unref&&this._timer.unref(),!0},t.prototype.attempt=function(e,t){this._fn=e,t&&(t.timeout&&(this._operationTimeout=t.timeout),t.cb&&(this._operationTimeoutCb=t.cb));var n=this;this._operationTimeoutCb&&(this._timeout=setTimeout((function(){n._operationTimeoutCb()}),n._operationTimeout)),this._operationStart=(new Date).getTime(),this._fn(this._attempts)},t.prototype.try=function(e){console.log("Using RetryOperation.try() is deprecated"),this.attempt(e)},t.prototype.start=function(e){console.log("Using RetryOperation.start() is deprecated"),this.attempt(e)},t.prototype.start=t.prototype.try,t.prototype.errors=function(){return this._errors},t.prototype.attempts=function(){return this._attempts},t.prototype.mainError=function(){if(0===this._errors.length)return null;for(var e={},t=null,n=0,r=0;r<this._errors.length;r++){var i=this._errors[r],s=i.message,o=(e[s]||0)+1;e[s]=o,o>=n&&(t=i,n=o)}return t}},9509:(e,t,n)=>{var r=n(8764),i=r.Buffer;function s(e,t){for(var n in e)t[n]=e[n]}function o(e,t,n){return i(e,t,n)}i.from&&i.alloc&&i.allocUnsafe&&i.allocUnsafeSlow?e.exports=r:(s(r,t),t.Buffer=o),o.prototype=Object.create(i.prototype),s(i,o),o.from=function(e,t,n){if("number"==typeof e)throw new TypeError("Argument must not be a number");return i(e,t,n)},o.alloc=function(e,t,n){if("number"!=typeof e)throw new TypeError("Argument must be a number");var r=i(e);return void 0!==t?"string"==typeof n?r.fill(t,n):r.fill(t):r.fill(0),r},o.allocUnsafe=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return i(e)},o.allocUnsafeSlow=function(e){if("number"!=typeof e)throw new TypeError("Argument must be a number");return r.SlowBuffer(e)}},7771:(e,t,n)=>{"use strict";var r=n(210),i=n(2296),s=n(1044)(),o=n(7296),a=r("%TypeError%"),c=r("%Math.floor%");e.exports=function(e,t){if("function"!=typeof e)throw new a("`fn` is not a function");if("number"!=typeof t||t<0||t>4294967295||c(t)!==t)throw new a("`length` must be a positive 32-bit integer");var n=arguments.length>2&&!!arguments[2],r=!0,l=!0;if("length"in e&&o){var d=o(e,"length");d&&!d.configurable&&(r=!1),d&&!d.writable&&(l=!1)}return(r||l||!n)&&(s?i(e,"length",t,!0,!0):i(e,"length",t)),e}},7478:(e,t,n)=>{"use strict";var r=n(210),i=n(1924),s=n(631),o=r("%TypeError%"),a=r("%WeakMap%",!0),c=r("%Map%",!0),l=i("WeakMap.prototype.get",!0),d=i("WeakMap.prototype.set",!0),u=i("WeakMap.prototype.has",!0),h=i("Map.prototype.get",!0),f=i("Map.prototype.set",!0),g=i("Map.prototype.has",!0),p=function(e,t){for(var n,r=e;null!==(n=r.next);r=n)if(n.key===t)return r.next=n.next,n.next=e.next,e.next=n,n};e.exports=function(){var e,t,n,r={assert:function(e){if(!r.has(e))throw new o("Side channel does not contain "+s(e))},get:function(r){if(a&&r&&("object"==typeof r||"function"==typeof r)){if(e)return l(e,r)}else if(c){if(t)return h(t,r)}else if(n)return function(e,t){var n=p(e,t);return n&&n.value}(n,r)},has:function(r){if(a&&r&&("object"==typeof r||"function"==typeof r)){if(e)return u(e,r)}else if(c){if(t)return g(t,r)}else if(n)return function(e,t){return!!p(e,t)}(n,r);return!1},set:function(r,i){a&&r&&("object"==typeof r||"function"==typeof r)?(e||(e=new a),d(e,r,i)):c?(t||(t=new c),f(t,r,i)):(n||(n={key:{},next:null}),function(e,t,n){var r=p(e,t);r?r.value=n:e.next={key:t,next:e.next,value:n}}(n,r,i))}};return r}},8853:(e,t,n)=>{const r=n(1227)("simple-peer"),i=n(5177),s=n(1798),o=n(8473),a=n(4375),c=n(2114),{Buffer:l}=n(8764),d=65536;function u(e){return e.replace(/a=ice-options:trickle\s\n/g,"")}class h extends o.Duplex{constructor(e){if(super(e=Object.assign({allowHalfOpen:!1},e)),this._id=s(4).toString("hex").slice(0,7),this._debug("new peer %o",e),this.channelName=e.initiator?e.channelName||s(20).toString("hex"):null,this.initiator=e.initiator||!1,this.channelConfig=e.channelConfig||h.channelConfig,this.channelNegotiated=this.channelConfig.negotiated,this.config=Object.assign({},h.config,e.config),this.offerOptions=e.offerOptions||{},this.answerOptions=e.answerOptions||{},this.sdpTransform=e.sdpTransform||(e=>e),this.streams=e.streams||(e.stream?[e.stream]:[]),this.trickle=void 0===e.trickle||e.trickle,this.allowHalfTrickle=void 0!==e.allowHalfTrickle&&e.allowHalfTrickle,this.iceCompleteTimeout=e.iceCompleteTimeout||5e3,this.destroyed=!1,this.destroying=!1,this._connected=!1,this.remoteAddress=void 0,this.remoteFamily=void 0,this.remotePort=void 0,this.localAddress=void 0,this.localFamily=void 0,this.localPort=void 0,this._wrtc=e.wrtc&&"object"==typeof e.wrtc?e.wrtc:i(),!this._wrtc)throw"undefined"==typeof window?c(new Error("No WebRTC support: Specify `opts.wrtc` option in this environment"),"ERR_WEBRTC_SUPPORT"):c(new Error("No WebRTC support: Not a supported browser"),"ERR_WEBRTC_SUPPORT");this._pcReady=!1,this._channelReady=!1,this._iceComplete=!1,this._iceCompleteTimer=null,this._channel=null,this._pendingCandidates=[],this._isNegotiating=!1,this._firstNegotiation=!0,this._batchedNegotiation=!1,this._queuedNegotiation=!1,this._sendersAwaitingStable=[],this._senderMap=new Map,this._closingInterval=null,this._remoteTracks=[],this._remoteStreams=[],this._chunk=null,this._cb=null,this._interval=null;try{this._pc=new this._wrtc.RTCPeerConnection(this.config)}catch(e){return void this.destroy(c(e,"ERR_PC_CONSTRUCTOR"))}this._isReactNativeWebrtc="number"==typeof this._pc._peerConnectionId,this._pc.oniceconnectionstatechange=()=>{this._onIceStateChange()},this._pc.onicegatheringstatechange=()=>{this._onIceStateChange()},this._pc.onconnectionstatechange=()=>{this._onConnectionStateChange()},this._pc.onsignalingstatechange=()=>{this._onSignalingStateChange()},this._pc.onicecandidate=e=>{this._onIceCandidate(e)},"object"==typeof this._pc.peerIdentity&&this._pc.peerIdentity.catch((e=>{this.destroy(c(e,"ERR_PC_PEER_IDENTITY"))})),this.initiator||this.channelNegotiated?this._setupData({channel:this._pc.createDataChannel(this.channelName,this.channelConfig)}):this._pc.ondatachannel=e=>{this._setupData(e)},this.streams&&this.streams.forEach((e=>{this.addStream(e)})),this._pc.ontrack=e=>{this._onTrack(e)},this._debug("initial negotiation"),this._needsNegotiation(),this._onFinishBound=()=>{this._onFinish()},this.once("finish",this._onFinishBound)}get bufferSize(){return this._channel&&this._channel.bufferedAmount||0}get connected(){return this._connected&&"open"===this._channel.readyState}address(){return{port:this.localPort,family:this.localFamily,address:this.localAddress}}signal(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot signal after peer is destroyed"),"ERR_DESTROYED");if("string"==typeof e)try{e=JSON.parse(e)}catch(t){e={}}this._debug("signal()"),e.renegotiate&&this.initiator&&(this._debug("got request to renegotiate"),this._needsNegotiation()),e.transceiverRequest&&this.initiator&&(this._debug("got request for transceiver"),this.addTransceiver(e.transceiverRequest.kind,e.transceiverRequest.init)),e.candidate&&(this._pc.remoteDescription&&this._pc.remoteDescription.type?this._addIceCandidate(e.candidate):this._pendingCandidates.push(e.candidate)),e.sdp&&this._pc.setRemoteDescription(new this._wrtc.RTCSessionDescription(e)).then((()=>{this.destroyed||(this._pendingCandidates.forEach((e=>{this._addIceCandidate(e)})),this._pendingCandidates=[],"offer"===this._pc.remoteDescription.type&&this._createAnswer())})).catch((e=>{this.destroy(c(e,"ERR_SET_REMOTE_DESCRIPTION"))})),e.sdp||e.candidate||e.renegotiate||e.transceiverRequest||this.destroy(c(new Error("signal() called with invalid signal data"),"ERR_SIGNALING"))}}_addIceCandidate(e){const t=new this._wrtc.RTCIceCandidate(e);this._pc.addIceCandidate(t).catch((e=>{!t.address||t.address.endsWith(".local")?("Ignoring unsupported ICE candidate.",console.warn("Ignoring unsupported ICE candidate.")):this.destroy(c(e,"ERR_ADD_ICE_CANDIDATE"))}))}send(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot send after peer is destroyed"),"ERR_DESTROYED");this._channel.send(e)}}addTransceiver(e,t){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addTransceiver after peer is destroyed"),"ERR_DESTROYED");if(this._debug("addTransceiver()"),this.initiator)try{this._pc.addTransceiver(e,t),this._needsNegotiation()}catch(e){this.destroy(c(e,"ERR_ADD_TRANSCEIVER"))}else this.emit("signal",{type:"transceiverRequest",transceiverRequest:{kind:e,init:t}})}}addStream(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot addStream after peer is destroyed"),"ERR_DESTROYED");this._debug("addStream()"),e.getTracks().forEach((t=>{this.addTrack(t,e)}))}}addTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot addTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("addTrack()");const n=this._senderMap.get(e)||new Map;let r=n.get(t);if(r)throw r.removed?c(new Error("Track has been removed. You should enable/disable tracks that you want to re-add."),"ERR_SENDER_REMOVED"):c(new Error("Track has already been added to that stream."),"ERR_SENDER_ALREADY_ADDED");r=this._pc.addTrack(e,t),n.set(t,r),this._senderMap.set(e,n),this._needsNegotiation()}replaceTrack(e,t,n){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot replaceTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("replaceTrack()");const r=this._senderMap.get(e),i=r?r.get(n):null;if(!i)throw c(new Error("Cannot replace track that was never added."),"ERR_TRACK_NOT_ADDED");t&&this._senderMap.set(t,r),null!=i.replaceTrack?i.replaceTrack(t):this.destroy(c(new Error("replaceTrack is not supported in this browser"),"ERR_UNSUPPORTED_REPLACETRACK"))}removeTrack(e,t){if(this.destroying)return;if(this.destroyed)throw c(new Error("cannot removeTrack after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSender()");const n=this._senderMap.get(e),r=n?n.get(t):null;if(!r)throw c(new Error("Cannot remove track that was never added."),"ERR_TRACK_NOT_ADDED");try{r.removed=!0,this._pc.removeTrack(r)}catch(e){"NS_ERROR_UNEXPECTED"===e.name?this._sendersAwaitingStable.push(r):this.destroy(c(e,"ERR_REMOVE_TRACK"))}this._needsNegotiation()}removeStream(e){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot removeStream after peer is destroyed"),"ERR_DESTROYED");this._debug("removeSenders()"),e.getTracks().forEach((t=>{this.removeTrack(t,e)}))}}_needsNegotiation(){this._debug("_needsNegotiation"),this._batchedNegotiation||(this._batchedNegotiation=!0,a((()=>{this._batchedNegotiation=!1,this.initiator||!this._firstNegotiation?(this._debug("starting batched negotiation"),this.negotiate()):this._debug("non-initiator initial negotiation request discarded"),this._firstNegotiation=!1})))}negotiate(){if(!this.destroying){if(this.destroyed)throw c(new Error("cannot negotiate after peer is destroyed"),"ERR_DESTROYED");this.initiator?this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("start negotiation"),setTimeout((()=>{this._createOffer()}),0)):this._isNegotiating?(this._queuedNegotiation=!0,this._debug("already negotiating, queueing")):(this._debug("requesting negotiation from initiator"),this.emit("signal",{type:"renegotiate",renegotiate:!0})),this._isNegotiating=!0}}destroy(e){this._destroy(e,(()=>{}))}_destroy(e,t){this.destroyed||this.destroying||(this.destroying=!0,this._debug("destroying (error: %s)",e&&(e.message||e)),a((()=>{if(this.destroyed=!0,this.destroying=!1,this._debug("destroy (error: %s)",e&&(e.message||e)),this.readable=this.writable=!1,this._readableState.ended||this.push(null),this._writableState.finished||this.end(),this._connected=!1,this._pcReady=!1,this._channelReady=!1,this._remoteTracks=null,this._remoteStreams=null,this._senderMap=null,clearInterval(this._closingInterval),this._closingInterval=null,clearInterval(this._interval),this._interval=null,this._chunk=null,this._cb=null,this._onFinishBound&&this.removeListener("finish",this._onFinishBound),this._onFinishBound=null,this._channel){try{this._channel.close()}catch(e){}this._channel.onmessage=null,this._channel.onopen=null,this._channel.onclose=null,this._channel.onerror=null}if(this._pc){try{this._pc.close()}catch(e){}this._pc.oniceconnectionstatechange=null,this._pc.onicegatheringstatechange=null,this._pc.onsignalingstatechange=null,this._pc.onicecandidate=null,this._pc.ontrack=null,this._pc.ondatachannel=null}this._pc=null,this._channel=null,e&&this.emit("error",e),this.emit("close"),t()})))}_setupData(e){if(!e.channel)return this.destroy(c(new Error("Data channel event is missing `channel` property"),"ERR_DATA_CHANNEL"));this._channel=e.channel,this._channel.binaryType="arraybuffer","number"==typeof this._channel.bufferedAmountLowThreshold&&(this._channel.bufferedAmountLowThreshold=d),this.channelName=this._channel.label,this._channel.onmessage=e=>{this._onChannelMessage(e)},this._channel.onbufferedamountlow=()=>{this._onChannelBufferedAmountLow()},this._channel.onopen=()=>{this._onChannelOpen()},this._channel.onclose=()=>{this._onChannelClose()},this._channel.onerror=e=>{const t=e.error instanceof Error?e.error:new Error(`Datachannel error: ${e.message} ${e.filename}:${e.lineno}:${e.colno}`);this.destroy(c(t,"ERR_DATA_CHANNEL"))};let t=!1;this._closingInterval=setInterval((()=>{this._channel&&"closing"===this._channel.readyState?(t&&this._onChannelClose(),t=!0):t=!1}),5e3)}_read(){}_write(e,t,n){if(this.destroyed)return n(c(new Error("cannot write after peer is destroyed"),"ERR_DATA_CHANNEL"));if(this._connected){try{this.send(e)}catch(e){return this.destroy(c(e,"ERR_DATA_CHANNEL"))}this._channel.bufferedAmount>d?(this._debug("start backpressure: bufferedAmount %d",this._channel.bufferedAmount),this._cb=n):n(null)}else this._debug("write before connect"),this._chunk=e,this._cb=n}_onFinish(){if(this.destroyed)return;const e=()=>{setTimeout((()=>this.destroy()),1e3)};this._connected?e():this.once("connect",e)}_startIceCompleteTimeout(){this.destroyed||this._iceCompleteTimer||(this._debug("started iceComplete timeout"),this._iceCompleteTimer=setTimeout((()=>{this._iceComplete||(this._iceComplete=!0,this._debug("iceComplete timeout completed"),this.emit("iceTimeout"),this.emit("_iceComplete"))}),this.iceCompleteTimeout))}_createOffer(){this.destroyed||this._pc.createOffer(this.offerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=u(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp})};this._pc.setLocalDescription(e).then((()=>{this._debug("createOffer success"),this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_OFFER"))}))}_requestMissingTransceivers(){this._pc.getTransceivers&&this._pc.getTransceivers().forEach((e=>{e.mid||!e.sender.track||e.requested||(e.requested=!0,this.addTransceiver(e.sender.track.kind))}))}_createAnswer(){this.destroyed||this._pc.createAnswer(this.answerOptions).then((e=>{if(this.destroyed)return;this.trickle||this.allowHalfTrickle||(e.sdp=u(e.sdp)),e.sdp=this.sdpTransform(e.sdp);const t=()=>{if(this.destroyed)return;const t=this._pc.localDescription||e;this._debug("signal"),this.emit("signal",{type:t.type,sdp:t.sdp}),this.initiator||this._requestMissingTransceivers()};this._pc.setLocalDescription(e).then((()=>{this.destroyed||(this.trickle||this._iceComplete?t():this.once("_iceComplete",t))})).catch((e=>{this.destroy(c(e,"ERR_SET_LOCAL_DESCRIPTION"))}))})).catch((e=>{this.destroy(c(e,"ERR_CREATE_ANSWER"))}))}_onConnectionStateChange(){this.destroyed||"failed"===this._pc.connectionState&&this.destroy(c(new Error("Connection failed."),"ERR_CONNECTION_FAILURE"))}_onIceStateChange(){if(this.destroyed)return;const e=this._pc.iceConnectionState,t=this._pc.iceGatheringState;this._debug("iceStateChange (connection: %s) (gathering: %s)",e,t),this.emit("iceStateChange",e,t),"connected"!==e&&"completed"!==e||(this._pcReady=!0,this._maybeReady()),"failed"===e&&this.destroy(c(new Error("Ice connection failed."),"ERR_ICE_CONNECTION_FAILURE")),"closed"===e&&this.destroy(c(new Error("Ice connection closed."),"ERR_ICE_CONNECTION_CLOSED"))}getStats(e){const t=e=>("[object Array]"===Object.prototype.toString.call(e.values)&&e.values.forEach((t=>{Object.assign(e,t)})),e);0===this._pc.getStats.length||this._isReactNativeWebrtc?this._pc.getStats().then((n=>{const r=[];n.forEach((e=>{r.push(t(e))})),e(null,r)}),(t=>e(t))):this._pc.getStats.length>0?this._pc.getStats((n=>{if(this.destroyed)return;const r=[];n.result().forEach((e=>{const n={};e.names().forEach((t=>{n[t]=e.stat(t)})),n.id=e.id,n.type=e.type,n.timestamp=e.timestamp,r.push(t(n))})),e(null,r)}),(t=>e(t))):e(null,[])}_maybeReady(){if(this._debug("maybeReady pc %s channel %s",this._pcReady,this._channelReady),this._connected||this._connecting||!this._pcReady||!this._channelReady)return;this._connecting=!0;const e=()=>{this.destroyed||this.getStats(((t,n)=>{if(this.destroyed)return;t&&(n=[]);const r={},i={},s={};let o=!1;n.forEach((e=>{"remotecandidate"!==e.type&&"remote-candidate"!==e.type||(r[e.id]=e),"localcandidate"!==e.type&&"local-candidate"!==e.type||(i[e.id]=e),"candidatepair"!==e.type&&"candidate-pair"!==e.type||(s[e.id]=e)}));const a=e=>{o=!0;let t=i[e.localCandidateId];t&&(t.ip||t.address)?(this.localAddress=t.ip||t.address,this.localPort=Number(t.port)):t&&t.ipAddress?(this.localAddress=t.ipAddress,this.localPort=Number(t.portNumber)):"string"==typeof e.googLocalAddress&&(t=e.googLocalAddress.split(":"),this.localAddress=t[0],this.localPort=Number(t[1])),this.localAddress&&(this.localFamily=this.localAddress.includes(":")?"IPv6":"IPv4");let n=r[e.remoteCandidateId];n&&(n.ip||n.address)?(this.remoteAddress=n.ip||n.address,this.remotePort=Number(n.port)):n&&n.ipAddress?(this.remoteAddress=n.ipAddress,this.remotePort=Number(n.portNumber)):"string"==typeof e.googRemoteAddress&&(n=e.googRemoteAddress.split(":"),this.remoteAddress=n[0],this.remotePort=Number(n[1])),this.remoteAddress&&(this.remoteFamily=this.remoteAddress.includes(":")?"IPv6":"IPv4"),this._debug("connect local: %s:%s remote: %s:%s",this.localAddress,this.localPort,this.remoteAddress,this.remotePort)};if(n.forEach((e=>{"transport"===e.type&&e.selectedCandidatePairId&&a(s[e.selectedCandidatePairId]),("googCandidatePair"===e.type&&"true"===e.googActiveConnection||("candidatepair"===e.type||"candidate-pair"===e.type)&&e.selected)&&a(e)})),o||Object.keys(s).length&&!Object.keys(i).length){if(this._connecting=!1,this._connected=!0,this._chunk){try{this.send(this._chunk)}catch(t){return this.destroy(c(t,"ERR_DATA_CHANNEL"))}this._chunk=null,this._debug('sent chunk from "write before connect"');const e=this._cb;this._cb=null,e(null)}"number"!=typeof this._channel.bufferedAmountLowThreshold&&(this._interval=setInterval((()=>this._onInterval()),150),this._interval.unref&&this._interval.unref()),this._debug("connect"),this.emit("connect")}else setTimeout(e,100)}))};e()}_onInterval(){!this._cb||!this._channel||this._channel.bufferedAmount>d||this._onChannelBufferedAmountLow()}_onSignalingStateChange(){this.destroyed||("stable"===this._pc.signalingState&&(this._isNegotiating=!1,this._debug("flushing sender queue",this._sendersAwaitingStable),this._sendersAwaitingStable.forEach((e=>{this._pc.removeTrack(e),this._queuedNegotiation=!0})),this._sendersAwaitingStable=[],this._queuedNegotiation?(this._debug("flushing negotiation queue"),this._queuedNegotiation=!1,this._needsNegotiation()):(this._debug("negotiated"),this.emit("negotiated"))),this._debug("signalingStateChange %s",this._pc.signalingState),this.emit("signalingStateChange",this._pc.signalingState))}_onIceCandidate(e){this.destroyed||(e.candidate&&this.trickle?this.emit("signal",{type:"candidate",candidate:{candidate:e.candidate.candidate,sdpMLineIndex:e.candidate.sdpMLineIndex,sdpMid:e.candidate.sdpMid}}):e.candidate||this._iceComplete||(this._iceComplete=!0,this.emit("_iceComplete")),e.candidate&&this._startIceCompleteTimeout())}_onChannelMessage(e){if(this.destroyed)return;let t=e.data;t instanceof ArrayBuffer&&(t=l.from(t)),this.push(t)}_onChannelBufferedAmountLow(){if(this.destroyed||!this._cb)return;this._debug("ending backpressure: bufferedAmount %d",this._channel.bufferedAmount);const e=this._cb;this._cb=null,e(null)}_onChannelOpen(){this._connected||this.destroyed||(this._debug("on channel open"),this._channelReady=!0,this._maybeReady())}_onChannelClose(){this.destroyed||(this._debug("on channel close"),this.destroy())}_onTrack(e){this.destroyed||e.streams.forEach((t=>{this._debug("on track"),this.emit("track",e.track,t),this._remoteTracks.push({track:e.track,stream:t}),this._remoteStreams.some((e=>e.id===t.id))||(this._remoteStreams.push(t),a((()=>{this._debug("on stream"),this.emit("stream",t)})))}))}_debug(){const e=[].slice.call(arguments);e[0]="["+this._id+"] "+e[0],r.apply(null,e)}}h.WEBRTC_SUPPORT=!!i(),h.config={iceServers:[{urls:["stun:stun.l.google.com:19302","stun:global.stun.twilio.com:3478"]}],sdpSemantics:"unified-plan"},h.channelConfig={},e.exports=h},2553:(e,t,n)=>{"use strict";var r=n(9509).Buffer,i=r.isEncoding||function(e){switch((e=""+e)&&e.toLowerCase()){case"hex":case"utf8":case"utf-8":case"ascii":case"binary":case"base64":case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":case"raw":return!0;default:return!1}};function s(e){var t;switch(this.encoding=function(e){var t=function(e){if(!e)return"utf8";for(var t;;)switch(e){case"utf8":case"utf-8":return"utf8";case"ucs2":case"ucs-2":case"utf16le":case"utf-16le":return"utf16le";case"latin1":case"binary":return"latin1";case"base64":case"ascii":case"hex":return e;default:if(t)return;e=(""+e).toLowerCase(),t=!0}}(e);if("string"!=typeof t&&(r.isEncoding===i||!i(e)))throw new Error("Unknown encoding: "+e);return t||e}(e),this.encoding){case"utf16le":this.text=c,this.end=l,t=4;break;case"utf8":this.fillLast=a,t=4;break;case"base64":this.text=d,this.end=u,t=3;break;default:return this.write=h,void(this.end=f)}this.lastNeed=0,this.lastTotal=0,this.lastChar=r.allocUnsafe(t)}function o(e){return e<=127?0:e>>5==6?2:e>>4==14?3:e>>3==30?4:e>>6==2?-1:-2}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"<22>";if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"<22>";if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"<22>"}}(this,e);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function c(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var r=n.charCodeAt(n.length-1);if(r>=55296&&r<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function l(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function d(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function u(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function h(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.s=s,s.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n<e.length?t?t+this.text(e,n):this.text(e,n):t||""},s.prototype.end=function(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+"<22>":t},s.prototype.text=function(e,t){var n=function(e,t,n){var r=t.length-1;if(r<n)return 0;var i=o(t[r]);return i>=0?(i>0&&(e.lastNeed=i-1),i):--r<n||-2===i?0:(i=o(t[r]))>=0?(i>0&&(e.lastNeed=i-2),i):--r<n||-2===i?0:(i=o(t[r]))>=0?(i>0&&(2===i?i=0:e.lastNeed=i-3),i):0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var r=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,r),e.toString("utf8",t,r)},s.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},5067:(e,t,n)=>{"use strict";var r=n(7873),i=RegExp(Object.keys(r).map((function(e){return e.replace(/([.?*+^$[\]\\(){}|-])/g,"\\$1")})).join("|"),"g");function s(e){return r[e]}e.exports=function(e){return e.replace(i,s)}},4927:(e,t,n)=>{function r(e){try{if(!n.g.localStorage)return!1}catch(e){return!1}var t=n.g.localStorage[e];return null!=t&&"true"===String(t).toLowerCase()}e.exports=function(e,t){if(r("noDeprecation"))return e;var n=!1;return function(){if(!n){if(r("throwDeprecation"))throw new Error(t);r("traceDeprecation")?console.trace(t):console.warn(t),n=!0}return e.apply(this,arguments)}}},4654:()=>{},2361:()=>{},4616:()=>{},8416:(e,t,n)=>{var r=n(4062);e.exports=function(e,t,n){return(t=r(t))in e?Object.defineProperty(e,t,{value:n,enumerable:!0,configurable:!0,writable:!0}):e[t]=n,e},e.exports.__esModule=!0,e.exports.default=e.exports},4836:e=>{e.exports=function(e){return e&&e.__esModule?e:{default:e}},e.exports.__esModule=!0,e.exports.default=e.exports},5036:(e,t,n)=>{var r=n(8698).default;e.exports=function(e,t){if("object"!=r(e)||!e)return e;var n=e[Symbol.toPrimitive];if(void 0!==n){var i=n.call(e,t||"default");if("object"!=r(i))return i;throw new TypeError("@@toPrimitive must return a primitive value.")}return("string"===t?String:Number)(e)},e.exports.__esModule=!0,e.exports.default=e.exports},4062:(e,t,n)=>{var r=n(8698).default,i=n(5036);e.exports=function(e){var t=i(e,"string");return"symbol"==r(t)?t:String(t)},e.exports.__esModule=!0,e.exports.default=e.exports},8698:e=>{function t(n){return e.exports=t="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol&&e!==Symbol.prototype?"symbol":typeof e},e.exports.__esModule=!0,e.exports.default=e.exports,t(n)}e.exports=t,e.exports.__esModule=!0,e.exports.default=e.exports},7873:e=>{"use strict";e.exports=JSON.parse('{"0":"O","1":"l","֭":"֖","֮":"֘","֨":"֙","֤":"֚","᪴":"ۛ","⃛":"ۛ","ؙ":"̓","ࣳ":"̓","̓":"̓","̕":"̓","ُ":"̓","ٝ":"̔","֜":"́","֝":"́","ؘ":"́","݇":"́","́":"́","॔":"́","َ":"́","̀":"̀","॓":"̀","̌":"̆","꙼":"̆","٘":"̆","ٚ":"̆","ͮ":"̆","ۨ":"̆̇","̐":"̆̇","ँ":"̆̇","ঁ":"̆̇","ઁ":"̆̇","ଁ":"̆̇","ఀ":"̆̇","ಁ":"̆̇","ഁ":"̆̇","𑒿":"̆̇","᳐":"̂","̑":"̂","ٛ":"̂","߮":"̂","꛰":"̂","֯":"̊","۟":"̊","៓":"̊","゚":"̊","ْ":"̊","ஂ":"̊","ံ":"̊","ំ":"̊","𑌀":"̊","ํ":"̊","ໍ":"̊","ͦ":"̊","ⷪ":"̊","࣫":"̈","߳":"̈","ً":"̋","ࣰ":"̋","͂":"̃","ٓ":"̃","ׄ":"̇","۬":"̇","݀":"̇","࣪":"̇","݁":"̇","͘":"̇","ֹ":"̇","ֺ":"̇","ׂ":"̇","ׁ":"̇","߭":"̇","ं":"̇","ਂ":"̇","ં":"̇","்":"̇","̷":"̸","᪷":"̨","̢":"̨","ͅ":"̨","᳒":"̄","̅":"̄","ٙ":"̄","߫":"̄","꛱":"̄","᳚":"̎","ٗ":"̒","͗":"͐","ࣿ":"͐","ࣸ":"͐","ऀ":"͒","᳭":"̖","᳜":"̩","ٖ":"̩","᳕":"̫","͇":"̳","ࣹ":"͔","ࣺ":"͕","゛":"゙","゜":"゚","̶":"̵","〬":"̉","ׅ":"̣","࣭":"̣","᳝":"̣","ִ":"̣","ٜ":"̣","़":"̣","়":"̣","਼":"̣","઼":"̣","଼":"̣","𑇊":"̣","𑓃":"̣","𐨺":"̣","࣮":"̤","᳞":"̤","༷":"̥","〭":"̥","̧":"̦","̡":"̦","̹":"̦","᳙":"̭","᳘":"̮","॒":"̱","̠":"̱","ࣱ":"ٌ","ࣨ":"ٌ","ࣥ":"ٌ","ﱞ":"ﹲّ","ࣲ":"ٍ","ﱟ":"ﹴّ","ﳲ":"ﹷّ","ﱠ":"ﹶّ","ﳳ":"ﹹّ","ﱡ":"ﹸّ","ؚ":"ِ","̗":"ِ","ﳴ":"ﹻّ","ﱢ":"ﹺّ","ﱣ":"ﹼٰ","ٟ":"ٕ","̍":"ٰ","݂":"ܼ","ਃ":"ঃ","ః":"ঃ","ಃ":"ঃ","ഃ":"ঃ","ඃ":"ঃ","း":"ঃ","𑓁":"ঃ","់":"่","່":"่","້":"้","໊":"๊","໋":"๋","꙯":"⃩","\\u2028":" ","\\u2029":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" "," ":" ","ߺ":"_","﹍":"_","﹎":"_","﹏":"_","‐":"-","‑":"-","‒":"-","–":"-","﹘":"-","۔":"-","⁃":"-","˗":"-","−":"-","➖":"-","Ⲻ":"-","⨩":"-̓","⸚":"-̈","﬩":"-̇","∸":"-̇","⨪":"-̣","꓾":"-.","~":"〜","؍":",","٫":",","‚":",","¸":",","ꓹ":",","⸲":"،","٬":"،",";":";","⸵":"؛","ः":":","ઃ":":",":":":","։":":","܃":":","܄":":","᛬":":","︰":":","᠃":":","᠉":":","⁚":":","׃":":","˸":":","꞉":":","∶":":","ː":":","ꓽ":":","⩴":"::=","⧴":":→","!":"!","ǃ":"!","ⵑ":"!","‼":"!!","⁉":"!?","ʔ":"?","Ɂ":"?","ॽ":"?","Ꭾ":"?","ꛫ":"?","⁈":"?!","⁇":"??","⸮":"؟","𝅭":".","․":".","܁":".","܂":".","꘎":".","𐩐":".","٠":".","۰":".","ꓸ":".","ꓻ":".,","‥":"..","ꓺ":"..","…":"...","꛴":"꛳꛳","・":"·","・":"·","᛫":"·","·":"·","⸱":"·","𐄁":"·","•":"·","‧":"·","∙":"·","⋅":"·","ꞏ":"·","ᐧ":"·","⋯":"···","ⵈ":"···","ᑄ":"·<","⋗":"·>","ᐷ":"·>","ᑀ":"·>","ᔯ":"·4","ᑾ":"·b","ᒀ":"·ḃ","ᑺ":"·d","ᒘ":"·J","ᒶ":"·L","ᑶ":"·P","ᑗ":"·U","ᐺ":"·V","ᐼ":"·Ʌ","ᒮ":"·Γ","ᐎ":"·Δ","ᑙ":"·Ո","ᐌ":"·ᐁ","ᐐ":"·ᐄ","ᐒ":"·ᐅ","ᐔ":"·ᐆ","ᐗ":"·ᐊ","ᐙ":"·ᐋ","ᐾ":"·ᐲ","ᑂ":"·ᐴ","ᑆ":"·ᐹ","ᑛ":"·ᑏ","ᑔ":"·ᑐ","ᑝ":"·ᑐ","ᑟ":"·ᑑ","ᑡ":"·ᑕ","ᑣ":"·ᑖ","ᑴ":"·ᑫ","ᑸ":"·ᑮ","ᑼ":"·ᑰ","ᒒ":"·ᒉ","ᒔ":"·ᒋ","ᒖ":"·ᒌ","ᒚ":"·ᒎ","ᒜ":"·ᒐ","ᒞ":"·ᒑ","ᒬ":"·ᒣ","ᒰ":"·ᒦ","ᒲ":"·ᒧ","ᒴ":"·ᒨ","ᒸ":"·ᒫ","ᓉ":"·ᓀ","ᣆ":"·ᓂ","ᣈ":"·ᓃ","ᣊ":"·ᓄ","ᣌ":"·ᓅ","ᓋ":"·ᓇ","ᓍ":"·ᓈ","ᓜ":"·ᓓ","ᓞ":"·ᓕ","ᓠ":"·ᓖ","ᓢ":"·ᓗ","ᓤ":"·ᓘ","ᓦ":"·ᓚ","ᓨ":"·ᓛ","ᓶ":"·ᓭ","ᓸ":"·ᓯ","ᓺ":"·ᓰ","ᓼ":"·ᓱ","ᓾ":"·ᓲ","ᔀ":"·ᓴ","ᔂ":"·ᓵ","ᔗ":"·ᔐ","ᔙ":"·ᔑ","ᔛ":"·ᔒ","ᔝ":"·ᔓ","ᔟ":"·ᔔ","ᔡ":"·ᔕ","ᔣ":"·ᔖ","ᔱ":"·ᔨ","ᔳ":"·ᔩ","ᔵ":"·ᔪ","ᔷ":"·ᔫ","ᔹ":"·ᔭ","ᔻ":"·ᔮ","ᣎ":"·ᕃ","ᣏ":"·ᕆ","ᣐ":"·ᕇ","ᣑ":"·ᕈ","ᣒ":"·ᕉ","ᣓ":"·ᕋ","ᕎ":"·ᕌ","ᕛ":"·ᕚ","ᕨ":"·ᕧ","ᢳ":"·ᢱ","ᢶ":"·ᢴ","ᢹ":"·ᢸ","ᣂ":"·ᣀ","꠰":"।","॥":"।।","᰼":"᰻᰻","။":"၊၊","᪩":"᪨᪨","᪫":"᪪᪨","᭟":"᭞᭞","𐩗":"𐩖𐩖","𑑌":"𑑋𑑋","𑙂":"𑙁𑙁","𑱂":"𑱁𑱁","᱿":"᱾᱾","՝":"\'","'":"\'","‘":"\'","’":"\'","‛":"\'","′":"\'","‵":"\'","՚":"\'","׳":"\'","`":"\'","`":"\'","`":"\'","´":"\'","΄":"\'","´":"\'","᾽":"\'","᾿":"\'","῾":"\'","ʹ":"\'","ʹ":"\'","ˈ":"\'","ˊ":"\'","ˋ":"\'","˴":"\'","ʻ":"\'","ʽ":"\'","ʼ":"\'","ʾ":"\'","ꞌ":"\'","י":"\'","ߴ":"\'","ߵ":"\'","ᑊ":"\'","ᛌ":"\'","𖽑":"\'","𖽒":"\'","᳓":"\'\'","\\"":"\'\'",""":"\'\'","“":"\'\'","”":"\'\'","‟":"\'\'","″":"\'\'","‶":"\'\'","〃":"\'\'","״":"\'\'","˝":"\'\'","ʺ":"\'\'","˶":"\'\'","ˮ":"\'\'","ײ":"\'\'","‴":"\'\'\'","‷":"\'\'\'","⁗":"\'\'\'\'","Ɓ":"\'B","Ɗ":"\'D","ʼn":"\'n","Ƥ":"\'P","Ƭ":"\'T","Ƴ":"\'Y","[":"(","❨":"(","❲":"(","〔":"(","﴾":"(","⸨":"((","㈠":"(ー)","⑵":"(2)","⒇":"(2O)","⑶":"(3)","⑷":"(4)","⑸":"(5)","⑹":"(6)","⑺":"(7)","⑻":"(8)","⑼":"(9)","⒜":"(a)","🄐":"(A)","⒝":"(b)","🄑":"(B)","⒞":"(c)","🄒":"(C)","⒟":"(d)","🄓":"(D)","⒠":"(e)","🄔":"(E)","⒡":"(f)","🄕":"(F)","⒢":"(g)","🄖":"(G)","⒣":"(h)","🄗":"(H)","⒤":"(i)","⒥":"(j)","🄙":"(J)","⒦":"(k)","🄚":"(K)","⑴":"(l)","🄘":"(l)","⒧":"(l)","🄛":"(L)","⑿":"(l2)","⒀":"(l3)","⒁":"(l4)","⒂":"(l5)","⒃":"(l6)","⒄":"(l7)","⒅":"(l8)","⒆":"(l9)","⑾":"(ll)","⑽":"(lO)","🄜":"(M)","⒩":"(n)","🄝":"(N)","⒪":"(o)","🄞":"(O)","⒫":"(p)","🄟":"(P)","⒬":"(q)","🄠":"(Q)","⒭":"(r)","🄡":"(R)","⒨":"(rn)","⒮":"(s)","🄢":"(S)","🄪":"(S)","⒯":"(t)","🄣":"(T)","⒰":"(u)","🄤":"(U)","⒱":"(v)","🄥":"(V)","⒲":"(w)","🄦":"(W)","⒳":"(x)","🄧":"(X)","⒴":"(y)","🄨":"(Y)","⒵":"(z)","🄩":"(Z)","㈀":"(ᄀ)","㈎":"(가)","㈁":"(ᄂ)","㈏":"(나)","㈂":"(ᄃ)","㈐":"(다)","㈃":"(ᄅ)","㈑":"(라)","㈄":"(ᄆ)","㈒":"(마)","㈅":"(ᄇ)","㈓":"(바)","㈆":"(ᄉ)","㈔":"(사)","㈇":"(ᄋ)","㈕":"(아)","㈝":"(오전)","㈞":"(오후)","㈈":"(ᄌ)","㈖":"(자)","㈜":"(주)","㈉":"(ᄎ)","㈗":"(차)","㈊":"(ᄏ)","㈘":"(카)","㈋":"(ᄐ)","㈙":"(타)","㈌":"(ᄑ)","㈚":"(파)","㈍":"(ᄒ)","㈛":"(하)","㈦":"(七)","㈢":"(三)","🉁":"(三)","㈨":"(九)","㈡":"(二)","🉂":"(二)","㈤":"(五)","㈹":"(代)","㈽":"(企)","㉁":"(休)","㈧":"(八)","㈥":"(六)","㈸":"(労)","🉇":"(勝)","㈩":"(十)","㈿":"(協)","㈴":"(名)","㈺":"(呼)","㈣":"(四)","㈯":"(土)","㈻":"(学)","🉃":"(安)","🉅":"(打)","🉈":"(敗)","㈰":"(日)","㈪":"(月)","㈲":"(有)","㈭":"(木)","🉀":"(本)","㈱":"(株)","㈬":"(水)","㈫":"(火)","🉄":"(点)","㈵":"(特)","🉆":"(盗)","㈼":"(監)","㈳":"(社)","㈷":"(祝)","㉀":"(祭)","㉂":"(自)","㉃":"(至)","㈶":"(財)","㈾":"(資)","㈮":"(金)","]":")","❩":")","❳":")","〕":")","﴿":")","⸩":"))","❴":"{","𝄔":"{","❵":"}","〚":"⟦","〛":"⟧","⟨":"❬","〈":"❬","〈":"❬","㇛":"❬","く":"❬","𡿨":"❬","⟩":"❭","〉":"❭","〉":"❭","^":"︿","⸿":"¶","⁎":"*","٭":"*","∗":"*","𐌟":"*","᜵":"/","⁁":"/","∕":"/","⁄":"/","╱":"/","⟋":"/","⧸":"/","𝈺":"/","㇓":"/","〳":"/","Ⳇ":"/","ノ":"/","丿":"/","⼃":"/","⧶":"/̄","⫽":"//","⫻":"///","\":"\\\\","﹨":"\\\\","∖":"\\\\","⟍":"\\\\","⧵":"\\\\","⧹":"\\\\","𝈏":"\\\\","𝈻":"\\\\","㇔":"\\\\","丶":"\\\\","⼂":"\\\\","⳹":"\\\\\\\\","⑊":"\\\\\\\\","⟈":"\\\\ᑕ","ꝸ":"&","૰":"॰","𑂻":"॰","𑇇":"॰","⚬":"॰","𑇛":"꣼","៙":"๏","៕":"๚","៚":"๛","༌":"་","༎":"།།","˄":"^","ˆ":"^","꙾":"ˇ","˘":"ˇ","‾":"ˉ","﹉":"ˉ","﹊":"ˉ","﹋":"ˉ","﹌":"ˉ","¯":"ˉ"," ̄":"ˉ","▔":"ˉ","ъ":"ˉb","ꙑ":"ˉbi","͵":"ˏ","˻":"˪","꜖":"˪","꜔":"˫","。":"˳","⸰":"°","˚":"°","∘":"°","○":"°","◦":"°","⍜":"°̲","⍤":"°̈","℃":"°C","℉":"°F","௵":"௳","༛":"༚༚","༟":"༚༝","࿎":"༝༚","༞":"༝༝","Ⓒ":"©","Ⓡ":"®","Ⓟ":"℗","𝈛":"⅄","⯬":"↞","⯭":"↟","⯮":"↠","⯯":"↡","↵":"↲","⥥":"⇃⇂","⥯":"⇃ᛚ","𝛛":"∂","𝜕":"∂","𝝏":"∂","𝞉":"∂","𝟃":"∂","𞣌":"∂","𞣍":"∂̵","ð":"∂̵","⌀":"∅","𝛁":"∇","𝛻":"∇","𝜵":"∇","𝝯":"∇","𝞩":"∇","𑢨":"∇","⍢":"∇̈","⍫":"∇̴","█":"∎","■":"∎","⨿":"∐","᛭":"+","➕":"+","𐊛":"+","⨣":"+̂","⨢":"+̊","⨤":"+̃","∔":"+̇","⨥":"+̣","⨦":"+̰","⨧":"+₂","➗":"÷","‹":"<","❮":"<","˂":"<","𝈶":"<","ᐸ":"<","ᚲ":"<","⋖":"<·","Ⲵ":"<·","ᑅ":"<·","≪":"<<","⋘":"<<<","᐀":"=","⹀":"=","゠":"=","꓿":"=","≚":"=̆","≙":"=̂","≗":"=̊","≐":"=̇","≑":"=̣̇","⩮":"=⃰","⩵":"==","⩶":"===","≞":"=ͫ","›":">","❯":">","˃":">","𝈷":">","ᐳ":">","𖼿":">","ᑁ":">·","⪥":"><","≫":">>","⨠":">>","⋙":">>>","⁓":"~","˜":"~","῀":"~","∼":"~","⍨":"~̈","⸞":"~̇","⩪":"~̇","⸟":"~̣","𞣈":"∠","⋀":"∧","∯":"∮∮","∰":"∮∮∮","⸫":"∴","⸪":"∵","⸬":"∷","𑇞":"≈","♎":"≏","🝞":"≏","≣":"≡","⨃":"⊍","⨄":"⊎","𝈸":"⊏","𝈹":"⊐","⨅":"⊓","⨆":"⊔","⨂":"⊗","⍟":"⊛","🝱":"⊠","🝕":"⊡","◁":"⊲","▷":"⊳","⍣":"⋆̈","︴":"⌇","◠":"⌒","⨽":"⌙","⌥":"⌤","⧇":"⌻","◎":"⌾","⦾":"⌾","⧅":"⍂","⦰":"⍉","⏃":"⍋","⏂":"⍎","⏁":"⍕","⏆":"⍭","☸":"⎈","︵":"⏜","︶":"⏝","︷":"⏞","︸":"⏟","︹":"⏠","︺":"⏡","▱":"⏥","⏼":"⏻","︱":"│","|":"│","┃":"│","┏":"┌","┣":"├","▐":"▌","▗":"▖","▝":"▘","☐":"□","■":"▪","▸":"▶","►":"▶","⳩":"☧","🜊":"☩","🌒":"☽","🌙":"☽","⏾":"☾","🌘":"☾","⧙":"⦚","🜺":"⧟","⨾":"⨟","𐆠":"⳨","♩":"𝅘𝅥","♪":"𝅘𝅥𝅮","⓪":"🄍","↺":"🄎","˙":"ॱ","ൎ":"ॱ","-":"ー","—":"ー","―":"ー","─":"ー","━":"ー","㇐":"ー","ꟷ":"ー","ᅳ":"ー","ㅡ":"ー","一":"ー","⼀":"ー","ᆖ":"ーー","ힹ":"ーᅡ","ힺ":"ーᅥ","ힻ":"ーᅥ丨","ힼ":"ーᅩ","ᆕ":"ーᅮ","ᅴ":"ー丨","ㅢ":"ー丨","ᆗ":"ー丨ᅮ","🄏":"$⃠","₤":"£","〒":"₸","〶":"₸","᭜":"᭐","꧆":"꧐","𑓑":"১","೧":"౧","ၥ":"၁","①":"➀","⑩":"➉","⏨":"₁₀","𝟐":"2","𝟚":"2","𝟤":"2","𝟮":"2","𝟸":"2","🯲":"2","Ꝛ":"2","Ƨ":"2","Ϩ":"2","Ꙅ":"2","ᒿ":"2","ꛯ":"2","ꧏ":"٢","۲":"٢","૨":"२","𑓒":"২","೨":"౨","②":"➁","ƻ":"2̵","🄃":"2,","⒉":"2.","㏵":"22日","㍮":"22点","㏶":"23日","㍯":"23点","㏷":"24日","㍰":"24点","㏸":"25日","㏹":"26日","㏺":"27日","㏻":"28日","㏼":"29日","㏴":"2l日","㍭":"2l点","⒛":"2O.","㏳":"2O日","㍬":"2O点","෩":"෨ා","෯":"෨ී","㏡":"2日","㋁":"2月","㍚":"2点","𝈆":"3","𝟑":"3","𝟛":"3","𝟥":"3","𝟯":"3","𝟹":"3","🯳":"3","Ɜ":"3","Ȝ":"3","Ʒ":"3","Ꝫ":"3","Ⳍ":"3","З":"3","Ӡ":"3","𖼻":"3","𑣊":"3","۳":"٣","𞣉":"٣","૩":"३","③":"➂","Ҙ":"3̦","🄄":"3,","⒊":"3.","㏾":"3l日","㏽":"3O日","㏢":"3日","㋂":"3月","㍛":"3点","𝟒":"4","𝟜":"4","𝟦":"4","𝟰":"4","𝟺":"4","🯴":"4","Ꮞ":"4","𑢯":"4","۴":"٤","૪":"४","④":"➃","🄅":"4,","⒋":"4.","ᔰ":"4·","㏣":"4日","㋃":"4月","㍜":"4点","𝟓":"5","𝟝":"5","𝟧":"5","𝟱":"5","𝟻":"5","🯵":"5","Ƽ":"5","𑢻":"5","⑤":"➄","🄆":"5,","⒌":"5.","㏤":"5日","㋄":"5月","㍝":"5点","𝟔":"6","𝟞":"6","𝟨":"6","𝟲":"6","𝟼":"6","🯶":"6","Ⳓ":"6","б":"6","Ꮾ":"6","𑣕":"6","۶":"٦","𑓖":"৬","⑥":"➅","🄇":"6,","⒍":"6.","㏥":"6日","㋅":"6月","㍞":"6点","𝈒":"7","𝟕":"7","𝟟":"7","𝟩":"7","𝟳":"7","𝟽":"7","🯷":"7","𐓒":"7","𑣆":"7","⑦":"➆","🄈":"7,","⒎":"7.","㏦":"7日","㋆":"7月","㍟":"7点","ଃ":"8","৪":"8","੪":"8","𞣋":"8","𝟖":"8","𝟠":"8","𝟪":"8","𝟴":"8","𝟾":"8","🯸":"8","ȣ":"8","Ȣ":"8","𐌚":"8","૮":"८","⑧":"➇","🄉":"8,","⒏":"8.","㏧":"8日","㋇":"8月","㍠":"8点","੧":"9","୨":"9","৭":"9","൭":"9","𝟗":"9","𝟡":"9","𝟫":"9","𝟵":"9","𝟿":"9","🯹":"9","Ꝯ":"9","Ⳋ":"9","𑣌":"9","𑢬":"9","𑣖":"9","१":"٩","𑣤":"٩","۹":"٩","೯":"౯","⑨":"➈","🄊":"9,","⒐":"9.","㏨":"9日","㋈":"9月","㍡":"9点","⍺":"a","a":"a","𝐚":"a","𝑎":"a","𝒂":"a","𝒶":"a","𝓪":"a","𝔞":"a","𝕒":"a","𝖆":"a","𝖺":"a","𝗮":"a","𝘢":"a","𝙖":"a","𝚊":"a","ɑ":"a","α":"a","𝛂":"a","𝛼":"a","𝜶":"a","𝝰":"a","𝞪":"a","а":"a","ⷶ":"ͣ","A":"A","𝐀":"A","𝐴":"A","𝑨":"A","𝒜":"A","𝓐":"A","𝔄":"A","𝔸":"A","𝕬":"A","𝖠":"A","𝗔":"A","𝘈":"A","𝘼":"A","𝙰":"A","Α":"A","𝚨":"A","𝛢":"A","𝜜":"A","𝝖":"A","𝞐":"A","А":"A","Ꭺ":"A","ᗅ":"A","ꓮ":"A","𖽀":"A","𐊠":"A","⍶":"a̲","ǎ":"ă","Ǎ":"Ă","ȧ":"å","Ȧ":"Å","ẚ":"ả","℀":"a/c","℁":"a/s","ꜳ":"aa","Ꜳ":"AA","æ":"ae","ӕ":"ae","Æ":"AE","Ӕ":"AE","ꜵ":"ao","Ꜵ":"AO","🜇":"AR","ꜷ":"au","Ꜷ":"AU","ꜹ":"av","ꜻ":"av","Ꜹ":"AV","Ꜻ":"AV","ꜽ":"ay","Ꜽ":"AY","ꭺ":"ᴀ","∀":"Ɐ","𝈗":"Ɐ","ᗄ":"Ɐ","ꓯ":"Ɐ","𐐟":"Ɒ","𝐛":"b","𝑏":"b","𝒃":"b","𝒷":"b","𝓫":"b","𝔟":"b","𝕓":"b","𝖇":"b","𝖻":"b","𝗯":"b","𝘣":"b","𝙗":"b","𝚋":"b","Ƅ":"b","Ь":"b","Ꮟ":"b","ᑲ":"b","ᖯ":"b","B":"B","ℬ":"B","𝐁":"B","𝐵":"B","𝑩":"B","𝓑":"B","𝔅":"B","𝔹":"B","𝕭":"B","𝖡":"B","𝗕":"B","𝘉":"B","𝘽":"B","𝙱":"B","Ꞵ":"B","Β":"B","𝚩":"B","𝛣":"B","𝜝":"B","𝝗":"B","𝞑":"B","В":"B","Ᏼ":"B","ᗷ":"B","ꓐ":"B","𐊂":"B","𐊡":"B","𐌁":"B","ɓ":"b̔","ᑳ":"ḃ","ƃ":"b̄","Ƃ":"b̄","Б":"b̄","ƀ":"b̵","ҍ":"b̵","Ҍ":"b̵","ѣ":"b̵","Ѣ":"b̵","ᑿ":"b·","ᒁ":"ḃ·","ᒈ":"b\'","Ы":"bl","в":"ʙ","ᏼ":"ʙ","c":"c","ⅽ":"c","𝐜":"c","𝑐":"c","𝒄":"c","𝒸":"c","𝓬":"c","𝔠":"c","𝕔":"c","𝖈":"c","𝖼":"c","𝗰":"c","𝘤":"c","𝙘":"c","𝚌":"c","ᴄ":"c","ϲ":"c","ⲥ":"c","с":"c","ꮯ":"c","𐐽":"c","ⷭ":"ͨ","🝌":"C","𑣲":"C","𑣩":"C","C":"C","Ⅽ":"C","ℂ":"C","ℭ":"C","𝐂":"C","𝐶":"C","𝑪":"C","𝒞":"C","𝓒":"C","𝕮":"C","𝖢":"C","𝗖":"C","𝘊":"C","𝘾":"C","𝙲":"C","Ϲ":"C","Ⲥ":"C","С":"C","Ꮯ":"C","ꓚ":"C","𐊢":"C","𐌂":"C","𐐕":"C","𐔜":"C","¢":"c̸","ȼ":"c̸","₡":"C⃫","🅮":"C⃠","ç":"c̦","ҫ":"c̦","Ç":"C̦","Ҫ":"C̦","Ƈ":"C\'","℅":"c/o","℆":"c/u","🅭":"㏄\\t⃝","⋴":"ꞓ","ɛ":"ꞓ","ε":"ꞓ","ϵ":"ꞓ","𝛆":"ꞓ","𝛜":"ꞓ","𝜀":"ꞓ","𝜖":"ꞓ","𝜺":"ꞓ","𝝐":"ꞓ","𝝴":"ꞓ","𝞊":"ꞓ","𝞮":"ꞓ","𝟄":"ꞓ","ⲉ":"ꞓ","є":"ꞓ","ԑ":"ꞓ","ꮛ":"ꞓ","𑣎":"ꞓ","𐐩":"ꞓ","€":"Ꞓ","Ⲉ":"Ꞓ","Є":"Ꞓ","⍷":"ꞓ̲","ͽ":"ꜿ","Ͽ":"Ꜿ","ⅾ":"d","ⅆ":"d","𝐝":"d","𝑑":"d","𝒅":"d","𝒹":"d","𝓭":"d","𝔡":"d","𝕕":"d","𝖉":"d","𝖽":"d","𝗱":"d","𝘥":"d","𝙙":"d","𝚍":"d","ԁ":"d","Ꮷ":"d","ᑯ":"d","ꓒ":"d","Ⅾ":"D","ⅅ":"D","𝐃":"D","𝐷":"D","𝑫":"D","𝒟":"D","𝓓":"D","𝔇":"D","𝔻":"D","𝕯":"D","𝖣":"D","𝗗":"D","𝘋":"D","𝘿":"D","𝙳":"D","Ꭰ":"D","ᗞ":"D","ᗪ":"D","ꓓ":"D","ɗ":"d̔","ɖ":"d̨","ƌ":"d̄","đ":"d̵","Đ":"D̵","Ð":"D̵","Ɖ":"D̵","₫":"ḏ̵","ꝺ":"Ꝺ","ᑻ":"d·","ᒇ":"d\'","ʤ":"dȝ","dz":"dz","ʣ":"dz","Dz":"Dz","DZ":"DZ","dž":"dž","Dž":"Dž","DŽ":"DŽ","ʥ":"dʑ","ꭰ":"ᴅ","⸹":"ẟ","δ":"ẟ","𝛅":"ẟ","𝛿":"ẟ","𝜹":"ẟ","𝝳":"ẟ","𝞭":"ẟ","ծ":"ẟ","ᕷ":"ẟ","℮":"e","e":"e","ℯ":"e","ⅇ":"e","𝐞":"e","𝑒":"e","𝒆":"e","𝓮":"e","𝔢":"e","𝕖":"e","𝖊":"e","𝖾":"e","𝗲":"e","𝘦":"e","𝙚":"e","𝚎":"e","ꬲ":"e","е":"e","ҽ":"e","ⷷ":"ͤ","⋿":"E","E":"E","ℰ":"E","𝐄":"E","𝐸":"E","𝑬":"E","𝓔":"E","𝔈":"E","𝔼":"E","𝕰":"E","𝖤":"E","𝗘":"E","𝘌":"E","𝙀":"E","𝙴":"E","Ε":"E","𝚬":"E","𝛦":"E","𝜠":"E","𝝚":"E","𝞔":"E","Е":"E","ⴹ":"E","Ꭼ":"E","ꓰ":"E","𑢦":"E","𑢮":"E","𐊆":"E","ě":"ĕ","Ě":"Ĕ","ɇ":"e̸","Ɇ":"E̸","ҿ":"ę","ꭼ":"ᴇ","ə":"ǝ","ә":"ǝ","∃":"Ǝ","ⴺ":"Ǝ","ꓱ":"Ǝ","ɚ":"ǝ˞","ᴔ":"ǝo","ꭁ":"ǝo̸","ꭂ":"ǝo̵","Ә":"Ə","𝈡":"Ɛ","ℇ":"Ɛ","Ԑ":"Ɛ","Ꮛ":"Ɛ","𖼭":"Ɛ","𐐁":"Ɛ","ᶟ":"ᵋ","ᴈ":"ɜ","з":"ɜ","ҙ":"ɜ̦","𐑂":"ɞ","ꞝ":"ʚ","𐐪":"ʚ","𝐟":"f","𝑓":"f","𝒇":"f","𝒻":"f","𝓯":"f","𝔣":"f","𝕗":"f","𝖋":"f","𝖿":"f","𝗳":"f","𝘧":"f","𝙛":"f","𝚏":"f","ꬵ":"f","ꞙ":"f","ſ":"f","ẝ":"f","ք":"f","𝈓":"F","ℱ":"F","𝐅":"F","𝐹":"F","𝑭":"F","𝓕":"F","𝔉":"F","𝔽":"F","𝕱":"F","𝖥":"F","𝗙":"F","𝘍":"F","𝙁":"F","𝙵":"F","Ꞙ":"F","Ϝ":"F","𝟊":"F","ᖴ":"F","ꓝ":"F","𑣂":"F","𑢢":"F","𐊇":"F","𐊥":"F","𐔥":"F","ƒ":"f̦","Ƒ":"F̦","ᵮ":"f̴","℻":"FAX","ff":"ff","ffi":"ffi","ffl":"ffl","fi":"fi","fl":"fl","ʩ":"fŋ","ᖵ":"Ⅎ","ꓞ":"Ⅎ","𝈰":"ꟻ","ᖷ":"ꟻ","g":"g","ℊ":"g","𝐠":"g","𝑔":"g","𝒈":"g","𝓰":"g","𝔤":"g","𝕘":"g","𝖌":"g","𝗀":"g","𝗴":"g","𝘨":"g","𝙜":"g","𝚐":"g","ɡ":"g","ᶃ":"g","ƍ":"g","ց":"g","𝐆":"G","𝐺":"G","𝑮":"G","𝒢":"G","𝓖":"G","𝔊":"G","𝔾":"G","𝕲":"G","𝖦":"G","𝗚":"G","𝘎":"G","𝙂":"G","𝙶":"G","Ԍ":"G","Ꮐ":"G","Ᏻ":"G","ꓖ":"G","ᶢ":"ᵍ","ɠ":"g̔","ǧ":"ğ","Ǧ":"Ğ","ǵ":"ģ","ǥ":"g̵","Ǥ":"G̵","Ɠ":"G\'","ԍ":"ɢ","ꮐ":"ɢ","ᏻ":"ɢ","h":"h","ℎ":"h","𝐡":"h","𝒉":"h","𝒽":"h","𝓱":"h","𝔥":"h","𝕙":"h","𝖍":"h","𝗁":"h","𝗵":"h","𝘩":"h","𝙝":"h","𝚑":"h","һ":"h","հ":"h","Ꮒ":"h","H":"H","ℋ":"H","ℌ":"H","ℍ":"H","𝐇":"H","𝐻":"H","𝑯":"H","𝓗":"H","𝕳":"H","𝖧":"H","𝗛":"H","𝘏":"H","𝙃":"H","𝙷":"H","Η":"H","𝚮":"H","𝛨":"H","𝜢":"H","𝝜":"H","𝞖":"H","Ⲏ":"H","Н":"H","Ꮋ":"H","ᕼ":"H","ꓧ":"H","𐋏":"H","ᵸ":"ᴴ","ɦ":"h̔","ꚕ":"h̔","Ᏺ":"h̔","Ⱨ":"H̩","Ң":"H̩","ħ":"h̵","ℏ":"h̵","ћ":"h̵","Ħ":"H̵","Ӊ":"H̦","Ӈ":"H̦","н":"ʜ","ꮋ":"ʜ","ң":"ʜ̩","ӊ":"ʜ̦","ӈ":"ʜ̦","Ԋ":"Ƕ","ꮀ":"ⱶ","Ͱ":"Ⱶ","Ꭸ":"Ⱶ","Ꮀ":"Ⱶ","ꚱ":"Ⱶ","ꞕ":"ꜧ","˛":"i","⍳":"i","i":"i","ⅰ":"i","ℹ":"i","ⅈ":"i","𝐢":"i","𝑖":"i","𝒊":"i","𝒾":"i","𝓲":"i","𝔦":"i","𝕚":"i","𝖎":"i","𝗂":"i","𝗶":"i","𝘪":"i","𝙞":"i","𝚒":"i","ı":"i","𝚤":"i","ɪ":"i","ɩ":"i","ι":"i","ι":"i","ͺ":"i","𝛊":"i","𝜄":"i","𝜾":"i","𝝸":"i","𝞲":"i","і":"i","ꙇ":"i","ӏ":"i","ꭵ":"i","Ꭵ":"i","𑣃":"i","ⓛ":"Ⓘ","⍸":"i̲","ǐ":"ĭ","Ǐ":"Ĭ","ɨ":"i̵","ᵻ":"i̵","ᵼ":"i̵","ⅱ":"ii","ⅲ":"iii","ij":"ij","ⅳ":"iv","ⅸ":"ix","j":"j","ⅉ":"j","𝐣":"j","𝑗":"j","𝒋":"j","𝒿":"j","𝓳":"j","𝔧":"j","𝕛":"j","𝖏":"j","𝗃":"j","𝗷":"j","𝘫":"j","𝙟":"j","𝚓":"j","ϳ":"j","ј":"j","J":"J","𝐉":"J","𝐽":"J","𝑱":"J","𝒥":"J","𝓙":"J","𝔍":"J","𝕁":"J","𝕵":"J","𝖩":"J","𝗝":"J","𝘑":"J","𝙅":"J","𝙹":"J","Ʝ":"J","Ϳ":"J","Ј":"J","Ꭻ":"J","ᒍ":"J","ꓙ":"J","ɉ":"j̵","Ɉ":"J̵","ᒙ":"J·","𝚥":"ȷ","յ":"ȷ","ꭻ":"ᴊ","𝐤":"k","𝑘":"k","𝒌":"k","𝓀":"k","𝓴":"k","𝔨":"k","𝕜":"k","𝖐":"k","𝗄":"k","𝗸":"k","𝘬":"k","𝙠":"k","𝚔":"k","K":"K","K":"K","𝐊":"K","𝐾":"K","𝑲":"K","𝒦":"K","𝓚":"K","𝔎":"K","𝕂":"K","𝕶":"K","𝖪":"K","𝗞":"K","𝘒":"K","𝙆":"K","𝙺":"K","Κ":"K","𝚱":"K","𝛫":"K","𝜥":"K","𝝟":"K","𝞙":"K","Ⲕ":"K","К":"K","Ꮶ":"K","ᛕ":"K","ꓗ":"K","𐔘":"K","ƙ":"k̔","Ⱪ":"K̩","Қ":"K̩","₭":"K̵","Ꝁ":"K̵","Ҟ":"K̵","Ƙ":"K\'","׀":"l","|":"l","∣":"l","⏽":"l","│":"l","١":"l","۱":"l","𐌠":"l","𞣇":"l","𝟏":"l","𝟙":"l","𝟣":"l","𝟭":"l","𝟷":"l","🯱":"l","I":"l","I":"l","Ⅰ":"l","ℐ":"l","ℑ":"l","𝐈":"l","𝐼":"l","𝑰":"l","𝓘":"l","𝕀":"l","𝕴":"l","𝖨":"l","𝗜":"l","𝘐":"l","𝙄":"l","𝙸":"l","Ɩ":"l","l":"l","ⅼ":"l","ℓ":"l","𝐥":"l","𝑙":"l","𝒍":"l","𝓁":"l","𝓵":"l","𝔩":"l","𝕝":"l","𝖑":"l","𝗅":"l","𝗹":"l","𝘭":"l","𝙡":"l","𝚕":"l","ǀ":"l","Ι":"l","𝚰":"l","𝛪":"l","𝜤":"l","𝝞":"l","𝞘":"l","Ⲓ":"l","І":"l","Ӏ":"l","ו":"l","ן":"l","ا":"l","𞸀":"l","𞺀":"l","ﺎ":"l","ﺍ":"l","ߊ":"l","ⵏ":"l","ᛁ":"l","ꓲ":"l","𖼨":"l","𐊊":"l","𐌉":"l","𝈪":"L","Ⅼ":"L","ℒ":"L","𝐋":"L","𝐿":"L","𝑳":"L","𝓛":"L","𝔏":"L","𝕃":"L","𝕷":"L","𝖫":"L","𝗟":"L","𝘓":"L","𝙇":"L","𝙻":"L","Ⳑ":"L","Ꮮ":"L","ᒪ":"L","ꓡ":"L","𖼖":"L","𑢣":"L","𑢲":"L","𐐛":"L","𐔦":"L","ﴼ":"l̋","ﴽ":"l̋","ł":"l̸","Ł":"L̸","ɭ":"l̨","Ɨ":"l̵","ƚ":"l̵","ɫ":"l̴","إ":"lٕ","ﺈ":"lٕ","ﺇ":"lٕ","ٳ":"lٕ","ŀ":"l·","Ŀ":"l·","ᒷ":"l·","🄂":"l,","⒈":"l.","ױ":"l\'","⒓":"l2.","㏫":"l2日","㋋":"l2月","㍤":"l2点","⒔":"l3.","㏬":"l3日","㍥":"l3点","⒕":"l4.","㏭":"l4日","㍦":"l4点","⒖":"l5.","㏮":"l5日","㍧":"l5点","⒗":"l6.","㏯":"l6日","㍨":"l6点","⒘":"l7.","㏰":"l7日","㍩":"l7点","⒙":"l8.","㏱":"l8日","㍪":"l8点","⒚":"l9.","㏲":"l9日","㍫":"l9点","lj":"lj","IJ":"lJ","Lj":"Lj","LJ":"LJ","‖":"ll","∥":"ll","Ⅱ":"ll","ǁ":"ll","װ":"ll","𐆙":"l̵l̵","⒒":"ll.","Ⅲ":"lll","𐆘":"l̵l̵S̵","㏪":"ll日","㋊":"ll月","㍣":"ll点","Ю":"lO","⒑":"lO.","㏩":"lO日","㋉":"lO月","㍢":"lO点","ʪ":"ls","₶":"lt","Ⅳ":"lV","Ⅸ":"lX","ɮ":"lȝ","ʫ":"lz","أ":"lٴ","ﺄ":"lٴ","ﺃ":"lٴ","ٲ":"lٴ","ٵ":"lٴ","ﷳ":"lكبر","ﷲ":"lللّٰo","㏠":"l日","㋀":"l月","㍙":"l点","ⳑ":"ʟ","ꮮ":"ʟ","𐑃":"ʟ","M":"M","Ⅿ":"M","ℳ":"M","𝐌":"M","𝑀":"M","𝑴":"M","𝓜":"M","𝔐":"M","𝕄":"M","𝕸":"M","𝖬":"M","𝗠":"M","𝘔":"M","𝙈":"M","𝙼":"M","Μ":"M","𝚳":"M","𝛭":"M","𝜧":"M","𝝡":"M","𝞛":"M","Ϻ":"M","Ⲙ":"M","М":"M","Ꮇ":"M","ᗰ":"M","ᛖ":"M","ꓟ":"M","𐊰":"M","𐌑":"M","Ӎ":"M̦","🝫":"MB","ⷨ":"ᷟ","𝐧":"n","𝑛":"n","𝒏":"n","𝓃":"n","𝓷":"n","𝔫":"n","𝕟":"n","𝖓":"n","𝗇":"n","𝗻":"n","𝘯":"n","𝙣":"n","𝚗":"n","ո":"n","ռ":"n","N":"N","ℕ":"N","𝐍":"N","𝑁":"N","𝑵":"N","𝒩":"N","𝓝":"N","𝔑":"N","𝕹":"N","𝖭":"N","𝗡":"N","𝘕":"N","𝙉":"N","𝙽":"N","Ν":"N","𝚴":"N","𝛮":"N","𝜨":"N","𝝢":"N","𝞜":"N","Ⲛ":"N","ꓠ":"N","𐔓":"N","𐆎":"N̊","ɳ":"n̨","ƞ":"n̩","η":"n̩","𝛈":"n̩","𝜂":"n̩","𝜼":"n̩","𝝶":"n̩","𝞰":"n̩","Ɲ":"N̦","ᵰ":"n̴","nj":"nj","Nj":"Nj","NJ":"NJ","№":"No","ͷ":"ᴎ","и":"ᴎ","𐑍":"ᴎ","ņ":"ɲ","ం":"o","ಂ":"o","ം":"o","ං":"o","०":"o","੦":"o","૦":"o","௦":"o","౦":"o","೦":"o","൦":"o","๐":"o","໐":"o","၀":"o","٥":"o","۵":"o","o":"o","ℴ":"o","𝐨":"o","𝑜":"o","𝒐":"o","𝓸":"o","𝔬":"o","𝕠":"o","𝖔":"o","𝗈":"o","𝗼":"o","𝘰":"o","𝙤":"o","𝚘":"o","ᴏ":"o","ᴑ":"o","ꬽ":"o","ο":"o","𝛐":"o","𝜊":"o","𝝄":"o","𝝾":"o","𝞸":"o","σ":"o","𝛔":"o","𝜎":"o","𝝈":"o","𝞂":"o","𝞼":"o","ⲟ":"o","о":"o","ჿ":"o","օ":"o","ס":"o","ه":"o","𞸤":"o","𞹤":"o","𞺄":"o","ﻫ":"o","ﻬ":"o","ﻪ":"o","ﻩ":"o","ھ":"o","ﮬ":"o","ﮭ":"o","ﮫ":"o","ﮪ":"o","ہ":"o","ﮨ":"o","ﮩ":"o","ﮧ":"o","ﮦ":"o","ە":"o","ഠ":"o","ဝ":"o","𐓪":"o","𑣈":"o","𑣗":"o","𐐬":"o","߀":"O","০":"O","୦":"O","〇":"O","𑓐":"O","𑣠":"O","𝟎":"O","𝟘":"O","𝟢":"O","𝟬":"O","𝟶":"O","🯰":"O","O":"O","𝐎":"O","𝑂":"O","𝑶":"O","𝒪":"O","𝓞":"O","𝔒":"O","𝕆":"O","𝕺":"O","𝖮":"O","𝗢":"O","𝘖":"O","𝙊":"O","𝙾":"O","Ο":"O","𝚶":"O","𝛰":"O","𝜪":"O","𝝤":"O","𝞞":"O","Ⲟ":"O","О":"O","Օ":"O","ⵔ":"O","ዐ":"O","ଠ":"O","𐓂":"O","ꓳ":"O","𑢵":"O","𐊒":"O","𐊫":"O","𐐄":"O","𐔖":"O","⁰":"º","ᵒ":"º","ǒ":"ŏ","Ǒ":"Ŏ","ۿ":"ô","Ő":"Ö","ø":"o̸","ꬾ":"o̸","Ø":"O̸","ⵁ":"O̸","Ǿ":"Ó̸","ɵ":"o̵","ꝋ":"o̵","ө":"o̵","ѳ":"o̵","ꮎ":"o̵","ꮻ":"o̵","⊖":"O̵","⊝":"O̵","⍬":"O̵","𝈚":"O̵","🜔":"O̵","Ɵ":"O̵","Ꝋ":"O̵","θ":"O̵","ϑ":"O̵","𝛉":"O̵","𝛝":"O̵","𝜃":"O̵","𝜗":"O̵","𝜽":"O̵","𝝑":"O̵","𝝷":"O̵","𝞋":"O̵","𝞱":"O̵","𝟅":"O̵","Θ":"O̵","ϴ":"O̵","𝚯":"O̵","𝚹":"O̵","𝛩":"O̵","𝛳":"O̵","𝜣":"O̵","𝜭":"O̵","𝝝":"O̵","𝝧":"O̵","𝞗":"O̵","𝞡":"O̵","Ө":"O̵","Ѳ":"O̵","ⴱ":"O̵","Ꮎ":"O̵","Ꮻ":"O̵","ꭴ":"ơ","ﳙ":"oٰ","🄁":"O,","🄀":"O.","ơ":"o\'","Ơ":"O\'","Ꭴ":"O\'","%":"º/₀","٪":"º/₀","⁒":"º/₀","‰":"º/₀₀","؉":"º/₀₀","‱":"º/₀₀₀","؊":"º/₀₀₀","œ":"oe","Œ":"OE","ɶ":"oᴇ","∞":"oo","ꝏ":"oo","ꚙ":"oo","Ꝏ":"OO","Ꚙ":"OO","ﳗ":"oج","ﱑ":"oج","ﳘ":"oم","ﱒ":"oم","ﶓ":"oمج","ﶔ":"oمم","ﱓ":"oى","ﱔ":"oى","ൟ":"oരo","တ":"oာ","㍘":"O点","ↄ":"ɔ","ᴐ":"ɔ","ͻ":"ɔ","𐑋":"ɔ","Ↄ":"Ɔ","Ͻ":"Ɔ","ꓛ":"Ɔ","𐐣":"Ɔ","ꬿ":"ɔ̸","ꭢ":"ɔe","𐐿":"ɷ","⍴":"p","p":"p","𝐩":"p","𝑝":"p","𝒑":"p","𝓅":"p","𝓹":"p","𝔭":"p","𝕡":"p","𝖕":"p","𝗉":"p","𝗽":"p","𝘱":"p","𝙥":"p","𝚙":"p","ρ":"p","ϱ":"p","𝛒":"p","𝛠":"p","𝜌":"p","𝜚":"p","𝝆":"p","𝝔":"p","𝞀":"p","𝞎":"p","𝞺":"p","𝟈":"p","ⲣ":"p","р":"p","P":"P","ℙ":"P","𝐏":"P","𝑃":"P","𝑷":"P","𝒫":"P","𝓟":"P","𝔓":"P","𝕻":"P","𝖯":"P","𝗣":"P","𝘗":"P","𝙋":"P","𝙿":"P","Ρ":"P","𝚸":"P","𝛲":"P","𝜬":"P","𝝦":"P","𝞠":"P","Ⲣ":"P","Р":"P","Ꮲ":"P","ᑭ":"P","ꓑ":"P","𐊕":"P","ƥ":"p̔","ᵽ":"p̵","ᑷ":"p·","ᒆ":"P\'","ᴩ":"ᴘ","ꮲ":"ᴘ","φ":"ɸ","ϕ":"ɸ","𝛗":"ɸ","𝛟":"ɸ","𝜑":"ɸ","𝜙":"ɸ","𝝋":"ɸ","𝝓":"ɸ","𝞅":"ɸ","𝞍":"ɸ","𝞿":"ɸ","𝟇":"ɸ","ⲫ":"ɸ","ф":"ɸ","𝐪":"q","𝑞":"q","𝒒":"q","𝓆":"q","𝓺":"q","𝔮":"q","𝕢":"q","𝖖":"q","𝗊":"q","𝗾":"q","𝘲":"q","𝙦":"q","𝚚":"q","ԛ":"q","գ":"q","զ":"q","ℚ":"Q","𝐐":"Q","𝑄":"Q","𝑸":"Q","𝒬":"Q","𝓠":"Q","𝔔":"Q","𝕼":"Q","𝖰":"Q","𝗤":"Q","𝘘":"Q","𝙌":"Q","𝚀":"Q","ⵕ":"Q","ʠ":"q̔","🜀":"QE","ᶐ":"ɋ","ᴋ":"ĸ","κ":"ĸ","ϰ":"ĸ","𝛋":"ĸ","𝛞":"ĸ","𝜅":"ĸ","𝜘":"ĸ","𝜿":"ĸ","𝝒":"ĸ","𝝹":"ĸ","𝞌":"ĸ","𝞳":"ĸ","𝟆":"ĸ","ⲕ":"ĸ","к":"ĸ","ꮶ":"ĸ","қ":"ĸ̩","ҟ":"ĸ̵","𝐫":"r","𝑟":"r","𝒓":"r","𝓇":"r","𝓻":"r","𝔯":"r","𝕣":"r","𝖗":"r","𝗋":"r","𝗿":"r","𝘳":"r","𝙧":"r","𝚛":"r","ꭇ":"r","ꭈ":"r","ᴦ":"r","ⲅ":"r","г":"r","ꮁ":"r","𝈖":"R","ℛ":"R","ℜ":"R","ℝ":"R","𝐑":"R","𝑅":"R","𝑹":"R","𝓡":"R","𝕽":"R","𝖱":"R","𝗥":"R","𝘙":"R","𝙍":"R","𝚁":"R","Ʀ":"R","Ꭱ":"R","Ꮢ":"R","𐒴":"R","ᖇ":"R","ꓣ":"R","𖼵":"R","ɽ":"r̨","ɼ":"r̩","ɍ":"r̵","ғ":"r̵","ᵲ":"r̴","ґ":"r\'","𑣣":"rn","m":"rn","ⅿ":"rn","𝐦":"rn","𝑚":"rn","𝒎":"rn","𝓂":"rn","𝓶":"rn","𝔪":"rn","𝕞":"rn","𝖒":"rn","𝗆":"rn","𝗺":"rn","𝘮":"rn","𝙢":"rn","𝚖":"rn","𑜀":"rn","₥":"rn̸","ɱ":"rn̦","ᵯ":"rn̴","₨":"Rs","ꭱ":"ʀ","ꮢ":"ʀ","я":"ᴙ","ᵳ":"ɾ̴","℩":"ɿ","s":"s","𝐬":"s","𝑠":"s","𝒔":"s","𝓈":"s","𝓼":"s","𝔰":"s","𝕤":"s","𝖘":"s","𝗌":"s","𝘀":"s","𝘴":"s","𝙨":"s","𝚜":"s","ꜱ":"s","ƽ":"s","ѕ":"s","ꮪ":"s","𑣁":"s","𐑈":"s","S":"S","𝐒":"S","𝑆":"S","𝑺":"S","𝒮":"S","𝓢":"S","𝔖":"S","𝕊":"S","𝕾":"S","𝖲":"S","𝗦":"S","𝘚":"S","𝙎":"S","𝚂":"S","Ѕ":"S","Տ":"S","Ꮥ":"S","Ꮪ":"S","ꓢ":"S","𖼺":"S","𐊖":"S","𐐠":"S","ʂ":"s̨","ᵴ":"s̴","ꞵ":"ß","β":"ß","ϐ":"ß","𝛃":"ß","𝛽":"ß","𝜷":"ß","𝝱":"ß","𝞫":"ß","Ᏸ":"ß","🝜":"sss","st":"st","∫":"ʃ","ꭍ":"ʃ","∑":"Ʃ","⅀":"Ʃ","Σ":"Ʃ","𝚺":"Ʃ","𝛴":"Ʃ","𝜮":"Ʃ","𝝨":"Ʃ","𝞢":"Ʃ","ⵉ":"Ʃ","∬":"ʃʃ","∭":"ʃʃʃ","⨌":"ʃʃʃʃ","𝐭":"t","𝑡":"t","𝒕":"t","𝓉":"t","𝓽":"t","𝔱":"t","𝕥":"t","𝖙":"t","𝗍":"t","𝘁":"t","𝘵":"t","𝙩":"t","𝚝":"t","⊤":"T","⟙":"T","🝨":"T","T":"T","𝐓":"T","𝑇":"T","𝑻":"T","𝒯":"T","𝓣":"T","𝔗":"T","𝕋":"T","𝕿":"T","𝖳":"T","𝗧":"T","𝘛":"T","𝙏":"T","𝚃":"T","Τ":"T","𝚻":"T","𝛵":"T","𝜯":"T","𝝩":"T","𝞣":"T","Ⲧ":"T","Т":"T","Ꭲ":"T","ꓔ":"T","𖼊":"T","𑢼":"T","𐊗":"T","𐊱":"T","𐌕":"T","ƭ":"t̔","⍡":"T̈","Ⱦ":"T̸","Ț":"Ţ","Ʈ":"T̨","Ҭ":"T̩","₮":"T⃫","ŧ":"t̵","Ŧ":"T̵","ᵵ":"t̴","Ⴀ":"Ꞇ","Ꜩ":"T3","ʨ":"tɕ","℡":"TEL","ꝷ":"tf","ʦ":"ts","ʧ":"tʃ","ꜩ":"tȝ","τ":"ᴛ","𝛕":"ᴛ","𝜏":"ᴛ","𝝉":"ᴛ","𝞃":"ᴛ","𝞽":"ᴛ","т":"ᴛ","ꭲ":"ᴛ","ҭ":"ᴛ̩","ţ":"ƫ","ț":"ƫ","Ꮏ":"ƫ","𝐮":"u","𝑢":"u","𝒖":"u","𝓊":"u","𝓾":"u","𝔲":"u","𝕦":"u","𝖚":"u","𝗎":"u","𝘂":"u","𝘶":"u","𝙪":"u","𝚞":"u","ꞟ":"u","ᴜ":"u","ꭎ":"u","ꭒ":"u","ʋ":"u","υ":"u","𝛖":"u","𝜐":"u","𝝊":"u","𝞄":"u","𝞾":"u","ս":"u","𐓶":"u","𑣘":"u","∪":"U","⋃":"U","𝐔":"U","𝑈":"U","𝑼":"U","𝒰":"U","𝓤":"U","𝔘":"U","𝕌":"U","𝖀":"U","𝖴":"U","𝗨":"U","𝘜":"U","𝙐":"U","𝚄":"U","Ս":"U","ሀ":"U","𐓎":"U","ᑌ":"U","ꓴ":"U","𖽂":"U","𑢸":"U","ǔ":"ŭ","Ǔ":"Ŭ","ᵾ":"u̵","ꮜ":"u̵","Ʉ":"U̵","Ꮜ":"U̵","ᑘ":"U·","ᑧ":"U\'","ᵫ":"ue","ꭣ":"uo","ṃ":"ꭑ","պ":"ɰ","ሣ":"ɰ","℧":"Ʊ","ᘮ":"Ʊ","ᘴ":"Ʊ","ᵿ":"ʊ̵","∨":"v","⋁":"v","v":"v","ⅴ":"v","𝐯":"v","𝑣":"v","𝒗":"v","𝓋":"v","𝓿":"v","𝔳":"v","𝕧":"v","𝖛":"v","𝗏":"v","𝘃":"v","𝘷":"v","𝙫":"v","𝚟":"v","ᴠ":"v","ν":"v","𝛎":"v","𝜈":"v","𝝂":"v","𝝼":"v","𝞶":"v","ѵ":"v","ט":"v","𑜆":"v","ꮩ":"v","𑣀":"v","𝈍":"V","٧":"V","۷":"V","Ⅴ":"V","𝐕":"V","𝑉":"V","𝑽":"V","𝒱":"V","𝓥":"V","𝔙":"V","𝕍":"V","𝖁":"V","𝖵":"V","𝗩":"V","𝘝":"V","𝙑":"V","𝚅":"V","Ѵ":"V","ⴸ":"V","Ꮩ":"V","ᐯ":"V","ꛟ":"V","ꓦ":"V","𖼈":"V","𑢠":"V","𐔝":"V","𐆗":"V̵","ᐻ":"V·","🝬":"VB","ⅵ":"vi","ⅶ":"vii","ⅷ":"viii","Ⅵ":"Vl","Ⅶ":"Vll","Ⅷ":"Vlll","🜈":"Vᷤ","ᴧ":"ʌ","𐓘":"ʌ","٨":"Ʌ","۸":"Ʌ","Λ":"Ʌ","𝚲":"Ʌ","𝛬":"Ʌ","𝜦":"Ʌ","𝝠":"Ʌ","𝞚":"Ʌ","Л":"Ʌ","ⴷ":"Ʌ","𐒰":"Ʌ","ᐱ":"Ʌ","ꛎ":"Ʌ","ꓥ":"Ʌ","𖼽":"Ʌ","𐊍":"Ʌ","Ӆ":"Ʌ̦","ᐽ":"Ʌ·","ɯ":"w","𝐰":"w","𝑤":"w","𝒘":"w","𝓌":"w","𝔀":"w","𝔴":"w","𝕨":"w","𝖜":"w","𝗐":"w","𝘄":"w","𝘸":"w","𝙬":"w","𝚠":"w","ᴡ":"w","ѡ":"w","ԝ":"w","ա":"w","𑜊":"w","𑜎":"w","𑜏":"w","ꮃ":"w","𑣯":"W","𑣦":"W","𝐖":"W","𝑊":"W","𝑾":"W","𝒲":"W","𝓦":"W","𝔚":"W","𝕎":"W","𝖂":"W","𝖶":"W","𝗪":"W","𝘞":"W","𝙒":"W","𝚆":"W","Ԝ":"W","Ꮃ":"W","Ꮤ":"W","ꓪ":"W","ѽ":"w҆҇","𑓅":"ẇ","₩":"W̵","ꝡ":"w̦","ᴍ":"ʍ","м":"ʍ","ꮇ":"ʍ","ӎ":"ʍ̦","᙮":"x","×":"x","⤫":"x","⤬":"x","⨯":"x","x":"x","ⅹ":"x","𝐱":"x","𝑥":"x","𝒙":"x","𝓍":"x","𝔁":"x","𝔵":"x","𝕩":"x","𝖝":"x","𝗑":"x","𝘅":"x","𝘹":"x","𝙭":"x","𝚡":"x","х":"x","ᕁ":"x","ᕽ":"x","ⷯ":"ͯ","᙭":"X","╳":"X","𐌢":"X","𑣬":"X","X":"X","Ⅹ":"X","𝐗":"X","𝑋":"X","𝑿":"X","𝒳":"X","𝓧":"X","𝔛":"X","𝕏":"X","𝖃":"X","𝖷":"X","𝗫":"X","𝘟":"X","𝙓":"X","𝚇":"X","Ꭓ":"X","Χ":"X","𝚾":"X","𝛸":"X","𝜲":"X","𝝬":"X","𝞦":"X","Ⲭ":"X","Х":"X","ⵝ":"X","ᚷ":"X","ꓫ":"X","𐊐":"X","𐊴":"X","𐌗":"X","𐔧":"X","⨰":"ẋ","Ҳ":"X̩","𐆖":"X̵","ⅺ":"xi","ⅻ":"xii","Ⅺ":"Xl","Ⅻ":"Xll","ɣ":"y","ᶌ":"y","y":"y","𝐲":"y","𝑦":"y","𝒚":"y","𝓎":"y","𝔂":"y","𝔶":"y","𝕪":"y","𝖞":"y","𝗒":"y","𝘆":"y","𝘺":"y","𝙮":"y","𝚢":"y","ʏ":"y","ỿ":"y","ꭚ":"y","γ":"y","ℽ":"y","𝛄":"y","𝛾":"y","𝜸":"y","𝝲":"y","𝞬":"y","у":"y","ү":"y","ყ":"y","𑣜":"y","Y":"Y","𝐘":"Y","𝑌":"Y","𝒀":"Y","𝒴":"Y","𝓨":"Y","𝔜":"Y","𝕐":"Y","𝖄":"Y","𝖸":"Y","𝗬":"Y","𝘠":"Y","𝙔":"Y","𝚈":"Y","Υ":"Y","ϒ":"Y","𝚼":"Y","𝛶":"Y","𝜰":"Y","𝝪":"Y","𝞤":"Y","Ⲩ":"Y","У":"Y","Ү":"Y","Ꭹ":"Y","Ꮍ":"Y","ꓬ":"Y","𖽃":"Y","𑢤":"Y","𐊲":"Y","ƴ":"y̔","ɏ":"y̵","ұ":"y̵","¥":"Y̵","Ɏ":"Y̵","Ұ":"Y̵","ʒ":"ȝ","ꝫ":"ȝ","ⳍ":"ȝ","ӡ":"ȝ","ჳ":"ȝ","𝐳":"z","𝑧":"z","𝒛":"z","𝓏":"z","𝔃":"z","𝔷":"z","𝕫":"z","𝖟":"z","𝗓":"z","𝘇":"z","𝘻":"z","𝙯":"z","𝚣":"z","ᴢ":"z","ꮓ":"z","𑣄":"z","𐋵":"Z","𑣥":"Z","Z":"Z","ℤ":"Z","ℨ":"Z","𝐙":"Z","𝑍":"Z","𝒁":"Z","𝒵":"Z","𝓩":"Z","𝖅":"Z","𝖹":"Z","𝗭":"Z","𝘡":"Z","𝙕":"Z","𝚉":"Z","Ζ":"Z","𝚭":"Z","𝛧":"Z","𝜡":"Z","𝝛":"Z","𝞕":"Z","Ꮓ":"Z","ꓜ":"Z","𑢩":"Z","ʐ":"z̨","ƶ":"z̵","Ƶ":"Z̵","ȥ":"z̦","Ȥ":"Z̦","ᵶ":"z̴","ƿ":"þ","ϸ":"þ","Ϸ":"Þ","𐓄":"Þ","⁹":"ꝰ","ᴤ":"ƨ","ϩ":"ƨ","ꙅ":"ƨ","ь":"ƅ","ꮟ":"ƅ","ы":"ƅi","ꭾ":"ɂ","ˤ":"ˁ","ꛍ":"ʡ","⊙":"ʘ","☉":"ʘ","⨀":"ʘ","Ꙩ":"ʘ","ⵙ":"ʘ","𐓃":"ʘ","ℾ":"Γ","𝚪":"Γ","𝛤":"Γ","𝜞":"Γ","𝝘":"Γ","𝞒":"Γ","Ⲅ":"Γ","Г":"Γ","Ꮁ":"Γ","ᒥ":"Γ","𖼇":"Γ","Ғ":"Γ̵","ᒯ":"Γ·","Ґ":"Γ\'","∆":"Δ","△":"Δ","🜂":"Δ","𝚫":"Δ","𝛥":"Δ","𝜟":"Δ","𝝙":"Δ","𝞓":"Δ","Ⲇ":"Δ","ⵠ":"Δ","ᐃ":"Δ","𖼚":"Δ","𐊅":"Δ","𐊣":"Δ","⍙":"Δ̲","ᐏ":"Δ·","ᐬ":"Δᐠ","𝟋":"ϝ","𝛇":"ζ","𝜁":"ζ","𝜻":"ζ","𝝵":"ζ","𝞯":"ζ","ⳤ":"ϗ","𝛌":"λ","𝜆":"λ","𝝀":"λ","𝝺":"λ","𝞴":"λ","Ⲗ":"λ","𐓛":"λ","µ":"μ","𝛍":"μ","𝜇":"μ","𝝁":"μ","𝝻":"μ","𝞵":"μ","𝛏":"ξ","𝜉":"ξ","𝝃":"ξ","𝝽":"ξ","𝞷":"ξ","𝚵":"Ξ","𝛯":"Ξ","𝜩":"Ξ","𝝣":"Ξ","𝞝":"Ξ","ϖ":"π","ℼ":"π","𝛑":"π","𝛡":"π","𝜋":"π","𝜛":"π","𝝅":"π","𝝕":"π","𝝿":"π","𝞏":"π","𝞹":"π","𝟉":"π","ᴨ":"π","п":"π","∏":"Π","ℿ":"Π","𝚷":"Π","𝛱":"Π","𝜫":"Π","𝝥":"Π","𝞟":"Π","Ⲡ":"Π","П":"Π","ꛛ":"Π","𐊭":"Ϙ","𐌒":"Ϙ","ϛ":"ς","𝛓":"ς","𝜍":"ς","𝝇":"ς","𝞁":"ς","𝞻":"ς","𝚽":"Φ","𝛷":"Φ","𝜱":"Φ","𝝫":"Φ","𝞥":"Φ","Ⲫ":"Φ","Ф":"Φ","Փ":"Φ","ቀ":"Φ","ᛰ":"Φ","𐊳":"Φ","ꭓ":"χ","ꭕ":"χ","𝛘":"χ","𝜒":"χ","𝝌":"χ","𝞆":"χ","𝟀":"χ","ⲭ":"χ","𝛙":"ψ","𝜓":"ψ","𝝍":"ψ","𝞇":"ψ","𝟁":"ψ","ѱ":"ψ","𐓹":"ψ","𝚿":"Ψ","𝛹":"Ψ","𝜳":"Ψ","𝝭":"Ψ","𝞧":"Ψ","Ⲯ":"Ψ","Ѱ":"Ψ","𐓑":"Ψ","ᛘ":"Ψ","𐊵":"Ψ","⍵":"ω","ꞷ":"ω","𝛚":"ω","𝜔":"ω","𝝎":"ω","𝞈":"ω","𝟂":"ω","ⲱ":"ω","ꙍ":"ω","Ω":"Ω","𝛀":"Ω","𝛺":"Ω","𝜴":"Ω","𝝮":"Ω","𝞨":"Ω","ᘯ":"Ω","ᘵ":"Ω","𐊶":"Ω","⍹":"ω̲","ώ":"ῴ","☰":"Ⲷ","Ⳝ":"Ϭ","җ":"ж̩","Җ":"Ж̩","𝈋":"И","Ͷ":"И","ꚡ":"И","𐐥":"И","Й":"Ѝ","Ҋ":"Ѝ̦","ѝ":"й","ҋ":"й̦","𐒼":"Ӄ","ᴫ":"л","ӆ":"л̦","ꭠ":"љ","𐓫":"ꙩ","ᷮ":"ⷬ","𐓍":"Ћ","𝈂":"Ӿ","𝈢":"Ѡ","Ꮗ":"Ѡ","ᗯ":"Ѡ","Ѽ":"Ѡ҆҇","ᣭ":"Ѡ·","Ꞷ":"Ꙍ","ӌ":"ҷ","Ӌ":"Ҷ","Ҿ":"Ҽ̨","ⲽ":"ш","Ⲽ":"Ш","Ꙑ":"Ъl","℈":"Э","🜁":"Ꙙ","𖼜":"Ꙙ","ꦒ":"ⰿ","և":"եւ","ኔ":"ձ","ﬔ":"մե","ﬕ":"մի","ﬗ":"մխ","ﬓ":"մն","∩":"Ո","⋂":"Ո","𝉅":"Ո","በ":"Ո","ᑎ":"Ո","ꓵ":"Ո","ᑚ":"Ո·","ᑨ":"Ո\'","ﬖ":"վն","₽":"Ք","˓":"ՙ","ʿ":"ՙ","ℵ":"א","ﬡ":"א","אָ":"אַ","אּ":"אַ","ﭏ":"אל","ℶ":"ב","ℷ":"ג","ℸ":"ד","ﬢ":"ד","ﬣ":"ה","יּ":"יִ","ﬤ":"כ","ﬥ":"ל","ﬦ":"ם","ﬠ":"ע","ﬧ":"ר","שׂ":"שׁ","שּ":"שׁ","שּׂ":"שּׁ","ﬨ":"ת","ﺀ":"ء","۽":"ء͈","ﺂ":"آ","ﺁ":"آ","ﭑ":"ٱ","ﭐ":"ٱ","𞸁":"ب","𞸡":"ب","𞹡":"ب","𞺁":"ب","𞺡":"ب","ﺑ":"ب","ﺒ":"ب","ﺐ":"ب","ﺏ":"ب","ݑ":"بۛ","ࢶ":"بۢ","ࢡ":"بٔ","ﲠ":"بo","ﳢ":"بo","ﲜ":"بج","ﰅ":"بج","ﲝ":"بح","ﰆ":"بح","ﷂ":"بحى","ﲞ":"بخ","ﰇ":"بخ","ﳒ":"بخ","ﱋ":"بخ","ﶞ":"بخى","ﱪ":"بر","ﱫ":"بز","ﲟ":"بم","ﳡ":"بم","ﱬ":"بم","ﰈ":"بم","ﱭ":"بن","ﱮ":"بى","ﰉ":"بى","ﱯ":"بى","ﰊ":"بى","ﭔ":"ٻ","ﭕ":"ٻ","ﭓ":"ٻ","ﭒ":"ٻ","ې":"ٻ","ﯦ":"ٻ","ﯧ":"ٻ","ﯥ":"ٻ","ﯤ":"ٻ","ﭜ":"ڀ","ﭝ":"ڀ","ﭛ":"ڀ","ﭚ":"ڀ","ࢩ":"ݔ","ݧ":"ݔ","⍥":"ة","ö":"ة","ﺔ":"ة","ﺓ":"ة","ۃ":"ة","𞸕":"ت","𞸵":"ت","𞹵":"ت","𞺕":"ت","𞺵":"ت","ﺗ":"ت","ﺘ":"ت","ﺖ":"ت","ﺕ":"ت","ﲥ":"تo","ﳤ":"تo","ﲡ":"تج","ﰋ":"تج","ﵐ":"تجم","ﶠ":"تجى","ﶟ":"تجى","ﲢ":"تح","ﰌ":"تح","ﵒ":"تحج","ﵑ":"تحج","ﵓ":"تحم","ﲣ":"تخ","ﰍ":"تخ","ﵔ":"تخم","ﶢ":"تخى","ﶡ":"تخى","ﱰ":"تر","ﱱ":"تز","ﲤ":"تم","ﳣ":"تم","ﱲ":"تم","ﰎ":"تم","ﵕ":"تمج","ﵖ":"تمح","ﵗ":"تمخ","ﶤ":"تمى","ﶣ":"تمى","ﱳ":"تن","ﱴ":"تى","ﰏ":"تى","ﱵ":"تى","ﰐ":"تى","ﭠ":"ٺ","ﭡ":"ٺ","ﭟ":"ٺ","ﭞ":"ٺ","ﭤ":"ٿ","ﭥ":"ٿ","ﭣ":"ٿ","ﭢ":"ٿ","𞸂":"ج","𞸢":"ج","𞹂":"ج","𞹢":"ج","𞺂":"ج","𞺢":"ج","ﺟ":"ج","ﺠ":"ج","ﺞ":"ج","ﺝ":"ج","ﲧ":"جح","ﰕ":"جح","ﶦ":"جحى","ﶾ":"جحى","ﷻ":"جل جلlلo","ﲨ":"جم","ﰖ":"جم","ﵙ":"جمح","ﵘ":"جمح","ﶧ":"جمى","ﶥ":"جمى","ﴝ":"جى","ﴁ":"جى","ﴞ":"جى","ﴂ":"جى","ﭸ":"ڃ","ﭹ":"ڃ","ﭷ":"ڃ","ﭶ":"ڃ","ﭴ":"ڄ","ﭵ":"ڄ","ﭳ":"ڄ","ﭲ":"ڄ","ﭼ":"چ","ﭽ":"چ","ﭻ":"چ","ﭺ":"چ","ﮀ":"ڇ","ﮁ":"ڇ","ﭿ":"ڇ","ﭾ":"ڇ","𞸇":"ح","𞸧":"ح","𞹇":"ح","𞹧":"ح","𞺇":"ح","𞺧":"ح","ﺣ":"ح","ﺤ":"ح","ﺢ":"ح","ﺡ":"ح","څ":"حۛ","ځ":"حٔ","ݲ":"حٔ","ﲩ":"حج","ﰗ":"حج","ﶿ":"حجى","ﲪ":"حم","ﰘ":"حم","ﵛ":"حمى","ﵚ":"حمى","ﴛ":"حى","ﳿ":"حى","ﴜ":"حى","ﴀ":"حى","𞸗":"خ","𞸷":"خ","𞹗":"خ","𞹷":"خ","𞺗":"خ","𞺷":"خ","ﺧ":"خ","ﺨ":"خ","ﺦ":"خ","ﺥ":"خ","ﲫ":"خج","ﰙ":"خج","ﰚ":"خح","ﲬ":"خم","ﰛ":"خم","ﴟ":"خى","ﴃ":"خى","ﴠ":"خى","ﴄ":"خى","𐋡":"د","𞸃":"د","𞺃":"د","𞺣":"د","ﺪ":"د","ﺩ":"د","ڈ":"دؕ","ﮉ":"دؕ","ﮈ":"دؕ","ڎ":"دۛ","ﮇ":"دۛ","ﮆ":"دۛ","ۮ":"د̂","ࢮ":"د̤̣","𞸘":"ذ","𞺘":"ذ","𞺸":"ذ","ﺬ":"ذ","ﺫ":"ذ","ﱛ":"ذٰ","ڋ":"ڊؕ","ﮅ":"ڌ","ﮄ":"ڌ","ﮃ":"ڍ","ﮂ":"ڍ","𞸓":"ر","𞺓":"ر","𞺳":"ر","ﺮ":"ر","ﺭ":"ر","ڑ":"رؕ","ﮍ":"رؕ","ﮌ":"رؕ","ژ":"رۛ","ﮋ":"رۛ","ﮊ":"رۛ","ڒ":"ر̆","ࢹ":"ر̆̇","ۯ":"ر̂","ݬ":"رٔ","ﱜ":"رٰ","ﷶ":"رسول","﷼":"رىlل","𞸆":"ز","𞺆":"ز","𞺦":"ز","ﺰ":"ز","ﺯ":"ز","ࢲ":"ز̂","ݱ":"ڗؕ","𞸎":"س","𞸮":"س","𞹎":"س","𞹮":"س","𞺎":"س","𞺮":"س","ﺳ":"س","ﺴ":"س","ﺲ":"س","ﺱ":"س","ش":"سۛ","𞸔":"سۛ","𞸴":"سۛ","𞹔":"سۛ","𞹴":"سۛ","𞺔":"سۛ","𞺴":"سۛ","ﺷ":"سۛ","ﺸ":"سۛ","ﺶ":"سۛ","ﺵ":"سۛ","ݾ":"س̂","ﴱ":"سo","ﳨ":"سo","ﴲ":"سۛo","ﳪ":"سۛo","ﲭ":"سج","ﴴ":"سج","ﰜ":"سج","ﴭ":"سۛج","ﴷ":"سۛج","ﴥ":"سۛج","ﴉ":"سۛج","ﵝ":"سجح","ﵞ":"سجى","ﵩ":"سۛجى","ﲮ":"سح","ﴵ":"سح","ﰝ":"سح","ﴮ":"سۛح","ﴸ":"سۛح","ﴦ":"سۛح","ﴊ":"سۛح","ﵜ":"سحج","ﵨ":"سۛحم","ﵧ":"سۛحم","ﶪ":"سۛحى","ﲯ":"سخ","ﴶ":"سخ","ﰞ":"سخ","ﴯ":"سۛخ","ﴹ":"سۛخ","ﴧ":"سۛخ","ﴋ":"سۛخ","ﶨ":"سخى","ﷆ":"سخى","ﴪ":"سر","ﴎ":"سر","ﴩ":"سۛر","ﴍ":"سۛر","ﲰ":"سم","ﳧ":"سم","ﰟ":"سم","ﴰ":"سۛم","ﳩ":"سۛم","ﴨ":"سۛم","ﴌ":"سۛم","ﵡ":"سمج","ﵠ":"سمح","ﵟ":"سمح","ﵫ":"سۛمخ","ﵪ":"سۛمخ","ﵣ":"سمم","ﵢ":"سمم","ﵭ":"سۛمم","ﵬ":"سۛمم","ﴗ":"سى","ﳻ":"سى","ﴘ":"سى","ﳼ":"سى","ﴙ":"سۛى","ﳽ":"سۛى","ﴚ":"سۛى","ﳾ":"سۛى","𐋲":"ص","𞸑":"ص","𞸱":"ص","𞹑":"ص","𞹱":"ص","𞺑":"ص","𞺱":"ص","ﺻ":"ص","ﺼ":"ص","ﺺ":"ص","ﺹ":"ص","ڞ":"صۛ","ࢯ":"ص̤̣","ﲱ":"صح","ﰠ":"صح","ﵥ":"صحح","ﵤ":"صحح","ﶩ":"صحى","ﲲ":"صخ","ﴫ":"صر","ﴏ":"صر","ﷵ":"صلعم","ﷹ":"صلى","ﷰ":"صلى","ﷺ":"صلى lللo علىo وسلم","ﲳ":"صم","ﰡ":"صم","ﷅ":"صمم","ﵦ":"صمم","ﴡ":"صى","ﴅ":"صى","ﴢ":"صى","ﴆ":"صى","𞸙":"ض","𞸹":"ض","𞹙":"ض","𞹹":"ض","𞺙":"ض","𞺹":"ض","ﺿ":"ض","ﻀ":"ض","ﺾ":"ض","ﺽ":"ض","ﲴ":"ضج","ﰢ":"ضج","ﲵ":"ضح","ﰣ":"ضح","ﵮ":"ضحى","ﶫ":"ضحى","ﲶ":"ضخ","ﰤ":"ضخ","ﵰ":"ضخم","ﵯ":"ضخم","ﴬ":"ضر","ﴐ":"ضر","ﲷ":"ضم","ﰥ":"ضم","ﴣ":"ضى","ﴇ":"ضى","ﴤ":"ضى","ﴈ":"ضى","𐋨":"ط","𞸈":"ط","𞹨":"ط","𞺈":"ط","𞺨":"ط","ﻃ":"ط","ﻄ":"ط","ﻂ":"ط","ﻁ":"ط","ڟ":"طۛ","ﲸ":"طح","ﰦ":"طح","ﴳ":"طم","ﴺ":"طم","ﰧ":"طم","ﵲ":"طمح","ﵱ":"طمح","ﵳ":"طمم","ﵴ":"طمى","ﴑ":"طى","ﳵ":"طى","ﴒ":"طى","ﳶ":"طى","𞸚":"ظ","𞹺":"ظ","𞺚":"ظ","𞺺":"ظ","ﻇ":"ظ","ﻈ":"ظ","ﻆ":"ظ","ﻅ":"ظ","ﲹ":"ظم","ﴻ":"ظم","ﰨ":"ظم","؏":"ع","𞸏":"ع","𞸯":"ع","𞹏":"ع","𞹯":"ع","𞺏":"ع","𞺯":"ع","ﻋ":"ع","ﻌ":"ع","ﻊ":"ع","ﻉ":"ع","ﲺ":"عج","ﰩ":"عج","ﷄ":"عجم","ﵵ":"عجم","ﷷ":"علىo","ﲻ":"عم","ﰪ":"عم","ﵷ":"عمم","ﵶ":"عمم","ﵸ":"عمى","ﶶ":"عمى","ﴓ":"عى","ﳷ":"عى","ﴔ":"عى","ﳸ":"عى","𞸛":"غ","𞸻":"غ","𞹛":"غ","𞹻":"غ","𞺛":"غ","𞺻":"غ","ﻏ":"غ","ﻐ":"غ","ﻎ":"غ","ﻍ":"غ","ﲼ":"غج","ﰫ":"غج","ﲽ":"غم","ﰬ":"غم","ﵹ":"غمم","ﵻ":"غمى","ﵺ":"غمى","ﴕ":"غى","ﳹ":"غى","ﴖ":"غى","ﳺ":"غى","𞸐":"ف","𞸰":"ف","𞹰":"ف","𞺐":"ف","𞺰":"ف","ﻓ":"ف","ﻔ":"ف","ﻒ":"ف","ﻑ":"ف","ڧ":"ف","ﲾ":"فج","ﰭ":"فج","ﲿ":"فح","ﰮ":"فح","ﳀ":"فخ","ﰯ":"فخ","ﵽ":"فخم","ﵼ":"فخم","ﳁ":"فم","ﰰ":"فم","ﷁ":"فمى","ﱼ":"فى","ﰱ":"فى","ﱽ":"فى","ﰲ":"فى","𞸞":"ڡ","𞹾":"ڡ","ࢻ":"ڡ","ٯ":"ڡ","𞸟":"ڡ","𞹟":"ڡ","ࢼ":"ڡ","ڤ":"ڡۛ","ﭬ":"ڡۛ","ﭭ":"ڡۛ","ﭫ":"ڡۛ","ﭪ":"ڡۛ","ڨ":"ڡۛ","ࢤ":"ڢۛ","ﭰ":"ڦ","ﭱ":"ڦ","ﭯ":"ڦ","ﭮ":"ڦ","𞸒":"ق","𞸲":"ق","𞹒":"ق","𞹲":"ق","𞺒":"ق","𞺲":"ق","ﻗ":"ق","ﻘ":"ق","ﻖ":"ق","ﻕ":"ق","ﳂ":"قح","ﰳ":"قح","ﷱ":"قلى","ﳃ":"قم","ﰴ":"قم","ﶴ":"قمح","ﵾ":"قمح","ﵿ":"قمم","ﶲ":"قمى","ﱾ":"قى","ﰵ":"قى","ﱿ":"قى","ﰶ":"قى","𞸊":"ك","𞸪":"ك","𞹪":"ك","ﻛ":"ك","ﻜ":"ك","ﻚ":"ك","ﻙ":"ك","ک":"ك","ﮐ":"ك","ﮑ":"ك","ﮏ":"ك","ﮎ":"ك","ڪ":"ك","ڭ":"كۛ","ﯕ":"كۛ","ﯖ":"كۛ","ﯔ":"كۛ","ﯓ":"كۛ","ݣ":"كۛ","ﲀ":"كl","ﰷ":"كl","ﳄ":"كج","ﰸ":"كج","ﳅ":"كح","ﰹ":"كح","ﳆ":"كخ","ﰺ":"كخ","ﳇ":"كل","ﳫ":"كل","ﲁ":"كل","ﰻ":"كل","ﳈ":"كم","ﳬ":"كم","ﲂ":"كم","ﰼ":"كم","ﷃ":"كمم","ﶻ":"كمم","ﶷ":"كمى","ﲃ":"كى","ﰽ":"كى","ﲄ":"كى","ﰾ":"كى","ݢ":"ڬ","ﮔ":"گ","ﮕ":"گ","ﮓ":"گ","ﮒ":"گ","ࢰ":"گ","ڴ":"گۛ","ﮜ":"ڱ","ﮝ":"ڱ","ﮛ":"ڱ","ﮚ":"ڱ","ﮘ":"ڳ","ﮙ":"ڳ","ﮗ":"ڳ","ﮖ":"ڳ","𞸋":"ل","𞸫":"ل","𞹋":"ل","𞺋":"ل","𞺫":"ل","ﻟ":"ل","ﻠ":"ل","ﻞ":"ل","ﻝ":"ل","ڷ":"لۛ","ڵ":"ل̆","ﻼ":"لl","ﻻ":"لl","ﻺ":"لlٕ","ﻹ":"لlٕ","ﻸ":"لlٴ","ﻷ":"لlٴ","ﳍ":"لo","ﻶ":"لآ","ﻵ":"لآ","ﳉ":"لج","ﰿ":"لج","ﶃ":"لجج","ﶄ":"لجج","ﶺ":"لجم","ﶼ":"لجم","ﶬ":"لجى","ﳊ":"لح","ﱀ":"لح","ﶵ":"لحم","ﶀ":"لحم","ﶂ":"لحى","ﶁ":"لحى","ﳋ":"لخ","ﱁ":"لخ","ﶆ":"لخم","ﶅ":"لخم","ﳌ":"لم","ﳭ":"لم","ﲅ":"لم","ﱂ":"لم","ﶈ":"لمح","ﶇ":"لمح","ﶭ":"لمى","ﲆ":"لى","ﱃ":"لى","ﲇ":"لى","ﱄ":"لى","𞸌":"م","𞸬":"م","𞹬":"م","𞺌":"م","𞺬":"م","ﻣ":"م","ﻤ":"م","ﻢ":"م","ﻡ":"م","ࢧ":"مۛ","۾":"م͈","ﲈ":"مl","ﳎ":"مج","ﱅ":"مج","ﶌ":"مجح","ﶒ":"مجخ","ﶍ":"مجم","ﷀ":"مجى","ﳏ":"مح","ﱆ":"مح","ﶉ":"محج","ﶊ":"محم","ﷴ":"محمد","ﶋ":"محى","ﳐ":"مخ","ﱇ":"مخ","ﶎ":"مخج","ﶏ":"مخم","ﶹ":"مخى","ﳑ":"مم","ﲉ":"مم","ﱈ":"مم","ﶱ":"ممى","ﱉ":"مى","ﱊ":"مى","𞸍":"ن","𞸭":"ن","𞹍":"ن","𞹭":"ن","𞺍":"ن","𞺭":"ن","ﻧ":"ن","ﻨ":"ن","ﻦ":"ن","ﻥ":"ن","ݨ":"نؕ","ݩ":"ن̆","ﳖ":"نo","ﳯ":"نo","ﶸ":"نجح","ﶽ":"نجح","ﶘ":"نجم","ﶗ":"نجم","ﶙ":"نجى","ﷇ":"نجى","ﳓ":"نح","ﱌ":"نح","ﶕ":"نحم","ﶖ":"نحى","ﶳ":"نحى","ﳔ":"نخ","ﱍ":"نخ","ﲊ":"نر","ﲋ":"نز","ﳕ":"نم","ﳮ":"نم","ﲌ":"نم","ﱎ":"نم","ﶛ":"نمى","ﶚ":"نمى","ﲍ":"نن","ﲎ":"نى","ﱏ":"نى","ﲏ":"نى","ﱐ":"نى","ۂ":"ۀ","ﮥ":"ۀ","ﮤ":"ۀ","𐋤":"و","𞸅":"و","𞺅":"و","𞺥":"و","ﻮ":"و","ﻭ":"و","ࢱ":"و","ۋ":"وۛ","ﯟ":"وۛ","ﯞ":"وۛ","ۇ":"و̓","ﯘ":"و̓","ﯗ":"و̓","ۆ":"و̆","ﯚ":"و̆","ﯙ":"و̆","ۉ":"و̂","ﯣ":"و̂","ﯢ":"و̂","ۈ":"وٰ","ﯜ":"وٰ","ﯛ":"وٰ","ؤ":"وٴ","ﺆ":"وٴ","ﺅ":"وٴ","ٶ":"وٴ","ٷ":"و̓ٴ","ﯝ":"و̓ٴ","ﷸ":"وسلم","ﯡ":"ۅ","ﯠ":"ۅ","ٮ":"ى","𞸜":"ى","𞹼":"ى","ں":"ى","𞸝":"ى","𞹝":"ى","ﮟ":"ى","ﮞ":"ى","ࢽ":"ى","ﯨ":"ى","ﯩ":"ى","ﻰ":"ى","ﻯ":"ى","ي":"ى","𞸉":"ى","𞸩":"ى","𞹉":"ى","𞹩":"ى","𞺉":"ى","𞺩":"ى","ﻳ":"ى","ﻴ":"ى","ﻲ":"ى","ﻱ":"ى","ی":"ى","ﯾ":"ى","ﯿ":"ى","ﯽ":"ى","ﯼ":"ى","ے":"ى","ﮯ":"ى","ﮮ":"ى","ٹ":"ىؕ","ﭨ":"ىؕ","ﭩ":"ىؕ","ﭧ":"ىؕ","ﭦ":"ىؕ","ڻ":"ىؕ","ﮢ":"ىؕ","ﮣ":"ىؕ","ﮡ":"ىؕ","ﮠ":"ىؕ","پ":"ىۛ","ﭘ":"ىۛ","ﭙ":"ىۛ","ﭗ":"ىۛ","ﭖ":"ىۛ","ث":"ىۛ","𞸖":"ىۛ","𞸶":"ىۛ","𞹶":"ىۛ","𞺖":"ىۛ","𞺶":"ىۛ","ﺛ":"ىۛ","ﺜ":"ىۛ","ﺚ":"ىۛ","ﺙ":"ىۛ","ڽ":"ىۛ","ۑ":"ىۛ","ؿ":"ىۛ","ࢷ":"ىۛۢ","ݖ":"ى̆","ێ":"ى̆","ࢺ":"ى̆̇","ؽ":"ى̂","ࢨ":"ىٔ","ﲐ":"ىٰ","ﱝ":"ىٰ","ﳞ":"ىo","ﳱ":"ىo","ﳦ":"ىۛo","ئ":"ىٴ","ﺋ":"ىٴ","ﺌ":"ىٴ","ﺊ":"ىٴ","ﺉ":"ىٴ","ٸ":"ىٴ","ﯫ":"ىٴl","ﯪ":"ىٴl","ﲛ":"ىٴo","ﳠ":"ىٴo","ﯭ":"ىٴo","ﯬ":"ىٴo","ﯸ":"ىٴٻ","ﯷ":"ىٴٻ","ﯶ":"ىٴٻ","ﲗ":"ىٴج","ﰀ":"ىٴج","ﲘ":"ىٴح","ﰁ":"ىٴح","ﲙ":"ىٴخ","ﱤ":"ىٴر","ﱥ":"ىٴز","ﲚ":"ىٴم","ﳟ":"ىٴم","ﱦ":"ىٴم","ﰂ":"ىٴم","ﱧ":"ىٴن","ﯯ":"ىٴو","ﯮ":"ىٴو","ﯱ":"ىٴو̓","ﯰ":"ىٴو̓","ﯳ":"ىٴو̆","ﯲ":"ىٴو̆","ﯵ":"ىٴوٰ","ﯴ":"ىٴوٰ","ﯻ":"ىٴى","ﯺ":"ىٴى","ﱨ":"ىٴى","ﯹ":"ىٴى","ﰃ":"ىٴى","ﱩ":"ىٴى","ﰄ":"ىٴى","ﳚ":"ىج","ﱕ":"ىج","ﰑ":"ىۛج","ﶯ":"ىجى","ﳛ":"ىح","ﱖ":"ىح","ﶮ":"ىحى","ﳜ":"ىخ","ﱗ":"ىخ","ﲑ":"ىر","ﱶ":"ىۛر","ﲒ":"ىز","ﱷ":"ىۛز","ﳝ":"ىم","ﳰ":"ىم","ﲓ":"ىم","ﱘ":"ىم","ﲦ":"ىۛم","ﳥ":"ىۛم","ﱸ":"ىۛم","ﰒ":"ىۛم","ﶝ":"ىمم","ﶜ":"ىمم","ﶰ":"ىمى","ﲔ":"ىن","ﱹ":"ىۛن","ﲕ":"ىى","ﱙ":"ىى","ﲖ":"ىى","ﱚ":"ىى","ﱺ":"ىۛى","ﰓ":"ىۛى","ﱻ":"ىۛى","ﰔ":"ىۛى","ﮱ":"ۓ","ﮰ":"ۓ","𐊸":"ⵀ","⁞":"ⵂ","⸽":"ⵂ","⦙":"ⵂ","︙":"ⵗ","⁝":"ⵗ","⋮":"ⵗ","Մ":"ሆ","Ռ":"ቡ","Ի":"ኮ","Պ":"ጣ","आ":"अा","ऒ":"अाॆ","ओ":"अाे","औ":"अाै","ऄ":"अॆ","ऑ":"अॉ","ऍ":"एॅ","ऎ":"एॆ","ऐ":"एे","ई":"र्इ","ઽ":"ऽ","𑇜":"ꣻ","𑇋":"ऺ","ુ":"ु","ૂ":"ू","ੋ":"ॆ","੍":"्","્":"्","আ":"অা","ৠ":"ঋৃ","ৡ":"ঋৃ","𑒒":"ঘ","𑒔":"চ","𑒖":"জ","𑒘":"ঞ","𑒙":"ট","𑒛":"ড","𑒪":"ণ","𑒞":"ত","𑒟":"থ","𑒠":"দ","𑒡":"ধ","𑒢":"ন","𑒣":"প","𑒩":"ব","𑒧":"ম","𑒨":"য","𑒫":"র","𑒝":"ল","𑒭":"ষ","𑒮":"স","𑓄":"ঽ","𑒰":"া","𑒱":"ি","𑒹":"ে","𑒼":"ো","𑒾":"ৌ","𑓂":"্","𑒽":"ৗ","ਉ":"ੳੁ","ਊ":"ੳੂ","ਆ":"ਅਾ","ਐ":"ਅੈ","ਔ":"ਅੌ","ਇ":"ੲਿ","ਈ":"ੲੀ","ਏ":"ੲੇ","આ":"અા","ઑ":"અાૅ","ઓ":"અાે","ઔ":"અાૈ","ઍ":"અૅ","એ":"અે","ઐ":"અૈ","ଆ":"ଅା","௮":"அ","ர":"ஈ","ா":"ஈ","௫":"ஈு","௨":"உ","ഉ":"உ","ஊ":"உள","ഊ":"உൗ","௭":"எ","௷":"எவ","ஜ":"ஐ","ജ":"ஐ","௧":"க","௪":"ச","௬":"சு","௲":"சூ","ഺ":"டி","ണ":"ண","௺":"நீ","௴":"மீ","௰":"ய","ഴ":"ழ","ௗ":"ள","ை":"ன","ശ":"ஶ","௸":"ஷ","ി":"ி","ീ":"ி","ொ":"ெஈ","ௌ":"ெள","ோ":"ேஈ","ಅ":"అ","ಆ":"ఆ","ಇ":"ఇ","ౠ":"ఋా","ౡ":"ఌా","ಒ":"ఒ","ఔ":"ఒౌ","ಔ":"ఒౌ","ఓ":"ఒౕ","ಓ":"ఒౕ","ಜ":"జ","ಞ":"ఞ","ఢ":"డ̣","ಣ":"ణ","థ":"ధּ","భ":"బ̣","ಯ":"య","ఠ":"రּ","ಱ":"ఱ","ಲ":"ల","ష":"వ̣","హ":"వా","మ":"వు","ూ":"ుా","ౄ":"ృా","ೡ":"ಌಾ","ഈ":"ഇൗ","ഐ":"എെ","ഓ":"ഒാ","ഔ":"ഒൗ","ൡ":"ഞ","൫":"ദ്ര","൹":"നു","ഌ":"നു","ങ":"നു","൯":"ന്","ൻ":"ന്","൬":"ന്ന","൚":"ന്മ","റ":"ര","൪":"ര്","ർ":"ര്","൮":"വ്ര","൶":"ഹ്മ","ൂ":"ു","ൃ":"ു","ൈ":"െെ","෪":"ජ","෫":"ද","𑐓":"𑐴𑑂𑐒","𑐙":"𑐴𑑂𑐘","𑐤":"𑐴𑑂𑐣","𑐪":"𑐴𑑂𑐩","𑐭":"𑐴𑑂𑐬","𑐯":"𑐴𑑂𑐮","𑗘":"𑖂","𑗙":"𑖂","𑗚":"𑖃","𑗛":"𑖄","𑗜":"𑖲","𑗝":"𑖳","ฃ":"ข","ด":"ค","ต":"ค","ม":"ฆ","ຈ":"จ","ซ":"ช","ฏ":"ฎ","ท":"ฑ","ບ":"บ","ປ":"ป","ຝ":"ฝ","ພ":"พ","ຟ":"ฟ","ฦ":"ภ","ຍ":"ย","។":"ฯ","ๅ":"า","ำ":"̊า","ិ":"ิ","ី":"ี","ឹ":"ึ","ឺ":"ื","ຸ":"ุ","ູ":"ู","แ":"เเ","ໜ":"ຫນ","ໝ":"ຫມ","ຳ":"̊າ","༂":"འུྂཿ","༃":"འུྂ༔","ཪ":"ར","ༀ":"ཨོཾ","ཷ":"ྲཱྀ","ཹ":"ླཱྀ","𑲲":"𑲪","ႁ":"ဂှ","က":"ဂာ","ၰ":"ဃှ","ၦ":"ပှ","ဟ":"ပာ","ၯ":"ပာှ","ၾ":"ၽှ","ဩ":"သြ","ဪ":"သြော်","႞":"ႃ̊","ឣ":"អ","᧐":"ᦞ","᧑":"ᦱ","᪀":"ᩅ","᪐":"ᩅ","꩓":"ꨁ","꩖":"ꨣ","᭒":"ᬍ","᭓":"ᬑ","᭘":"ᬨ","ꦣ":"ꦝ","ᢖ":"ᡜ","ᡕ":"ᠵ","ῶ":"Ꮿ","ᐍ":"ᐁ·","ᐫ":"ᐁᐠ","ᐑ":"ᐄ·","ᐓ":"ᐅ·","ᐭ":"ᐅᐠ","ᐕ":"ᐆ·","ᐘ":"ᐊ·","ᐮ":"ᐊᐠ","ᐚ":"ᐋ·","ᣝ":"ᐞᣟ","ᓑ":"ᐡ","ᕀ":"ᐩ","ᐿ":"ᐲ·","ᑃ":"ᐴ·","⍩":"ᐵ","ᑇ":"ᐹ·","ᑜ":"ᑏ·","⸧":"ᑐ","⊃":"ᑐ","ᑞ":"ᑐ·","ᑩ":"ᑐ\'","⟉":"ᑐ/","⫗":"ᑐᑕ","ᑠ":"ᑑ·","⸦":"ᑕ","⊂":"ᑕ","ᑢ":"ᑕ·","ᑪ":"ᑕ\'","ᑤ":"ᑖ·","ᑵ":"ᑫ·","ᒅ":"ᑫ\'","ᑹ":"ᑮ·","ᑽ":"ᑰ·","ᘃ":"ᒉ","ᒓ":"ᒉ·","ᒕ":"ᒋ·","ᒗ":"ᒌ·","ᒛ":"ᒎ·","ᘂ":"ᒐ","ᒝ":"ᒐ·","ᒟ":"ᒑ·","ᒭ":"ᒣ·","ᒱ":"ᒦ·","ᒳ":"ᒧ·","ᒵ":"ᒨ·","ᒹ":"ᒫ·","ᓊ":"ᓀ·","ᣇ":"ᓂ·","ᣉ":"ᓃ·","ᣋ":"ᓄ·","ᣍ":"ᓅ·","ᓌ":"ᓇ·","ᓎ":"ᓈ·","ᘄ":"ᓓ","ᓝ":"ᓓ·","ᓟ":"ᓕ·","ᓡ":"ᓖ·","ᓣ":"ᓗ·","ᓥ":"ᓘ·","ᘇ":"ᓚ","ᓧ":"ᓚ·","ᓩ":"ᓛ·","ᓷ":"ᓭ·","ᓹ":"ᓯ·","ᓻ":"ᓰ·","ᓽ":"ᓱ·","ᓿ":"ᓲ·","ᔁ":"ᓴ·","ᔃ":"ᓵ·","ᔌ":"ᔋ<","ᔎ":"ᔋb","ᔍ":"ᔋᑕ","ᔏ":"ᔋᒐ","ᔘ":"ᔐ·","ᔚ":"ᔑ·","ᔜ":"ᔒ·","ᔞ":"ᔓ·","ᔠ":"ᔔ·","ᔢ":"ᔕ·","ᔤ":"ᔖ·","ᔲ":"ᔨ·","ᔴ":"ᔩ·","ᔶ":"ᔪ·","ᔸ":"ᔫ·","ᔺ":"ᔭ·","ᔼ":"ᔮ·","ᘢ":"ᕃ","ᣠ":"ᕃ·","ᘣ":"ᕆ","ᘤ":"ᕊ","ᕏ":"ᕌ·","ᖃ":"ᕐb","ᖄ":"ᕐḃ","ᖁ":"ᕐd","ᕿ":"ᕐP","ᙯ":"ᕐᑫ","ᕾ":"ᕐᑬ","ᖀ":"ᕐᑮ","ᖂ":"ᕐᑰ","ᖅ":"ᕐᒃ","ᕜ":"ᕚ·","ᣣ":"ᕞ·","ᣤ":"ᕦ·","ᕩ":"ᕧ·","ᣥ":"ᕫ·","ᣨ":"ᖆ·","ᖑ":"ᖕJ","ᙰ":"ᖕᒉ","ᖎ":"ᖕᒊ","ᖏ":"ᖕᒋ","ᖐ":"ᖕᒌ","ᖒ":"ᖕᒎ","ᖓ":"ᖕᒐ","ᖔ":"ᖕᒑ","ᙳ":"ᖖJ","ᙱ":"ᖖᒋ","ᙲ":"ᖖᒌ","ᙴ":"ᖖᒎ","ᙵ":"ᖖᒐ","ᙶ":"ᖖᒑ","ᣪ":"ᖗ·","ᙷ":"ᖧ·","ᙸ":"ᖨ·","ᙹ":"ᖩ·","ᙺ":"ᖪ·","ᙻ":"ᖫ·","ᙼ":"ᖬ·","ᙽ":"ᖭ·","⪫":"ᗒ","⪪":"ᗕ","ꓷ":"ᗡ","ᣰ":"ᗴ·","ᣲ":"ᘛ·","ᶻ":"ᙆ","ꓭ":"ᙠ","ᶺ":"ᣔ","ᴾ":"ᣖ","ᣜ":"ᣟᐞ","ˡ":"ᣳ","ʳ":"ᣴ","ˢ":"ᣵ","ᣛ":"ᣵ","ꚰ":"ᚹ","ᛡ":"ᚼ","⍿":"ᚽ","ᛂ":"ᚽ","𝈿":"ᛋ","↑":"ᛏ","↿":"ᛐ","⥮":"ᛐ⇂","⥣":"ᛐᛚ","ⵣ":"ᛯ","↾":"ᛚ","⨡":"ᛚ","⋄":"ᛜ","◇":"ᛜ","◊":"ᛜ","♢":"ᛜ","🝔":"ᛜ","𑢷":"ᛜ","𐊔":"ᛜ","⍚":"ᛜ̲","⋈":"ᛞ","⨝":"ᛞ","𐓐":"ᛦ","↕":"ᛨ","𐳼":"𐲂","𐳺":"𐲥","ㄱ":"ᄀ","ᆨ":"ᄀ","ᄁ":"ᄀᄀ","ㄲ":"ᄀᄀ","ᆩ":"ᄀᄀ","ᇺ":"ᄀᄂ","ᅚ":"ᄀᄃ","ᇃ":"ᄀᄅ","ᇻ":"ᄀᄇ","ᆪ":"ᄀᄉ","ㄳ":"ᄀᄉ","ᇄ":"ᄀᄉᄀ","ᇼ":"ᄀᄎ","ᇽ":"ᄀᄏ","ᇾ":"ᄀᄒ","ㄴ":"ᄂ","ᆫ":"ᄂ","ᄓ":"ᄂᄀ","ᇅ":"ᄂᄀ","ᄔ":"ᄂᄂ","ㅥ":"ᄂᄂ","ᇿ":"ᄂᄂ","ᄕ":"ᄂᄃ","ㅦ":"ᄂᄃ","ᇆ":"ᄂᄃ","ퟋ":"ᄂᄅ","ᄖ":"ᄂᄇ","ᅛ":"ᄂᄉ","ᇇ":"ᄂᄉ","ㅧ":"ᄂᄉ","ᅜ":"ᄂᄌ","ᆬ":"ᄂᄌ","ㄵ":"ᄂᄌ","ퟌ":"ᄂᄎ","ᇉ":"ᄂᄐ","ᅝ":"ᄂᄒ","ᆭ":"ᄂᄒ","ㄶ":"ᄂᄒ","ᇈ":"ᄂᅀ","ㅨ":"ᄂᅀ","ㄷ":"ᄃ","ᆮ":"ᄃ","ᄗ":"ᄃᄀ","ᇊ":"ᄃᄀ","ᄄ":"ᄃᄃ","ㄸ":"ᄃᄃ","ퟍ":"ᄃᄃ","ퟎ":"ᄃᄃᄇ","ᅞ":"ᄃᄅ","ᇋ":"ᄃᄅ","ꥠ":"ᄃᄆ","ꥡ":"ᄃᄇ","ퟏ":"ᄃᄇ","ꥢ":"ᄃᄉ","ퟐ":"ᄃᄉ","ퟑ":"ᄃᄉᄀ","ꥣ":"ᄃᄌ","ퟒ":"ᄃᄌ","ퟓ":"ᄃᄎ","ퟔ":"ᄃᄐ","ㄹ":"ᄅ","ᆯ":"ᄅ","ꥤ":"ᄅᄀ","ᆰ":"ᄅᄀ","ㄺ":"ᄅᄀ","ꥥ":"ᄅᄀᄀ","ퟕ":"ᄅᄀᄀ","ᇌ":"ᄅᄀᄉ","ㅩ":"ᄅᄀᄉ","ퟖ":"ᄅᄀᄒ","ᄘ":"ᄅᄂ","ᇍ":"ᄅᄂ","ꥦ":"ᄅᄃ","ᇎ":"ᄅᄃ","ㅪ":"ᄅᄃ","ꥧ":"ᄅᄃᄃ","ᇏ":"ᄅᄃᄒ","ᄙ":"ᄅᄅ","ᇐ":"ᄅᄅ","ퟗ":"ᄅᄅᄏ","ꥨ":"ᄅᄆ","ᆱ":"ᄅᄆ","ㄻ":"ᄅᄆ","ᇑ":"ᄅᄆᄀ","ᇒ":"ᄅᄆᄉ","ퟘ":"ᄅᄆᄒ","ꥩ":"ᄅᄇ","ᆲ":"ᄅᄇ","ㄼ":"ᄅᄇ","ퟙ":"ᄅᄇᄃ","ꥪ":"ᄅᄇᄇ","ᇓ":"ᄅᄇᄉ","ㅫ":"ᄅᄇᄉ","ꥫ":"ᄅᄇᄋ","ᇕ":"ᄅᄇᄋ","ퟚ":"ᄅᄇᄑ","ᇔ":"ᄅᄇᄒ","ꥬ":"ᄅᄉ","ᆳ":"ᄅᄉ","ㄽ":"ᄅᄉ","ᇖ":"ᄅᄉᄉ","ᄛ":"ᄅᄋ","ퟝ":"ᄅᄋ","ꥭ":"ᄅᄌ","ꥮ":"ᄅᄏ","ᇘ":"ᄅᄏ","ᆴ":"ᄅᄐ","ㄾ":"ᄅᄐ","ᆵ":"ᄅᄑ","ㄿ":"ᄅᄑ","ᄚ":"ᄅᄒ","ㅀ":"ᄅᄒ","ᄻ":"ᄅᄒ","ᆶ":"ᄅᄒ","ퟲ":"ᄅᄒ","ᇗ":"ᄅᅀ","ㅬ":"ᄅᅀ","ퟛ":"ᄅᅌ","ᇙ":"ᄅᅙ","ㅭ":"ᄅᅙ","ퟜ":"ᄅᅙᄒ","ㅁ":"ᄆ","ᆷ":"ᄆ","ꥯ":"ᄆᄀ","ᇚ":"ᄆᄀ","ퟞ":"ᄆᄂ","ퟟ":"ᄆᄂᄂ","ꥰ":"ᄆᄃ","ᇛ":"ᄆᄅ","ퟠ":"ᄆᄆ","ᄜ":"ᄆᄇ","ㅮ":"ᄆᄇ","ᇜ":"ᄆᄇ","ퟡ":"ᄆᄇᄉ","ꥱ":"ᄆᄉ","ᇝ":"ᄆᄉ","ㅯ":"ᄆᄉ","ᇞ":"ᄆᄉᄉ","ᄝ":"ᄆᄋ","ㅱ":"ᄆᄋ","ᇢ":"ᄆᄋ","ퟢ":"ᄆᄌ","ᇠ":"ᄆᄎ","ᇡ":"ᄆᄒ","ᇟ":"ᄆᅀ","ㅰ":"ᄆᅀ","ㅂ":"ᄇ","ᆸ":"ᄇ","ᄞ":"ᄇᄀ","ㅲ":"ᄇᄀ","ᄟ":"ᄇᄂ","ᄠ":"ᄇᄃ","ㅳ":"ᄇᄃ","ퟣ":"ᄇᄃ","ᇣ":"ᄇᄅ","ퟤ":"ᄇᄅᄑ","ퟥ":"ᄇᄆ","ᄈ":"ᄇᄇ","ㅃ":"ᄇᄇ","ퟦ":"ᄇᄇ","ᄬ":"ᄇᄇᄋ","ㅹ":"ᄇᄇᄋ","ᄡ":"ᄇᄉ","ㅄ":"ᄇᄉ","ᆹ":"ᄇᄉ","ᄢ":"ᄇᄉᄀ","ㅴ":"ᄇᄉᄀ","ᄣ":"ᄇᄉᄃ","ㅵ":"ᄇᄉᄃ","ퟧ":"ᄇᄉᄃ","ᄤ":"ᄇᄉᄇ","ᄥ":"ᄇᄉᄉ","ᄦ":"ᄇᄉᄌ","ꥲ":"ᄇᄉᄐ","ᄫ":"ᄇᄋ","ㅸ":"ᄇᄋ","ᇦ":"ᄇᄋ","ᄧ":"ᄇᄌ","ㅶ":"ᄇᄌ","ퟨ":"ᄇᄌ","ᄨ":"ᄇᄎ","ퟩ":"ᄇᄎ","ꥳ":"ᄇᄏ","ᄩ":"ᄇᄐ","ㅷ":"ᄇᄐ","ᄪ":"ᄇᄑ","ᇤ":"ᄇᄑ","ꥴ":"ᄇᄒ","ᇥ":"ᄇᄒ","ㅅ":"ᄉ","ᆺ":"ᄉ","ᄭ":"ᄉᄀ","ㅺ":"ᄉᄀ","ᇧ":"ᄉᄀ","ᄮ":"ᄉᄂ","ㅻ":"ᄉᄂ","ᄯ":"ᄉᄃ","ㅼ":"ᄉᄃ","ᇨ":"ᄉᄃ","ᄰ":"ᄉᄅ","ᇩ":"ᄉᄅ","ᄱ":"ᄉᄆ","ퟪ":"ᄉᄆ","ᄲ":"ᄉᄇ","ㅽ":"ᄉᄇ","ᇪ":"ᄉᄇ","ᄳ":"ᄉᄇᄀ","ퟫ":"ᄉᄇᄋ","ᄊ":"ᄉᄉ","ㅆ":"ᄉᄉ","ᆻ":"ᄉᄉ","ퟬ":"ᄉᄉᄀ","ퟭ":"ᄉᄉᄃ","ꥵ":"ᄉᄉᄇ","ᄴ":"ᄉᄉᄉ","ᄵ":"ᄉᄋ","ᄶ":"ᄉᄌ","ㅾ":"ᄉᄌ","ퟯ":"ᄉᄌ","ᄷ":"ᄉᄎ","ퟰ":"ᄉᄎ","ᄸ":"ᄉᄏ","ᄹ":"ᄉᄐ","ퟱ":"ᄉᄐ","ᄺ":"ᄉᄑ","ퟮ":"ᄉᅀ","ㅇ":"ᄋ","ᆼ":"ᄋ","ᅁ":"ᄋᄀ","ᇬ":"ᄋᄀ","ᇭ":"ᄋᄀᄀ","ᅂ":"ᄋᄃ","ꥶ":"ᄋᄅ","ᅃ":"ᄋᄆ","ᅄ":"ᄋᄇ","ᅅ":"ᄋᄉ","ᇱ":"ᄋᄉ","ㆂ":"ᄋᄉ","ᅇ":"ᄋᄋ","ㆀ":"ᄋᄋ","ᇮ":"ᄋᄋ","ᅈ":"ᄋᄌ","ᅉ":"ᄋᄎ","ᇯ":"ᄋᄏ","ᅊ":"ᄋᄐ","ᅋ":"ᄋᄑ","ꥷ":"ᄋᄒ","ᅆ":"ᄋᅀ","ᇲ":"ᄋᅀ","ㆃ":"ᄋᅀ","ㅈ":"ᄌ","ᆽ":"ᄌ","ퟷ":"ᄌᄇ","ퟸ":"ᄌᄇᄇ","ᅍ":"ᄌᄋ","ᄍ":"ᄌᄌ","ㅉ":"ᄌᄌ","ퟹ":"ᄌᄌ","ꥸ":"ᄌᄌᄒ","ㅊ":"ᄎ","ᆾ":"ᄎ","ᅒ":"ᄎᄏ","ᅓ":"ᄎᄒ","ㅋ":"ᄏ","ᆿ":"ᄏ","ㅌ":"ᄐ","ᇀ":"ᄐ","ꥹ":"ᄐᄐ","ㅍ":"ᄑ","ᇁ":"ᄑ","ᅖ":"ᄑᄇ","ᇳ":"ᄑᄇ","ퟺ":"ᄑᄉ","ᅗ":"ᄑᄋ","ㆄ":"ᄑᄋ","ᇴ":"ᄑᄋ","ퟻ":"ᄑᄐ","ꥺ":"ᄑᄒ","ㅎ":"ᄒ","ᇂ":"ᄒ","ᇵ":"ᄒᄂ","ᇶ":"ᄒᄅ","ᇷ":"ᄒᄆ","ᇸ":"ᄒᄇ","ꥻ":"ᄒᄉ","ᅘ":"ᄒᄒ","ㆅ":"ᄒᄒ","ᄽ":"ᄼᄼ","ᄿ":"ᄾᄾ","ㅿ":"ᅀ","ᇫ":"ᅀ","ퟳ":"ᅀᄇ","ퟴ":"ᅀᄇᄋ","ㆁ":"ᅌ","ᇰ":"ᅌ","ퟵ":"ᅌᄆ","ퟶ":"ᅌᄒ","ᅏ":"ᅎᅎ","ᅑ":"ᅐᅐ","ㆆ":"ᅙ","ᇹ":"ᅙ","ꥼ":"ᅙᅙ","ㅤ":"ᅠ","ㅏ":"ᅡ","ᆣ":"ᅡー","ᅶ":"ᅡᅩ","ᅷ":"ᅡᅮ","ᅢ":"ᅡ丨","ㅐ":"ᅡ丨","ㅑ":"ᅣ","ᅸ":"ᅣᅩ","ᅹ":"ᅣᅭ","ᆤ":"ᅣᅮ","ᅤ":"ᅣ丨","ㅒ":"ᅣ丨","ㅓ":"ᅥ","ᅼ":"ᅥー","ᅺ":"ᅥᅩ","ᅻ":"ᅥᅮ","ᅦ":"ᅥ丨","ㅔ":"ᅥ丨","ㅕ":"ᅧ","ᆥ":"ᅧᅣ","ᅽ":"ᅧᅩ","ᅾ":"ᅧᅮ","ᅨ":"ᅧ丨","ㅖ":"ᅧ丨","ㅗ":"ᅩ","ᅪ":"ᅩᅡ","ㅘ":"ᅩᅡ","ᅫ":"ᅩᅡ丨","ㅙ":"ᅩᅡ丨","ᆦ":"ᅩᅣ","ᆧ":"ᅩᅣ丨","ᅿ":"ᅩᅥ","ᆀ":"ᅩᅥ丨","ힰ":"ᅩᅧ","ᆁ":"ᅩᅧ丨","ᆂ":"ᅩᅩ","ힱ":"ᅩᅩ丨","ᆃ":"ᅩᅮ","ᅬ":"ᅩ丨","ㅚ":"ᅩ丨","ㅛ":"ᅭ","ힲ":"ᅭᅡ","ힳ":"ᅭᅡ丨","ᆄ":"ᅭᅣ","ㆇ":"ᅭᅣ","ᆆ":"ᅭᅣ","ᆅ":"ᅭᅣ丨","ㆈ":"ᅭᅣ丨","ힴ":"ᅭᅥ","ᆇ":"ᅭᅩ","ᆈ":"ᅭ丨","ㆉ":"ᅭ丨","ㅜ":"ᅮ","ᆉ":"ᅮᅡ","ᆊ":"ᅮᅡ丨","ᅯ":"ᅮᅥ","ㅝ":"ᅮᅥ","ᆋ":"ᅮᅥー","ᅰ":"ᅮᅥ丨","ㅞ":"ᅮᅥ丨","ힵ":"ᅮᅧ","ᆌ":"ᅮᅧ丨","ᆍ":"ᅮᅮ","ᅱ":"ᅮ丨","ㅟ":"ᅮ丨","ힶ":"ᅮ丨丨","ㅠ":"ᅲ","ᆎ":"ᅲᅡ","ힷ":"ᅲᅡ丨","ᆏ":"ᅲᅥ","ᆐ":"ᅲᅥ丨","ᆑ":"ᅲᅧ","ㆊ":"ᅲᅧ","ᆒ":"ᅲᅧ丨","ㆋ":"ᅲᅧ丨","ힸ":"ᅲᅩ","ᆓ":"ᅲᅮ","ᆔ":"ᅲ丨","ㆌ":"ᅲ丨","ㆍ":"ᆞ","ퟅ":"ᆞᅡ","ᆟ":"ᆞᅥ","ퟆ":"ᆞᅥ丨","ᆠ":"ᆞᅮ","ᆢ":"ᆞᆞ","ᆡ":"ᆞ丨","ㆎ":"ᆞ丨","ヘ":"へ","⍁":"〼","⧄":"〼","꒞":"ꁊ","꒬":"ꁐ","꒜":"ꃀ","꒨":"ꄲ","꒿":"ꉙ","꒾":"ꊱ","꒔":"ꋍ","꓀":"ꎫ","꓂":"ꎵ","꒺":"ꎿ","꒰":"ꏂ","꒧":"ꑘ","⊥":"ꓕ","⟂":"ꓕ","𝈜":"ꓕ","Ʇ":"ꓕ","Ꞟ":"ꓤ","⅁":"ꓨ","⅂":"ꓶ","𝈕":"ꓶ","𝈫":"ꓶ","𖼦":"ꓶ","𐐑":"ꓶ","⅃":"𖼀","𑫦":"𑫥𑫯","𑫨":"𑫥𑫥","𑫩":"𑫥𑫥𑫯","𑫪":"𑫥𑫥𑫰","𑫧":"𑫥𑫰","𑫴":"𑫳𑫯","𑫶":"𑫳𑫳","𑫷":"𑫳𑫳𑫯","𑫸":"𑫳𑫳𑫰","𑫵":"𑫳𑫰","𑫬":"𑫫𑫯","𑫭":"𑫫𑫫","𑫮":"𑫫𑫫𑫯","⊕":"𐊨","⨁":"𐊨","🜨":"𐊨","Ꚛ":"𐊨","▽":"𐊼","𝈔":"𐊼","🜄":"𐊼","⧖":"𐋀","ꞛ":"𐐺","Ꞛ":"𐐒","𐒠":"𐒆","𐏑":"𐎂","𐏓":"𐎓","𒀸":"𐎚","☥":"𐦞","𓋹":"𐦞","〹":"卄","不":"不","丽":"丽","並":"並","⎜":"丨","⎟":"丨","⎢":"丨","⎥":"丨","⎪":"丨","⎮":"丨","㇑":"丨","ᅵ":"丨","ㅣ":"丨","⼁":"丨","ᆜ":"丨ー","ᆘ":"丨ᅡ","ᆙ":"丨ᅣ","ힽ":"丨ᅣᅩ","ힾ":"丨ᅣ丨","ힿ":"丨ᅧ","ퟀ":"丨ᅧ丨","ᆚ":"丨ᅩ","ퟁ":"丨ᅩ丨","ퟂ":"丨ᅭ","ᆛ":"丨ᅮ","ퟃ":"丨ᅲ","ᆝ":"丨ᆞ","ퟄ":"丨丨","串":"串","丸":"丸","丹":"丹","乁":"乁","㇠":"乙","⼄":"乙","㇟":"乚","⺃":"乚","㇖":"乛","⺂":"乛","⻲":"亀","亂":"亂","㇚":"亅","⼅":"亅","了":"了","ニ":"二","⼆":"二","𠄢":"𠄢","⼇":"亠","亮":"亮","⼈":"人","イ":"亻","⺅":"亻","什":"什","仌":"仌","令":"令","你":"你","倂":"併","倂":"併","侀":"侀","來":"來","例":"例","侮":"侮","侮":"侮","侻":"侻","便":"便","值":"値","倫":"倫","偺":"偺","備":"備","像":"像","僚":"僚","僧":"僧","僧":"僧","㒞":"㒞","⼉":"儿","兀":"兀","⺎":"兀","充":"充","免":"免","免":"免","兔":"兔","兤":"兤","⼊":"入","內":"內","全":"全","兩":"兩","ハ":"八","⼋":"八","六":"六","具":"具","𠔜":"𠔜","𠔥":"𠔥","冀":"冀","㒹":"㒹","⼌":"冂","再":"再","𠕋":"𠕋","冒":"冒","冕":"冕","㒻":"㒻","最":"最","⼍":"冖","冗":"冗","冤":"冤","⼎":"冫","冬":"冬","况":"况","况":"况","冷":"冷","凉":"凉","凌":"凌","凜":"凜","凞":"凞","⼏":"几","𠘺":"𠘺","凵":"凵","⼐":"凵","⼑":"刀","⺉":"刂","刃":"刃","切":"切","切":"切","列":"列","利":"利","㓟":"㓟","刺":"刺","刻":"刻","剆":"剆","割":"割","剷":"剷","劉":"劉","𠠄":"𠠄","カ":"力","力":"力","⼒":"力","劣":"劣","㔕":"㔕","劳":"劳","勇":"勇","勇":"勇","勉":"勉","勉":"勉","勒":"勒","勞":"勞","勤":"勤","勤":"勤","勵":"勵","⼓":"勹","勺":"勺","勺":"勺","包":"包","匆":"匆","𠣞":"𠣞","⼔":"匕","北":"北","北":"北","⼕":"匚","⼖":"匸","匿":"匿","⼗":"十","〸":"十","〺":"卅","卉":"卉","࿖":"卍","࿕":"卐","卑":"卑","卑":"卑","博":"博","ト":"卜","⼘":"卜","⼙":"卩","⺋":"㔾","即":"即","卵":"卵","卽":"卽","卿":"卿","卿":"卿","卿":"卿","⼚":"厂","𠨬":"𠨬","⼛":"厶","參":"參","⼜":"又","及":"及","叟":"叟","𠭣":"𠭣","ロ":"口","⼝":"口","囗":"口","⼞":"口","句":"句","叫":"叫","叱":"叱","吆":"吆","吏":"吏","吝":"吝","吸":"吸","呂":"呂","呈":"呈","周":"周","咞":"咞","咢":"咢","咽":"咽","䎛":"㖈","哶":"哶","唐":"唐","啓":"啓","啟":"啓","啕":"啕","啣":"啣","善":"善","善":"善","喇":"喇","喙":"喙","喙":"喙","喝":"喝","喝":"喝","喫":"喫","喳":"喳","嗀":"嗀","嗂":"嗂","嗢":"嗢","嘆":"嘆","嘆":"嘆","噑":"噑","噴":"噴","器":"器","囹":"囹","圖":"圖","圗":"圗","⼟":"土","士":"土","⼠":"土","型":"型","城":"城","㦳":"㘽","埴":"埴","堍":"堍","報":"報","堲":"堲","塀":"塀","塚":"塚","塚":"塚","塞":"塞","填":"塡","壿":"墫","墬":"墬","墳":"墳","壘":"壘","壟":"壟","𡓤":"𡓤","壮":"壮","売":"売","壷":"壷","⼡":"夂","夆":"夆","⼢":"夊","タ":"夕","⼣":"夕","多":"多","夢":"夢","⼤":"大","奄":"奄","奈":"奈","契":"契","奔":"奔","奢":"奢","女":"女","⼥":"女","𡚨":"𡚨","𡛪":"𡛪","姘":"姘","姬":"姬","娛":"娛","娧":"娧","婢":"婢","婦":"婦","嬀":"媯","㛮":"㛮","㛼":"㛼","媵":"媵","嬈":"嬈","嬨":"嬨","嬾":"嬾","嬾":"嬾","⼦":"子","⼧":"宀","宅":"宅","𡧈":"𡧈","寃":"寃","寘":"寘","寧":"寧","寧":"寧","寧":"寧","寮":"寮","寳":"寳","𡬘":"𡬘","⼨":"寸","寿":"寿","将":"将","⼩":"小","尢":"尢","⺐":"尢","⼪":"尢","⺏":"尣","㞁":"㞁","⼫":"尸","尿":"尿","屠":"屠","屢":"屢","層":"層","履":"履","屮":"屮","屮":"屮","⼬":"屮","𡴋":"𡴋","⼭":"山","峀":"峀","岍":"岍","𡷤":"𡷤","𡷦":"𡷦","崙":"崙","嵃":"嵃","嵐":"嵐","嵫":"嵫","嵮":"嵮","嵼":"嵼","嶲":"嶲","嶺":"嶺","⼮":"巛","巢":"巢","エ":"工","⼯":"工","⼰":"己","⺒":"巳","㠯":"㠯","巽":"巽","⼱":"巾","帲":"帡","帨":"帨","帽":"帽","幩":"幩","㡢":"㡢","𢆃":"𢆃","⼲":"干","年":"年","𢆟":"𢆟","⺓":"幺","⼳":"幺","⼴":"广","度":"度","㡼":"㡼","庰":"庰","庳":"庳","庶":"庶","廊":"廊","廊":"廊","廉":"廉","廒":"廒","廓":"廓","廙":"廙","廬":"廬","⼵":"廴","廾":"廾","⼶":"廾","𢌱":"𢌱","𢌱":"𢌱","弄":"弄","⼷":"弋","⼸":"弓","弢":"弢","弢":"弢","⼹":"彐","⺔":"彑","当":"当","㣇":"㣇","⼺":"彡","形":"形","彩":"彩","彫":"彫","⼻":"彳","律":"律","㣣":"㣣","徚":"徚","復":"復","徭":"徭","⼼":"心","⺖":"忄","⺗":"㣺","忍":"忍","志":"志","念":"念","忹":"忹","怒":"怒","怜":"怜","恵":"恵","㤜":"㤜","㤺":"㤺","悁":"悁","悔":"悔","悔":"悔","惇":"惇","惘":"惘","惡":"惡","𢛔":"𢛔","愈":"愈","慨":"慨","慄":"慄","慈":"慈","慌":"慌","慌":"慌","慎":"慎","慎":"慎","慠":"慠","慺":"慺","憎":"憎","憎":"憎","憎":"憎","憐":"憐","憤":"憤","憯":"憯","憲":"憲","𢡄":"𢡄","𢡊":"𢡊","懞":"懞","懲":"懲","懲":"懲","懲":"懲","懶":"懶","懶":"懶","戀":"戀","⼽":"戈","成":"成","戛":"戛","戮":"戮","戴":"戴","⼾":"戶","戸":"戶","⼿":"手","⺘":"扌","扝":"扝","抱":"抱","拉":"拉","拏":"拏","拓":"拓","拔":"拔","拼":"拼","拾":"拾","𢬌":"𢬌","挽":"挽","捐":"捐","捨":"捨","捻":"捻","掃":"掃","掠":"掠","掩":"掩","揄":"揄","揤":"揤","摒":"摒","𢯱":"𢯱","搜":"搜","搢":"搢","揅":"揅","摩":"摩","摷":"摷","摾":"摾","㨮":"㨮","搉":"㩁","撚":"撚","撝":"撝","擄":"擄","㩬":"㩬","⽀":"支","⽁":"攴","⺙":"攵","敏":"敏","敏":"敏","敖":"敖","敬":"敬","數":"數","𣀊":"𣀊","⽂":"文","⻫":"斉","⽃":"斗","料":"料","⽄":"斤","⽅":"方","旅":"旅","⽆":"无","⺛":"旡","既":"既","旣":"旣","⽇":"日","易":"易","曶":"㫚","㫤":"㫤","晉":"晉","晩":"晚","晴":"晴","晴":"晴","暑":"暑","暑":"暑","暈":"暈","㬈":"㬈","暜":"暜","暴":"暴","曆":"曆","㬙":"㬙","𣊸":"𣊸","⽈":"曰","更":"更","書":"書","⽉":"月","𣍟":"𣍟","肦":"朌","胐":"朏","胊":"朐","脁":"朓","胶":"㬵","朗":"朗","朗":"朗","朗":"朗","脧":"朘","望":"望","望":"望","幐":"㬺","䐠":"㬻","𣎓":"𣎓","膧":"朣","𣎜":"𣎜","⽊":"木","李":"李","杓":"杓","杖":"杖","杞":"杞","𣏃":"𣏃","柿":"杮","杻":"杻","枅":"枅","林":"林","㭉":"㭉","𣏕":"𣏕","柳":"柳","柺":"柺","栗":"栗","栟":"栟","桒":"桒","𣑭":"𣑭","梁":"梁","梅":"梅","梅":"梅","梎":"梎","梨":"梨","椔":"椔","楂":"楂","㮝":"㮝","㮝":"㮝","槩":"㮣","樧":"榝","榣":"榣","槪":"槪","樂":"樂","樂":"樂","樂":"樂","樓":"樓","𣚣":"𣚣","檨":"檨","櫓":"櫓","櫛":"櫛","欄":"欄","㰘":"㰘","⽋":"欠","次":"次","𣢧":"𣢧","歔":"歔","㱎":"㱎","⽌":"止","⻭":"歯","歲":"歲","歷":"歷","歹":"歹","⽍":"歹","⺞":"歺","殟":"殟","殮":"殮","⽎":"殳","殺":"殺","殺":"殺","殺":"殺","殻":"殻","𣪍":"𣪍","⽏":"毋","⺟":"母","𣫺":"𣫺","⽐":"比","⽑":"毛","⽒":"氏","⺠":"民","⽓":"气","⽔":"水","⺡":"氵","⺢":"氺","汎":"汎","汧":"汧","沈":"沈","沿":"沿","泌":"泌","泍":"泍","泥":"泥","𣲼":"𣲼","洛":"洛","洞":"洞","洴":"洴","派":"派","流":"流","流":"流","流":"流","洖":"洖","浩":"浩","浪":"浪","海":"海","海":"海","浸":"浸","涅":"涅","𣴞":"𣴞","淋":"淋","淚":"淚","淪":"淪","淹":"淹","渚":"渚","港":"港","湮":"湮","潙":"溈","滋":"滋","滋":"滋","溜":"溜","溺":"溺","滇":"滇","滑":"滑","滛":"滛","㴳":"㴳","漏":"漏","漢":"漢","漢":"漢","漣":"漣","𣻑":"𣻑","潮":"潮","𣽞":"𣽞","𣾎":"𣾎","濆":"濆","濫":"濫","濾":"濾","瀛":"瀛","瀞":"瀞","瀞":"瀞","瀹":"瀹","灊":"灊","㶖":"㶖","⽕":"火","⺣":"灬","灰":"灰","灷":"灷","災":"災","炙":"炙","炭":"炭","烈":"烈","烙":"烙","煮":"煮","煮":"煮","𤉣":"𤉣","煅":"煅","煉":"煉","𤋮":"𤋮","熜":"熜","燎":"燎","燐":"燐","𤎫":"𤎫","爐":"爐","爛":"爛","爨":"爨","⽖":"爪","爫":"爫","⺤":"爫","爵":"爵","爵":"爵","⽗":"父","⽘":"爻","⺦":"丬","⽙":"爿","⽚":"片","牐":"牐","⽛":"牙","𤘈":"𤘈","⽜":"牛","牢":"牢","犀":"犀","犕":"犕","⽝":"犬","⺨":"犭","犯":"犯","狀":"狀","𤜵":"𤜵","狼":"狼","猪":"猪","猪":"猪","𤠔":"𤠔","獵":"獵","獺":"獺","⽞":"玄","率":"率","率":"率","⽟":"玉","王":"王","㺬":"㺬","玥":"玥","玲":"玲","㺸":"㺸","㺸":"㺸","珞":"珞","琉":"琉","理":"理","琢":"琢","瑇":"瑇","瑜":"瑜","瑩":"瑩","瑱":"瑱","瑱":"瑱","璅":"璅","璉":"璉","璘":"璘","瓊":"瓊","⽠":"瓜","⽡":"瓦","㼛":"㼛","甆":"甆","⽢":"甘","⽣":"生","甤":"甤","⽤":"用","⽥":"田","画":"画","甾":"甾","𤰶":"𤰶","留":"留","略":"略","異":"異","異":"異","𤲒":"𤲒","⽦":"疋","⽧":"疒","痢":"痢","瘐":"瘐","瘟":"瘟","瘝":"瘝","療":"療","癩":"癩","⽨":"癶","⽩":"白","𤾡":"𤾡","𤾸":"𤾸","⽪":"皮","⽫":"皿","𥁄":"𥁄","㿼":"㿼","益":"益","益":"益","盛":"盛","盧":"盧","䀈":"䀈","⽬":"目","直":"直","直":"直","𥃲":"𥃲","𥃳":"𥃳","省":"省","䀘":"䀘","𥄙":"𥄙","眞":"眞","真":"真","真":"真","𥄳":"𥄳","着":"着","睊":"睊","睊":"睊","鿃":"䀹","䀹":"䀹","䀹":"䀹","晣":"䀿","䁆":"䁆","瞋":"瞋","𥉉":"𥉉","瞧":"瞧","⽭":"矛","⽮":"矢","⽯":"石","䂖":"䂖","𥐝":"𥐝","硏":"研","硎":"硎","硫":"硫","碌":"碌","碌":"碌","碑":"碑","磊":"磊","磌":"磌","磌":"磌","磻":"磻","䃣":"䃣","礪":"礪","⽰":"示","⺭":"礻","礼":"礼","社":"社","祈":"祈","祉":"祉","𥘦":"𥘦","祐":"祐","祖":"祖","祖":"祖","祝":"祝","神":"神","祥":"祥","視":"視","視":"視","祿":"祿","𥚚":"𥚚","禍":"禍","禎":"禎","福":"福","福":"福","𥛅":"𥛅","禮":"禮","⽱":"禸","⽲":"禾","秊":"秊","䄯":"䄯","秫":"秫","稜":"稜","穊":"穊","穀":"穀","穀":"穀","穏":"穏","⽳":"穴","突":"突","𥥼":"𥥼","窱":"窱","立":"立","⽴":"立","⻯":"竜","𥪧":"𥪧","𥪧":"𥪧","竮":"竮","⽵":"竹","笠":"笠","節":"節","節":"節","䈂":"䈂","𥮫":"𥮫","篆":"篆","䈧":"䈧","築":"築","𥲀":"𥲀","𥳐":"𥳐","簾":"簾","籠":"籠","⽶":"米","类":"类","粒":"粒","精":"精","糒":"糒","糖":"糖","糨":"糨","䊠":"䊠","糣":"糣","糧":"糧","⽷":"糸","⺯":"糹","𥾆":"𥾆","紀":"紀","紐":"紐","索":"索","累":"累","絶":"絕","絣":"絣","絛":"絛","綠":"綠","綾":"綾","緇":"緇","練":"練","練":"練","練":"練","縂":"縂","䌁":"䌁","縉":"縉","縷":"縷","繁":"繁","繅":"繅","𦇚":"𦇚","䌴":"䌴","⽸":"缶","𦈨":"𦈨","缾":"缾","𦉇":"𦉇","⽹":"网","⺫":"罒","⺲":"罒","⺱":"罓","䍙":"䍙","署":"署","𦋙":"𦋙","罹":"罹","罺":"罺","羅":"羅","𦌾":"𦌾","⽺":"羊","羕":"羕","羚":"羚","羽":"羽","⽻":"羽","翺":"翺","老":"老","⽼":"老","⺹":"耂","者":"者","者":"者","者":"者","⽽":"而","𦓚":"𦓚","⽾":"耒","𦔣":"𦔣","⽿":"耳","聆":"聆","聠":"聠","𦖨":"𦖨","聯":"聯","聰":"聰","聾":"聾","⾀":"聿","⺺":"肀","⾁":"肉","肋":"肋","肭":"肭","育":"育","䏕":"䏕","䏙":"䏙","腁":"胼","脃":"脃","脾":"脾","䐋":"䐋","朡":"朡","𦞧":"𦞧","𦞵":"𦞵","朦":"䑃","臘":"臘","⾂":"臣","臨":"臨","⾃":"自","臭":"臭","⾄":"至","⾅":"臼","舁":"舁","舁":"舁","舄":"舄","⾆":"舌","舘":"舘","⾇":"舛","⾈":"舟","䑫":"䑫","⾉":"艮","良":"良","⾊":"色","⾋":"艸","艹":"艹","艹":"艹","⺾":"艹","⺿":"艹","⻀":"艹","芋":"芋","芑":"芑","芝":"芝","花":"花","芳":"芳","芽":"芽","若":"若","若":"若","苦":"苦","𦬼":"𦬼","茶":"茶","荒":"荒","荣":"荣","茝":"茝","茣":"茣","莽":"莽","荓":"荓","菉":"菉","菊":"菊","菌":"菌","菜":"菜","菧":"菧","華":"華","菱":"菱","著":"著","著":"著","𦰶":"𦰶","莭":"莭","落":"落","葉":"葉","蔿":"蒍","𦳕":"𦳕","𦵫":"𦵫","蓮":"蓮","蓱":"蓱","蓳":"蓳","蓼":"蓼","蔖":"蔖","䔫":"䔫","蕤":"蕤","𦼬":"𦼬","藍":"藍","䕝":"䕝","𦾱":"𦾱","䕡":"䕡","藺":"藺","蘆":"蘆","䕫":"䕫","蘒":"蘒","蘭":"蘭","𧃒":"𧃒","虁":"蘷","蘿":"蘿","⾌":"虍","⻁":"虎","虐":"虐","虜":"虜","虜":"虜","虧":"虧","虩":"虩","⾍":"虫","蚩":"蚩","蚈":"蚈","蛢":"蛢","蜎":"蜎","蜨":"蜨","蝫":"蝫","蟡":"蟡","蝹":"蝹","蝹":"蝹","螆":"螆","䗗":"䗗","𧏊":"𧏊","螺":"螺","蠁":"蠁","䗹":"䗹","蠟":"蠟","⾎":"血","行":"行","⾏":"行","衠":"衠","衣":"衣","⾐":"衣","⻂":"衤","裂":"裂","𧙧":"𧙧","裏":"裏","裗":"裗","裞":"裞","裡":"裡","裸":"裸","裺":"裺","䘵":"䘵","褐":"褐","襁":"襁","襤":"襤","⾑":"襾","⻄":"西","⻃":"覀","覆":"覆","見":"見","⾒":"見","𧢮":"𧢮","⻅":"见","⾓":"角","⾔":"言","𧥦":"𧥦","詽":"訮","訞":"䚶","䚾":"䚾","䛇":"䛇","誠":"誠","說":"說","說":"說","調":"調","請":"請","諒":"諒","論":"論","諭":"諭","諭":"諭","諸":"諸","諸":"諸","諾":"諾","諾":"諾","謁":"謁","謁":"謁","謹":"謹","謹":"謹","識":"識","讀":"讀","讏":"讆","變":"變","變":"變","⻈":"讠","⾕":"谷","⾖":"豆","豈":"豈","豕":"豕","⾗":"豕","豣":"豜","⾘":"豸","𧲨":"𧲨","⾙":"貝","貫":"貫","賁":"賁","賂":"賂","賈":"賈","賓":"賓","贈":"贈","贈":"贈","贛":"贛","⻉":"贝","⾚":"赤","⾛":"走","起":"起","趆":"赿","𧻓":"𧻓","𧼯":"𧼯","⾜":"足","跋":"跋","趼":"趼","跺":"跥","路":"路","跰":"跰","躛":"躗","⾝":"身","車":"車","⾞":"車","軔":"軔","輧":"軿","輦":"輦","輪":"輪","輸":"輸","輸":"輸","輻":"輻","轢":"轢","⻋":"车","⾟":"辛","辞":"辞","辰":"辰","⾠":"辰","⾡":"辵","辶":"辶","⻌":"辶","⻍":"辶","巡":"巡","連":"連","逸":"逸","逸":"逸","遲":"遲","遼":"遼","𨗒":"𨗒","𨗭":"𨗭","邏":"邏","⾢":"邑","邔":"邔","郎":"郎","郞":"郎","郞":"郎","郱":"郱","都":"都","𨜮":"𨜮","鄑":"鄑","鄛":"鄛","⾣":"酉","酪":"酪","醙":"醙","醴":"醴","⾤":"釆","里":"里","⾥":"里","量":"量","金":"金","⾦":"金","鈴":"鈴","鈸":"鈸","鉶":"鉶","鋗":"鋗","鋘":"鋘","鉼":"鉼","錄":"錄","鍊":"鍊","鎮":"鎭","鏹":"鏹","鐕":"鐕","𨯺":"𨯺","⻐":"钅","⻑":"長","⾧":"長","⻒":"镸","⻓":"长","⾨":"門","開":"開","䦕":"䦕","閭":"閭","閷":"閷","𨵷":"𨵷","⻔":"门","⾩":"阜","⻏":"阝","⻖":"阝","阮":"阮","陋":"陋","降":"降","陵":"陵","陸":"陸","陼":"陼","隆":"隆","隣":"隣","䧦":"䧦","⾪":"隶","隷":"隷","隸":"隷","隸":"隷","⾫":"隹","雃":"雃","離":"離","難":"難","難":"難","⾬":"雨","零":"零","雷":"雷","霣":"霣","𩅅":"𩅅","露":"露","靈":"靈","⾭":"靑","⻘":"青","靖":"靖","靖":"靖","𩇟":"𩇟","⾮":"非","⾯":"面","𩈚":"𩈚","⾰":"革","䩮":"䩮","䩶":"䩶","⾱":"韋","韛":"韛","韠":"韠","⻙":"韦","⾲":"韭","𩐊":"𩐊","⾳":"音","響":"響","響":"響","⾴":"頁","䪲":"䪲","頋":"頋","頋":"頋","頋":"頋","領":"領","頩":"頩","𩒖":"𩒖","頻":"頻","頻":"頻","類":"類","⻚":"页","⾵":"風","𩖶":"𩖶","⻛":"风","⾶":"飛","⻜":"飞","⻝":"食","⾷":"食","⻟":"飠","飢":"飢","飯":"飯","飼":"飼","䬳":"䬳","館":"館","餩":"餩","⻠":"饣","⾸":"首","⾹":"香","馧":"馧","⾺":"馬","駂":"駂","駱":"駱","駾":"駾","驪":"驪","⻢":"马","⾻":"骨","䯎":"䯎","⾼":"高","⾽":"髟","𩬰":"𩬰","鬒":"鬒","鬒":"鬒","⾾":"鬥","⾿":"鬯","⿀":"鬲","⿁":"鬼","⻤":"鬼","⿂":"魚","魯":"魯","鱀":"鱀","鱗":"鱗","⻥":"鱼","⿃":"鳥","鳽":"鳽","䳎":"䳎","鵧":"鵧","䳭":"䳭","𪃎":"𪃎","鶴":"鶴","𪄅":"𪄅","䳸":"䳸","鷺":"鷺","𪈎":"𪈎","鸞":"鸞","鹃":"鹂","⿄":"鹵","鹿":"鹿","⿅":"鹿","𪊑":"𪊑","麗":"麗","麟":"麟","⿆":"麥","⻨":"麦","麻":"麻","⿇":"麻","𪎒":"𪎒","⿈":"黃","⻩":"黄","⿉":"黍","黎":"黎","䵖":"䵖","⿊":"黑","黒":"黑","墨":"墨","黹":"黹","⿋":"黹","⿌":"黽","鼅":"鼅","黾":"黾","⿍":"鼎","鼏":"鼏","⿎":"鼓","鼖":"鼖","⿏":"鼠","鼻":"鼻","⿐":"鼻","齃":"齃","⿑":"齊","⻬":"齐","⿒":"齒","𪘀":"𪘀","⻮":"齿","龍":"龍","⿓":"龍","龎":"龎","⻰":"龙","龜":"龜","龜":"龜","龜":"龜","⿔":"龜","⻳":"龟","⿕":"龠"}')}},t={};function n(r){var i=t[r];if(void 0!==i)return i.exports;var s=t[r]={exports:{}};return e[r].call(s.exports,s,s.exports,n),s.exports}n.d=(e,t)=>{for(var r in t)n.o(t,r)&&!n.o(e,r)&&Object.defineProperty(e,r,{enumerable:!0,get:t[r]})},n.g=function(){if("object"==typeof globalThis)return globalThis;try{return this||new Function("return this")()}catch(e){if("object"==typeof window)return window}}(),n.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),n.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var r={};return(()=>{"use strict";n.r(r),n.d(r,{Buffer:()=>qu.Buffer,MatrixProvider:()=>Ku,Y:()=>t,sdk:()=>Vc});var e,t={};function i(e,t,...n){return function(e,t){let n;return n=0===t.length?e:e.replace(/\{(\d+)\}/g,(function(e,n){const r=n[0];return void 0!==t[r]?t[r]:e})),n}(t,n)}function s(e){const t=this;let n,r=!1;return function(){return r||(r=!0,n=e.apply(t,arguments)),n}}n.r(t),n.d(t,{AbsolutePosition:()=>Js,AbstractConnector:()=>Xi,AbstractStruct:()=>hc,AbstractType:()=>_a,Array:()=>Ka,ContentAny:()=>Ec,ContentBinary:()=>gc,ContentDeleted:()=>pc,ContentDoc:()=>yc,ContentEmbed:()=>vc,ContentFormat:()=>bc,ContentJSON:()=>_c,ContentString:()=>wc,ContentType:()=>Dc,Doc:()=>fs,GC:()=>fc,ID:()=>Bs,Item:()=>xc,Map:()=>$a,PermanentUserData:()=>Ws,RelativePosition:()=>Hs,Skip:()=>Fc,Snapshot:()=>ro,Text:()=>sc,Transaction:()=>Io,UndoManager:()=>jo,UpdateDecoderV1:()=>ps,UpdateDecoderV2:()=>ys,UpdateEncoderV1:()=>bs,UpdateEncoderV2:()=>Es,XmlElement:()=>cc,XmlFragment:()=>ac,XmlHook:()=>dc,XmlText:()=>uc,YArrayEvent:()=>Fa,YEvent:()=>ua,YMapEvent:()=>qa,YTextEvent:()=>ic,YXmlEvent:()=>lc,applyUpdate:()=>Rs,applyUpdateV2:()=>Ts,cleanupYTextFormatting:()=>tc,compareIDs:()=>js,compareRelativePositions:()=>no,convertUpdateFormatV1ToV2:()=>ca,convertUpdateFormatV2ToV1:()=>la,createAbsolutePositionFromRelativePosition:()=>to,createDeleteSet:()=>os,createDeleteSetFromStructStore:()=>as,createDocFromSnapshot:()=>po,createID:()=>Fs,createRelativePositionFromJSON:()=>zs,createRelativePositionFromTypeIndex:()=>Xs,createSnapshot:()=>lo,decodeRelativePosition:()=>eo,decodeSnapshot:()=>co,decodeSnapshotV2:()=>ao,decodeStateVector:()=>As,decodeUpdate:()=>$o,decodeUpdateV2:()=>Vo,diffUpdate:()=>ea,diffUpdateV2:()=>Zo,emptySnapshot:()=>uo,encodeRelativePosition:()=>Zs,encodeSnapshot:()=>oo,encodeSnapshotV2:()=>so,encodeStateAsUpdate:()=>ks,encodeStateAsUpdateV2:()=>Is,encodeStateVector:()=>Ms,encodeStateVectorFromUpdate:()=>Yo,encodeStateVectorFromUpdateV2:()=>Ho,equalDeleteSets:()=>us,equalSnapshots:()=>io,findIndexSS:()=>Eo,findRootTypeKey:()=>$s,getItem:()=>wo,getState:()=>bo,getTypeChildren:()=>va,isDeleted:()=>ns,isParentOf:()=>Vs,iterateDeletedStructs:()=>ts,logType:()=>Gs,logUpdate:()=>Ko,logUpdateV2:()=>qo,mergeUpdates:()=>Wo,mergeUpdatesV2:()=>Xo,obfuscateUpdate:()=>oa,obfuscateUpdateV2:()=>aa,parseUpdateMeta:()=>Jo,parseUpdateMetaV2:()=>zo,readUpdate:()=>Cs,readUpdateV2:()=>Ss,relativePositionToJSON:()=>Ys,snapshot:()=>ho,snapshotContainsUpdate:()=>mo,transact:()=>Lo,tryGc:()=>Po,typeListToArraySnapshot:()=>Sa,typeMapGetAllSnapshot:()=>Ba,typeMapGetSnapshot:()=>xa}),function(e){e.is=function(e){return e&&"object"==typeof e&&"function"==typeof e[Symbol.iterator]};const t=Object.freeze([]);e.empty=function(){return t},e.single=function*(e){yield e},e.from=function(e){return e||t},e.isEmpty=function(e){return!e||!0===e[Symbol.iterator]().next().done},e.first=function(e){return e[Symbol.iterator]().next().value},e.some=function(e,t){for(const n of e)if(t(n))return!0;return!1},e.find=function(e,t){for(const n of e)if(t(n))return n},e.filter=function*(e,t){for(const n of e)t(n)&&(yield n)},e.map=function*(e,t){let n=0;for(const r of e)yield t(r,n++)},e.concat=function*(...e){for(const t of e)for(const e of t)yield e},e.concatNested=function*(e){for(const t of e)for(const e of t)yield e},e.reduce=function(e,t,n){let r=n;for(const n of e)r=t(r,n);return r},e.slice=function*(e,t,n=e.length){for(t<0&&(t+=e.length),n<0?n+=e.length:n>e.length&&(n=e.length);t<n;t++)yield e[t]},e.consume=function(t,n=Number.POSITIVE_INFINITY){const r=[];if(0===n)return[r,t];const i=t[Symbol.iterator]();for(let t=0;t<n;t++){const t=i.next();if(t.done)return[r,e.empty()];r.push(t.value)}return[r,{[Symbol.iterator]:()=>i}]},e.equals=function(e,t,n=((e,t)=>e===t)){const r=e[Symbol.iterator](),i=t[Symbol.iterator]();for(;;){const e=r.next(),t=i.next();if(e.done!==t.done)return!1;if(e.done)return!0;if(!n(e.value,t.value))return!1}}}(e||(e={}));let o=null;function a(e){var t;return null==(t=o)||t.trackDisposable(e),e}function c(e){var t;null==(t=o)||t.markAsDisposed(e)}function l(e,t){var n;null==(n=o)||n.setParent(e,t)}class d extends Error{constructor(e){super(`Encountered errors while disposing of store. Errors: [${e.join(", ")}]`),this.errors=e}}function u(t){if(e.is(t)){let e=[];for(const n of t)if(n)try{n.dispose()}catch(t){e.push(t)}if(1===e.length)throw e[0];if(e.length>1)throw new d(e);return Array.isArray(t)?[]:t}if(t)return t.dispose(),t}function h(e){const t=a({dispose:s((()=>{c(t),e()}))});return t}class f{constructor(){this._toDispose=new Set,this._isDisposed=!1,a(this)}dispose(){this._isDisposed||(c(this),this._isDisposed=!0,this.clear())}clear(){try{u(this._toDispose.values())}finally{this._toDispose.clear()}}add(e){if(!e)return e;if(e===this)throw new Error("Cannot register a disposable on itself!");return l(e,this),this._isDisposed?f.DISABLE_DISPOSED_WARNING||console.warn(new Error("Trying to add a disposable to a DisposableStore that has already been disposed of. The added object will be leaked!").stack):this._toDispose.add(e),e}}f.DISABLE_DISPOSED_WARNING=!1;class g{constructor(){this._store=new f,a(this),l(this._store,this)}dispose(){c(this),this._store.dispose()}_register(e){if(e===this)throw new Error("Cannot register a disposable on itself!");return this._store.add(e)}}g.None=Object.freeze({dispose(){}});var p=g;function m(){return m=Object.assign||function(e){for(var t=1;t<arguments.length;t++){var n=arguments[t];for(var r in n)Object.prototype.hasOwnProperty.call(n,r)&&(e[r]=n[r])}return e},m.apply(this,arguments)}const y=new class{constructor(){this.listeners=[],this.unexpectedErrorHandler=function(e){setTimeout((()=>{if(e.stack)throw new Error(e.message+"\n\n"+e.stack);throw e}),0)}}addListener(e){return this.listeners.push(e),()=>{this._removeListener(e)}}emit(e){this.listeners.forEach((t=>{t(e)}))}_removeListener(e){this.listeners.splice(this.listeners.indexOf(e),1)}setUnexpectedErrorHandler(e){this.unexpectedErrorHandler=e}getUnexpectedErrorHandler(){return this.unexpectedErrorHandler}onUnexpectedError(e){this.unexpectedErrorHandler(e),this.emit(e)}onUnexpectedExternalError(e){this.unexpectedErrorHandler(e)}};function v(e){var t;(t=e)instanceof Error&&t.name===b&&t.message===b||y.onUnexpectedError(e)}const b="Canceled";Error,Error,Error,Error;class _{constructor(e){this.element=e,this.next=_.Undefined,this.prev=_.Undefined}}_.Undefined=new _(void 0);class E{constructor(){this._first=_.Undefined,this._last=_.Undefined,this._size=0}get size(){return this._size}isEmpty(){return this._first===_.Undefined}clear(){let e=this._first;for(;e!==_.Undefined;){const t=e.next;e.prev=_.Undefined,e.next=_.Undefined,e=t}this._first=_.Undefined,this._last=_.Undefined,this._size=0}unshift(e){return this._insert(e,!1)}push(e){return this._insert(e,!0)}_insert(e,t){const n=new _(e);if(this._first===_.Undefined)this._first=n,this._last=n;else if(t){const e=this._last;this._last=n,n.prev=e,e.next=n}else{const e=this._first;this._first=n,n.next=e,e.prev=n}this._size+=1;let r=!1;return()=>{r||(r=!0,this._remove(n))}}shift(){if(this._first!==_.Undefined){const e=this._first.element;return this._remove(this._first),e}}pop(){if(this._last!==_.Undefined){const e=this._last.element;return this._remove(this._last),e}}_remove(e){if(e.prev!==_.Undefined&&e.next!==_.Undefined){const t=e.prev;t.next=e.next,e.next.prev=t}else e.prev===_.Undefined&&e.next===_.Undefined?(this._first=_.Undefined,this._last=_.Undefined):e.next===_.Undefined?(this._last=this._last.prev,this._last.next=_.Undefined):e.prev===_.Undefined&&(this._first=this._first.next,this._first.prev=_.Undefined);this._size-=1}*[Symbol.iterator](){let e=this._first;for(;e!==_.Undefined;)yield e.element,e=e.next}}var w,S,C;const T="en";let R,I,k,O=!1,A=!1,D=!1,M=!1,P=!1,U=!1,L=!1,N=T;const x="object"==typeof self?self:"object"==typeof global?global:{};let B;void 0!==x.vscode&&void 0!==x.vscode.process?B=x.vscode.process:"undefined"!=typeof process&&(B=process);const j="string"==typeof(null==(w=B)||null==(S=w.versions)?void 0:S.electron)&&"renderer"===B.type,F=j&&(null==(C=B)?void 0:C.sandboxed),K="string"==typeof(()=>{var e;if(F)return"bypassHeatCheck";const t=null==(e=B)?void 0:e.env.VSCODE_BROWSER_CODE_LOADING;return"string"==typeof t?"none"===t||"code"===t||"bypassHeatCheck"===t||"bypassHeatCheckAndEagerCompile"===t?t:"bypassHeatCheck":void 0})();if("object"!=typeof navigator||j)if("object"==typeof B){O="win32"===B.platform,A="darwin"===B.platform,D="linux"===B.platform,M=D&&!!B.env.SNAP&&!!B.env.SNAP_REVISION,R=T,N=T;const e=B.env.VSCODE_NLS_CONFIG;if(e)try{const t=JSON.parse(e),n=t.availableLanguages["*"];R=t.locale,N=n||T,I=t._translationsConfigFile}catch(e){}P=!0}else console.error("Unable to resolve platform.");else k=navigator.userAgent,O=k.indexOf("Windows")>=0,A=k.indexOf("Macintosh")>=0,(k.indexOf("Macintosh")>=0||k.indexOf("iPad")>=0||k.indexOf("iPhone")>=0)&&!!navigator.maxTouchPoints&&navigator.maxTouchPoints>0,D=k.indexOf("Linux")>=0,U=!0,R=navigator.language,N=R;var q;!function(e){e[e.Web=0]="Web",e[e.Mac=1]="Mac",e[e.Linux=2]="Linux",e[e.Windows=3]="Windows"}(q||(q={}));let $=0;A?$=1:O?$=3:D&&($=2);const V=O,G=A,W=D,H=P,Y=U,z=N;var J;!function(e){e.value=function(){return z},e.isDefaultVariant=function(){return 2===z.length?"en"===z:z.length>=3&&"e"===z[0]&&"n"===z[1]&&"-"===z[2]},e.isDefault=function(){return"en"===z}}(J||(J={}));const Q=function(){var e;if(x.setImmediate)return x.setImmediate.bind(x);if("function"==typeof x.postMessage&&!x.importScripts){let e=[];x.addEventListener("message",(t=>{if(t.data&&t.data.vscodeSetImmediateId)for(let n=0,r=e.length;n<r;n++){const r=e[n];if(r.id===t.data.vscodeSetImmediateId)return e.splice(n,1),void r.callback()}}));let t=0;return n=>{const r=++t;e.push({id:r,callback:n}),x.postMessage({vscodeSetImmediateId:r},"*")}}if("function"==typeof(null==(e=B)?void 0:e.nextTick))return B.nextTick.bind(B);const t=Promise.resolve();return e=>t.then(e)}();var X;!function(e){e[e.Windows=1]="Windows",e[e.Macintosh=2]="Macintosh",e[e.Linux=3]="Linux"}(X||(X={}));const Z=x.performance&&"function"==typeof x.performance.now;class ee{constructor(e){this._highResolution=Z&&e,this._startTime=this._now(),this._stopTime=-1}static create(e=!0){return new ee(e)}stop(){this._stopTime=this._now()}elapsed(){return-1!==this._stopTime?this._stopTime-this._startTime:this._now()-this._startTime}_now(){return this._highResolution?x.performance.now():Date.now()}}var te;!function(e){function t(e){return(t,n=null,r)=>{let i,s=!1;return i=e((e=>{if(!s)return i?i.dispose():s=!0,t.call(n,e)}),null,r),s&&i.dispose(),i}}function n(e,t){return a(((n,r=null,i)=>e((e=>n.call(r,t(e))),null,i)))}function r(e,t){return a(((n,r=null,i)=>e((e=>{t(e),n.call(r,e)}),null,i)))}function i(e,t){return a(((n,r=null,i)=>e((e=>t(e)&&n.call(r,e)),null,i)))}function s(e,t,r){let i=r;return n(e,(e=>(i=t(i,e),i)))}function a(e){let t;const n=new se({onFirstListenerAdd(){t=e(n.fire,n)},onLastListenerRemove(){t.dispose()}});return n.event}function c(e,t,n=100,r=!1,i){let s,o,a,c=0;const l=new se({leakWarningThreshold:i,onFirstListenerAdd(){s=e((e=>{c++,o=t(o,e),r&&!a&&(l.fire(o),o=void 0),clearTimeout(a),a=setTimeout((()=>{const e=o;o=void 0,a=void 0,(!r||c>1)&&l.fire(e),c=0}),n)}))},onLastListenerRemove(){s.dispose()}});return l.event}function l(e,t=((e,t)=>e===t)){let n,r=!0;return i(e,(e=>{const i=r||!t(e,n);return r=!1,n=e,i}))}e.None=()=>g.None,e.once=t,e.map=n,e.forEach=r,e.filter=i,e.signal=function(e){return e},e.any=function(...e){return(t,n=null,r)=>function(...e){const t=h((()=>u(e)));return function(e,t){if(o)for(const n of e)o.setParent(n,t)}(e,t),t}(...e.map((e=>e((e=>t.call(n,e)),null,r))))},e.reduce=s,e.debounce=c,e.latch=l,e.split=function(t,n){return[e.filter(t,n),e.filter(t,(e=>!n(e)))]},e.buffer=function(e,t=!1,n=[]){let r=n.slice(),i=e((e=>{r?r.push(e):o.fire(e)}));const s=()=>{r&&r.forEach((e=>o.fire(e))),r=null},o=new se({onFirstListenerAdd(){i||(i=e((e=>o.fire(e))))},onFirstListenerDidAdd(){r&&(t?setTimeout(s):s())},onLastListenerRemove(){i&&i.dispose(),i=null}});return o.event};class d{constructor(e){this.event=e}map(e){return new d(n(this.event,e))}forEach(e){return new d(r(this.event,e))}filter(e){return new d(i(this.event,e))}reduce(e,t){return new d(s(this.event,e,t))}latch(){return new d(l(this.event))}debounce(e,t=100,n=!1,r){return new d(c(this.event,e,t,n,r))}on(e,t,n){return this.event(e,t,n)}once(e,n,r){return t(this.event)(e,n,r)}}e.chain=function(e){return new d(e)},e.fromNodeEventEmitter=function(e,t,n=(e=>e)){const r=(...e)=>i.fire(n(...e)),i=new se({onFirstListenerAdd:()=>e.on(t,r),onLastListenerRemove:()=>e.removeListener(t,r)});return i.event},e.fromDOMEventEmitter=function(e,t,n=(e=>e)){const r=(...e)=>i.fire(n(...e)),i=new se({onFirstListenerAdd:()=>e.addEventListener(t,r),onLastListenerRemove:()=>e.removeEventListener(t,r)});return i.event},e.toPromise=function(e){return new Promise((n=>t(e)(n)))}}(te||(te={}));class ne{constructor(e){this._listenerCount=0,this._invocationCount=0,this._elapsedOverall=0,this._name=`${e}_${ne._idPool++}`}start(e){this._stopWatch=new ee(!0),this._listenerCount=e}stop(){if(this._stopWatch){const e=this._stopWatch.elapsed();this._elapsedOverall+=e,this._invocationCount+=1,console.info(`did FIRE ${this._name}: elapsed_ms: ${e.toFixed(5)}, listener: ${this._listenerCount} (elapsed_overall: ${this._elapsedOverall.toFixed(2)}, invocations: ${this._invocationCount})`),this._stopWatch=void 0}}}ne._idPool=0;let re=-1;class ie{constructor(e,t=Math.random().toString(18).slice(2,5)){this.customThreshold=e,this.name=t,this._warnCountdown=0}dispose(){this._stacks&&this._stacks.clear()}check(e){let t=re;if("number"==typeof this.customThreshold&&(t=this.customThreshold),t<=0||e<t)return;this._stacks||(this._stacks=new Map);const n=(new Error).stack.split("\n").slice(3).join("\n"),r=this._stacks.get(n)||0;if(this._stacks.set(n,r+1),this._warnCountdown-=1,this._warnCountdown<=0){let n;this._warnCountdown=.5*t;let r=0;for(const[e,t]of this._stacks)(!n||r<t)&&(n=e,r=t);console.warn(`[${this.name}] potential listener LEAK detected, having ${e} listeners already. MOST frequent listener (${r}):`),console.warn(n)}return()=>{const e=this._stacks.get(n)||0;this._stacks.set(n,e-1)}}}class se{constructor(e){var t;this._disposed=!1,this._options=e,this._leakageMon=re>0?new ie(this._options&&this._options.leakWarningThreshold):void 0,this._perfMon=null!=(t=this._options)&&t._profName?new ne(this._options._profName):void 0}get event(){return this._event||(this._event=(e,t,n)=>{var r;this._listeners||(this._listeners=new E);const i=this._listeners.isEmpty();i&&this._options&&this._options.onFirstListenerAdd&&this._options.onFirstListenerAdd(this);const s=this._listeners.push(t?[e,t]:e);i&&this._options&&this._options.onFirstListenerDidAdd&&this._options.onFirstListenerDidAdd(this),this._options&&this._options.onListenerDidAdd&&this._options.onListenerDidAdd(this,e,t);const o=null==(r=this._leakageMon)?void 0:r.check(this._listeners.size),a=h((()=>{o&&o(),!this._disposed&&(s(),this._options&&this._options.onLastListenerRemove)&&(this._listeners&&!this._listeners.isEmpty()||this._options.onLastListenerRemove(this))}));return n instanceof f?n.add(a):Array.isArray(n)&&n.push(a),a}),this._event}fire(e){if(this._listeners){var t,n;this._deliveryQueue||(this._deliveryQueue=new E);for(let t of this._listeners)this._deliveryQueue.push([t,e]);for(null==(t=this._perfMon)||t.start(this._deliveryQueue.size);this._deliveryQueue.size>0;){const[e,t]=this._deliveryQueue.shift();try{"function"==typeof e?e.call(void 0,t):e[0].call(e[1],t)}catch(e){v(e)}}null==(n=this._perfMon)||n.stop()}}dispose(){var e,t,n,r;this._disposed||(this._disposed=!0,null==(e=this._listeners)||e.clear(),null==(t=this._deliveryQueue)||t.clear(),null==(n=this._options)||null==n.onLastListenerRemove||n.onLastListenerRemove(),null==(r=this._leakageMon)||r.dispose())}}class oe extends se{constructor(e){super(e),this._isPaused=0,this._eventQueue=new E,this._mergeFn=null==e?void 0:e.merge}pause(){this._isPaused++}resume(){if(0!==this._isPaused&&0==--this._isPaused)if(this._mergeFn){const e=Array.from(this._eventQueue);this._eventQueue.clear(),super.fire(this._mergeFn(e))}else for(;!this._isPaused&&0!==this._eventQueue.size;)super.fire(this._eventQueue.shift())}fire(e){this._listeners&&(0!==this._isPaused?this._eventQueue.push(e):super.fire(e))}}var ae={__proto__:null,get Event(){return te},setGlobalLeakWarningThreshold:function(e){const t=re;return re=e,{dispose(){re=t}}},Emitter:se,AsyncEmitter:class extends se{async fireAsync(e,t,n){if(this._listeners){this._asyncDeliveryQueue||(this._asyncDeliveryQueue=new E);for(const t of this._listeners)this._asyncDeliveryQueue.push([t,e]);for(;this._asyncDeliveryQueue.size>0&&!t.isCancellationRequested;){const[e,t]=this._asyncDeliveryQueue.shift(),r=[],i=m({},t,{waitUntil:t=>{if(Object.isFrozen(r))throw new Error("waitUntil can NOT be called asynchronous");n&&(t=n(t,"function"==typeof e?e:e[0])),r.push(t)}});try{"function"==typeof e?e.call(void 0,i):e[0].call(e[1],i)}catch(e){v(e);continue}Object.freeze(r),await Promise.allSettled(r).then((e=>{for(const t of e)"rejected"===t.status&&v(t.reason)}))}}}},PauseableEmitter:oe,DebounceEmitter:class extends oe{constructor(e){var t;super(e),this._delay=null!=(t=e.delay)?t:100}fire(e){this._handle||(this.pause(),this._handle=setTimeout((()=>{this._handle=void 0,this.resume()}),this._delay)),super.fire(e)}},EventMultiplexer:class{constructor(){this.hasListeners=!1,this.events=[],this.emitter=new se({onFirstListenerAdd:()=>this.onFirstListenerAdd(),onLastListenerRemove:()=>this.onLastListenerRemove()})}get event(){return this.emitter.event}add(e){const t={event:e,listener:null};return this.events.push(t),this.hasListeners&&this.hook(t),h(s((()=>{this.hasListeners&&this.unhook(t);const e=this.events.indexOf(t);this.events.splice(e,1)})))}onFirstListenerAdd(){this.hasListeners=!0,this.events.forEach((e=>this.hook(e)))}onLastListenerRemove(){this.hasListeners=!1,this.events.forEach((e=>this.unhook(e)))}hook(e){e.listener=e.event((e=>this.emitter.fire(e)))}unhook(e){e.listener&&e.listener.dispose(),e.listener=null}dispose(){this.emitter.dispose()}},EventBufferer:class{constructor(){this.buffers=[]}wrapEvent(e){return(t,n,r)=>e((e=>{const r=this.buffers[this.buffers.length-1];r?r.push((()=>t.call(n,e))):t.call(n,e)}),void 0,r)}bufferEvents(e){const t=[];this.buffers.push(t);const n=e();return this.buffers.pop(),t.forEach((e=>e())),n}},Relay:class{constructor(){this.listening=!1,this.inputEvent=te.None,this.inputEventListener=g.None,this.emitter=new se({onFirstListenerDidAdd:()=>{this.listening=!0,this.inputEventListener=this.inputEvent(this.emitter.fire,this.emitter)},onLastListenerRemove:()=>{this.listening=!1,this.inputEventListener.dispose()}}),this.event=this.emitter.event}set input(e){this.inputEvent=e,this.listening&&(this.inputEventListener.dispose(),this.inputEventListener=e(this.emitter.fire,this.emitter))}dispose(){this.inputEventListener.dispose(),this.emitter.dispose()}}};class ce extends g{constructor(e,t="",n="",r=!0,i){super(),this._onDidChange=this._register(new se),this.onDidChange=this._onDidChange.event,this._enabled=!0,this._checked=!1,this._id=e,this._label=t,this._cssClass=n,this._enabled=r,this._actionCallback=i}get id(){return this._id}get label(){return this._label}set label(e){this._setLabel(e)}_setLabel(e){this._label!==e&&(this._label=e,this._onDidChange.fire({label:e}))}get tooltip(){return this._tooltip||""}set tooltip(e){this._setTooltip(e)}_setTooltip(e){this._tooltip!==e&&(this._tooltip=e,this._onDidChange.fire({tooltip:e}))}get class(){return this._cssClass}set class(e){this._setClass(e)}_setClass(e){this._cssClass!==e&&(this._cssClass=e,this._onDidChange.fire({class:e}))}get enabled(){return this._enabled}set enabled(e){this._setEnabled(e)}_setEnabled(e){this._enabled!==e&&(this._enabled=e,this._onDidChange.fire({enabled:e}))}get checked(){return this._checked}set checked(e){this._setChecked(e)}_setChecked(e){this._checked!==e&&(this._checked=e,this._onDidChange.fire({checked:e}))}async run(e,t){this._actionCallback&&await this._actionCallback(e)}}class le extends ce{constructor(e){super(le.ID,e,e?"separator text":"separator"),this.checked=!1,this.enabled=!1}static join(...e){let t=[];for(const n of e)n.length&&(t=t.length?[...t,new le,...n]:n);return t}}le.ID="vs.actions.separator";class de extends ce{constructor(){super(de.ID,i(0,"(empty)"),void 0,!1)}}de.ID="vs.actions.empty";const ue=Object.freeze((function(e,t){const n=setTimeout(e.bind(t),0);return{dispose(){clearTimeout(n)}}}));var he,fe,ge;!function(e){e.isCancellationToken=function(t){return t===e.None||t===e.Cancelled||t instanceof pe||!(!t||"object"!=typeof t)&&"boolean"==typeof t.isCancellationRequested&&"function"==typeof t.onCancellationRequested},e.None=Object.freeze({isCancellationRequested:!1,onCancellationRequested:te.None}),e.Cancelled=Object.freeze({isCancellationRequested:!0,onCancellationRequested:ue})}(he||(he={}));class pe{constructor(){this._isCancelled=!1,this._emitter=null}cancel(){this._isCancelled||(this._isCancelled=!0,this._emitter&&(this._emitter.fire(void 0),this.dispose()))}get isCancellationRequested(){return this._isCancelled}get onCancellationRequested(){return this._isCancelled?ue:(this._emitter||(this._emitter=new se),this._emitter.event)}dispose(){this._emitter&&(this._emitter.dispose(),this._emitter=null)}}function me(e){return function(e){return e>=97&&e<=122}(e)||function(e){return e>=65&&e<=90}(e)}function ye(e,t){return e.length===t.length&&ve(e,t)}function ve(e,t,n=e.length){for(let r=0;r<n;r++){const n=e.charCodeAt(r),i=t.charCodeAt(r);if(n!==i)if(me(n)&&me(i)){const e=Math.abs(n-i);if(0!==e&&32!==e)return!1}else if(String.fromCharCode(n).toLowerCase()!==String.fromCharCode(i).toLowerCase())return!1}return!0}function be(e,t){const n=t.length;return!(t.length>e.length)&&ve(e,t,n)}function _e(e){return 55296<=e&&e<=56319}function Ee(e){return 56320<=e&&e<=57343}String.fromCharCode(65279),function(e){e[e.Other=0]="Other",e[e.Prepend=1]="Prepend",e[e.CR=2]="CR",e[e.LF=3]="LF",e[e.Control=4]="Control",e[e.Extend=5]="Extend",e[e.Regional_Indicator=6]="Regional_Indicator",e[e.SpacingMark=7]="SpacingMark",e[e.L=8]="L",e[e.V=9]="V",e[e.T=10]="T",e[e.LV=11]="LV",e[e.LVT=12]="LVT",e[e.ZWJ=13]="ZWJ",e[e.Extended_Pictographic=14]="Extended_Pictographic"}(fe||(fe={}));class we{constructor(){this._data=JSON.parse("[0,0,0,51592,51592,11,44424,44424,11,72251,72254,5,7150,7150,7,48008,48008,11,55176,55176,11,128420,128420,14,3276,3277,5,9979,9980,14,46216,46216,11,49800,49800,11,53384,53384,11,70726,70726,5,122915,122916,5,129320,129327,14,2558,2558,5,5906,5908,5,9762,9763,14,43360,43388,8,45320,45320,11,47112,47112,11,48904,48904,11,50696,50696,11,52488,52488,11,54280,54280,11,70082,70083,1,71350,71350,7,73111,73111,5,127892,127893,14,128726,128727,14,129473,129474,14,2027,2035,5,2901,2902,5,3784,3789,5,6754,6754,5,8418,8420,5,9877,9877,14,11088,11088,14,44008,44008,5,44872,44872,11,45768,45768,11,46664,46664,11,47560,47560,11,48456,48456,11,49352,49352,11,50248,50248,11,51144,51144,11,52040,52040,11,52936,52936,11,53832,53832,11,54728,54728,11,69811,69814,5,70459,70460,5,71096,71099,7,71998,71998,5,72874,72880,5,119149,119149,7,127374,127374,14,128335,128335,14,128482,128482,14,128765,128767,14,129399,129400,14,129680,129685,14,1476,1477,5,2377,2380,7,2759,2760,5,3137,3140,7,3458,3459,7,4153,4154,5,6432,6434,5,6978,6978,5,7675,7679,5,9723,9726,14,9823,9823,14,9919,9923,14,10035,10036,14,42736,42737,5,43596,43596,5,44200,44200,11,44648,44648,11,45096,45096,11,45544,45544,11,45992,45992,11,46440,46440,11,46888,46888,11,47336,47336,11,47784,47784,11,48232,48232,11,48680,48680,11,49128,49128,11,49576,49576,11,50024,50024,11,50472,50472,11,50920,50920,11,51368,51368,11,51816,51816,11,52264,52264,11,52712,52712,11,53160,53160,11,53608,53608,11,54056,54056,11,54504,54504,11,54952,54952,11,68108,68111,5,69933,69940,5,70197,70197,7,70498,70499,7,70845,70845,5,71229,71229,5,71727,71735,5,72154,72155,5,72344,72345,5,73023,73029,5,94095,94098,5,121403,121452,5,126981,127182,14,127538,127546,14,127990,127990,14,128391,128391,14,128445,128449,14,128500,128505,14,128752,128752,14,129160,129167,14,129356,129356,14,129432,129442,14,129648,129651,14,129751,131069,14,173,173,4,1757,1757,1,2274,2274,1,2494,2494,5,2641,2641,5,2876,2876,5,3014,3016,7,3262,3262,7,3393,3396,5,3570,3571,7,3968,3972,5,4228,4228,7,6086,6086,5,6679,6680,5,6912,6915,5,7080,7081,5,7380,7392,5,8252,8252,14,9096,9096,14,9748,9749,14,9784,9786,14,9833,9850,14,9890,9894,14,9938,9938,14,9999,9999,14,10085,10087,14,12349,12349,14,43136,43137,7,43454,43456,7,43755,43755,7,44088,44088,11,44312,44312,11,44536,44536,11,44760,44760,11,44984,44984,11,45208,45208,11,45432,45432,11,45656,45656,11,45880,45880,11,46104,46104,11,46328,46328,11,46552,46552,11,46776,46776,11,47000,47000,11,47224,47224,11,47448,47448,11,47672,47672,11,47896,47896,11,48120,48120,11,48344,48344,11,48568,48568,11,48792,48792,11,49016,49016,11,49240,49240,11,49464,49464,11,49688,49688,11,49912,49912,11,50136,50136,11,50360,50360,11,50584,50584,11,50808,50808,11,51032,51032,11,51256,51256,11,51480,51480,11,51704,51704,11,51928,51928,11,52152,52152,11,52376,52376,11,52600,52600,11,52824,52824,11,53048,53048,11,53272,53272,11,53496,53496,11,53720,53720,11,53944,53944,11,54168,54168,11,54392,54392,11,54616,54616,11,54840,54840,11,55064,55064,11,65438,65439,5,69633,69633,5,69837,69837,1,70018,70018,7,70188,70190,7,70368,70370,7,70465,70468,7,70712,70719,5,70835,70840,5,70850,70851,5,71132,71133,5,71340,71340,7,71458,71461,5,71985,71989,7,72002,72002,7,72193,72202,5,72281,72283,5,72766,72766,7,72885,72886,5,73104,73105,5,92912,92916,5,113824,113827,4,119173,119179,5,121505,121519,5,125136,125142,5,127279,127279,14,127489,127490,14,127570,127743,14,127900,127901,14,128254,128254,14,128369,128370,14,128400,128400,14,128425,128432,14,128468,128475,14,128489,128494,14,128715,128720,14,128745,128745,14,128759,128760,14,129004,129023,14,129296,129304,14,129340,129342,14,129388,129392,14,129404,129407,14,129454,129455,14,129485,129487,14,129659,129663,14,129719,129727,14,917536,917631,5,13,13,2,1160,1161,5,1564,1564,4,1807,1807,1,2085,2087,5,2363,2363,7,2402,2403,5,2507,2508,7,2622,2624,7,2691,2691,7,2786,2787,5,2881,2884,5,3006,3006,5,3072,3072,5,3170,3171,5,3267,3268,7,3330,3331,7,3406,3406,1,3538,3540,5,3655,3662,5,3897,3897,5,4038,4038,5,4184,4185,5,4352,4447,8,6068,6069,5,6155,6157,5,6448,6449,7,6742,6742,5,6783,6783,5,6966,6970,5,7042,7042,7,7143,7143,7,7212,7219,5,7412,7412,5,8206,8207,4,8294,8303,4,8596,8601,14,9410,9410,14,9742,9742,14,9757,9757,14,9770,9770,14,9794,9794,14,9828,9828,14,9855,9855,14,9882,9882,14,9900,9903,14,9929,9933,14,9963,9967,14,9987,9988,14,10006,10006,14,10062,10062,14,10175,10175,14,11744,11775,5,42607,42607,5,43043,43044,7,43263,43263,5,43444,43445,7,43569,43570,5,43698,43700,5,43766,43766,5,44032,44032,11,44144,44144,11,44256,44256,11,44368,44368,11,44480,44480,11,44592,44592,11,44704,44704,11,44816,44816,11,44928,44928,11,45040,45040,11,45152,45152,11,45264,45264,11,45376,45376,11,45488,45488,11,45600,45600,11,45712,45712,11,45824,45824,11,45936,45936,11,46048,46048,11,46160,46160,11,46272,46272,11,46384,46384,11,46496,46496,11,46608,46608,11,46720,46720,11,46832,46832,11,46944,46944,11,47056,47056,11,47168,47168,11,47280,47280,11,47392,47392,11,47504,47504,11,47616,47616,11,47728,47728,11,47840,47840,11,47952,47952,11,48064,48064,11,48176,48176,11,48288,48288,11,48400,48400,11,48512,48512,11,48624,48624,11,48736,48736,11,48848,48848,11,48960,48960,11,49072,49072,11,49184,49184,11,49296,49296,11,49408,49408,11,49520,49520,11,49632,49632,11,49744,49744,11,49856,49856,11,49968,49968,11,50080,50080,11,50192,50192,11,50304,50304,11,50416,50416,11,50528,50528,11,50640,50640,11,50752,50752,11,50864,50864,11,50976,50976,11,51088,51088,11,51200,51200,11,51312,51312,11,51424,51424,11,51536,51536,11,51648,51648,11,51760,51760,11,51872,51872,11,51984,51984,11,52096,52096,11,52208,52208,11,52320,52320,11,52432,52432,11,52544,52544,11,52656,52656,11,52768,52768,11,52880,52880,11,52992,52992,11,53104,53104,11,53216,53216,11,53328,53328,11,53440,53440,11,53552,53552,11,53664,53664,11,53776,53776,11,53888,53888,11,54000,54000,11,54112,54112,11,54224,54224,11,54336,54336,11,54448,54448,11,54560,54560,11,54672,54672,11,54784,54784,11,54896,54896,11,55008,55008,11,55120,55120,11,64286,64286,5,66272,66272,5,68900,68903,5,69762,69762,7,69817,69818,5,69927,69931,5,70003,70003,5,70070,70078,5,70094,70094,7,70194,70195,7,70206,70206,5,70400,70401,5,70463,70463,7,70475,70477,7,70512,70516,5,70722,70724,5,70832,70832,5,70842,70842,5,70847,70848,5,71088,71089,7,71102,71102,7,71219,71226,5,71231,71232,5,71342,71343,7,71453,71455,5,71463,71467,5,71737,71738,5,71995,71996,5,72000,72000,7,72145,72147,7,72160,72160,5,72249,72249,7,72273,72278,5,72330,72342,5,72752,72758,5,72850,72871,5,72882,72883,5,73018,73018,5,73031,73031,5,73109,73109,5,73461,73462,7,94031,94031,5,94192,94193,7,119142,119142,7,119155,119162,4,119362,119364,5,121476,121476,5,122888,122904,5,123184,123190,5,126976,126979,14,127184,127231,14,127344,127345,14,127405,127461,14,127514,127514,14,127561,127567,14,127778,127779,14,127896,127896,14,127985,127986,14,127995,127999,5,128326,128328,14,128360,128366,14,128378,128378,14,128394,128397,14,128405,128406,14,128422,128423,14,128435,128443,14,128453,128464,14,128479,128480,14,128484,128487,14,128496,128498,14,128640,128709,14,128723,128724,14,128736,128741,14,128747,128748,14,128755,128755,14,128762,128762,14,128981,128991,14,129096,129103,14,129292,129292,14,129311,129311,14,129329,129330,14,129344,129349,14,129360,129374,14,129394,129394,14,129402,129402,14,129413,129425,14,129445,129450,14,129466,129471,14,129483,129483,14,129511,129535,14,129653,129655,14,129667,129670,14,129705,129711,14,129731,129743,14,917505,917505,4,917760,917999,5,10,10,3,127,159,4,768,879,5,1471,1471,5,1536,1541,1,1648,1648,5,1767,1768,5,1840,1866,5,2070,2073,5,2137,2139,5,2307,2307,7,2366,2368,7,2382,2383,7,2434,2435,7,2497,2500,5,2519,2519,5,2563,2563,7,2631,2632,5,2677,2677,5,2750,2752,7,2763,2764,7,2817,2817,5,2879,2879,5,2891,2892,7,2914,2915,5,3008,3008,5,3021,3021,5,3076,3076,5,3146,3149,5,3202,3203,7,3264,3265,7,3271,3272,7,3298,3299,5,3390,3390,5,3402,3404,7,3426,3427,5,3535,3535,5,3544,3550,7,3635,3635,7,3763,3763,7,3893,3893,5,3953,3966,5,3981,3991,5,4145,4145,7,4157,4158,5,4209,4212,5,4237,4237,5,4520,4607,10,5970,5971,5,6071,6077,5,6089,6099,5,6277,6278,5,6439,6440,5,6451,6456,7,6683,6683,5,6744,6750,5,6765,6770,7,6846,6846,5,6964,6964,5,6972,6972,5,7019,7027,5,7074,7077,5,7083,7085,5,7146,7148,7,7154,7155,7,7222,7223,5,7394,7400,5,7416,7417,5,8204,8204,5,8233,8233,4,8288,8292,4,8413,8416,5,8482,8482,14,8986,8987,14,9193,9203,14,9654,9654,14,9733,9733,14,9745,9745,14,9752,9752,14,9760,9760,14,9766,9766,14,9774,9775,14,9792,9792,14,9800,9811,14,9825,9826,14,9831,9831,14,9852,9853,14,9872,9873,14,9880,9880,14,9885,9887,14,9896,9897,14,9906,9916,14,9926,9927,14,9936,9936,14,9941,9960,14,9974,9974,14,9982,9985,14,9992,9997,14,10002,10002,14,10017,10017,14,10055,10055,14,10071,10071,14,10145,10145,14,11013,11015,14,11503,11505,5,12334,12335,5,12951,12951,14,42612,42621,5,43014,43014,5,43047,43047,7,43204,43205,5,43335,43345,5,43395,43395,7,43450,43451,7,43561,43566,5,43573,43574,5,43644,43644,5,43710,43711,5,43758,43759,7,44005,44005,5,44012,44012,7,44060,44060,11,44116,44116,11,44172,44172,11,44228,44228,11,44284,44284,11,44340,44340,11,44396,44396,11,44452,44452,11,44508,44508,11,44564,44564,11,44620,44620,11,44676,44676,11,44732,44732,11,44788,44788,11,44844,44844,11,44900,44900,11,44956,44956,11,45012,45012,11,45068,45068,11,45124,45124,11,45180,45180,11,45236,45236,11,45292,45292,11,45348,45348,11,45404,45404,11,45460,45460,11,45516,45516,11,45572,45572,11,45628,45628,11,45684,45684,11,45740,45740,11,45796,45796,11,45852,45852,11,45908,45908,11,45964,45964,11,46020,46020,11,46076,46076,11,46132,46132,11,46188,46188,11,46244,46244,11,46300,46300,11,46356,46356,11,46412,46412,11,46468,46468,11,46524,46524,11,46580,46580,11,46636,46636,11,46692,46692,11,46748,46748,11,46804,46804,11,46860,46860,11,46916,46916,11,46972,46972,11,47028,47028,11,47084,47084,11,47140,47140,11,47196,47196,11,47252,47252,11,47308,47308,11,47364,47364,11,47420,47420,11,47476,47476,11,47532,47532,11,47588,47588,11,47644,47644,11,47700,47700,11,47756,47756,11,47812,47812,11,47868,47868,11,47924,47924,11,47980,47980,11,48036,48036,11,48092,48092,11,48148,48148,11,48204,48204,11,48260,48260,11,48316,48316,11,48372,48372,11,48428,48428,11,48484,48484,11,48540,48540,11,48596,48596,11,48652,48652,11,48708,48708,11,48764,48764,11,48820,48820,11,48876,48876,11,48932,48932,11,48988,48988,11,49044,49044,11,49100,49100,11,49156,49156,11,49212,49212,11,49268,49268,11,49324,49324,11,49380,49380,11,49436,49436,11,49492,49492,11,49548,49548,11,49604,49604,11,49660,49660,11,49716,49716,11,49772,49772,11,49828,49828,11,49884,49884,11,49940,49940,11,49996,49996,11,50052,50052,11,50108,50108,11,50164,50164,11,50220,50220,11,50276,50276,11,50332,50332,11,50388,50388,11,50444,50444,11,50500,50500,11,50556,50556,11,50612,50612,11,50668,50668,11,50724,50724,11,50780,50780,11,50836,50836,11,50892,50892,11,50948,50948,11,51004,51004,11,51060,51060,11,51116,51116,11,51172,51172,11,51228,51228,11,51284,51284,11,51340,51340,11,51396,51396,11,51452,51452,11,51508,51508,11,51564,51564,11,51620,51620,11,51676,51676,11,51732,51732,11,51788,51788,11,51844,51844,11,51900,51900,11,51956,51956,11,52012,52012,11,52068,52068,11,52124,52124,11,52180,52180,11,52236,52236,11,52292,52292,11,52348,52348,11,52404,52404,11,52460,52460,11,52516,52516,11,52572,52572,11,52628,52628,11,52684,52684,11,52740,52740,11,52796,52796,11,52852,52852,11,52908,52908,11,52964,52964,11,53020,53020,11,53076,53076,11,53132,53132,11,53188,53188,11,53244,53244,11,53300,53300,11,53356,53356,11,53412,53412,11,53468,53468,11,53524,53524,11,53580,53580,11,53636,53636,11,53692,53692,11,53748,53748,11,53804,53804,11,53860,53860,11,53916,53916,11,53972,53972,11,54028,54028,11,54084,54084,11,54140,54140,11,54196,54196,11,54252,54252,11,54308,54308,11,54364,54364,11,54420,54420,11,54476,54476,11,54532,54532,11,54588,54588,11,54644,54644,11,54700,54700,11,54756,54756,11,54812,54812,11,54868,54868,11,54924,54924,11,54980,54980,11,55036,55036,11,55092,55092,11,55148,55148,11,55216,55238,9,65056,65071,5,65529,65531,4,68097,68099,5,68159,68159,5,69446,69456,5,69688,69702,5,69808,69810,7,69815,69816,7,69821,69821,1,69888,69890,5,69932,69932,7,69957,69958,7,70016,70017,5,70067,70069,7,70079,70080,7,70089,70092,5,70095,70095,5,70191,70193,5,70196,70196,5,70198,70199,5,70367,70367,5,70371,70378,5,70402,70403,7,70462,70462,5,70464,70464,5,70471,70472,7,70487,70487,5,70502,70508,5,70709,70711,7,70720,70721,7,70725,70725,7,70750,70750,5,70833,70834,7,70841,70841,7,70843,70844,7,70846,70846,7,70849,70849,7,71087,71087,5,71090,71093,5,71100,71101,5,71103,71104,5,71216,71218,7,71227,71228,7,71230,71230,7,71339,71339,5,71341,71341,5,71344,71349,5,71351,71351,5,71456,71457,7,71462,71462,7,71724,71726,7,71736,71736,7,71984,71984,5,71991,71992,7,71997,71997,7,71999,71999,1,72001,72001,1,72003,72003,5,72148,72151,5,72156,72159,7,72164,72164,7,72243,72248,5,72250,72250,1,72263,72263,5,72279,72280,7,72324,72329,1,72343,72343,7,72751,72751,7,72760,72765,5,72767,72767,5,72873,72873,7,72881,72881,7,72884,72884,7,73009,73014,5,73020,73021,5,73030,73030,1,73098,73102,7,73107,73108,7,73110,73110,7,73459,73460,5,78896,78904,4,92976,92982,5,94033,94087,7,94180,94180,5,113821,113822,5,119141,119141,5,119143,119145,5,119150,119154,5,119163,119170,5,119210,119213,5,121344,121398,5,121461,121461,5,121499,121503,5,122880,122886,5,122907,122913,5,122918,122922,5,123628,123631,5,125252,125258,5,126980,126980,14,127183,127183,14,127245,127247,14,127340,127343,14,127358,127359,14,127377,127386,14,127462,127487,6,127491,127503,14,127535,127535,14,127548,127551,14,127568,127569,14,127744,127777,14,127780,127891,14,127894,127895,14,127897,127899,14,127902,127984,14,127987,127989,14,127991,127994,14,128000,128253,14,128255,128317,14,128329,128334,14,128336,128359,14,128367,128368,14,128371,128377,14,128379,128390,14,128392,128393,14,128398,128399,14,128401,128404,14,128407,128419,14,128421,128421,14,128424,128424,14,128433,128434,14,128444,128444,14,128450,128452,14,128465,128467,14,128476,128478,14,128481,128481,14,128483,128483,14,128488,128488,14,128495,128495,14,128499,128499,14,128506,128591,14,128710,128714,14,128721,128722,14,128725,128725,14,128728,128735,14,128742,128744,14,128746,128746,14,128749,128751,14,128753,128754,14,128756,128758,14,128761,128761,14,128763,128764,14,128884,128895,14,128992,129003,14,129036,129039,14,129114,129119,14,129198,129279,14,129293,129295,14,129305,129310,14,129312,129319,14,129328,129328,14,129331,129338,14,129343,129343,14,129351,129355,14,129357,129359,14,129375,129387,14,129393,129393,14,129395,129398,14,129401,129401,14,129403,129403,14,129408,129412,14,129426,129431,14,129443,129444,14,129451,129453,14,129456,129465,14,129472,129472,14,129475,129482,14,129484,129484,14,129488,129510,14,129536,129647,14,129652,129652,14,129656,129658,14,129664,129666,14,129671,129679,14,129686,129704,14,129712,129718,14,129728,129730,14,129744,129750,14,917504,917504,4,917506,917535,4,917632,917759,4,918000,921599,4,0,9,4,11,12,4,14,31,4,169,169,14,174,174,14,1155,1159,5,1425,1469,5,1473,1474,5,1479,1479,5,1552,1562,5,1611,1631,5,1750,1756,5,1759,1764,5,1770,1773,5,1809,1809,5,1958,1968,5,2045,2045,5,2075,2083,5,2089,2093,5,2259,2273,5,2275,2306,5,2362,2362,5,2364,2364,5,2369,2376,5,2381,2381,5,2385,2391,5,2433,2433,5,2492,2492,5,2495,2496,7,2503,2504,7,2509,2509,5,2530,2531,5,2561,2562,5,2620,2620,5,2625,2626,5,2635,2637,5,2672,2673,5,2689,2690,5,2748,2748,5,2753,2757,5,2761,2761,7,2765,2765,5,2810,2815,5,2818,2819,7,2878,2878,5,2880,2880,7,2887,2888,7,2893,2893,5,2903,2903,5,2946,2946,5,3007,3007,7,3009,3010,7,3018,3020,7,3031,3031,5,3073,3075,7,3134,3136,5,3142,3144,5,3157,3158,5,3201,3201,5,3260,3260,5,3263,3263,5,3266,3266,5,3270,3270,5,3274,3275,7,3285,3286,5,3328,3329,5,3387,3388,5,3391,3392,7,3398,3400,7,3405,3405,5,3415,3415,5,3457,3457,5,3530,3530,5,3536,3537,7,3542,3542,5,3551,3551,5,3633,3633,5,3636,3642,5,3761,3761,5,3764,3772,5,3864,3865,5,3895,3895,5,3902,3903,7,3967,3967,7,3974,3975,5,3993,4028,5,4141,4144,5,4146,4151,5,4155,4156,7,4182,4183,7,4190,4192,5,4226,4226,5,4229,4230,5,4253,4253,5,4448,4519,9,4957,4959,5,5938,5940,5,6002,6003,5,6070,6070,7,6078,6085,7,6087,6088,7,6109,6109,5,6158,6158,4,6313,6313,5,6435,6438,7,6441,6443,7,6450,6450,5,6457,6459,5,6681,6682,7,6741,6741,7,6743,6743,7,6752,6752,5,6757,6764,5,6771,6780,5,6832,6845,5,6847,6848,5,6916,6916,7,6965,6965,5,6971,6971,7,6973,6977,7,6979,6980,7,7040,7041,5,7073,7073,7,7078,7079,7,7082,7082,7,7142,7142,5,7144,7145,5,7149,7149,5,7151,7153,5,7204,7211,7,7220,7221,7,7376,7378,5,7393,7393,7,7405,7405,5,7415,7415,7,7616,7673,5,8203,8203,4,8205,8205,13,8232,8232,4,8234,8238,4,8265,8265,14,8293,8293,4,8400,8412,5,8417,8417,5,8421,8432,5,8505,8505,14,8617,8618,14,9000,9000,14,9167,9167,14,9208,9210,14,9642,9643,14,9664,9664,14,9728,9732,14,9735,9741,14,9743,9744,14,9746,9746,14,9750,9751,14,9753,9756,14,9758,9759,14,9761,9761,14,9764,9765,14,9767,9769,14,9771,9773,14,9776,9783,14,9787,9791,14,9793,9793,14,9795,9799,14,9812,9822,14,9824,9824,14,9827,9827,14,9829,9830,14,9832,9832,14,9851,9851,14,9854,9854,14,9856,9861,14,9874,9876,14,9878,9879,14,9881,9881,14,9883,9884,14,9888,9889,14,9895,9895,14,9898,9899,14,9904,9905,14,9917,9918,14,9924,9925,14,9928,9928,14,9934,9935,14,9937,9937,14,9939,9940,14,9961,9962,14,9968,9973,14,9975,9978,14,9981,9981,14,9986,9986,14,9989,9989,14,9998,9998,14,10000,10001,14,10004,10004,14,10013,10013,14,10024,10024,14,10052,10052,14,10060,10060,14,10067,10069,14,10083,10084,14,10133,10135,14,10160,10160,14,10548,10549,14,11035,11036,14,11093,11093,14,11647,11647,5,12330,12333,5,12336,12336,14,12441,12442,5,12953,12953,14,42608,42610,5,42654,42655,5,43010,43010,5,43019,43019,5,43045,43046,5,43052,43052,5,43188,43203,7,43232,43249,5,43302,43309,5,43346,43347,7,43392,43394,5,43443,43443,5,43446,43449,5,43452,43453,5,43493,43493,5,43567,43568,7,43571,43572,7,43587,43587,5,43597,43597,7,43696,43696,5,43703,43704,5,43713,43713,5,43756,43757,5,43765,43765,7,44003,44004,7,44006,44007,7,44009,44010,7,44013,44013,5,44033,44059,12,44061,44087,12,44089,44115,12,44117,44143,12,44145,44171,12,44173,44199,12,44201,44227,12,44229,44255,12,44257,44283,12,44285,44311,12,44313,44339,12,44341,44367,12,44369,44395,12,44397,44423,12,44425,44451,12,44453,44479,12,44481,44507,12,44509,44535,12,44537,44563,12,44565,44591,12,44593,44619,12,44621,44647,12,44649,44675,12,44677,44703,12,44705,44731,12,44733,44759,12,44761,44787,12,44789,44815,12,44817,44843,12,44845,44871,12,44873,44899,12,44901,44927,12,44929,44955,12,44957,44983,12,44985,45011,12,45013,45039,12,45041,45067,12,45069,45095,12,45097,45123,12,45125,45151,12,45153,45179,12,45181,45207,12,45209,45235,12,45237,45263,12,45265,45291,12,45293,45319,12,45321,45347,12,45349,45375,12,45377,45403,12,45405,45431,12,45433,45459,12,45461,45487,12,45489,45515,12,45517,45543,12,45545,45571,12,45573,45599,12,45601,45627,12,45629,45655,12,45657,45683,12,45685,45711,12,45713,45739,12,45741,45767,12,45769,45795,12,45797,45823,12,45825,45851,12,45853,45879,12,45881,45907,12,45909,45935,12,45937,45963,12,45965,45991,12,45993,46019,12,46021,46047,12,46049,46075,12,46077,46103,12,46105,46131,12,46133,46159,12,46161,46187,12,46189,46215,12,46217,46243,12,46245,46271,12,46273,46299,12,46301,46327,12,46329,46355,12,46357,46383,12,46385,46411,12,46413,46439,12,46441,46467,12,46469,46495,12,46497,46523,12,46525,46551,12,46553,46579,12,46581,46607,12,46609,46635,12,46637,46663,12,46665,46691,12,46693,46719,12,46721,46747,12,46749,46775,12,46777,46803,12,46805,46831,12,46833,46859,12,46861,46887,12,46889,46915,12,46917,46943,12,46945,46971,12,46973,46999,12,47001,47027,12,47029,47055,12,47057,47083,12,47085,47111,12,47113,47139,12,47141,47167,12,47169,47195,12,47197,47223,12,47225,47251,12,47253,47279,12,47281,47307,12,47309,47335,12,47337,47363,12,47365,47391,12,47393,47419,12,47421,47447,12,47449,47475,12,47477,47503,12,47505,47531,12,47533,47559,12,47561,47587,12,47589,47615,12,47617,47643,12,47645,47671,12,47673,47699,12,47701,47727,12,47729,47755,12,47757,47783,12,47785,47811,12,47813,47839,12,47841,47867,12,47869,47895,12,47897,47923,12,47925,47951,12,47953,47979,12,47981,48007,12,48009,48035,12,48037,48063,12,48065,48091,12,48093,48119,12,48121,48147,12,48149,48175,12,48177,48203,12,48205,48231,12,48233,48259,12,48261,48287,12,48289,48315,12,48317,48343,12,48345,48371,12,48373,48399,12,48401,48427,12,48429,48455,12,48457,48483,12,48485,48511,12,48513,48539,12,48541,48567,12,48569,48595,12,48597,48623,12,48625,48651,12,48653,48679,12,48681,48707,12,48709,48735,12,48737,48763,12,48765,48791,12,48793,48819,12,48821,48847,12,48849,48875,12,48877,48903,12,48905,48931,12,48933,48959,12,48961,48987,12,48989,49015,12,49017,49043,12,49045,49071,12,49073,49099,12,49101,49127,12,49129,49155,12,49157,49183,12,49185,49211,12,49213,49239,12,49241,49267,12,49269,49295,12,49297,49323,12,49325,49351,12,49353,49379,12,49381,49407,12,49409,49435,12,49437,49463,12,49465,49491,12,49493,49519,12,49521,49547,12,49549,49575,12,49577,49603,12,49605,49631,12,49633,49659,12,49661,49687,12,49689,49715,12,49717,49743,12,49745,49771,12,49773,49799,12,49801,49827,12,49829,49855,12,49857,49883,12,49885,49911,12,49913,49939,12,49941,49967,12,49969,49995,12,49997,50023,12,50025,50051,12,50053,50079,12,50081,50107,12,50109,50135,12,50137,50163,12,50165,50191,12,50193,50219,12,50221,50247,12,50249,50275,12,50277,50303,12,50305,50331,12,50333,50359,12,50361,50387,12,50389,50415,12,50417,50443,12,50445,50471,12,50473,50499,12,50501,50527,12,50529,50555,12,50557,50583,12,50585,50611,12,50613,50639,12,50641,50667,12,50669,50695,12,50697,50723,12,50725,50751,12,50753,50779,12,50781,50807,12,50809,50835,12,50837,50863,12,50865,50891,12,50893,50919,12,50921,50947,12,50949,50975,12,50977,51003,12,51005,51031,12,51033,51059,12,51061,51087,12,51089,51115,12,51117,51143,12,51145,51171,12,51173,51199,12,51201,51227,12,51229,51255,12,51257,51283,12,51285,51311,12,51313,51339,12,51341,51367,12,51369,51395,12,51397,51423,12,51425,51451,12,51453,51479,12,51481,51507,12,51509,51535,12,51537,51563,12,51565,51591,12,51593,51619,12,51621,51647,12,51649,51675,12,51677,51703,12,51705,51731,12,51733,51759,12,51761,51787,12,51789,51815,12,51817,51843,12,51845,51871,12,51873,51899,12,51901,51927,12,51929,51955,12,51957,51983,12,51985,52011,12,52013,52039,12,52041,52067,12,52069,52095,12,52097,52123,12,52125,52151,12,52153,52179,12,52181,52207,12,52209,52235,12,52237,52263,12,52265,52291,12,52293,52319,12,52321,52347,12,52349,52375,12,52377,52403,12,52405,52431,12,52433,52459,12,52461,52487,12,52489,52515,12,52517,52543,12,52545,52571,12,52573,52599,12,52601,52627,12,52629,52655,12,52657,52683,12,52685,52711,12,52713,52739,12,52741,52767,12,52769,52795,12,52797,52823,12,52825,52851,12,52853,52879,12,52881,52907,12,52909,52935,12,52937,52963,12,52965,52991,12,52993,53019,12,53021,53047,12,53049,53075,12,53077,53103,12,53105,53131,12,53133,53159,12,53161,53187,12,53189,53215,12,53217,53243,12,53245,53271,12,53273,53299,12,53301,53327,12,53329,53355,12,53357,53383,12,53385,53411,12,53413,53439,12,53441,53467,12,53469,53495,12,53497,53523,12,53525,53551,12,53553,53579,12,53581,53607,12,53609,53635,12,53637,53663,12,53665,53691,12,53693,53719,12,53721,53747,12,53749,53775,12,53777,53803,12,53805,53831,12,53833,53859,12,53861,53887,12,53889,53915,12,53917,53943,12,53945,53971,12,53973,53999,12,54001,54027,12,54029,54055,12,54057,54083,12,54085,54111,12,54113,54139,12,54141,54167,12,54169,54195,12,54197,54223,12,54225,54251,12,54253,54279,12,54281,54307,12,54309,54335,12,54337,54363,12,54365,54391,12,54393,54419,12,54421,54447,12,54449,54475,12,54477,54503,12,54505,54531,12,54533,54559,12,54561,54587,12,54589,54615,12,54617,54643,12,54645,54671,12,54673,54699,12,54701,54727,12,54729,54755,12,54757,54783,12,54785,54811,12,54813,54839,12,54841,54867,12,54869,54895,12,54897,54923,12,54925,54951,12,54953,54979,12,54981,55007,12,55009,55035,12,55037,55063,12,55065,55091,12,55093,55119,12,55121,55147,12,55149,55175,12,55177,55203,12,55243,55291,10,65024,65039,5,65279,65279,4,65520,65528,4,66045,66045,5,66422,66426,5,68101,68102,5,68152,68154,5,68325,68326,5,69291,69292,5,69632,69632,7,69634,69634,7,69759,69761,5]")}static getInstance(){return we._INSTANCE||(we._INSTANCE=new we),we._INSTANCE}getGraphemeBreakType(e){if(e<32)return 10===e?3:13===e?2:4;if(e<127)return 0;const t=this._data,n=t.length/3;let r=1;for(;r<=n;)if(e<t[3*r])r*=2;else{if(!(e>t[3*r+1]))return t[3*r+2];r=2*r+1}return 0}}let Se;if(we._INSTANCE=null,function(e){e[e.zwj=8205]="zwj",e[e.emojiVariantSelector=65039]="emojiVariantSelector",e[e.enclosingKeyCap=8419]="enclosingKeyCap"}(ge||(ge={})),void 0!==x.vscode&&void 0!==x.vscode.process){const e=x.vscode.process;Se={get platform(){return e.platform},get env(){return e.env},cwd:()=>e.cwd(),nextTick:e=>Q(e)}}else Se="undefined"!=typeof process?{get platform(){return process.platform},get env(){return process.env},cwd:()=>process.env.VSCODE_CWD||process.cwd(),nextTick:e=>process.nextTick(e)}:{get platform(){return V?"win32":G?"darwin":"linux"},nextTick:e=>Q(e),get env(){return{}},cwd:()=>"/"};const Ce=Se.cwd,Te=Se.env,Re=Se.platform;Se.nextTick;const Ie=46,ke=47,Oe=92,Ae=58;class De extends Error{constructor(e,t,n){let r;"string"==typeof t&&0===t.indexOf("not ")?(r="must not be",t=t.replace(/^not /,"")):r="must be";const i=-1!==e.indexOf(".")?"property":"argument";let s=`The "${e}" ${i} ${r} of type ${t}`;s+=". Received type "+typeof n,super(s),this.code="ERR_INVALID_ARG_TYPE"}}function Me(e,t){if("string"!=typeof e)throw new De(t,"string",e)}function Pe(e){return e===ke||e===Oe}function Ue(e){return e===ke}function Le(e){return e>=65&&e<=90||e>=97&&e<=122}function Ne(e,t,n,r){let i="",s=0,o=-1,a=0,c=0;for(let l=0;l<=e.length;++l){if(l<e.length)c=e.charCodeAt(l);else{if(r(c))break;c=ke}if(r(c)){if(o===l-1||1===a);else if(2===a){if(i.length<2||2!==s||i.charCodeAt(i.length-1)!==Ie||i.charCodeAt(i.length-2)!==Ie){if(i.length>2){const e=i.lastIndexOf(n);-1===e?(i="",s=0):(i=i.slice(0,e),s=i.length-1-i.lastIndexOf(n)),o=l,a=0;continue}if(0!==i.length){i="",s=0,o=l,a=0;continue}}t&&(i+=i.length>0?`${n}..`:"..",s=2)}else i.length>0?i+=`${n}${e.slice(o+1,l)}`:i=e.slice(o+1,l),s=l-o-1;o=l,a=0}else c===Ie&&-1!==a?++a:a=-1}return i}function xe(e,t){if(null===t||"object"!=typeof t)throw new De("pathObject","Object",t);const n=t.dir||t.root,r=t.base||`${t.name||""}${t.ext||""}`;return n?n===t.root?`${n}${r}`:`${n}${e}${r}`:r}const Be={resolve(...e){let t="",n="",r=!1;for(let i=e.length-1;i>=-1;i--){let s;if(i>=0){if(s=e[i],Me(s,"path"),0===s.length)continue}else 0===t.length?s=Ce():(s=Te[`=${t}`]||Ce(),(void 0===s||s.slice(0,2).toLowerCase()!==t.toLowerCase()&&s.charCodeAt(2)===Oe)&&(s=`${t}\\`));const o=s.length;let a=0,c="",l=!1;const d=s.charCodeAt(0);if(1===o)Pe(d)&&(a=1,l=!0);else if(Pe(d))if(l=!0,Pe(s.charCodeAt(1))){let e=2,t=e;for(;e<o&&!Pe(s.charCodeAt(e));)e++;if(e<o&&e!==t){const n=s.slice(t,e);for(t=e;e<o&&Pe(s.charCodeAt(e));)e++;if(e<o&&e!==t){for(t=e;e<o&&!Pe(s.charCodeAt(e));)e++;e!==o&&e===t||(c=`\\\\${n}\\${s.slice(t,e)}`,a=e)}}}else a=1;else Le(d)&&s.charCodeAt(1)===Ae&&(c=s.slice(0,2),a=2,o>2&&Pe(s.charCodeAt(2))&&(l=!0,a=3));if(c.length>0)if(t.length>0){if(c.toLowerCase()!==t.toLowerCase())continue}else t=c;if(r){if(t.length>0)break}else if(n=`${s.slice(a)}\\${n}`,r=l,l&&t.length>0)break}return n=Ne(n,!r,"\\",Pe),r?`${t}\\${n}`:`${t}${n}`||"."},normalize(e){Me(e,"path");const t=e.length;if(0===t)return".";let n,r=0,i=!1;const s=e.charCodeAt(0);if(1===t)return Ue(s)?"\\":e;if(Pe(s))if(i=!0,Pe(e.charCodeAt(1))){let i=2,s=i;for(;i<t&&!Pe(e.charCodeAt(i));)i++;if(i<t&&i!==s){const o=e.slice(s,i);for(s=i;i<t&&Pe(e.charCodeAt(i));)i++;if(i<t&&i!==s){for(s=i;i<t&&!Pe(e.charCodeAt(i));)i++;if(i===t)return`\\\\${o}\\${e.slice(s)}\\`;i!==s&&(n=`\\\\${o}\\${e.slice(s,i)}`,r=i)}}}else r=1;else Le(s)&&e.charCodeAt(1)===Ae&&(n=e.slice(0,2),r=2,t>2&&Pe(e.charCodeAt(2))&&(i=!0,r=3));let o=r<t?Ne(e.slice(r),!i,"\\",Pe):"";return 0!==o.length||i||(o="."),o.length>0&&Pe(e.charCodeAt(t-1))&&(o+="\\"),void 0===n?i?`\\${o}`:o:i?`${n}\\${o}`:`${n}${o}`},isAbsolute(e){Me(e,"path");const t=e.length;if(0===t)return!1;const n=e.charCodeAt(0);return Pe(n)||t>2&&Le(n)&&e.charCodeAt(1)===Ae&&Pe(e.charCodeAt(2))},join(...e){if(0===e.length)return".";let t,n;for(let r=0;r<e.length;++r){const i=e[r];Me(i,"path"),i.length>0&&(void 0===t?t=n=i:t+=`\\${i}`)}if(void 0===t)return".";let r=!0,i=0;if("string"==typeof n&&Pe(n.charCodeAt(0))){++i;const e=n.length;e>1&&Pe(n.charCodeAt(1))&&(++i,e>2&&(Pe(n.charCodeAt(2))?++i:r=!1))}if(r){for(;i<t.length&&Pe(t.charCodeAt(i));)i++;i>=2&&(t=`\\${t.slice(i)}`)}return Be.normalize(t)},relative(e,t){if(Me(e,"from"),Me(t,"to"),e===t)return"";const n=Be.resolve(e),r=Be.resolve(t);if(n===r)return"";if((e=n.toLowerCase())===(t=r.toLowerCase()))return"";let i=0;for(;i<e.length&&e.charCodeAt(i)===Oe;)i++;let s=e.length;for(;s-1>i&&e.charCodeAt(s-1)===Oe;)s--;const o=s-i;let a=0;for(;a<t.length&&t.charCodeAt(a)===Oe;)a++;let c=t.length;for(;c-1>a&&t.charCodeAt(c-1)===Oe;)c--;const l=c-a,d=o<l?o:l;let u=-1,h=0;for(;h<d;h++){const n=e.charCodeAt(i+h);if(n!==t.charCodeAt(a+h))break;n===Oe&&(u=h)}if(h!==d){if(-1===u)return r}else{if(l>d){if(t.charCodeAt(a+h)===Oe)return r.slice(a+h+1);if(2===h)return r.slice(a+h)}o>d&&(e.charCodeAt(i+h)===Oe?u=h:2===h&&(u=3)),-1===u&&(u=0)}let f="";for(h=i+u+1;h<=s;++h)h!==s&&e.charCodeAt(h)!==Oe||(f+=0===f.length?"..":"\\..");return a+=u,f.length>0?`${f}${r.slice(a,c)}`:(r.charCodeAt(a)===Oe&&++a,r.slice(a,c))},toNamespacedPath(e){if("string"!=typeof e)return e;if(0===e.length)return"";const t=Be.resolve(e);if(t.length<=2)return e;if(t.charCodeAt(0)===Oe){if(t.charCodeAt(1)===Oe){const e=t.charCodeAt(2);if(63!==e&&e!==Ie)return`\\\\?\\UNC\\${t.slice(2)}`}}else if(Le(t.charCodeAt(0))&&t.charCodeAt(1)===Ae&&t.charCodeAt(2)===Oe)return`\\\\?\\${t}`;return e},dirname(e){Me(e,"path");const t=e.length;if(0===t)return".";let n=-1,r=0;const i=e.charCodeAt(0);if(1===t)return Pe(i)?e:".";if(Pe(i)){if(n=r=1,Pe(e.charCodeAt(1))){let i=2,s=i;for(;i<t&&!Pe(e.charCodeAt(i));)i++;if(i<t&&i!==s){for(s=i;i<t&&Pe(e.charCodeAt(i));)i++;if(i<t&&i!==s){for(s=i;i<t&&!Pe(e.charCodeAt(i));)i++;if(i===t)return e;i!==s&&(n=r=i+1)}}}}else Le(i)&&e.charCodeAt(1)===Ae&&(n=t>2&&Pe(e.charCodeAt(2))?3:2,r=n);let s=-1,o=!0;for(let n=t-1;n>=r;--n)if(Pe(e.charCodeAt(n))){if(!o){s=n;break}}else o=!1;if(-1===s){if(-1===n)return".";s=n}return e.slice(0,s)},basename(e,t){void 0!==t&&Me(t,"ext"),Me(e,"path");let n,r=0,i=-1,s=!0;if(e.length>=2&&Le(e.charCodeAt(0))&&e.charCodeAt(1)===Ae&&(r=2),void 0!==t&&t.length>0&&t.length<=e.length){if(t===e)return"";let o=t.length-1,a=-1;for(n=e.length-1;n>=r;--n){const c=e.charCodeAt(n);if(Pe(c)){if(!s){r=n+1;break}}else-1===a&&(s=!1,a=n+1),o>=0&&(c===t.charCodeAt(o)?-1==--o&&(i=n):(o=-1,i=a))}return r===i?i=a:-1===i&&(i=e.length),e.slice(r,i)}for(n=e.length-1;n>=r;--n)if(Pe(e.charCodeAt(n))){if(!s){r=n+1;break}}else-1===i&&(s=!1,i=n+1);return-1===i?"":e.slice(r,i)},extname(e){Me(e,"path");let t=0,n=-1,r=0,i=-1,s=!0,o=0;e.length>=2&&e.charCodeAt(1)===Ae&&Le(e.charCodeAt(0))&&(t=r=2);for(let a=e.length-1;a>=t;--a){const t=e.charCodeAt(a);if(Pe(t)){if(!s){r=a+1;break}}else-1===i&&(s=!1,i=a+1),t===Ie?-1===n?n=a:1!==o&&(o=1):-1!==n&&(o=-1)}return-1===n||-1===i||0===o||1===o&&n===i-1&&n===r+1?"":e.slice(n,i)},format:xe.bind(null,"\\"),parse(e){Me(e,"path");const t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;const n=e.length;let r=0,i=e.charCodeAt(0);if(1===n)return Pe(i)?(t.root=t.dir=e,t):(t.base=t.name=e,t);if(Pe(i)){if(r=1,Pe(e.charCodeAt(1))){let t=2,i=t;for(;t<n&&!Pe(e.charCodeAt(t));)t++;if(t<n&&t!==i){for(i=t;t<n&&Pe(e.charCodeAt(t));)t++;if(t<n&&t!==i){for(i=t;t<n&&!Pe(e.charCodeAt(t));)t++;t===n?r=t:t!==i&&(r=t+1)}}}}else if(Le(i)&&e.charCodeAt(1)===Ae){if(n<=2)return t.root=t.dir=e,t;if(r=2,Pe(e.charCodeAt(2))){if(3===n)return t.root=t.dir=e,t;r=3}}r>0&&(t.root=e.slice(0,r));let s=-1,o=r,a=-1,c=!0,l=e.length-1,d=0;for(;l>=r;--l)if(i=e.charCodeAt(l),Pe(i)){if(!c){o=l+1;break}}else-1===a&&(c=!1,a=l+1),i===Ie?-1===s?s=l:1!==d&&(d=1):-1!==s&&(d=-1);return-1!==a&&(-1===s||0===d||1===d&&s===a-1&&s===o+1?t.base=t.name=e.slice(o,a):(t.name=e.slice(o,s),t.base=e.slice(o,a),t.ext=e.slice(s,a))),t.dir=o>0&&o!==r?e.slice(0,o-1):t.root,t},sep:"\\",delimiter:";",win32:null,posix:null},je={resolve(...e){let t="",n=!1;for(let r=e.length-1;r>=-1&&!n;r--){const i=r>=0?e[r]:Ce();Me(i,"path"),0!==i.length&&(t=`${i}/${t}`,n=i.charCodeAt(0)===ke)}return t=Ne(t,!n,"/",Ue),n?`/${t}`:t.length>0?t:"."},normalize(e){if(Me(e,"path"),0===e.length)return".";const t=e.charCodeAt(0)===ke,n=e.charCodeAt(e.length-1)===ke;return 0===(e=Ne(e,!t,"/",Ue)).length?t?"/":n?"./":".":(n&&(e+="/"),t?`/${e}`:e)},isAbsolute:e=>(Me(e,"path"),e.length>0&&e.charCodeAt(0)===ke),join(...e){if(0===e.length)return".";let t;for(let n=0;n<e.length;++n){const r=e[n];Me(r,"path"),r.length>0&&(void 0===t?t=r:t+=`/${r}`)}return void 0===t?".":je.normalize(t)},relative(e,t){if(Me(e,"from"),Me(t,"to"),e===t)return"";if((e=je.resolve(e))===(t=je.resolve(t)))return"";const n=e.length,r=n-1,i=t.length-1,s=r<i?r:i;let o=-1,a=0;for(;a<s;a++){const n=e.charCodeAt(1+a);if(n!==t.charCodeAt(1+a))break;n===ke&&(o=a)}if(a===s)if(i>s){if(t.charCodeAt(1+a)===ke)return t.slice(1+a+1);if(0===a)return t.slice(1+a)}else r>s&&(e.charCodeAt(1+a)===ke?o=a:0===a&&(o=0));let c="";for(a=1+o+1;a<=n;++a)a!==n&&e.charCodeAt(a)!==ke||(c+=0===c.length?"..":"/..");return`${c}${t.slice(1+o)}`},toNamespacedPath:e=>e,dirname(e){if(Me(e,"path"),0===e.length)return".";const t=e.charCodeAt(0)===ke;let n=-1,r=!0;for(let t=e.length-1;t>=1;--t)if(e.charCodeAt(t)===ke){if(!r){n=t;break}}else r=!1;return-1===n?t?"/":".":t&&1===n?"//":e.slice(0,n)},basename(e,t){void 0!==t&&Me(t,"ext"),Me(e,"path");let n,r=0,i=-1,s=!0;if(void 0!==t&&t.length>0&&t.length<=e.length){if(t===e)return"";let o=t.length-1,a=-1;for(n=e.length-1;n>=0;--n){const c=e.charCodeAt(n);if(c===ke){if(!s){r=n+1;break}}else-1===a&&(s=!1,a=n+1),o>=0&&(c===t.charCodeAt(o)?-1==--o&&(i=n):(o=-1,i=a))}return r===i?i=a:-1===i&&(i=e.length),e.slice(r,i)}for(n=e.length-1;n>=0;--n)if(e.charCodeAt(n)===ke){if(!s){r=n+1;break}}else-1===i&&(s=!1,i=n+1);return-1===i?"":e.slice(r,i)},extname(e){Me(e,"path");let t=-1,n=0,r=-1,i=!0,s=0;for(let o=e.length-1;o>=0;--o){const a=e.charCodeAt(o);if(a!==ke)-1===r&&(i=!1,r=o+1),a===Ie?-1===t?t=o:1!==s&&(s=1):-1!==t&&(s=-1);else if(!i){n=o+1;break}}return-1===t||-1===r||0===s||1===s&&t===r-1&&t===n+1?"":e.slice(t,r)},format:xe.bind(null,"/"),parse(e){Me(e,"path");const t={root:"",dir:"",base:"",ext:"",name:""};if(0===e.length)return t;const n=e.charCodeAt(0)===ke;let r;n?(t.root="/",r=1):r=0;let i=-1,s=0,o=-1,a=!0,c=e.length-1,l=0;for(;c>=r;--c){const t=e.charCodeAt(c);if(t!==ke)-1===o&&(a=!1,o=c+1),t===Ie?-1===i?i=c:1!==l&&(l=1):-1!==i&&(l=-1);else if(!a){s=c+1;break}}if(-1!==o){const r=0===s&&n?1:s;-1===i||0===l||1===l&&i===o-1&&i===s+1?t.base=t.name=e.slice(r,o):(t.name=e.slice(r,i),t.base=e.slice(r,o),t.ext=e.slice(i,o))}return s>0?t.dir=e.slice(0,s-1):n&&(t.dir="/"),t},sep:"/",delimiter:":",win32:null,posix:null};je.win32=Be.win32=Be,je.posix=Be.posix=je;const Fe="win32"===Re?Be.normalize:je.normalize,Ke=("win32"===Re?Be.isAbsolute:je.isAbsolute,"win32"===Re?Be.join:je.join,"win32"===Re?Be.resolve:je.resolve),qe="win32"===Re?Be.relative:je.relative,$e="win32"===Re?Be.dirname:je.dirname,Ve=("win32"===Re?Be.basename:je.basename,"win32"===Re?Be.extname:je.extname,"win32"===Re?Be.format:je.format,"win32"===Re?Be.parse:je.parse,"win32"===Re?Be.toNamespacedPath:je.toNamespacedPath,"win32"===Re?Be.sep:je.sep);function Ge(e){return 47===e||92===e}function We(e){return e.replace(/[\\/]/g,je.sep)}function He(e,t=je.sep){if(!e)return"";const n=e.length,r=e.charCodeAt(0);if(Ge(r)){if(Ge(e.charCodeAt(1))&&!Ge(e.charCodeAt(2))){let r=3;const i=r;for(;r<n&&!Ge(e.charCodeAt(r));r++);if(i!==r&&!Ge(e.charCodeAt(r+1)))for(r+=1;r<n;r++)if(Ge(e.charCodeAt(r)))return e.slice(0,r+1).replace(/[\\/]/g,t)}return t}if(((i=r)>=65&&i<=90||i>=97&&i<=122)&&58===e.charCodeAt(1))return Ge(e.charCodeAt(2))?e.slice(0,2)+t:e.slice(0,2);var i;let s=e.indexOf("://");if(-1!==s)for(s+=3;s<n;s++)if(Ge(e.charCodeAt(s)))return e.slice(0,s+1);return""}function Ye(e,t,n,r=Ve){if(e===t)return!0;if(!e||!t)return!1;if(t.length>e.length)return!1;if(n){if(!be(e,t))return!1;if(t.length===e.length)return!0;let n=t.length;return t.charAt(t.length-1)===r&&n--,e.charAt(n)===r}return t.charAt(t.length-1)!==r&&(t+=r),0===e.indexOf(t)}"win32"===Re?Be.delimiter:je.delimiter,Object.prototype.hasOwnProperty;const ze=/^\w[\w\d+.-]*$/,Je=/^\//,Qe=/^\/\//;function Xe(e,t){if(!e.scheme&&t)throw new Error(`[UriError]: Scheme is missing: {scheme: "", authority: "${e.authority}", path: "${e.path}", query: "${e.query}", fragment: "${e.fragment}"}`);if(e.scheme&&!ze.test(e.scheme))throw new Error("[UriError]: Scheme contains illegal characters.");if(e.path)if(e.authority){if(!Je.test(e.path))throw new Error('[UriError]: If a URI contains an authority component, then the path component must either be empty or begin with a slash ("/") character')}else if(Qe.test(e.path))throw new Error('[UriError]: If a URI does not contain an authority component, then the path cannot begin with two slash characters ("//")')}const Ze="",et="/",tt=/^(([^:/?#]+?):)?(\/\/([^/?#]*))?([^?#]*)(\?([^#]*))?(#(.*))?/;class nt{constructor(e,t,n,r,i,s=!1){"object"==typeof e?(this.scheme=e.scheme||Ze,this.authority=e.authority||Ze,this.path=e.path||Ze,this.query=e.query||Ze,this.fragment=e.fragment||Ze):(this.scheme=function(e,t){return e||t?e:"file"}(e,s),this.authority=t||Ze,this.path=function(e,t){switch(e){case"https":case"http":case"file":t?t[0]!==et&&(t=et+t):t=et}return t}(this.scheme,n||Ze),this.query=r||Ze,this.fragment=i||Ze,Xe(this,s))}static isUri(e){return e instanceof nt||!!e&&"string"==typeof e.authority&&"string"==typeof e.fragment&&"string"==typeof e.path&&"string"==typeof e.query&&"string"==typeof e.scheme&&"string"==typeof e.fsPath&&"function"==typeof e.with&&"function"==typeof e.toString}get fsPath(){return ct(this,!1)}with(e){if(!e)return this;let{scheme:t,authority:n,path:r,query:i,fragment:s}=e;return void 0===t?t=this.scheme:null===t&&(t=Ze),void 0===n?n=this.authority:null===n&&(n=Ze),void 0===r?r=this.path:null===r&&(r=Ze),void 0===i?i=this.query:null===i&&(i=Ze),void 0===s?s=this.fragment:null===s&&(s=Ze),t===this.scheme&&n===this.authority&&r===this.path&&i===this.query&&s===this.fragment?this:new it(t,n,r,i,s)}static parse(e,t=!1){const n=tt.exec(e);return n?new it(n[2]||Ze,ht(n[4]||Ze),ht(n[5]||Ze),ht(n[7]||Ze),ht(n[9]||Ze),t):new it(Ze,Ze,Ze,Ze,Ze)}static file(e){let t=Ze;if(V&&(e=e.replace(/\\/g,et)),e[0]===et&&e[1]===et){const n=e.indexOf(et,2);-1===n?(t=e.substring(2),e=et):(t=e.substring(2,n),e=e.substring(n)||et)}return new it("file",t,e,Ze,Ze)}static from(e){const t=new it(e.scheme,e.authority,e.path,e.query,e.fragment);return Xe(t,!0),t}static joinPath(e,...t){if(!e.path)throw new Error("[UriError]: cannot call joinPath on URI without path");let n;return n=V&&"file"===e.scheme?nt.file(Be.join(ct(e,!0),...t)).path:je.join(e.path,...t),e.with({path:n})}toString(e=!1){return lt(this,e)}toJSON(){return this}static revive(e){if(e){if(e instanceof nt)return e;{const t=new it(e);return t._formatted=e.external,t._fsPath=e._sep===rt?e.fsPath:null,t}}return e}}const rt=V?1:void 0;class it extends nt{constructor(){super(...arguments),this._formatted=null,this._fsPath=null}get fsPath(){return this._fsPath||(this._fsPath=ct(this,!1)),this._fsPath}toString(e=!1){return e?lt(this,!0):(this._formatted||(this._formatted=lt(this,!1)),this._formatted)}toJSON(){const e={$mid:1};return this._fsPath&&(e.fsPath=this._fsPath,e._sep=rt),this._formatted&&(e.external=this._formatted),this.path&&(e.path=this.path),this.scheme&&(e.scheme=this.scheme),this.authority&&(e.authority=this.authority),this.query&&(e.query=this.query),this.fragment&&(e.fragment=this.fragment),e}}const st={58:"%3A",47:"%2F",63:"%3F",35:"%23",91:"%5B",93:"%5D",64:"%40",33:"%21",36:"%24",38:"%26",39:"%27",40:"%28",41:"%29",42:"%2A",43:"%2B",44:"%2C",59:"%3B",61:"%3D",32:"%20"};function ot(e,t){let n,r=-1;for(let i=0;i<e.length;i++){const s=e.charCodeAt(i);if(s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||45===s||46===s||95===s||126===s||t&&47===s)-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),void 0!==n&&(n+=e.charAt(i));else{void 0===n&&(n=e.substr(0,i));const t=st[s];void 0!==t?(-1!==r&&(n+=encodeURIComponent(e.substring(r,i)),r=-1),n+=t):-1===r&&(r=i)}}return-1!==r&&(n+=encodeURIComponent(e.substring(r))),void 0!==n?n:e}function at(e){let t;for(let n=0;n<e.length;n++){const r=e.charCodeAt(n);35===r||63===r?(void 0===t&&(t=e.substr(0,n)),t+=st[r]):void 0!==t&&(t+=e[n])}return void 0!==t?t:e}function ct(e,t){let n;return n=e.authority&&e.path.length>1&&"file"===e.scheme?`//${e.authority}${e.path}`:47===e.path.charCodeAt(0)&&(e.path.charCodeAt(1)>=65&&e.path.charCodeAt(1)<=90||e.path.charCodeAt(1)>=97&&e.path.charCodeAt(1)<=122)&&58===e.path.charCodeAt(2)?t?e.path.substr(1):e.path[1].toLowerCase()+e.path.substr(2):e.path,V&&(n=n.replace(/\//g,"\\")),n}function lt(e,t){const n=t?at:ot;let r="",{scheme:i,authority:s,path:o,query:a,fragment:c}=e;if(i&&(r+=i,r+=":"),(s||"file"===i)&&(r+=et,r+=et),s){let e=s.indexOf("@");if(-1!==e){const t=s.substr(0,e);s=s.substr(e+1),e=t.indexOf(":"),-1===e?r+=n(t,!1):(r+=n(t.substr(0,e),!1),r+=":",r+=n(t.substr(e+1),!1)),r+="@"}s=s.toLowerCase(),e=s.indexOf(":"),-1===e?r+=n(s,!1):(r+=n(s.substr(0,e),!1),r+=s.substr(e))}if(o){if(o.length>=3&&47===o.charCodeAt(0)&&58===o.charCodeAt(2)){const e=o.charCodeAt(1);e>=65&&e<=90&&(o=`/${String.fromCharCode(e+32)}:${o.substr(3)}`)}else if(o.length>=2&&58===o.charCodeAt(1)){const e=o.charCodeAt(0);e>=65&&e<=90&&(o=`${String.fromCharCode(e+32)}:${o.substr(2)}`)}r+=n(o,!0)}return a&&(r+="?",r+=n(a,!1)),c&&(r+="#",r+=t?c:ot(c,!1)),r}function dt(e){try{return decodeURIComponent(e)}catch(t){return e.length>3?e.substr(0,3)+dt(e.substr(3)):e}}const ut=/(%[0-9A-Za-z][0-9A-Za-z])+/g;function ht(e){return e.match(ut)?e.replace(ut,(e=>dt(e))):e}var ft;!function(e){e.inMemory="inmemory",e.vscode="vscode",e.internal="private",e.walkThrough="walkThrough",e.walkThroughSnippet="walkThroughSnippet",e.http="http",e.https="https",e.file="file",e.mailto="mailto",e.untitled="untitled",e.data="data",e.command="command",e.vscodeRemote="vscode-remote",e.vscodeRemoteResource="vscode-remote-resource",e.userData="vscode-userdata",e.vscodeCustomEditor="vscode-custom-editor",e.vscodeNotebook="vscode-notebook",e.vscodeNotebookCell="vscode-notebook-cell",e.vscodeNotebookCellMetadata="vscode-notebook-cell-metadata",e.vscodeNotebookCellOutput="vscode-notebook-cell-output",e.vscodeInteractive="vscode-interactive",e.vscodeInteractiveInput="vscode-interactive-input",e.vscodeSettings="vscode-settings",e.vscodeWorkspaceTrust="vscode-workspace-trust",e.vscodeTerminal="vscode-terminal",e.webviewPanel="webview-panel",e.vscodeWebview="vscode-webview",e.extension="extension",e.vscodeFileResource="vscode-file",e.tmp="tmp"}(ft||(ft={}));const gt=new class{constructor(){this._hosts=Object.create(null),this._ports=Object.create(null),this._connectionTokens=Object.create(null),this._preferredWebSchema="http",this._delegate=null}setPreferredWebSchema(e){this._preferredWebSchema=e}setDelegate(e){this._delegate=e}set(e,t,n){this._hosts[e]=t,this._ports[e]=n}setConnectionToken(e,t){this._connectionTokens[e]=t}rewrite(e){if(this._delegate)return this._delegate(e);const t=e.authority;let n=this._hosts[t];n&&-1!==n.indexOf(":")&&(n=`[${n}]`);const r=this._ports[t],i=this._connectionTokens[t];let s=`path=${encodeURIComponent(e.path)}`;return"string"==typeof i&&(s+=`&tkn=${encodeURIComponent(i)}`),nt.from({scheme:Y?this._preferredWebSchema:ft.vscodeRemoteResource,authority:`${n}:${r}`,path:"/vscode-remote-resource",query:s})}};function pt(e){return ct(e,!0)}new class{constructor(){this.FALLBACK_AUTHORITY="vscode-app"}asBrowserUri(e,t,n){const r=this.toUri(e,t);if(r.scheme===ft.vscodeRemote)return gt.rewrite(r);let i=!1;return H&&(n||K)&&r.scheme===ft.file&&(i=!0),r.scheme===ft.file&&"function"==typeof x.importScripts&&"vscode-file://vscode-app"===x.origin&&(i=!0),i?r.with({scheme:ft.vscodeFileResource,authority:r.authority||this.FALLBACK_AUTHORITY,query:null,fragment:null}):r}asFileUri(e,t){const n=this.toUri(e,t);return n.scheme===ft.vscodeFileResource?n.with({scheme:ft.file,authority:n.authority!==this.FALLBACK_AUTHORITY?n.authority:null,query:null,fragment:null}):n}toUri(e,t){return nt.isUri(e)?e:nt.parse(t.toUrl(e))}};class mt{constructor(e){this._ignorePathCasing=e}compare(e,t,n=!1){return e===t?0:(r=this.getComparisonKey(e,n),i=this.getComparisonKey(t,n),r<i?-1:r>i?1:0);var r,i}isEqual(e,t,n=!1){return e===t||!(!e||!t)&&this.getComparisonKey(e,n)===this.getComparisonKey(t,n)}getComparisonKey(e,t=!1){return e.with({path:this._ignorePathCasing(e)?e.path.toLowerCase():void 0,fragment:t?null:void 0}).toString()}ignorePathCasing(e){return this._ignorePathCasing(e)}isEqualOrParent(e,t,n=!1){if(e.scheme===t.scheme){if(e.scheme===ft.file)return Ye(pt(e),pt(t),this._ignorePathCasing(e))&&e.query===t.query&&(n||e.fragment===t.fragment);if(bt(e.authority,t.authority))return Ye(e.path,t.path,this._ignorePathCasing(e),"/")&&e.query===t.query&&(n||e.fragment===t.fragment)}return!1}joinPath(e,...t){return nt.joinPath(e,...t)}basenameOrAuthority(e){return vt(e)||e.authority}basename(e){return je.basename(e.path)}extname(e){return je.extname(e.path)}dirname(e){if(0===e.path.length)return e;let t;return e.scheme===ft.file?t=nt.file($e(pt(e))).path:(t=je.dirname(e.path),e.authority&&t.length&&47!==t.charCodeAt(0)&&(console.error(`dirname("${e.toString})) resulted in a relative path`),t="/")),e.with({path:t})}normalizePath(e){if(!e.path.length)return e;let t;return t=e.scheme===ft.file?nt.file(Fe(pt(e))).path:je.normalize(e.path),e.with({path:t})}relativePath(e,t){if(e.scheme!==t.scheme||!bt(e.authority,t.authority))return;if(e.scheme===ft.file){const n=qe(pt(e),pt(t));return V?We(n):n}let n=e.path||"/",r=t.path||"/";if(this._ignorePathCasing(e)){let e=0;for(const t=Math.min(n.length,r.length);e<t&&(n.charCodeAt(e)===r.charCodeAt(e)||n.charAt(e).toLowerCase()===r.charAt(e).toLowerCase());e++);n=r.substr(0,e)+n.substr(e)}return je.relative(n,r)}resolvePath(e,t){if(e.scheme===ft.file){const n=nt.file(Ke(pt(e),t));return e.with({authority:n.authority,path:n.path})}return-1===(n=t).indexOf("/")&&(n=We(n)),/^[a-zA-Z]:(\/|$)/.test(n)&&(n="/"+n),t=n,e.with({path:je.resolve(e.path,t)});var n}isAbsolutePath(e){return!!e.path&&"/"===e.path[0]}isEqualAuthority(e,t){return e===t||ye(e,t)}hasTrailingPathSeparator(e,t=Ve){if(e.scheme===ft.file){const n=pt(e);return n.length>He(n).length&&n[n.length-1]===t}{const t=e.path;return t.length>1&&47===t.charCodeAt(t.length-1)&&!/^[a-zA-Z]:(\/$|\\$)/.test(e.fsPath)}}removeTrailingPathSeparator(e,t=Ve){return _t(e,t)?e.with({path:e.path.substr(0,e.path.length-1)}):e}addTrailingPathSeparator(e,t=Ve){let n=!1;if(e.scheme===ft.file){const r=pt(e);n=void 0!==r&&r.length===He(r).length&&r[r.length-1]===t}else{t="/";const r=e.path;n=1===r.length&&47===r.charCodeAt(r.length-1)}return n||_t(e,t)?e:e.with({path:e.path+"/"})}}const yt=new mt((()=>!1)),vt=(new mt((e=>e.scheme!==ft.file||!W)),new mt((e=>!0)),yt.isEqual.bind(yt),yt.isEqualOrParent.bind(yt),yt.getComparisonKey.bind(yt),yt.basenameOrAuthority.bind(yt),yt.basename.bind(yt)),bt=(yt.extname.bind(yt),yt.dirname.bind(yt),yt.joinPath.bind(yt),yt.normalizePath.bind(yt),yt.relativePath.bind(yt),yt.resolvePath.bind(yt),yt.isAbsolutePath.bind(yt),yt.isEqualAuthority.bind(yt)),_t=yt.hasTrailingPathSeparator.bind(yt);var Et;let wt;yt.removeTrailingPathSeparator.bind(yt),yt.addTrailingPathSeparator.bind(yt),function(e){e.META_DATA_LABEL="label",e.META_DATA_DESCRIPTION="description",e.META_DATA_SIZE="size",e.META_DATA_MIME="mime",e.parseMetaData=function(t){const n=new Map;t.path.substring(t.path.indexOf(";")+1,t.path.lastIndexOf(";")).split(";").forEach((e=>{const[t,r]=e.split(":");t&&r&&n.set(t,r)}));const r=t.path.substring(0,t.path.indexOf(";"));return r&&n.set(e.META_DATA_MIME,r),n}}(Et||(Et={})),function(){if("function"!=typeof requestIdleCallback||"function"!=typeof cancelIdleCallback){const e=Object.freeze({didTimeout:!0,timeRemaining:()=>15});wt=t=>{const n=setTimeout((()=>t(e)));let r=!1;return{dispose(){r||(r=!0,clearTimeout(n))}}}}else wt=(e,t)=>{const n=requestIdleCallback(e,"number"==typeof t?{timeout:t}:void 0);let r=!1;return{dispose(){r||(r=!0,cancelIdleCallback(n))}}}}();class St{constructor(e){this._didRun=!1,this._executor=()=>{try{this._value=e()}catch(e){this._error=e}finally{this._didRun=!0}},this._handle=wt((()=>this._executor()))}dispose(){this._handle.dispose()}get value(){if(this._didRun||(this._handle.dispose(),this._executor()),this._error)throw this._error;return this._value}}var Ct,Tt;!function(e){e.settled=async function(e){let t;const n=await Promise.all(e.map((e=>e.then((e=>e),(e=>{t||(t=e)})))));if(void 0!==t)throw t;return n}}(Ct||(Ct={})),function(e){e[e.Null=0]="Null",e[e.Backspace=8]="Backspace",e[e.Tab=9]="Tab",e[e.LineFeed=10]="LineFeed",e[e.CarriageReturn=13]="CarriageReturn",e[e.Space=32]="Space",e[e.ExclamationMark=33]="ExclamationMark",e[e.DoubleQuote=34]="DoubleQuote",e[e.Hash=35]="Hash",e[e.DollarSign=36]="DollarSign",e[e.PercentSign=37]="PercentSign",e[e.Ampersand=38]="Ampersand",e[e.SingleQuote=39]="SingleQuote",e[e.OpenParen=40]="OpenParen",e[e.CloseParen=41]="CloseParen",e[e.Asterisk=42]="Asterisk",e[e.Plus=43]="Plus",e[e.Comma=44]="Comma",e[e.Dash=45]="Dash",e[e.Period=46]="Period",e[e.Slash=47]="Slash",e[e.Digit0=48]="Digit0",e[e.Digit1=49]="Digit1",e[e.Digit2=50]="Digit2",e[e.Digit3=51]="Digit3",e[e.Digit4=52]="Digit4",e[e.Digit5=53]="Digit5",e[e.Digit6=54]="Digit6",e[e.Digit7=55]="Digit7",e[e.Digit8=56]="Digit8",e[e.Digit9=57]="Digit9",e[e.Colon=58]="Colon",e[e.Semicolon=59]="Semicolon",e[e.LessThan=60]="LessThan",e[e.Equals=61]="Equals",e[e.GreaterThan=62]="GreaterThan",e[e.QuestionMark=63]="QuestionMark",e[e.AtSign=64]="AtSign",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.OpenSquareBracket=91]="OpenSquareBracket",e[e.Backslash=92]="Backslash",e[e.CloseSquareBracket=93]="CloseSquareBracket",e[e.Caret=94]="Caret",e[e.Underline=95]="Underline",e[e.BackTick=96]="BackTick",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.OpenCurlyBrace=123]="OpenCurlyBrace",e[e.Pipe=124]="Pipe",e[e.CloseCurlyBrace=125]="CloseCurlyBrace",e[e.Tilde=126]="Tilde",e[e.U_Combining_Grave_Accent=768]="U_Combining_Grave_Accent",e[e.U_Combining_Acute_Accent=769]="U_Combining_Acute_Accent",e[e.U_Combining_Circumflex_Accent=770]="U_Combining_Circumflex_Accent",e[e.U_Combining_Tilde=771]="U_Combining_Tilde",e[e.U_Combining_Macron=772]="U_Combining_Macron",e[e.U_Combining_Overline=773]="U_Combining_Overline",e[e.U_Combining_Breve=774]="U_Combining_Breve",e[e.U_Combining_Dot_Above=775]="U_Combining_Dot_Above",e[e.U_Combining_Diaeresis=776]="U_Combining_Diaeresis",e[e.U_Combining_Hook_Above=777]="U_Combining_Hook_Above",e[e.U_Combining_Ring_Above=778]="U_Combining_Ring_Above",e[e.U_Combining_Double_Acute_Accent=779]="U_Combining_Double_Acute_Accent",e[e.U_Combining_Caron=780]="U_Combining_Caron",e[e.U_Combining_Vertical_Line_Above=781]="U_Combining_Vertical_Line_Above",e[e.U_Combining_Double_Vertical_Line_Above=782]="U_Combining_Double_Vertical_Line_Above",e[e.U_Combining_Double_Grave_Accent=783]="U_Combining_Double_Grave_Accent",e[e.U_Combining_Candrabindu=784]="U_Combining_Candrabindu",e[e.U_Combining_Inverted_Breve=785]="U_Combining_Inverted_Breve",e[e.U_Combining_Turned_Comma_Above=786]="U_Combining_Turned_Comma_Above",e[e.U_Combining_Comma_Above=787]="U_Combining_Comma_Above",e[e.U_Combining_Reversed_Comma_Above=788]="U_Combining_Reversed_Comma_Above",e[e.U_Combining_Comma_Above_Right=789]="U_Combining_Comma_Above_Right",e[e.U_Combining_Grave_Accent_Below=790]="U_Combining_Grave_Accent_Below",e[e.U_Combining_Acute_Accent_Below=791]="U_Combining_Acute_Accent_Below",e[e.U_Combining_Left_Tack_Below=792]="U_Combining_Left_Tack_Below",e[e.U_Combining_Right_Tack_Below=793]="U_Combining_Right_Tack_Below",e[e.U_Combining_Left_Angle_Above=794]="U_Combining_Left_Angle_Above",e[e.U_Combining_Horn=795]="U_Combining_Horn",e[e.U_Combining_Left_Half_Ring_Below=796]="U_Combining_Left_Half_Ring_Below",e[e.U_Combining_Up_Tack_Below=797]="U_Combining_Up_Tack_Below",e[e.U_Combining_Down_Tack_Below=798]="U_Combining_Down_Tack_Below",e[e.U_Combining_Plus_Sign_Below=799]="U_Combining_Plus_Sign_Below",e[e.U_Combining_Minus_Sign_Below=800]="U_Combining_Minus_Sign_Below",e[e.U_Combining_Palatalized_Hook_Below=801]="U_Combining_Palatalized_Hook_Below",e[e.U_Combining_Retroflex_Hook_Below=802]="U_Combining_Retroflex_Hook_Below",e[e.U_Combining_Dot_Below=803]="U_Combining_Dot_Below",e[e.U_Combining_Diaeresis_Below=804]="U_Combining_Diaeresis_Below",e[e.U_Combining_Ring_Below=805]="U_Combining_Ring_Below",e[e.U_Combining_Comma_Below=806]="U_Combining_Comma_Below",e[e.U_Combining_Cedilla=807]="U_Combining_Cedilla",e[e.U_Combining_Ogonek=808]="U_Combining_Ogonek",e[e.U_Combining_Vertical_Line_Below=809]="U_Combining_Vertical_Line_Below",e[e.U_Combining_Bridge_Below=810]="U_Combining_Bridge_Below",e[e.U_Combining_Inverted_Double_Arch_Below=811]="U_Combining_Inverted_Double_Arch_Below",e[e.U_Combining_Caron_Below=812]="U_Combining_Caron_Below",e[e.U_Combining_Circumflex_Accent_Below=813]="U_Combining_Circumflex_Accent_Below",e[e.U_Combining_Breve_Below=814]="U_Combining_Breve_Below",e[e.U_Combining_Inverted_Breve_Below=815]="U_Combining_Inverted_Breve_Below",e[e.U_Combining_Tilde_Below=816]="U_Combining_Tilde_Below",e[e.U_Combining_Macron_Below=817]="U_Combining_Macron_Below",e[e.U_Combining_Low_Line=818]="U_Combining_Low_Line",e[e.U_Combining_Double_Low_Line=819]="U_Combining_Double_Low_Line",e[e.U_Combining_Tilde_Overlay=820]="U_Combining_Tilde_Overlay",e[e.U_Combining_Short_Stroke_Overlay=821]="U_Combining_Short_Stroke_Overlay",e[e.U_Combining_Long_Stroke_Overlay=822]="U_Combining_Long_Stroke_Overlay",e[e.U_Combining_Short_Solidus_Overlay=823]="U_Combining_Short_Solidus_Overlay",e[e.U_Combining_Long_Solidus_Overlay=824]="U_Combining_Long_Solidus_Overlay",e[e.U_Combining_Right_Half_Ring_Below=825]="U_Combining_Right_Half_Ring_Below",e[e.U_Combining_Inverted_Bridge_Below=826]="U_Combining_Inverted_Bridge_Below",e[e.U_Combining_Square_Below=827]="U_Combining_Square_Below",e[e.U_Combining_Seagull_Below=828]="U_Combining_Seagull_Below",e[e.U_Combining_X_Above=829]="U_Combining_X_Above",e[e.U_Combining_Vertical_Tilde=830]="U_Combining_Vertical_Tilde",e[e.U_Combining_Double_Overline=831]="U_Combining_Double_Overline",e[e.U_Combining_Grave_Tone_Mark=832]="U_Combining_Grave_Tone_Mark",e[e.U_Combining_Acute_Tone_Mark=833]="U_Combining_Acute_Tone_Mark",e[e.U_Combining_Greek_Perispomeni=834]="U_Combining_Greek_Perispomeni",e[e.U_Combining_Greek_Koronis=835]="U_Combining_Greek_Koronis",e[e.U_Combining_Greek_Dialytika_Tonos=836]="U_Combining_Greek_Dialytika_Tonos",e[e.U_Combining_Greek_Ypogegrammeni=837]="U_Combining_Greek_Ypogegrammeni",e[e.U_Combining_Bridge_Above=838]="U_Combining_Bridge_Above",e[e.U_Combining_Equals_Sign_Below=839]="U_Combining_Equals_Sign_Below",e[e.U_Combining_Double_Vertical_Line_Below=840]="U_Combining_Double_Vertical_Line_Below",e[e.U_Combining_Left_Angle_Below=841]="U_Combining_Left_Angle_Below",e[e.U_Combining_Not_Tilde_Above=842]="U_Combining_Not_Tilde_Above",e[e.U_Combining_Homothetic_Above=843]="U_Combining_Homothetic_Above",e[e.U_Combining_Almost_Equal_To_Above=844]="U_Combining_Almost_Equal_To_Above",e[e.U_Combining_Left_Right_Arrow_Below=845]="U_Combining_Left_Right_Arrow_Below",e[e.U_Combining_Upwards_Arrow_Below=846]="U_Combining_Upwards_Arrow_Below",e[e.U_Combining_Grapheme_Joiner=847]="U_Combining_Grapheme_Joiner",e[e.U_Combining_Right_Arrowhead_Above=848]="U_Combining_Right_Arrowhead_Above",e[e.U_Combining_Left_Half_Ring_Above=849]="U_Combining_Left_Half_Ring_Above",e[e.U_Combining_Fermata=850]="U_Combining_Fermata",e[e.U_Combining_X_Below=851]="U_Combining_X_Below",e[e.U_Combining_Left_Arrowhead_Below=852]="U_Combining_Left_Arrowhead_Below",e[e.U_Combining_Right_Arrowhead_Below=853]="U_Combining_Right_Arrowhead_Below",e[e.U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below=854]="U_Combining_Right_Arrowhead_And_Up_Arrowhead_Below",e[e.U_Combining_Right_Half_Ring_Above=855]="U_Combining_Right_Half_Ring_Above",e[e.U_Combining_Dot_Above_Right=856]="U_Combining_Dot_Above_Right",e[e.U_Combining_Asterisk_Below=857]="U_Combining_Asterisk_Below",e[e.U_Combining_Double_Ring_Below=858]="U_Combining_Double_Ring_Below",e[e.U_Combining_Zigzag_Above=859]="U_Combining_Zigzag_Above",e[e.U_Combining_Double_Breve_Below=860]="U_Combining_Double_Breve_Below",e[e.U_Combining_Double_Breve=861]="U_Combining_Double_Breve",e[e.U_Combining_Double_Macron=862]="U_Combining_Double_Macron",e[e.U_Combining_Double_Macron_Below=863]="U_Combining_Double_Macron_Below",e[e.U_Combining_Double_Tilde=864]="U_Combining_Double_Tilde",e[e.U_Combining_Double_Inverted_Breve=865]="U_Combining_Double_Inverted_Breve",e[e.U_Combining_Double_Rightwards_Arrow_Below=866]="U_Combining_Double_Rightwards_Arrow_Below",e[e.U_Combining_Latin_Small_Letter_A=867]="U_Combining_Latin_Small_Letter_A",e[e.U_Combining_Latin_Small_Letter_E=868]="U_Combining_Latin_Small_Letter_E",e[e.U_Combining_Latin_Small_Letter_I=869]="U_Combining_Latin_Small_Letter_I",e[e.U_Combining_Latin_Small_Letter_O=870]="U_Combining_Latin_Small_Letter_O",e[e.U_Combining_Latin_Small_Letter_U=871]="U_Combining_Latin_Small_Letter_U",e[e.U_Combining_Latin_Small_Letter_C=872]="U_Combining_Latin_Small_Letter_C",e[e.U_Combining_Latin_Small_Letter_D=873]="U_Combining_Latin_Small_Letter_D",e[e.U_Combining_Latin_Small_Letter_H=874]="U_Combining_Latin_Small_Letter_H",e[e.U_Combining_Latin_Small_Letter_M=875]="U_Combining_Latin_Small_Letter_M",e[e.U_Combining_Latin_Small_Letter_R=876]="U_Combining_Latin_Small_Letter_R",e[e.U_Combining_Latin_Small_Letter_T=877]="U_Combining_Latin_Small_Letter_T",e[e.U_Combining_Latin_Small_Letter_V=878]="U_Combining_Latin_Small_Letter_V",e[e.U_Combining_Latin_Small_Letter_X=879]="U_Combining_Latin_Small_Letter_X",e[e.LINE_SEPARATOR=8232]="LINE_SEPARATOR",e[e.PARAGRAPH_SEPARATOR=8233]="PARAGRAPH_SEPARATOR",e[e.NEXT_LINE=133]="NEXT_LINE",e[e.U_CIRCUMFLEX=94]="U_CIRCUMFLEX",e[e.U_GRAVE_ACCENT=96]="U_GRAVE_ACCENT",e[e.U_DIAERESIS=168]="U_DIAERESIS",e[e.U_MACRON=175]="U_MACRON",e[e.U_ACUTE_ACCENT=180]="U_ACUTE_ACCENT",e[e.U_CEDILLA=184]="U_CEDILLA",e[e.U_MODIFIER_LETTER_LEFT_ARROWHEAD=706]="U_MODIFIER_LETTER_LEFT_ARROWHEAD",e[e.U_MODIFIER_LETTER_RIGHT_ARROWHEAD=707]="U_MODIFIER_LETTER_RIGHT_ARROWHEAD",e[e.U_MODIFIER_LETTER_UP_ARROWHEAD=708]="U_MODIFIER_LETTER_UP_ARROWHEAD",e[e.U_MODIFIER_LETTER_DOWN_ARROWHEAD=709]="U_MODIFIER_LETTER_DOWN_ARROWHEAD",e[e.U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING=722]="U_MODIFIER_LETTER_CENTRED_RIGHT_HALF_RING",e[e.U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING=723]="U_MODIFIER_LETTER_CENTRED_LEFT_HALF_RING",e[e.U_MODIFIER_LETTER_UP_TACK=724]="U_MODIFIER_LETTER_UP_TACK",e[e.U_MODIFIER_LETTER_DOWN_TACK=725]="U_MODIFIER_LETTER_DOWN_TACK",e[e.U_MODIFIER_LETTER_PLUS_SIGN=726]="U_MODIFIER_LETTER_PLUS_SIGN",e[e.U_MODIFIER_LETTER_MINUS_SIGN=727]="U_MODIFIER_LETTER_MINUS_SIGN",e[e.U_BREVE=728]="U_BREVE",e[e.U_DOT_ABOVE=729]="U_DOT_ABOVE",e[e.U_RING_ABOVE=730]="U_RING_ABOVE",e[e.U_OGONEK=731]="U_OGONEK",e[e.U_SMALL_TILDE=732]="U_SMALL_TILDE",e[e.U_DOUBLE_ACUTE_ACCENT=733]="U_DOUBLE_ACUTE_ACCENT",e[e.U_MODIFIER_LETTER_RHOTIC_HOOK=734]="U_MODIFIER_LETTER_RHOTIC_HOOK",e[e.U_MODIFIER_LETTER_CROSS_ACCENT=735]="U_MODIFIER_LETTER_CROSS_ACCENT",e[e.U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR=741]="U_MODIFIER_LETTER_EXTRA_HIGH_TONE_BAR",e[e.U_MODIFIER_LETTER_HIGH_TONE_BAR=742]="U_MODIFIER_LETTER_HIGH_TONE_BAR",e[e.U_MODIFIER_LETTER_MID_TONE_BAR=743]="U_MODIFIER_LETTER_MID_TONE_BAR",e[e.U_MODIFIER_LETTER_LOW_TONE_BAR=744]="U_MODIFIER_LETTER_LOW_TONE_BAR",e[e.U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR=745]="U_MODIFIER_LETTER_EXTRA_LOW_TONE_BAR",e[e.U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK=746]="U_MODIFIER_LETTER_YIN_DEPARTING_TONE_MARK",e[e.U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK=747]="U_MODIFIER_LETTER_YANG_DEPARTING_TONE_MARK",e[e.U_MODIFIER_LETTER_UNASPIRATED=749]="U_MODIFIER_LETTER_UNASPIRATED",e[e.U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD=751]="U_MODIFIER_LETTER_LOW_DOWN_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_UP_ARROWHEAD=752]="U_MODIFIER_LETTER_LOW_UP_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD=753]="U_MODIFIER_LETTER_LOW_LEFT_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD=754]="U_MODIFIER_LETTER_LOW_RIGHT_ARROWHEAD",e[e.U_MODIFIER_LETTER_LOW_RING=755]="U_MODIFIER_LETTER_LOW_RING",e[e.U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT=756]="U_MODIFIER_LETTER_MIDDLE_GRAVE_ACCENT",e[e.U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT=757]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_GRAVE_ACCENT",e[e.U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT=758]="U_MODIFIER_LETTER_MIDDLE_DOUBLE_ACUTE_ACCENT",e[e.U_MODIFIER_LETTER_LOW_TILDE=759]="U_MODIFIER_LETTER_LOW_TILDE",e[e.U_MODIFIER_LETTER_RAISED_COLON=760]="U_MODIFIER_LETTER_RAISED_COLON",e[e.U_MODIFIER_LETTER_BEGIN_HIGH_TONE=761]="U_MODIFIER_LETTER_BEGIN_HIGH_TONE",e[e.U_MODIFIER_LETTER_END_HIGH_TONE=762]="U_MODIFIER_LETTER_END_HIGH_TONE",e[e.U_MODIFIER_LETTER_BEGIN_LOW_TONE=763]="U_MODIFIER_LETTER_BEGIN_LOW_TONE",e[e.U_MODIFIER_LETTER_END_LOW_TONE=764]="U_MODIFIER_LETTER_END_LOW_TONE",e[e.U_MODIFIER_LETTER_SHELF=765]="U_MODIFIER_LETTER_SHELF",e[e.U_MODIFIER_LETTER_OPEN_SHELF=766]="U_MODIFIER_LETTER_OPEN_SHELF",e[e.U_MODIFIER_LETTER_LOW_LEFT_ARROW=767]="U_MODIFIER_LETTER_LOW_LEFT_ARROW",e[e.U_GREEK_LOWER_NUMERAL_SIGN=885]="U_GREEK_LOWER_NUMERAL_SIGN",e[e.U_GREEK_TONOS=900]="U_GREEK_TONOS",e[e.U_GREEK_DIALYTIKA_TONOS=901]="U_GREEK_DIALYTIKA_TONOS",e[e.U_GREEK_KORONIS=8125]="U_GREEK_KORONIS",e[e.U_GREEK_PSILI=8127]="U_GREEK_PSILI",e[e.U_GREEK_PERISPOMENI=8128]="U_GREEK_PERISPOMENI",e[e.U_GREEK_DIALYTIKA_AND_PERISPOMENI=8129]="U_GREEK_DIALYTIKA_AND_PERISPOMENI",e[e.U_GREEK_PSILI_AND_VARIA=8141]="U_GREEK_PSILI_AND_VARIA",e[e.U_GREEK_PSILI_AND_OXIA=8142]="U_GREEK_PSILI_AND_OXIA",e[e.U_GREEK_PSILI_AND_PERISPOMENI=8143]="U_GREEK_PSILI_AND_PERISPOMENI",e[e.U_GREEK_DASIA_AND_VARIA=8157]="U_GREEK_DASIA_AND_VARIA",e[e.U_GREEK_DASIA_AND_OXIA=8158]="U_GREEK_DASIA_AND_OXIA",e[e.U_GREEK_DASIA_AND_PERISPOMENI=8159]="U_GREEK_DASIA_AND_PERISPOMENI",e[e.U_GREEK_DIALYTIKA_AND_VARIA=8173]="U_GREEK_DIALYTIKA_AND_VARIA",e[e.U_GREEK_DIALYTIKA_AND_OXIA=8174]="U_GREEK_DIALYTIKA_AND_OXIA",e[e.U_GREEK_VARIA=8175]="U_GREEK_VARIA",e[e.U_GREEK_OXIA=8189]="U_GREEK_OXIA",e[e.U_GREEK_DASIA=8190]="U_GREEK_DASIA",e[e.U_OVERLINE=8254]="U_OVERLINE",e[e.UTF8_BOM=65279]="UTF8_BOM"}(Tt||(Tt={}));const Rt=new class{constructor(){this._icons=new Map,this._onDidRegister=new se}add(e){const t=this._icons.get(e.id);t?e.description?t.description=e.description:console.error(`Duplicate registration of codicon ${e.id}`):(this._icons.set(e.id,e),this._onDidRegister.fire(e))}get(e){return this._icons.get(e)}get all(){return this._icons.values()}get onDidRegister(){return this._onDidRegister.event}};class It{constructor(e,t,n){this.id=e,this.definition=t,this.description=n,Rt.add(this)}get classNames(){return"codicon codicon-"+this.id}get classNamesArray(){return["codicon","codicon-"+this.id]}get cssSelector(){return".codicon.codicon-"+this.id}}var kt;function Ot(e,t){const n=Math.pow(10,t);return Math.round(e*n)/n}!function(e){e.iconNameSegment="[A-Za-z0-9]+",e.iconNameExpression="[A-Za-z0-9\\-]+",e.iconModifierExpression="~[A-Za-z]+";const t=new RegExp(`^(${e.iconNameExpression})(${e.iconModifierExpression})?$`);function n(e){if(e instanceof It)return["codicon","codicon-"+e.id];const r=t.exec(e.id);if(!r)return n(It.error);let[,i,s]=r;const o=["codicon","codicon-"+i];return s&&o.push("codicon-modifier-"+s.substr(1)),o}e.asClassNameArray=n,e.asClassName=function(e){return n(e).join(" ")},e.asCSSSelector=function(e){return"."+n(e).join(".")}}(kt||(kt={})),function(e){e.add=new e("add",{fontCharacter:"\\ea60"}),e.plus=new e("plus",{fontCharacter:"\\ea60"}),e.gistNew=new e("gist-new",{fontCharacter:"\\ea60"}),e.repoCreate=new e("repo-create",{fontCharacter:"\\ea60"}),e.lightbulb=new e("lightbulb",{fontCharacter:"\\ea61"}),e.lightBulb=new e("light-bulb",{fontCharacter:"\\ea61"}),e.repo=new e("repo",{fontCharacter:"\\ea62"}),e.repoDelete=new e("repo-delete",{fontCharacter:"\\ea62"}),e.gistFork=new e("gist-fork",{fontCharacter:"\\ea63"}),e.repoForked=new e("repo-forked",{fontCharacter:"\\ea63"}),e.gitPullRequest=new e("git-pull-request",{fontCharacter:"\\ea64"}),e.gitPullRequestAbandoned=new e("git-pull-request-abandoned",{fontCharacter:"\\ea64"}),e.recordKeys=new e("record-keys",{fontCharacter:"\\ea65"}),e.keyboard=new e("keyboard",{fontCharacter:"\\ea65"}),e.tag=new e("tag",{fontCharacter:"\\ea66"}),e.tagAdd=new e("tag-add",{fontCharacter:"\\ea66"}),e.tagRemove=new e("tag-remove",{fontCharacter:"\\ea66"}),e.person=new e("person",{fontCharacter:"\\ea67"}),e.personFollow=new e("person-follow",{fontCharacter:"\\ea67"}),e.personOutline=new e("person-outline",{fontCharacter:"\\ea67"}),e.personFilled=new e("person-filled",{fontCharacter:"\\ea67"}),e.gitBranch=new e("git-branch",{fontCharacter:"\\ea68"}),e.gitBranchCreate=new e("git-branch-create",{fontCharacter:"\\ea68"}),e.gitBranchDelete=new e("git-branch-delete",{fontCharacter:"\\ea68"}),e.sourceControl=new e("source-control",{fontCharacter:"\\ea68"}),e.mirror=new e("mirror",{fontCharacter:"\\ea69"}),e.mirrorPublic=new e("mirror-public",{fontCharacter:"\\ea69"}),e.star=new e("star",{fontCharacter:"\\ea6a"}),e.starAdd=new e("star-add",{fontCharacter:"\\ea6a"}),e.starDelete=new e("star-delete",{fontCharacter:"\\ea6a"}),e.starEmpty=new e("star-empty",{fontCharacter:"\\ea6a"}),e.comment=new e("comment",{fontCharacter:"\\ea6b"}),e.commentAdd=new e("comment-add",{fontCharacter:"\\ea6b"}),e.alert=new e("alert",{fontCharacter:"\\ea6c"}),e.warning=new e("warning",{fontCharacter:"\\ea6c"}),e.search=new e("search",{fontCharacter:"\\ea6d"}),e.searchSave=new e("search-save",{fontCharacter:"\\ea6d"}),e.logOut=new e("log-out",{fontCharacter:"\\ea6e"}),e.signOut=new e("sign-out",{fontCharacter:"\\ea6e"}),e.logIn=new e("log-in",{fontCharacter:"\\ea6f"}),e.signIn=new e("sign-in",{fontCharacter:"\\ea6f"}),e.eye=new e("eye",{fontCharacter:"\\ea70"}),e.eyeUnwatch=new e("eye-unwatch",{fontCharacter:"\\ea70"}),e.eyeWatch=new e("eye-watch",{fontCharacter:"\\ea70"}),e.circleFilled=new e("circle-filled",{fontCharacter:"\\ea71"}),e.primitiveDot=new e("primitive-dot",{fontCharacter:"\\ea71"}),e.closeDirty=new e("close-dirty",{fontCharacter:"\\ea71"}),e.debugBreakpoint=new e("debug-breakpoint",{fontCharacter:"\\ea71"}),e.debugBreakpointDisabled=new e("debug-breakpoint-disabled",{fontCharacter:"\\ea71"}),e.debugHint=new e("debug-hint",{fontCharacter:"\\ea71"}),e.primitiveSquare=new e("primitive-square",{fontCharacter:"\\ea72"}),e.edit=new e("edit",{fontCharacter:"\\ea73"}),e.pencil=new e("pencil",{fontCharacter:"\\ea73"}),e.info=new e("info",{fontCharacter:"\\ea74"}),e.issueOpened=new e("issue-opened",{fontCharacter:"\\ea74"}),e.gistPrivate=new e("gist-private",{fontCharacter:"\\ea75"}),e.gitForkPrivate=new e("git-fork-private",{fontCharacter:"\\ea75"}),e.lock=new e("lock",{fontCharacter:"\\ea75"}),e.mirrorPrivate=new e("mirror-private",{fontCharacter:"\\ea75"}),e.close=new e("close",{fontCharacter:"\\ea76"}),e.removeClose=new e("remove-close",{fontCharacter:"\\ea76"}),e.x=new e("x",{fontCharacter:"\\ea76"}),e.repoSync=new e("repo-sync",{fontCharacter:"\\ea77"}),e.sync=new e("sync",{fontCharacter:"\\ea77"}),e.clone=new e("clone",{fontCharacter:"\\ea78"}),e.desktopDownload=new e("desktop-download",{fontCharacter:"\\ea78"}),e.beaker=new e("beaker",{fontCharacter:"\\ea79"}),e.microscope=new e("microscope",{fontCharacter:"\\ea79"}),e.vm=new e("vm",{fontCharacter:"\\ea7a"}),e.deviceDesktop=new e("device-desktop",{fontCharacter:"\\ea7a"}),e.file=new e("file",{fontCharacter:"\\ea7b"}),e.fileText=new e("file-text",{fontCharacter:"\\ea7b"}),e.more=new e("more",{fontCharacter:"\\ea7c"}),e.ellipsis=new e("ellipsis",{fontCharacter:"\\ea7c"}),e.kebabHorizontal=new e("kebab-horizontal",{fontCharacter:"\\ea7c"}),e.mailReply=new e("mail-reply",{fontCharacter:"\\ea7d"}),e.reply=new e("reply",{fontCharacter:"\\ea7d"}),e.organization=new e("organization",{fontCharacter:"\\ea7e"}),e.organizationFilled=new e("organization-filled",{fontCharacter:"\\ea7e"}),e.organizationOutline=new e("organization-outline",{fontCharacter:"\\ea7e"}),e.newFile=new e("new-file",{fontCharacter:"\\ea7f"}),e.fileAdd=new e("file-add",{fontCharacter:"\\ea7f"}),e.newFolder=new e("new-folder",{fontCharacter:"\\ea80"}),e.fileDirectoryCreate=new e("file-directory-create",{fontCharacter:"\\ea80"}),e.trash=new e("trash",{fontCharacter:"\\ea81"}),e.trashcan=new e("trashcan",{fontCharacter:"\\ea81"}),e.history=new e("history",{fontCharacter:"\\ea82"}),e.clock=new e("clock",{fontCharacter:"\\ea82"}),e.folder=new e("folder",{fontCharacter:"\\ea83"}),e.fileDirectory=new e("file-directory",{fontCharacter:"\\ea83"}),e.symbolFolder=new e("symbol-folder",{fontCharacter:"\\ea83"}),e.logoGithub=new e("logo-github",{fontCharacter:"\\ea84"}),e.markGithub=new e("mark-github",{fontCharacter:"\\ea84"}),e.github=new e("github",{fontCharacter:"\\ea84"}),e.terminal=new e("terminal",{fontCharacter:"\\ea85"}),e.console=new e("console",{fontCharacter:"\\ea85"}),e.repl=new e("repl",{fontCharacter:"\\ea85"}),e.zap=new e("zap",{fontCharacter:"\\ea86"}),e.symbolEvent=new e("symbol-event",{fontCharacter:"\\ea86"}),e.error=new e("error",{fontCharacter:"\\ea87"}),e.stop=new e("stop",{fontCharacter:"\\ea87"}),e.variable=new e("variable",{fontCharacter:"\\ea88"}),e.symbolVariable=new e("symbol-variable",{fontCharacter:"\\ea88"}),e.array=new e("array",{fontCharacter:"\\ea8a"}),e.symbolArray=new e("symbol-array",{fontCharacter:"\\ea8a"}),e.symbolModule=new e("symbol-module",{fontCharacter:"\\ea8b"}),e.symbolPackage=new e("symbol-package",{fontCharacter:"\\ea8b"}),e.symbolNamespace=new e("symbol-namespace",{fontCharacter:"\\ea8b"}),e.symbolObject=new e("symbol-object",{fontCharacter:"\\ea8b"}),e.symbolMethod=new e("symbol-method",{fontCharacter:"\\ea8c"}),e.symbolFunction=new e("symbol-function",{fontCharacter:"\\ea8c"}),e.symbolConstructor=new e("symbol-constructor",{fontCharacter:"\\ea8c"}),e.symbolBoolean=new e("symbol-boolean",{fontCharacter:"\\ea8f"}),e.symbolNull=new e("symbol-null",{fontCharacter:"\\ea8f"}),e.symbolNumeric=new e("symbol-numeric",{fontCharacter:"\\ea90"}),e.symbolNumber=new e("symbol-number",{fontCharacter:"\\ea90"}),e.symbolStructure=new e("symbol-structure",{fontCharacter:"\\ea91"}),e.symbolStruct=new e("symbol-struct",{fontCharacter:"\\ea91"}),e.symbolParameter=new e("symbol-parameter",{fontCharacter:"\\ea92"}),e.symbolTypeParameter=new e("symbol-type-parameter",{fontCharacter:"\\ea92"}),e.symbolKey=new e("symbol-key",{fontCharacter:"\\ea93"}),e.symbolText=new e("symbol-text",{fontCharacter:"\\ea93"}),e.symbolReference=new e("symbol-reference",{fontCharacter:"\\ea94"}),e.goToFile=new e("go-to-file",{fontCharacter:"\\ea94"}),e.symbolEnum=new e("symbol-enum",{fontCharacter:"\\ea95"}),e.symbolValue=new e("symbol-value",{fontCharacter:"\\ea95"}),e.symbolRuler=new e("symbol-ruler",{fontCharacter:"\\ea96"}),e.symbolUnit=new e("symbol-unit",{fontCharacter:"\\ea96"}),e.activateBreakpoints=new e("activate-breakpoints",{fontCharacter:"\\ea97"}),e.archive=new e("archive",{fontCharacter:"\\ea98"}),e.arrowBoth=new e("arrow-both",{fontCharacter:"\\ea99"}),e.arrowDown=new e("arrow-down",{fontCharacter:"\\ea9a"}),e.arrowLeft=new e("arrow-left",{fontCharacter:"\\ea9b"}),e.arrowRight=new e("arrow-right",{fontCharacter:"\\ea9c"}),e.arrowSmallDown=new e("arrow-small-down",{fontCharacter:"\\ea9d"}),e.arrowSmallLeft=new e("arrow-small-left",{fontCharacter:"\\ea9e"}),e.arrowSmallRight=new e("arrow-small-right",{fontCharacter:"\\ea9f"}),e.arrowSmallUp=new e("arrow-small-up",{fontCharacter:"\\eaa0"}),e.arrowUp=new e("arrow-up",{fontCharacter:"\\eaa1"}),e.bell=new e("bell",{fontCharacter:"\\eaa2"}),e.bold=new e("bold",{fontCharacter:"\\eaa3"}),e.book=new e("book",{fontCharacter:"\\eaa4"}),e.bookmark=new e("bookmark",{fontCharacter:"\\eaa5"}),e.debugBreakpointConditionalUnverified=new e("debug-breakpoint-conditional-unverified",{fontCharacter:"\\eaa6"}),e.debugBreakpointConditional=new e("debug-breakpoint-conditional",{fontCharacter:"\\eaa7"}),e.debugBreakpointConditionalDisabled=new e("debug-breakpoint-conditional-disabled",{fontCharacter:"\\eaa7"}),e.debugBreakpointDataUnverified=new e("debug-breakpoint-data-unverified",{fontCharacter:"\\eaa8"}),e.debugBreakpointData=new e("debug-breakpoint-data",{fontCharacter:"\\eaa9"}),e.debugBreakpointDataDisabled=new e("debug-breakpoint-data-disabled",{fontCharacter:"\\eaa9"}),e.debugBreakpointLogUnverified=new e("debug-breakpoint-log-unverified",{fontCharacter:"\\eaaa"}),e.debugBreakpointLog=new e("debug-breakpoint-log",{fontCharacter:"\\eaab"}),e.debugBreakpointLogDisabled=new e("debug-breakpoint-log-disabled",{fontCharacter:"\\eaab"}),e.briefcase=new e("briefcase",{fontCharacter:"\\eaac"}),e.broadcast=new e("broadcast",{fontCharacter:"\\eaad"}),e.browser=new e("browser",{fontCharacter:"\\eaae"}),e.bug=new e("bug",{fontCharacter:"\\eaaf"}),e.calendar=new e("calendar",{fontCharacter:"\\eab0"}),e.caseSensitive=new e("case-sensitive",{fontCharacter:"\\eab1"}),e.check=new e("check",{fontCharacter:"\\eab2"}),e.checklist=new e("checklist",{fontCharacter:"\\eab3"}),e.chevronDown=new e("chevron-down",{fontCharacter:"\\eab4"}),e.chevronLeft=new e("chevron-left",{fontCharacter:"\\eab5"}),e.chevronRight=new e("chevron-right",{fontCharacter:"\\eab6"}),e.chevronUp=new e("chevron-up",{fontCharacter:"\\eab7"}),e.chromeClose=new e("chrome-close",{fontCharacter:"\\eab8"}),e.chromeMaximize=new e("chrome-maximize",{fontCharacter:"\\eab9"}),e.chromeMinimize=new e("chrome-minimize",{fontCharacter:"\\eaba"}),e.chromeRestore=new e("chrome-restore",{fontCharacter:"\\eabb"}),e.circleOutline=new e("circle-outline",{fontCharacter:"\\eabc"}),e.debugBreakpointUnverified=new e("debug-breakpoint-unverified",{fontCharacter:"\\eabc"}),e.circleSlash=new e("circle-slash",{fontCharacter:"\\eabd"}),e.circuitBoard=new e("circuit-board",{fontCharacter:"\\eabe"}),e.clearAll=new e("clear-all",{fontCharacter:"\\eabf"}),e.clippy=new e("clippy",{fontCharacter:"\\eac0"}),e.closeAll=new e("close-all",{fontCharacter:"\\eac1"}),e.cloudDownload=new e("cloud-download",{fontCharacter:"\\eac2"}),e.cloudUpload=new e("cloud-upload",{fontCharacter:"\\eac3"}),e.code=new e("code",{fontCharacter:"\\eac4"}),e.collapseAll=new e("collapse-all",{fontCharacter:"\\eac5"}),e.colorMode=new e("color-mode",{fontCharacter:"\\eac6"}),e.commentDiscussion=new e("comment-discussion",{fontCharacter:"\\eac7"}),e.compareChanges=new e("compare-changes",{fontCharacter:"\\eafd"}),e.creditCard=new e("credit-card",{fontCharacter:"\\eac9"}),e.dash=new e("dash",{fontCharacter:"\\eacc"}),e.dashboard=new e("dashboard",{fontCharacter:"\\eacd"}),e.database=new e("database",{fontCharacter:"\\eace"}),e.debugContinue=new e("debug-continue",{fontCharacter:"\\eacf"}),e.debugDisconnect=new e("debug-disconnect",{fontCharacter:"\\ead0"}),e.debugPause=new e("debug-pause",{fontCharacter:"\\ead1"}),e.debugRestart=new e("debug-restart",{fontCharacter:"\\ead2"}),e.debugStart=new e("debug-start",{fontCharacter:"\\ead3"}),e.debugStepInto=new e("debug-step-into",{fontCharacter:"\\ead4"}),e.debugStepOut=new e("debug-step-out",{fontCharacter:"\\ead5"}),e.debugStepOver=new e("debug-step-over",{fontCharacter:"\\ead6"}),e.debugStop=new e("debug-stop",{fontCharacter:"\\ead7"}),e.debug=new e("debug",{fontCharacter:"\\ead8"}),e.deviceCameraVideo=new e("device-camera-video",{fontCharacter:"\\ead9"}),e.deviceCamera=new e("device-camera",{fontCharacter:"\\eada"}),e.deviceMobile=new e("device-mobile",{fontCharacter:"\\eadb"}),e.diffAdded=new e("diff-added",{fontCharacter:"\\eadc"}),e.diffIgnored=new e("diff-ignored",{fontCharacter:"\\eadd"}),e.diffModified=new e("diff-modified",{fontCharacter:"\\eade"}),e.diffRemoved=new e("diff-removed",{fontCharacter:"\\eadf"}),e.diffRenamed=new e("diff-renamed",{fontCharacter:"\\eae0"}),e.diff=new e("diff",{fontCharacter:"\\eae1"}),e.discard=new e("discard",{fontCharacter:"\\eae2"}),e.editorLayout=new e("editor-layout",{fontCharacter:"\\eae3"}),e.emptyWindow=new e("empty-window",{fontCharacter:"\\eae4"}),e.exclude=new e("exclude",{fontCharacter:"\\eae5"}),e.extensions=new e("extensions",{fontCharacter:"\\eae6"}),e.eyeClosed=new e("eye-closed",{fontCharacter:"\\eae7"}),e.fileBinary=new e("file-binary",{fontCharacter:"\\eae8"}),e.fileCode=new e("file-code",{fontCharacter:"\\eae9"}),e.fileMedia=new e("file-media",{fontCharacter:"\\eaea"}),e.filePdf=new e("file-pdf",{fontCharacter:"\\eaeb"}),e.fileSubmodule=new e("file-submodule",{fontCharacter:"\\eaec"}),e.fileSymlinkDirectory=new e("file-symlink-directory",{fontCharacter:"\\eaed"}),e.fileSymlinkFile=new e("file-symlink-file",{fontCharacter:"\\eaee"}),e.fileZip=new e("file-zip",{fontCharacter:"\\eaef"}),e.files=new e("files",{fontCharacter:"\\eaf0"}),e.filter=new e("filter",{fontCharacter:"\\eaf1"}),e.flame=new e("flame",{fontCharacter:"\\eaf2"}),e.foldDown=new e("fold-down",{fontCharacter:"\\eaf3"}),e.foldUp=new e("fold-up",{fontCharacter:"\\eaf4"}),e.fold=new e("fold",{fontCharacter:"\\eaf5"}),e.folderActive=new e("folder-active",{fontCharacter:"\\eaf6"}),e.folderOpened=new e("folder-opened",{fontCharacter:"\\eaf7"}),e.gear=new e("gear",{fontCharacter:"\\eaf8"}),e.gift=new e("gift",{fontCharacter:"\\eaf9"}),e.gistSecret=new e("gist-secret",{fontCharacter:"\\eafa"}),e.gist=new e("gist",{fontCharacter:"\\eafb"}),e.gitCommit=new e("git-commit",{fontCharacter:"\\eafc"}),e.gitCompare=new e("git-compare",{fontCharacter:"\\eafd"}),e.gitMerge=new e("git-merge",{fontCharacter:"\\eafe"}),e.githubAction=new e("github-action",{fontCharacter:"\\eaff"}),e.githubAlt=new e("github-alt",{fontCharacter:"\\eb00"}),e.globe=new e("globe",{fontCharacter:"\\eb01"}),e.grabber=new e("grabber",{fontCharacter:"\\eb02"}),e.graph=new e("graph",{fontCharacter:"\\eb03"}),e.gripper=new e("gripper",{fontCharacter:"\\eb04"}),e.heart=new e("heart",{fontCharacter:"\\eb05"}),e.home=new e("home",{fontCharacter:"\\eb06"}),e.horizontalRule=new e("horizontal-rule",{fontCharacter:"\\eb07"}),e.hubot=new e("hubot",{fontCharacter:"\\eb08"}),e.inbox=new e("inbox",{fontCharacter:"\\eb09"}),e.issueClosed=new e("issue-closed",{fontCharacter:"\\eba4"}),e.issueReopened=new e("issue-reopened",{fontCharacter:"\\eb0b"}),e.issues=new e("issues",{fontCharacter:"\\eb0c"}),e.italic=new e("italic",{fontCharacter:"\\eb0d"}),e.jersey=new e("jersey",{fontCharacter:"\\eb0e"}),e.json=new e("json",{fontCharacter:"\\eb0f"}),e.kebabVertical=new e("kebab-vertical",{fontCharacter:"\\eb10"}),e.key=new e("key",{fontCharacter:"\\eb11"}),e.law=new e("law",{fontCharacter:"\\eb12"}),e.lightbulbAutofix=new e("lightbulb-autofix",{fontCharacter:"\\eb13"}),e.linkExternal=new e("link-external",{fontCharacter:"\\eb14"}),e.link=new e("link",{fontCharacter:"\\eb15"}),e.listOrdered=new e("list-ordered",{fontCharacter:"\\eb16"}),e.listUnordered=new e("list-unordered",{fontCharacter:"\\eb17"}),e.liveShare=new e("live-share",{fontCharacter:"\\eb18"}),e.loading=new e("loading",{fontCharacter:"\\eb19"}),e.location=new e("location",{fontCharacter:"\\eb1a"}),e.mailRead=new e("mail-read",{fontCharacter:"\\eb1b"}),e.mail=new e("mail",{fontCharacter:"\\eb1c"}),e.markdown=new e("markdown",{fontCharacter:"\\eb1d"}),e.megaphone=new e("megaphone",{fontCharacter:"\\eb1e"}),e.mention=new e("mention",{fontCharacter:"\\eb1f"}),e.milestone=new e("milestone",{fontCharacter:"\\eb20"}),e.mortarBoard=new e("mortar-board",{fontCharacter:"\\eb21"}),e.move=new e("move",{fontCharacter:"\\eb22"}),e.multipleWindows=new e("multiple-windows",{fontCharacter:"\\eb23"}),e.mute=new e("mute",{fontCharacter:"\\eb24"}),e.noNewline=new e("no-newline",{fontCharacter:"\\eb25"}),e.note=new e("note",{fontCharacter:"\\eb26"}),e.octoface=new e("octoface",{fontCharacter:"\\eb27"}),e.openPreview=new e("open-preview",{fontCharacter:"\\eb28"}),e.package_=new e("package",{fontCharacter:"\\eb29"}),e.paintcan=new e("paintcan",{fontCharacter:"\\eb2a"}),e.pin=new e("pin",{fontCharacter:"\\eb2b"}),e.play=new e("play",{fontCharacter:"\\eb2c"}),e.run=new e("run",{fontCharacter:"\\eb2c"}),e.plug=new e("plug",{fontCharacter:"\\eb2d"}),e.preserveCase=new e("preserve-case",{fontCharacter:"\\eb2e"}),e.preview=new e("preview",{fontCharacter:"\\eb2f"}),e.project=new e("project",{fontCharacter:"\\eb30"}),e.pulse=new e("pulse",{fontCharacter:"\\eb31"}),e.question=new e("question",{fontCharacter:"\\eb32"}),e.quote=new e("quote",{fontCharacter:"\\eb33"}),e.radioTower=new e("radio-tower",{fontCharacter:"\\eb34"}),e.reactions=new e("reactions",{fontCharacter:"\\eb35"}),e.references=new e("references",{fontCharacter:"\\eb36"}),e.refresh=new e("refresh",{fontCharacter:"\\eb37"}),e.regex=new e("regex",{fontCharacter:"\\eb38"}),e.remoteExplorer=new e("remote-explorer",{fontCharacter:"\\eb39"}),e.remote=new e("remote",{fontCharacter:"\\eb3a"}),e.remove=new e("remove",{fontCharacter:"\\eb3b"}),e.replaceAll=new e("replace-all",{fontCharacter:"\\eb3c"}),e.replace=new e("replace",{fontCharacter:"\\eb3d"}),e.repoClone=new e("repo-clone",{fontCharacter:"\\eb3e"}),e.repoForcePush=new e("repo-force-push",{fontCharacter:"\\eb3f"}),e.repoPull=new e("repo-pull",{fontCharacter:"\\eb40"}),e.repoPush=new e("repo-push",{fontCharacter:"\\eb41"}),e.report=new e("report",{fontCharacter:"\\eb42"}),e.requestChanges=new e("request-changes",{fontCharacter:"\\eb43"}),e.rocket=new e("rocket",{fontCharacter:"\\eb44"}),e.rootFolderOpened=new e("root-folder-opened",{fontCharacter:"\\eb45"}),e.rootFolder=new e("root-folder",{fontCharacter:"\\eb46"}),e.rss=new e("rss",{fontCharacter:"\\eb47"}),e.ruby=new e("ruby",{fontCharacter:"\\eb48"}),e.saveAll=new e("save-all",{fontCharacter:"\\eb49"}),e.saveAs=new e("save-as",{fontCharacter:"\\eb4a"}),e.save=new e("save",{fontCharacter:"\\eb4b"}),e.screenFull=new e("screen-full",{fontCharacter:"\\eb4c"}),e.screenNormal=new e("screen-normal",{fontCharacter:"\\eb4d"}),e.searchStop=new e("search-stop",{fontCharacter:"\\eb4e"}),e.server=new e("server",{fontCharacter:"\\eb50"}),e.settingsGear=new e("settings-gear",{fontCharacter:"\\eb51"}),e.settings=new e("settings",{fontCharacter:"\\eb52"}),e.shield=new e("shield",{fontCharacter:"\\eb53"}),e.smiley=new e("smiley",{fontCharacter:"\\eb54"}),e.sortPrecedence=new e("sort-precedence",{fontCharacter:"\\eb55"}),e.splitHorizontal=new e("split-horizontal",{fontCharacter:"\\eb56"}),e.splitVertical=new e("split-vertical",{fontCharacter:"\\eb57"}),e.squirrel=new e("squirrel",{fontCharacter:"\\eb58"}),e.starFull=new e("star-full",{fontCharacter:"\\eb59"}),e.starHalf=new e("star-half",{fontCharacter:"\\eb5a"}),e.symbolClass=new e("symbol-class",{fontCharacter:"\\eb5b"}),e.symbolColor=new e("symbol-color",{fontCharacter:"\\eb5c"}),e.symbolConstant=new e("symbol-constant",{fontCharacter:"\\eb5d"}),e.symbolEnumMember=new e("symbol-enum-member",{fontCharacter:"\\eb5e"}),e.symbolField=new e("symbol-field",{fontCharacter:"\\eb5f"}),e.symbolFile=new e("symbol-file",{fontCharacter:"\\eb60"}),e.symbolInterface=new e("symbol-interface",{fontCharacter:"\\eb61"}),e.symbolKeyword=new e("symbol-keyword",{fontCharacter:"\\eb62"}),e.symbolMisc=new e("symbol-misc",{fontCharacter:"\\eb63"}),e.symbolOperator=new e("symbol-operator",{fontCharacter:"\\eb64"}),e.symbolProperty=new e("symbol-property",{fontCharacter:"\\eb65"}),e.wrench=new e("wrench",{fontCharacter:"\\eb65"}),e.wrenchSubaction=new e("wrench-subaction",{fontCharacter:"\\eb65"}),e.symbolSnippet=new e("symbol-snippet",{fontCharacter:"\\eb66"}),e.tasklist=new e("tasklist",{fontCharacter:"\\eb67"}),e.telescope=new e("telescope",{fontCharacter:"\\eb68"}),e.textSize=new e("text-size",{fontCharacter:"\\eb69"}),e.threeBars=new e("three-bars",{fontCharacter:"\\eb6a"}),e.thumbsdown=new e("thumbsdown",{fontCharacter:"\\eb6b"}),e.thumbsup=new e("thumbsup",{fontCharacter:"\\eb6c"}),e.tools=new e("tools",{fontCharacter:"\\eb6d"}),e.triangleDown=new e("triangle-down",{fontCharacter:"\\eb6e"}),e.triangleLeft=new e("triangle-left",{fontCharacter:"\\eb6f"}),e.triangleRight=new e("triangle-right",{fontCharacter:"\\eb70"}),e.triangleUp=new e("triangle-up",{fontCharacter:"\\eb71"}),e.twitter=new e("twitter",{fontCharacter:"\\eb72"}),e.unfold=new e("unfold",{fontCharacter:"\\eb73"}),e.unlock=new e("unlock",{fontCharacter:"\\eb74"}),e.unmute=new e("unmute",{fontCharacter:"\\eb75"}),e.unverified=new e("unverified",{fontCharacter:"\\eb76"}),e.verified=new e("verified",{fontCharacter:"\\eb77"}),e.versions=new e("versions",{fontCharacter:"\\eb78"}),e.vmActive=new e("vm-active",{fontCharacter:"\\eb79"}),e.vmOutline=new e("vm-outline",{fontCharacter:"\\eb7a"}),e.vmRunning=new e("vm-running",{fontCharacter:"\\eb7b"}),e.watch=new e("watch",{fontCharacter:"\\eb7c"}),e.whitespace=new e("whitespace",{fontCharacter:"\\eb7d"}),e.wholeWord=new e("whole-word",{fontCharacter:"\\eb7e"}),e.window=new e("window",{fontCharacter:"\\eb7f"}),e.wordWrap=new e("word-wrap",{fontCharacter:"\\eb80"}),e.zoomIn=new e("zoom-in",{fontCharacter:"\\eb81"}),e.zoomOut=new e("zoom-out",{fontCharacter:"\\eb82"}),e.listFilter=new e("list-filter",{fontCharacter:"\\eb83"}),e.listFlat=new e("list-flat",{fontCharacter:"\\eb84"}),e.listSelection=new e("list-selection",{fontCharacter:"\\eb85"}),e.selection=new e("selection",{fontCharacter:"\\eb85"}),e.listTree=new e("list-tree",{fontCharacter:"\\eb86"}),e.debugBreakpointFunctionUnverified=new e("debug-breakpoint-function-unverified",{fontCharacter:"\\eb87"}),e.debugBreakpointFunction=new e("debug-breakpoint-function",{fontCharacter:"\\eb88"}),e.debugBreakpointFunctionDisabled=new e("debug-breakpoint-function-disabled",{fontCharacter:"\\eb88"}),e.debugStackframeActive=new e("debug-stackframe-active",{fontCharacter:"\\eb89"}),e.debugStackframeDot=new e("debug-stackframe-dot",{fontCharacter:"\\eb8a"}),e.debugStackframe=new e("debug-stackframe",{fontCharacter:"\\eb8b"}),e.debugStackframeFocused=new e("debug-stackframe-focused",{fontCharacter:"\\eb8b"}),e.debugBreakpointUnsupported=new e("debug-breakpoint-unsupported",{fontCharacter:"\\eb8c"}),e.symbolString=new e("symbol-string",{fontCharacter:"\\eb8d"}),e.debugReverseContinue=new e("debug-reverse-continue",{fontCharacter:"\\eb8e"}),e.debugStepBack=new e("debug-step-back",{fontCharacter:"\\eb8f"}),e.debugRestartFrame=new e("debug-restart-frame",{fontCharacter:"\\eb90"}),e.callIncoming=new e("call-incoming",{fontCharacter:"\\eb92"}),e.callOutgoing=new e("call-outgoing",{fontCharacter:"\\eb93"}),e.menu=new e("menu",{fontCharacter:"\\eb94"}),e.expandAll=new e("expand-all",{fontCharacter:"\\eb95"}),e.feedback=new e("feedback",{fontCharacter:"\\eb96"}),e.groupByRefType=new e("group-by-ref-type",{fontCharacter:"\\eb97"}),e.ungroupByRefType=new e("ungroup-by-ref-type",{fontCharacter:"\\eb98"}),e.account=new e("account",{fontCharacter:"\\eb99"}),e.bellDot=new e("bell-dot",{fontCharacter:"\\eb9a"}),e.debugConsole=new e("debug-console",{fontCharacter:"\\eb9b"}),e.library=new e("library",{fontCharacter:"\\eb9c"}),e.output=new e("output",{fontCharacter:"\\eb9d"}),e.runAll=new e("run-all",{fontCharacter:"\\eb9e"}),e.syncIgnored=new e("sync-ignored",{fontCharacter:"\\eb9f"}),e.pinned=new e("pinned",{fontCharacter:"\\eba0"}),e.githubInverted=new e("github-inverted",{fontCharacter:"\\eba1"}),e.debugAlt=new e("debug-alt",{fontCharacter:"\\eb91"}),e.serverProcess=new e("server-process",{fontCharacter:"\\eba2"}),e.serverEnvironment=new e("server-environment",{fontCharacter:"\\eba3"}),e.pass=new e("pass",{fontCharacter:"\\eba4"}),e.stopCircle=new e("stop-circle",{fontCharacter:"\\eba5"}),e.playCircle=new e("play-circle",{fontCharacter:"\\eba6"}),e.record=new e("record",{fontCharacter:"\\eba7"}),e.debugAltSmall=new e("debug-alt-small",{fontCharacter:"\\eba8"}),e.vmConnect=new e("vm-connect",{fontCharacter:"\\eba9"}),e.cloud=new e("cloud",{fontCharacter:"\\ebaa"}),e.merge=new e("merge",{fontCharacter:"\\ebab"}),e.exportIcon=new e("export",{fontCharacter:"\\ebac"}),e.graphLeft=new e("graph-left",{fontCharacter:"\\ebad"}),e.magnet=new e("magnet",{fontCharacter:"\\ebae"}),e.notebook=new e("notebook",{fontCharacter:"\\ebaf"}),e.redo=new e("redo",{fontCharacter:"\\ebb0"}),e.checkAll=new e("check-all",{fontCharacter:"\\ebb1"}),e.pinnedDirty=new e("pinned-dirty",{fontCharacter:"\\ebb2"}),e.passFilled=new e("pass-filled",{fontCharacter:"\\ebb3"}),e.circleLargeFilled=new e("circle-large-filled",{fontCharacter:"\\ebb4"}),e.circleLargeOutline=new e("circle-large-outline",{fontCharacter:"\\ebb5"}),e.combine=new e("combine",{fontCharacter:"\\ebb6"}),e.gather=new e("gather",{fontCharacter:"\\ebb6"}),e.table=new e("table",{fontCharacter:"\\ebb7"}),e.variableGroup=new e("variable-group",{fontCharacter:"\\ebb8"}),e.typeHierarchy=new e("type-hierarchy",{fontCharacter:"\\ebb9"}),e.typeHierarchySub=new e("type-hierarchy-sub",{fontCharacter:"\\ebba"}),e.typeHierarchySuper=new e("type-hierarchy-super",{fontCharacter:"\\ebbb"}),e.gitPullRequestCreate=new e("git-pull-request-create",{fontCharacter:"\\ebbc"}),e.runAbove=new e("run-above",{fontCharacter:"\\ebbd"}),e.runBelow=new e("run-below",{fontCharacter:"\\ebbe"}),e.notebookTemplate=new e("notebook-template",{fontCharacter:"\\ebbf"}),e.debugRerun=new e("debug-rerun",{fontCharacter:"\\ebc0"}),e.workspaceTrusted=new e("workspace-trusted",{fontCharacter:"\\ebc1"}),e.workspaceUntrusted=new e("workspace-untrusted",{fontCharacter:"\\ebc2"}),e.workspaceUnspecified=new e("workspace-unspecified",{fontCharacter:"\\ebc3"}),e.terminalCmd=new e("terminal-cmd",{fontCharacter:"\\ebc4"}),e.terminalDebian=new e("terminal-debian",{fontCharacter:"\\ebc5"}),e.terminalLinux=new e("terminal-linux",{fontCharacter:"\\ebc6"}),e.terminalPowershell=new e("terminal-powershell",{fontCharacter:"\\ebc7"}),e.terminalTmux=new e("terminal-tmux",{fontCharacter:"\\ebc8"}),e.terminalUbuntu=new e("terminal-ubuntu",{fontCharacter:"\\ebc9"}),e.terminalBash=new e("terminal-bash",{fontCharacter:"\\ebca"}),e.arrowSwap=new e("arrow-swap",{fontCharacter:"\\ebcb"}),e.copy=new e("copy",{fontCharacter:"\\ebcc"}),e.personAdd=new e("person-add",{fontCharacter:"\\ebcd"}),e.filterFilled=new e("filter-filled",{fontCharacter:"\\ebce"}),e.wand=new e("wand",{fontCharacter:"\\ebcf"}),e.debugLineByLine=new e("debug-line-by-line",{fontCharacter:"\\ebd0"}),e.inspect=new e("inspect",{fontCharacter:"\\ebd1"}),e.layers=new e("layers",{fontCharacter:"\\ebd2"}),e.layersDot=new e("layers-dot",{fontCharacter:"\\ebd3"}),e.layersActive=new e("layers-active",{fontCharacter:"\\ebd4"}),e.compass=new e("compass",{fontCharacter:"\\ebd5"}),e.compassDot=new e("compass-dot",{fontCharacter:"\\ebd6"}),e.compassActive=new e("compass-active",{fontCharacter:"\\ebd7"}),e.azure=new e("azure",{fontCharacter:"\\ebd8"}),e.issueDraft=new e("issue-draft",{fontCharacter:"\\ebd9"}),e.gitPullRequestClosed=new e("git-pull-request-closed",{fontCharacter:"\\ebda"}),e.gitPullRequestDraft=new e("git-pull-request-draft",{fontCharacter:"\\ebdb"}),e.debugAll=new e("debug-all",{fontCharacter:"\\ebdc"}),e.debugCoverage=new e("debug-coverage",{fontCharacter:"\\ebdd"}),e.dropDownButton=new e("drop-down-button",e.chevronDown.definition)}(It||(It={})),Object.prototype.hasOwnProperty;class At{constructor(e,t,n,r=1){this._rgbaBrand=void 0,this.r=0|Math.min(255,Math.max(0,e)),this.g=0|Math.min(255,Math.max(0,t)),this.b=0|Math.min(255,Math.max(0,n)),this.a=Ot(Math.max(Math.min(1,r),0),3)}static equals(e,t){return e.r===t.r&&e.g===t.g&&e.b===t.b&&e.a===t.a}}class Dt{constructor(e,t,n,r){this._hslaBrand=void 0,this.h=0|Math.max(Math.min(360,e),0),this.s=Ot(Math.max(Math.min(1,t),0),3),this.l=Ot(Math.max(Math.min(1,n),0),3),this.a=Ot(Math.max(Math.min(1,r),0),3)}static equals(e,t){return e.h===t.h&&e.s===t.s&&e.l===t.l&&e.a===t.a}static fromRGBA(e){const t=e.r/255,n=e.g/255,r=e.b/255,i=e.a,s=Math.max(t,n,r),o=Math.min(t,n,r);let a=0,c=0;const l=(o+s)/2,d=s-o;if(d>0){switch(c=Math.min(l<=.5?d/(2*l):d/(2-2*l),1),s){case t:a=(n-r)/d+(n<r?6:0);break;case n:a=(r-t)/d+2;break;case r:a=(t-n)/d+4}a*=60,a=Math.round(a)}return new Dt(a,c,l,i)}static _hue2rgb(e,t,n){return n<0&&(n+=1),n>1&&(n-=1),n<1/6?e+6*(t-e)*n:n<.5?t:n<2/3?e+(t-e)*(2/3-n)*6:e}static toRGBA(e){const t=e.h/360,{s:n,l:r,a:i}=e;let s,o,a;if(0===n)s=o=a=r;else{const e=r<.5?r*(1+n):r+n-r*n,i=2*r-e;s=Dt._hue2rgb(i,e,t+1/3),o=Dt._hue2rgb(i,e,t),a=Dt._hue2rgb(i,e,t-1/3)}return new At(Math.round(255*s),Math.round(255*o),Math.round(255*a),i)}}class Mt{constructor(e,t,n,r){this._hsvaBrand=void 0,this.h=0|Math.max(Math.min(360,e),0),this.s=Ot(Math.max(Math.min(1,t),0),3),this.v=Ot(Math.max(Math.min(1,n),0),3),this.a=Ot(Math.max(Math.min(1,r),0),3)}static equals(e,t){return e.h===t.h&&e.s===t.s&&e.v===t.v&&e.a===t.a}static fromRGBA(e){const t=e.r/255,n=e.g/255,r=e.b/255,i=Math.max(t,n,r),s=i-Math.min(t,n,r),o=0===i?0:s/i;let a;return a=0===s?0:i===t?((n-r)/s%6+6)%6:i===n?(r-t)/s+2:(t-n)/s+4,new Mt(Math.round(60*a),o,i,e.a)}static toRGBA(e){const{h:t,s:n,v:r,a:i}=e,s=r*n,o=s*(1-Math.abs(t/60%2-1)),a=r-s;let[c,l,d]=[0,0,0];return t<60?(c=s,l=o):t<120?(c=o,l=s):t<180?(l=s,d=o):t<240?(l=o,d=s):t<300?(c=o,d=s):t<=360&&(c=s,d=o),c=Math.round(255*(c+a)),l=Math.round(255*(l+a)),d=Math.round(255*(d+a)),new At(c,l,d,i)}}class Pt{constructor(e){if(!e)throw new Error("Color needs a value");if(e instanceof At)this.rgba=e;else if(e instanceof Dt)this._hsla=e,this.rgba=Dt.toRGBA(e);else{if(!(e instanceof Mt))throw new Error("Invalid color ctor argument");this._hsva=e,this.rgba=Mt.toRGBA(e)}}static fromHex(e){return Pt.Format.CSS.parseHex(e)||Pt.red}get hsla(){return this._hsla?this._hsla:Dt.fromRGBA(this.rgba)}get hsva(){return this._hsva?this._hsva:Mt.fromRGBA(this.rgba)}equals(e){return!!e&&At.equals(this.rgba,e.rgba)&&Dt.equals(this.hsla,e.hsla)&&Mt.equals(this.hsva,e.hsva)}getRelativeLuminance(){return Ot(.2126*Pt._relativeLuminanceForComponent(this.rgba.r)+.7152*Pt._relativeLuminanceForComponent(this.rgba.g)+.0722*Pt._relativeLuminanceForComponent(this.rgba.b),4)}static _relativeLuminanceForComponent(e){const t=e/255;return t<=.03928?t/12.92:Math.pow((t+.055)/1.055,2.4)}getContrastRatio(e){const t=this.getRelativeLuminance(),n=e.getRelativeLuminance();return t>n?(t+.05)/(n+.05):(n+.05)/(t+.05)}isDarker(){return(299*this.rgba.r+587*this.rgba.g+114*this.rgba.b)/1e3<128}isLighter(){return(299*this.rgba.r+587*this.rgba.g+114*this.rgba.b)/1e3>=128}isLighterThan(e){return this.getRelativeLuminance()>e.getRelativeLuminance()}isDarkerThan(e){return this.getRelativeLuminance()<e.getRelativeLuminance()}lighten(e){return new Pt(new Dt(this.hsla.h,this.hsla.s,this.hsla.l+this.hsla.l*e,this.hsla.a))}darken(e){return new Pt(new Dt(this.hsla.h,this.hsla.s,this.hsla.l-this.hsla.l*e,this.hsla.a))}transparent(e){const{r:t,g:n,b:r,a:i}=this.rgba;return new Pt(new At(t,n,r,i*e))}isTransparent(){return 0===this.rgba.a}isOpaque(){return 1===this.rgba.a}opposite(){return new Pt(new At(255-this.rgba.r,255-this.rgba.g,255-this.rgba.b,this.rgba.a))}blend(e){const t=e.rgba,n=this.rgba.a,r=t.a,i=n+r*(1-n);if(i<1e-6)return Pt.transparent;const s=this.rgba.r*n/i+t.r*r*(1-n)/i,o=this.rgba.g*n/i+t.g*r*(1-n)/i,a=this.rgba.b*n/i+t.b*r*(1-n)/i;return new Pt(new At(s,o,a,i))}makeOpaque(e){if(this.isOpaque()||1!==e.rgba.a)return this;const{r:t,g:n,b:r,a:i}=this.rgba;return new Pt(new At(e.rgba.r-i*(e.rgba.r-t),e.rgba.g-i*(e.rgba.g-n),e.rgba.b-i*(e.rgba.b-r),1))}flatten(...e){const t=e.reduceRight(((e,t)=>Pt._flatten(t,e)));return Pt._flatten(this,t)}static _flatten(e,t){const n=1-e.rgba.a;return new Pt(new At(n*t.rgba.r+e.rgba.a*e.rgba.r,n*t.rgba.g+e.rgba.a*e.rgba.g,n*t.rgba.b+e.rgba.a*e.rgba.b))}toString(){return""+Pt.Format.CSS.format(this)}static getLighterColor(e,t,n){if(e.isLighterThan(t))return e;n=n||.5;const r=e.getRelativeLuminance(),i=t.getRelativeLuminance();return n=n*(i-r)/i,e.lighten(n)}static getDarkerColor(e,t,n){if(e.isDarkerThan(t))return e;n=n||.5;const r=e.getRelativeLuminance();return n=n*(r-t.getRelativeLuminance())/r,e.darken(n)}}function Ut(e,t,n){let r=null,i=null;if("function"==typeof n.value?(r="value",i=n.value,0!==i.length&&console.warn("Memoize should only be used in functions with zero parameters")):"function"==typeof n.get&&(r="get",i=n.get),!i)throw new Error("not supported");const s=`$memoize$${t}`;n[r]=function(...e){return this.hasOwnProperty(s)||Object.defineProperty(this,s,{configurable:!1,enumerable:!1,writable:!1,value:i.apply(this,e)}),this[s]}}let Lt;var Nt,xt,Bt,jt;Pt.white=new Pt(new At(255,255,255,1)),Pt.black=new Pt(new At(0,0,0,1)),Pt.red=new Pt(new At(255,0,0,1)),Pt.blue=new Pt(new At(0,0,255,1)),Pt.green=new Pt(new At(0,255,0,1)),Pt.cyan=new Pt(new At(0,255,255,1)),Pt.lightgrey=new Pt(new At(211,211,211,1)),Pt.transparent=new Pt(new At(0,0,0,0)),function(e){var t;!function(t){function n(e){const t=e.toString(16);return 2!==t.length?"0"+t:t}function r(e){switch(e){case 48:return 0;case 49:return 1;case 50:return 2;case 51:return 3;case 52:return 4;case 53:return 5;case 54:return 6;case 55:return 7;case 56:return 8;case 57:return 9;case 97:case 65:return 10;case 98:case 66:return 11;case 99:case 67:return 12;case 100:case 68:return 13;case 101:case 69:return 14;case 102:case 70:return 15}return 0}t.formatRGB=function(t){return 1===t.rgba.a?`rgb(${t.rgba.r}, ${t.rgba.g}, ${t.rgba.b})`:e.Format.CSS.formatRGBA(t)},t.formatRGBA=function(e){return`rgba(${e.rgba.r}, ${e.rgba.g}, ${e.rgba.b}, ${+e.rgba.a.toFixed(2)})`},t.formatHSL=function(t){return 1===t.hsla.a?`hsl(${t.hsla.h}, ${(100*t.hsla.s).toFixed(2)}%, ${(100*t.hsla.l).toFixed(2)}%)`:e.Format.CSS.formatHSLA(t)},t.formatHSLA=function(e){return`hsla(${e.hsla.h}, ${(100*e.hsla.s).toFixed(2)}%, ${(100*e.hsla.l).toFixed(2)}%, ${e.hsla.a.toFixed(2)})`},t.formatHex=function(e){return`#${n(e.rgba.r)}${n(e.rgba.g)}${n(e.rgba.b)}`},t.formatHexA=function(t,r=!1){return r&&1===t.rgba.a?e.Format.CSS.formatHex(t):`#${n(t.rgba.r)}${n(t.rgba.g)}${n(t.rgba.b)}${n(Math.round(255*t.rgba.a))}`},t.format=function(t){return t.isOpaque()?e.Format.CSS.formatHex(t):e.Format.CSS.formatRGBA(t)},t.parseHex=function(t){const n=t.length;if(0===n)return null;if(35!==t.charCodeAt(0))return null;if(7===n){const n=16*r(t.charCodeAt(1))+r(t.charCodeAt(2)),i=16*r(t.charCodeAt(3))+r(t.charCodeAt(4)),s=16*r(t.charCodeAt(5))+r(t.charCodeAt(6));return new e(new At(n,i,s,1))}if(9===n){const n=16*r(t.charCodeAt(1))+r(t.charCodeAt(2)),i=16*r(t.charCodeAt(3))+r(t.charCodeAt(4)),s=16*r(t.charCodeAt(5))+r(t.charCodeAt(6)),o=16*r(t.charCodeAt(7))+r(t.charCodeAt(8));return new e(new At(n,i,s,o/255))}if(4===n){const n=r(t.charCodeAt(1)),i=r(t.charCodeAt(2)),s=r(t.charCodeAt(3));return new e(new At(16*n+n,16*i+i,16*s+s))}if(5===n){const n=r(t.charCodeAt(1)),i=r(t.charCodeAt(2)),s=r(t.charCodeAt(3)),o=r(t.charCodeAt(4));return new e(new At(16*n+n,16*i+i,16*s+s,(16*o+o)/255))}return null}}((t=e.Format||(e.Format={})).CSS||(t.CSS={}))}(Pt||(Pt={})),new St((()=>{const e=new Intl.Collator(void 0,{numeric:!0,sensitivity:"base"});return{collator:e,collatorIsNumeric:e.resolvedOptions().numeric}})),new St((()=>({collator:new Intl.Collator(void 0,{numeric:!0})}))),new St((()=>({collator:new Intl.Collator(void 0,{numeric:!0,sensitivity:"accent"})}))),function(e){e[e.Scheme=1]="Scheme",e[e.Authority=2]="Authority",e[e.Path=3]="Path",e[e.Query=4]="Query",e[e.Fragment=5]="Fragment"}(Bt||(Bt={})),Symbol.iterator;class Ft{constructor(e,t){this[Nt]="ResourceMap",e instanceof Ft?(this.map=new Map(e.map),this.toKey=null!=t?t:Ft.defaultToKey):(this.map=new Map,this.toKey=null!=e?e:Ft.defaultToKey)}set(e,t){return this.map.set(this.toKey(e),t),this}get(e){return this.map.get(this.toKey(e))}has(e){return this.map.has(this.toKey(e))}get size(){return this.map.size}clear(){this.map.clear()}delete(e){return this.map.delete(this.toKey(e))}forEach(e,t){void 0!==t&&(e=e.bind(t));for(let[t,n]of this.map)e(n,nt.parse(t),this)}values(){return this.map.values()}*keys(){for(let e of this.map.keys())yield nt.parse(e)}*entries(){for(let e of this.map.entries())yield[nt.parse(e[0]),e[1]]}*[(Nt=Symbol.toStringTag,Symbol.iterator)](){for(let e of this.map)yield[nt.parse(e[0]),e[1]]}}Ft.defaultToKey=e=>e.toString(),function(e){e[e.None=0]="None",e[e.AsOld=1]="AsOld",e[e.AsNew=2]="AsNew"}(jt||(jt={}));class Kt{constructor(){this[xt]="LinkedMap",this._map=new Map,this._head=void 0,this._tail=void 0,this._size=0,this._state=0}clear(){this._map.clear(),this._head=void 0,this._tail=void 0,this._size=0,this._state++}isEmpty(){return!this._head&&!this._tail}get size(){return this._size}get first(){var e;return null==(e=this._head)?void 0:e.value}get last(){var e;return null==(e=this._tail)?void 0:e.value}has(e){return this._map.has(e)}get(e,t=0){const n=this._map.get(e);if(n)return 0!==t&&this.touch(n,t),n.value}set(e,t,n=0){let r=this._map.get(e);if(r)r.value=t,0!==n&&this.touch(r,n);else{switch(r={key:e,value:t,next:void 0,previous:void 0},n){case 0:case 2:default:this.addItemLast(r);break;case 1:this.addItemFirst(r)}this._map.set(e,r),this._size++}return this}delete(e){return!!this.remove(e)}remove(e){const t=this._map.get(e);if(t)return this._map.delete(e),this.removeItem(t),this._size--,t.value}shift(){if(!this._head&&!this._tail)return;if(!this._head||!this._tail)throw new Error("Invalid list");const e=this._head;return this._map.delete(e.key),this.removeItem(e),this._size--,e.value}forEach(e,t){const n=this._state;let r=this._head;for(;r;){if(t?e.bind(t)(r.value,r.key,this):e(r.value,r.key,this),this._state!==n)throw new Error("LinkedMap got modified during iteration.");r=r.next}}keys(){const e=this,t=this._state;let n=this._head;const r={[Symbol.iterator]:()=>r,next(){if(e._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){const e={value:n.key,done:!1};return n=n.next,e}return{value:void 0,done:!0}}};return r}values(){const e=this,t=this._state;let n=this._head;const r={[Symbol.iterator]:()=>r,next(){if(e._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){const e={value:n.value,done:!1};return n=n.next,e}return{value:void 0,done:!0}}};return r}entries(){const e=this,t=this._state;let n=this._head;const r={[Symbol.iterator]:()=>r,next(){if(e._state!==t)throw new Error("LinkedMap got modified during iteration.");if(n){const e={value:[n.key,n.value],done:!1};return n=n.next,e}return{value:void 0,done:!0}}};return r}[(xt=Symbol.toStringTag,Symbol.iterator)](){return this.entries()}trimOld(e){if(e>=this.size)return;if(0===e)return void this.clear();let t=this._head,n=this.size;for(;t&&n>e;)this._map.delete(t.key),t=t.next,n--;this._head=t,this._size=n,t&&(t.previous=void 0),this._state++}addItemFirst(e){if(this._head||this._tail){if(!this._head)throw new Error("Invalid list");e.next=this._head,this._head.previous=e}else this._tail=e;this._head=e,this._state++}addItemLast(e){if(this._head||this._tail){if(!this._tail)throw new Error("Invalid list");e.previous=this._tail,this._tail.next=e}else this._head=e;this._tail=e,this._state++}removeItem(e){if(e===this._head&&e===this._tail)this._head=void 0,this._tail=void 0;else if(e===this._head){if(!e.next)throw new Error("Invalid list");e.next.previous=void 0,this._head=e.next}else if(e===this._tail){if(!e.previous)throw new Error("Invalid list");e.previous.next=void 0,this._tail=e.previous}else{const t=e.next,n=e.previous;if(!t||!n)throw new Error("Invalid list");t.previous=n,n.next=t}e.next=void 0,e.previous=void 0,this._state++}touch(e,t){if(!this._head||!this._tail)throw new Error("Invalid list");if(1===t||2===t)if(1===t){if(e===this._head)return;const t=e.next,n=e.previous;e===this._tail?(n.next=void 0,this._tail=n):(t.previous=n,n.next=t),e.previous=void 0,e.next=this._head,this._head.previous=e,this._head=e,this._state++}else if(2===t){if(e===this._tail)return;const t=e.next,n=e.previous;e===this._head?(t.previous=void 0,this._head=t):(t.previous=n,n.next=t),e.next=void 0,e.previous=this._tail,this._tail.next=e,this._tail=e,this._state++}}toJSON(){const e=[];return this.forEach(((t,n)=>{e.push([n,t])})),e}fromJSON(e){this.clear();for(const[t,n]of e)this.set(t,n)}}class qt extends Kt{constructor(e,t=1){super(),this._limit=e,this._ratio=Math.min(Math.max(0,t),1)}get limit(){return this._limit}set limit(e){this._limit=e,this.checkTrim()}get ratio(){return this._ratio}set ratio(e){this._ratio=Math.min(Math.max(0,e),1),this.checkTrim()}get(e,t=2){return super.get(e,t)}peek(e){return super.get(e,0)}set(e,t){return super.set(e,t,2),this.checkTrim(),this}checkTrim(){this.size>this._limit&&this.trimOld(Math.round(this._limit*this._ratio))}}function $t(...e){return function(t,n){for(let r=0,i=e.length;r<i;r++){const i=e[r](t,n);if(i)return i}return null}}Lt=Symbol.iterator,Gt.bind(void 0,!1);const Vt=Gt.bind(void 0,!0);function Gt(e,t,n){if(!n||n.length<t.length)return null;let r;return r=e?be(n,t):0===n.indexOf(t),r?t.length>0?[{start:0,end:t.length}]:[]:null}function Wt(e,t,n,r){if(n===e.length)return[];if(r===t.length)return null;if(e[n]===t[r]){let i=null;return(i=Wt(e,t,n+1,r+1))?Zt({start:r,end:r+1},i):null}return Wt(e,t,n,r+1)}function Ht(e){return 97<=e&&e<=122}function Yt(e){return 65<=e&&e<=90}function zt(e){return 48<=e&&e<=57}function Jt(e){return 32===e||9===e||10===e||13===e}const Qt=new Set;function Xt(e){return Ht(e)||Yt(e)||zt(e)}function Zt(e,t){return 0===t.length?t=[e]:e.end===t[0].start?t[0].start=e.start:t.unshift(e),t}function en(e,t){for(let n=t;n<e.length;n++){const t=e.charCodeAt(n);if(Yt(t)||zt(t)||n>0&&!Xt(e.charCodeAt(n-1)))return n}return e.length}function tn(e,t,n,r){if(n===e.length)return[];if(r===t.length)return null;if(e[n]!==t[r].toLowerCase())return null;{let i=null,s=r+1;for(i=tn(e,t,n+1,r+1);!i&&(s=en(t,s))<t.length;)i=tn(e,t,n+1,s),s++;return null===i?null:Zt({start:r,end:r+1},i)}}function nn(e,t){if(!t)return null;if(0===(t=t.trim()).length)return null;if(!function(e){let t=0,n=0,r=0,i=0;for(let s=0;s<e.length;s++)r=e.charCodeAt(s),Yt(r)&&t++,Ht(r)&&n++,Jt(r)&&i++;return 0!==t&&0!==n||0!==i?t<=5:e.length<=30}(e))return null;if(t.length>60)return null;const n=function(e){let t=0,n=0,r=0,i=0,s=0;for(let o=0;o<e.length;o++)s=e.charCodeAt(o),Yt(s)&&t++,Ht(s)&&n++,Xt(s)&&r++,zt(s)&&i++;return{upperPercent:t/e.length,lowerPercent:n/e.length,alphaPercent:r/e.length,numericPercent:i/e.length}}(t);if(!function(e){const{upperPercent:t,lowerPercent:n,alphaPercent:r,numericPercent:i}=e;return n>.2&&t<.8&&r>.6&&i<.2}(n)){if(!function(e){const{upperPercent:t,lowerPercent:n}=e;return 0===n&&t>.6}(n))return null;t=t.toLowerCase()}let r=null,i=0;for(e=e.toLowerCase();i<t.length&&null===(r=tn(e,t,0,i));)i=en(t,i+1);return r}"`~!@#$%^&*()-=+[{]}\\|;:'\",.<>/?".split("").forEach((e=>Qt.add(e.charCodeAt(0)))),$t(Vt,nn,(function(e,t){const n=t.toLowerCase().indexOf(e.toLowerCase());return-1===n?null:[{start:n,end:n+e.length}]})),$t(Vt,nn,(function(e,t){return Wt(e.toLowerCase(),t.toLowerCase(),0,0)})),new qt(1e4);const rn=128;function sn(){const e=[],t=[];for(let e=0;e<=rn;e++)t[e]=0;for(let n=0;n<=rn;n++)e.push(t.slice(0));return e}function on(e){const t=[];for(let n=0;n<=e;n++)t[n]=0;return t}var an,cn,ln;function dn(e,t,n=32){const r=n-t;return(e<<t|(~((1<<r)-1)&e)>>>r)>>>0}function un(e,t=0,n=e.byteLength,r=0){for(let i=0;i<n;i++)e[t+i]=r}function hn(e,t=32){return e instanceof ArrayBuffer?Array.from(new Uint8Array(e)).map((e=>e.toString(16).padStart(2,"0"))).join(""):function(e,t,n="0"){for(;e.length<t;)e=n+e;return e}((e>>>0).toString(16),t/4)}on(256),on(256),sn(),sn(),sn(),function(e){e[e.Diag=1]="Diag",e[e.Left=2]="Left",e[e.LeftLeft=3]="LeftLeft"}(an||(an={})),function(e){e.Default=[-100,0],e.isDefault=function(e){return!e||2===e.length&&-100===e[0]&&0===e[1]}}(cn||(cn={})),Object.freeze({score:0}),new qt(1e4),function(e){e[e.BLOCK_SIZE=64]="BLOCK_SIZE",e[e.UNICODE_REPLACEMENT=65533]="UNICODE_REPLACEMENT"}(ln||(ln={}));class fn{constructor(){this._h0=1732584193,this._h1=4023233417,this._h2=2562383102,this._h3=271733878,this._h4=3285377520,this._buff=new Uint8Array(67),this._buffDV=new DataView(this._buff.buffer),this._buffLen=0,this._totalLen=0,this._leftoverHighSurrogate=0,this._finished=!1}update(e){const t=e.length;if(0===t)return;const n=this._buff;let r,i,s=this._buffLen,o=this._leftoverHighSurrogate;for(0!==o?(r=o,i=-1,o=0):(r=e.charCodeAt(0),i=0);;){let a=r;if(_e(r)){if(!(i+1<t)){o=r;break}{const t=e.charCodeAt(i+1);Ee(t)?(i++,a=t-56320+(r-55296<<10)+65536):a=65533}}else Ee(r)&&(a=65533);if(s=this._push(n,s,a),i++,!(i<t))break;r=e.charCodeAt(i)}this._buffLen=s,this._leftoverHighSurrogate=o}_push(e,t,n){return n<128?e[t++]=n:n<2048?(e[t++]=192|(1984&n)>>>6,e[t++]=128|(63&n)>>>0):n<65536?(e[t++]=224|(61440&n)>>>12,e[t++]=128|(4032&n)>>>6,e[t++]=128|(63&n)>>>0):(e[t++]=240|(1835008&n)>>>18,e[t++]=128|(258048&n)>>>12,e[t++]=128|(4032&n)>>>6,e[t++]=128|(63&n)>>>0),t>=64&&(this._step(),t-=64,this._totalLen+=64,e[0]=e[64],e[1]=e[65],e[2]=e[66]),t}digest(){return this._finished||(this._finished=!0,this._leftoverHighSurrogate&&(this._leftoverHighSurrogate=0,this._buffLen=this._push(this._buff,this._buffLen,65533)),this._totalLen+=this._buffLen,this._wrapUp()),hn(this._h0)+hn(this._h1)+hn(this._h2)+hn(this._h3)+hn(this._h4)}_wrapUp(){this._buff[this._buffLen++]=128,un(this._buff,this._buffLen),this._buffLen>56&&(this._step(),un(this._buff));const e=8*this._totalLen;this._buffDV.setUint32(56,Math.floor(e/4294967296),!1),this._buffDV.setUint32(60,e%4294967296,!1),this._step()}_step(){const e=fn._bigBlock32,t=this._buffDV;for(let n=0;n<64;n+=4)e.setUint32(n,t.getUint32(n,!1),!1);for(let t=64;t<320;t+=4)e.setUint32(t,dn(e.getUint32(t-12,!1)^e.getUint32(t-32,!1)^e.getUint32(t-56,!1)^e.getUint32(t-64,!1),1),!1);let n,r,i,s=this._h0,o=this._h1,a=this._h2,c=this._h3,l=this._h4;for(let t=0;t<80;t++)t<20?(n=o&a|~o&c,r=1518500249):t<40?(n=o^a^c,r=1859775393):t<60?(n=o&a|o&c|a&c,r=2400959708):(n=o^a^c,r=3395469782),i=dn(s,5)+n+l+r+e.getUint32(4*t,!1)&4294967295,l=c,c=a,a=dn(o,30),o=s,s=i;this._h0=this._h0+s&4294967295,this._h1=this._h1+o&4294967295,this._h2=this._h2+a&4294967295,this._h3=this._h3+c&4294967295,this._h4=this._h4+l&4294967295}}fn._bigBlock32=new DataView(new ArrayBuffer(320)),Symbol.iterator;const gn=new RegExp(`\\$\\(${kt.iconNameExpression}(?:${kt.iconModifierExpression})?\\)`,"g");var pn,mn,yn,vn,bn,_n,En;new RegExp(`(\\\\)?${gn.source}`,"g"),new RegExp(`\\\\${gn.source}`,"g"),new RegExp(`(\\s)?(\\\\)?${gn.source}(\\s)?`,"g"),function(e){e[e.Paragraph=0]="Paragraph",e[e.Break=1]="Break"}(pn||(pn={}));new class{constructor(e){this._prefix=e,this._lastId=0}nextId(){return this._prefix+ ++this._lastId}}("id#"),function(e){e[e.None=0]="None",e[e.UnexpectedEndOfComment=1]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=2]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=3]="UnexpectedEndOfNumber",e[e.InvalidUnicode=4]="InvalidUnicode",e[e.InvalidEscapeCharacter=5]="InvalidEscapeCharacter",e[e.InvalidCharacter=6]="InvalidCharacter"}(mn||(mn={})),function(e){e[e.OpenBraceToken=1]="OpenBraceToken",e[e.CloseBraceToken=2]="CloseBraceToken",e[e.OpenBracketToken=3]="OpenBracketToken",e[e.CloseBracketToken=4]="CloseBracketToken",e[e.CommaToken=5]="CommaToken",e[e.ColonToken=6]="ColonToken",e[e.NullKeyword=7]="NullKeyword",e[e.TrueKeyword=8]="TrueKeyword",e[e.FalseKeyword=9]="FalseKeyword",e[e.StringLiteral=10]="StringLiteral",e[e.NumericLiteral=11]="NumericLiteral",e[e.LineCommentTrivia=12]="LineCommentTrivia",e[e.BlockCommentTrivia=13]="BlockCommentTrivia",e[e.LineBreakTrivia=14]="LineBreakTrivia",e[e.Trivia=15]="Trivia",e[e.Unknown=16]="Unknown",e[e.EOF=17]="EOF"}(yn||(yn={})),function(e){e[e.InvalidSymbol=1]="InvalidSymbol",e[e.InvalidNumberFormat=2]="InvalidNumberFormat",e[e.PropertyNameExpected=3]="PropertyNameExpected",e[e.ValueExpected=4]="ValueExpected",e[e.ColonExpected=5]="ColonExpected",e[e.CommaExpected=6]="CommaExpected",e[e.CloseBraceExpected=7]="CloseBraceExpected",e[e.CloseBracketExpected=8]="CloseBracketExpected",e[e.EndOfFileExpected=9]="EndOfFileExpected",e[e.InvalidCommentToken=10]="InvalidCommentToken",e[e.UnexpectedEndOfComment=11]="UnexpectedEndOfComment",e[e.UnexpectedEndOfString=12]="UnexpectedEndOfString",e[e.UnexpectedEndOfNumber=13]="UnexpectedEndOfNumber",e[e.InvalidUnicode=14]="InvalidUnicode",e[e.InvalidEscapeCharacter=15]="InvalidEscapeCharacter",e[e.InvalidCharacter=16]="InvalidCharacter"}(vn||(vn={})),function(e){e.DEFAULT={allowTrailingComma:!0}}(bn||(bn={})),function(e){e[e.nullCharacter=0]="nullCharacter",e[e.maxAsciiCharacter=127]="maxAsciiCharacter",e[e.lineFeed=10]="lineFeed",e[e.carriageReturn=13]="carriageReturn",e[e.lineSeparator=8232]="lineSeparator",e[e.paragraphSeparator=8233]="paragraphSeparator",e[e.nextLine=133]="nextLine",e[e.space=32]="space",e[e.nonBreakingSpace=160]="nonBreakingSpace",e[e.enQuad=8192]="enQuad",e[e.emQuad=8193]="emQuad",e[e.enSpace=8194]="enSpace",e[e.emSpace=8195]="emSpace",e[e.threePerEmSpace=8196]="threePerEmSpace",e[e.fourPerEmSpace=8197]="fourPerEmSpace",e[e.sixPerEmSpace=8198]="sixPerEmSpace",e[e.figureSpace=8199]="figureSpace",e[e.punctuationSpace=8200]="punctuationSpace",e[e.thinSpace=8201]="thinSpace",e[e.hairSpace=8202]="hairSpace",e[e.zeroWidthSpace=8203]="zeroWidthSpace",e[e.narrowNoBreakSpace=8239]="narrowNoBreakSpace",e[e.ideographicSpace=12288]="ideographicSpace",e[e.mathematicalSpace=8287]="mathematicalSpace",e[e.ogham=5760]="ogham",e[e._=95]="_",e[e.$=36]="$",e[e._0=48]="_0",e[e._1=49]="_1",e[e._2=50]="_2",e[e._3=51]="_3",e[e._4=52]="_4",e[e._5=53]="_5",e[e._6=54]="_6",e[e._7=55]="_7",e[e._8=56]="_8",e[e._9=57]="_9",e[e.a=97]="a",e[e.b=98]="b",e[e.c=99]="c",e[e.d=100]="d",e[e.e=101]="e",e[e.f=102]="f",e[e.g=103]="g",e[e.h=104]="h",e[e.i=105]="i",e[e.j=106]="j",e[e.k=107]="k",e[e.l=108]="l",e[e.m=109]="m",e[e.n=110]="n",e[e.o=111]="o",e[e.p=112]="p",e[e.q=113]="q",e[e.r=114]="r",e[e.s=115]="s",e[e.t=116]="t",e[e.u=117]="u",e[e.v=118]="v",e[e.w=119]="w",e[e.x=120]="x",e[e.y=121]="y",e[e.z=122]="z",e[e.A=65]="A",e[e.B=66]="B",e[e.C=67]="C",e[e.D=68]="D",e[e.E=69]="E",e[e.F=70]="F",e[e.G=71]="G",e[e.H=72]="H",e[e.I=73]="I",e[e.J=74]="J",e[e.K=75]="K",e[e.L=76]="L",e[e.M=77]="M",e[e.N=78]="N",e[e.O=79]="O",e[e.P=80]="P",e[e.Q=81]="Q",e[e.R=82]="R",e[e.S=83]="S",e[e.T=84]="T",e[e.U=85]="U",e[e.V=86]="V",e[e.W=87]="W",e[e.X=88]="X",e[e.Y=89]="Y",e[e.Z=90]="Z",e[e.ampersand=38]="ampersand",e[e.asterisk=42]="asterisk",e[e.at=64]="at",e[e.backslash=92]="backslash",e[e.bar=124]="bar",e[e.caret=94]="caret",e[e.closeBrace=125]="closeBrace",e[e.closeBracket=93]="closeBracket",e[e.closeParen=41]="closeParen",e[e.colon=58]="colon",e[e.comma=44]="comma",e[e.dot=46]="dot",e[e.doubleQuote=34]="doubleQuote",e[e.equals=61]="equals",e[e.exclamation=33]="exclamation",e[e.greaterThan=62]="greaterThan",e[e.lessThan=60]="lessThan",e[e.minus=45]="minus",e[e.openBrace=123]="openBrace",e[e.openBracket=91]="openBracket",e[e.openParen=40]="openParen",e[e.percent=37]="percent",e[e.plus=43]="plus",e[e.question=63]="question",e[e.semicolon=59]="semicolon",e[e.singleQuote=39]="singleQuote",e[e.slash=47]="slash",e[e.tilde=126]="tilde",e[e.backspace=8]="backspace",e[e.formFeed=12]="formFeed",e[e.byteOrderMark=65279]="byteOrderMark",e[e.tab=9]="tab",e[e.verticalTab=11]="verticalTab"}(_n||(_n={})),function(e){e[e.DependsOnKbLayout=-1]="DependsOnKbLayout",e[e.Unknown=0]="Unknown",e[e.Backspace=1]="Backspace",e[e.Tab=2]="Tab",e[e.Enter=3]="Enter",e[e.Shift=4]="Shift",e[e.Ctrl=5]="Ctrl",e[e.Alt=6]="Alt",e[e.PauseBreak=7]="PauseBreak",e[e.CapsLock=8]="CapsLock",e[e.Escape=9]="Escape",e[e.Space=10]="Space",e[e.PageUp=11]="PageUp",e[e.PageDown=12]="PageDown",e[e.End=13]="End",e[e.Home=14]="Home",e[e.LeftArrow=15]="LeftArrow",e[e.UpArrow=16]="UpArrow",e[e.RightArrow=17]="RightArrow",e[e.DownArrow=18]="DownArrow",e[e.Insert=19]="Insert",e[e.Delete=20]="Delete",e[e.KEY_0=21]="KEY_0",e[e.KEY_1=22]="KEY_1",e[e.KEY_2=23]="KEY_2",e[e.KEY_3=24]="KEY_3",e[e.KEY_4=25]="KEY_4",e[e.KEY_5=26]="KEY_5",e[e.KEY_6=27]="KEY_6",e[e.KEY_7=28]="KEY_7",e[e.KEY_8=29]="KEY_8",e[e.KEY_9=30]="KEY_9",e[e.KEY_A=31]="KEY_A",e[e.KEY_B=32]="KEY_B",e[e.KEY_C=33]="KEY_C",e[e.KEY_D=34]="KEY_D",e[e.KEY_E=35]="KEY_E",e[e.KEY_F=36]="KEY_F",e[e.KEY_G=37]="KEY_G",e[e.KEY_H=38]="KEY_H",e[e.KEY_I=39]="KEY_I",e[e.KEY_J=40]="KEY_J",e[e.KEY_K=41]="KEY_K",e[e.KEY_L=42]="KEY_L",e[e.KEY_M=43]="KEY_M",e[e.KEY_N=44]="KEY_N",e[e.KEY_O=45]="KEY_O",e[e.KEY_P=46]="KEY_P",e[e.KEY_Q=47]="KEY_Q",e[e.KEY_R=48]="KEY_R",e[e.KEY_S=49]="KEY_S",e[e.KEY_T=50]="KEY_T",e[e.KEY_U=51]="KEY_U",e[e.KEY_V=52]="KEY_V",e[e.KEY_W=53]="KEY_W",e[e.KEY_X=54]="KEY_X",e[e.KEY_Y=55]="KEY_Y",e[e.KEY_Z=56]="KEY_Z",e[e.Meta=57]="Meta",e[e.ContextMenu=58]="ContextMenu",e[e.F1=59]="F1",e[e.F2=60]="F2",e[e.F3=61]="F3",e[e.F4=62]="F4",e[e.F5=63]="F5",e[e.F6=64]="F6",e[e.F7=65]="F7",e[e.F8=66]="F8",e[e.F9=67]="F9",e[e.F10=68]="F10",e[e.F11=69]="F11",e[e.F12=70]="F12",e[e.F13=71]="F13",e[e.F14=72]="F14",e[e.F15=73]="F15",e[e.F16=74]="F16",e[e.F17=75]="F17",e[e.F18=76]="F18",e[e.F19=77]="F19",e[e.NumLock=78]="NumLock",e[e.ScrollLock=79]="ScrollLock",e[e.US_SEMICOLON=80]="US_SEMICOLON",e[e.US_EQUAL=81]="US_EQUAL",e[e.US_COMMA=82]="US_COMMA",e[e.US_MINUS=83]="US_MINUS",e[e.US_DOT=84]="US_DOT",e[e.US_SLASH=85]="US_SLASH",e[e.US_BACKTICK=86]="US_BACKTICK",e[e.US_OPEN_SQUARE_BRACKET=87]="US_OPEN_SQUARE_BRACKET",e[e.US_BACKSLASH=88]="US_BACKSLASH",e[e.US_CLOSE_SQUARE_BRACKET=89]="US_CLOSE_SQUARE_BRACKET",e[e.US_QUOTE=90]="US_QUOTE",e[e.OEM_8=91]="OEM_8",e[e.OEM_102=92]="OEM_102",e[e.NUMPAD_0=93]="NUMPAD_0",e[e.NUMPAD_1=94]="NUMPAD_1",e[e.NUMPAD_2=95]="NUMPAD_2",e[e.NUMPAD_3=96]="NUMPAD_3",e[e.NUMPAD_4=97]="NUMPAD_4",e[e.NUMPAD_5=98]="NUMPAD_5",e[e.NUMPAD_6=99]="NUMPAD_6",e[e.NUMPAD_7=100]="NUMPAD_7",e[e.NUMPAD_8=101]="NUMPAD_8",e[e.NUMPAD_9=102]="NUMPAD_9",e[e.NUMPAD_MULTIPLY=103]="NUMPAD_MULTIPLY",e[e.NUMPAD_ADD=104]="NUMPAD_ADD",e[e.NUMPAD_SEPARATOR=105]="NUMPAD_SEPARATOR",e[e.NUMPAD_SUBTRACT=106]="NUMPAD_SUBTRACT",e[e.NUMPAD_DECIMAL=107]="NUMPAD_DECIMAL",e[e.NUMPAD_DIVIDE=108]="NUMPAD_DIVIDE",e[e.KEY_IN_COMPOSITION=109]="KEY_IN_COMPOSITION",e[e.ABNT_C1=110]="ABNT_C1",e[e.ABNT_C2=111]="ABNT_C2",e[e.MAX_VALUE=112]="MAX_VALUE"}(En||(En={}));class wn{constructor(){this._keyCodeToStr=[],this._strToKeyCode=Object.create(null)}define(e,t){this._keyCodeToStr[e]=t,this._strToKeyCode[t.toLowerCase()]=e}keyCodeToStr(e){return this._keyCodeToStr[e]}strToKeyCode(e){return this._strToKeyCode[e.toLowerCase()]||0}}const Sn=new wn,Cn=new wn,Tn=new wn;var Rn,In,kn,On;!function(){function e(e,t,n=t,r=n){Sn.define(e,t),Cn.define(e,n),Tn.define(e,r)}e(0,"unknown"),e(1,"Backspace"),e(2,"Tab"),e(3,"Enter"),e(4,"Shift"),e(5,"Ctrl"),e(6,"Alt"),e(7,"PauseBreak"),e(8,"CapsLock"),e(9,"Escape"),e(10,"Space"),e(11,"PageUp"),e(12,"PageDown"),e(13,"End"),e(14,"Home"),e(15,"LeftArrow","Left"),e(16,"UpArrow","Up"),e(17,"RightArrow","Right"),e(18,"DownArrow","Down"),e(19,"Insert"),e(20,"Delete"),e(21,"0"),e(22,"1"),e(23,"2"),e(24,"3"),e(25,"4"),e(26,"5"),e(27,"6"),e(28,"7"),e(29,"8"),e(30,"9"),e(31,"A"),e(32,"B"),e(33,"C"),e(34,"D"),e(35,"E"),e(36,"F"),e(37,"G"),e(38,"H"),e(39,"I"),e(40,"J"),e(41,"K"),e(42,"L"),e(43,"M"),e(44,"N"),e(45,"O"),e(46,"P"),e(47,"Q"),e(48,"R"),e(49,"S"),e(50,"T"),e(51,"U"),e(52,"V"),e(53,"W"),e(54,"X"),e(55,"Y"),e(56,"Z"),e(57,"Meta"),e(58,"ContextMenu"),e(59,"F1"),e(60,"F2"),e(61,"F3"),e(62,"F4"),e(63,"F5"),e(64,"F6"),e(65,"F7"),e(66,"F8"),e(67,"F9"),e(68,"F10"),e(69,"F11"),e(70,"F12"),e(71,"F13"),e(72,"F14"),e(73,"F15"),e(74,"F16"),e(75,"F17"),e(76,"F18"),e(77,"F19"),e(78,"NumLock"),e(79,"ScrollLock"),e(80,";",";","OEM_1"),e(81,"=","=","OEM_PLUS"),e(82,",",",","OEM_COMMA"),e(83,"-","-","OEM_MINUS"),e(84,".",".","OEM_PERIOD"),e(85,"/","/","OEM_2"),e(86,"`","`","OEM_3"),e(110,"ABNT_C1"),e(111,"ABNT_C2"),e(87,"[","[","OEM_4"),e(88,"\\","\\","OEM_5"),e(89,"]","]","OEM_6"),e(90,"'","'","OEM_7"),e(91,"OEM_8"),e(92,"OEM_102"),e(93,"NumPad0"),e(94,"NumPad1"),e(95,"NumPad2"),e(96,"NumPad3"),e(97,"NumPad4"),e(98,"NumPad5"),e(99,"NumPad6"),e(100,"NumPad7"),e(101,"NumPad8"),e(102,"NumPad9"),e(103,"NumPad_Multiply"),e(104,"NumPad_Add"),e(105,"NumPad_Separator"),e(106,"NumPad_Subtract"),e(107,"NumPad_Decimal"),e(108,"NumPad_Divide")}(),function(e){e.toString=function(e){return Sn.keyCodeToStr(e)},e.fromString=function(e){return Sn.strToKeyCode(e)},e.toUserSettingsUS=function(e){return Cn.keyCodeToStr(e)},e.toUserSettingsGeneral=function(e){return Tn.keyCodeToStr(e)},e.fromUserSettings=function(e){return Cn.strToKeyCode(e)||Tn.strToKeyCode(e)}}(Rn||(Rn={})),function(e){e[e.CtrlCmd=2048]="CtrlCmd",e[e.Shift=1024]="Shift",e[e.Alt=512]="Alt",e[e.WinCtrl=256]="WinCtrl",e[e.KeyCode=255]="KeyCode"}(In||(In={})),function(e){e[e.CtrlCmd=2048]="CtrlCmd",e[e.Shift=1024]="Shift",e[e.Alt=512]="Alt",e[e.WinCtrl=256]="WinCtrl"}(kn||(kn={}));class An{constructor(e,t,n=t){this.modifierLabels=[null],this.modifierLabels[2]=e,this.modifierLabels[1]=t,this.modifierLabels[3]=n}toLabel(e,t,n){if(0===t.length)return null;const r=[];for(let i=0,s=t.length;i<s;i++){const s=t[i],o=n(s);if(null===o)return null;r[i]=Dn(s,o,this.modifierLabels[e])}return r.join(" ")}}function Dn(e,t,n){if(null===t)return"";const r=[];return e.ctrlKey&&r.push(n.ctrlKey),e.shiftKey&&r.push(n.shiftKey),e.altKey&&r.push(n.altKey),e.metaKey&&r.push(n.metaKey),""!==t&&r.push(t),r.join(n.separator)}new An({ctrlKey:"⌃",shiftKey:"⇧",altKey:"⌥",metaKey:"⌘",separator:""},{ctrlKey:i(0,"Ctrl"),shiftKey:i(0,"Shift"),altKey:i(0,"Alt"),metaKey:i(0,"Windows"),separator:"+"},{ctrlKey:i(0,"Ctrl"),shiftKey:i(0,"Shift"),altKey:i(0,"Alt"),metaKey:i(0,"Super"),separator:"+"}),new An({ctrlKey:i(0,"Control"),shiftKey:i(0,"Shift"),altKey:i(0,"Alt"),metaKey:i(0,"Command"),separator:"+"},{ctrlKey:i(0,"Control"),shiftKey:i(0,"Shift"),altKey:i(0,"Alt"),metaKey:i(0,"Windows"),separator:"+"},{ctrlKey:i(0,"Control"),shiftKey:i(0,"Shift"),altKey:i(0,"Alt"),metaKey:i(0,"Super"),separator:"+"}),new An({ctrlKey:"Ctrl",shiftKey:"Shift",altKey:"Alt",metaKey:"Cmd",separator:"+"},{ctrlKey:"Ctrl",shiftKey:"Shift",altKey:"Alt",metaKey:"Super",separator:"+"}),new An({ctrlKey:"ctrl",shiftKey:"shift",altKey:"alt",metaKey:"cmd",separator:"+"},{ctrlKey:"ctrl",shiftKey:"shift",altKey:"alt",metaKey:"win",separator:"+"},{ctrlKey:"ctrl",shiftKey:"shift",altKey:"alt",metaKey:"meta",separator:"+"}),function(e){e[e.DependsOnKbLayout=-1]="DependsOnKbLayout",e[e.None=0]="None",e[e.Hyper=1]="Hyper",e[e.Super=2]="Super",e[e.Fn=3]="Fn",e[e.FnLock=4]="FnLock",e[e.Suspend=5]="Suspend",e[e.Resume=6]="Resume",e[e.Turbo=7]="Turbo",e[e.Sleep=8]="Sleep",e[e.WakeUp=9]="WakeUp",e[e.KeyA=10]="KeyA",e[e.KeyB=11]="KeyB",e[e.KeyC=12]="KeyC",e[e.KeyD=13]="KeyD",e[e.KeyE=14]="KeyE",e[e.KeyF=15]="KeyF",e[e.KeyG=16]="KeyG",e[e.KeyH=17]="KeyH",e[e.KeyI=18]="KeyI",e[e.KeyJ=19]="KeyJ",e[e.KeyK=20]="KeyK",e[e.KeyL=21]="KeyL",e[e.KeyM=22]="KeyM",e[e.KeyN=23]="KeyN",e[e.KeyO=24]="KeyO",e[e.KeyP=25]="KeyP",e[e.KeyQ=26]="KeyQ",e[e.KeyR=27]="KeyR",e[e.KeyS=28]="KeyS",e[e.KeyT=29]="KeyT",e[e.KeyU=30]="KeyU",e[e.KeyV=31]="KeyV",e[e.KeyW=32]="KeyW",e[e.KeyX=33]="KeyX",e[e.KeyY=34]="KeyY",e[e.KeyZ=35]="KeyZ",e[e.Digit1=36]="Digit1",e[e.Digit2=37]="Digit2",e[e.Digit3=38]="Digit3",e[e.Digit4=39]="Digit4",e[e.Digit5=40]="Digit5",e[e.Digit6=41]="Digit6",e[e.Digit7=42]="Digit7",e[e.Digit8=43]="Digit8",e[e.Digit9=44]="Digit9",e[e.Digit0=45]="Digit0",e[e.Enter=46]="Enter",e[e.Escape=47]="Escape",e[e.Backspace=48]="Backspace",e[e.Tab=49]="Tab",e[e.Space=50]="Space",e[e.Minus=51]="Minus",e[e.Equal=52]="Equal",e[e.BracketLeft=53]="BracketLeft",e[e.BracketRight=54]="BracketRight",e[e.Backslash=55]="Backslash",e[e.IntlHash=56]="IntlHash",e[e.Semicolon=57]="Semicolon",e[e.Quote=58]="Quote",e[e.Backquote=59]="Backquote",e[e.Comma=60]="Comma",e[e.Period=61]="Period",e[e.Slash=62]="Slash",e[e.CapsLock=63]="CapsLock",e[e.F1=64]="F1",e[e.F2=65]="F2",e[e.F3=66]="F3",e[e.F4=67]="F4",e[e.F5=68]="F5",e[e.F6=69]="F6",e[e.F7=70]="F7",e[e.F8=71]="F8",e[e.F9=72]="F9",e[e.F10=73]="F10",e[e.F11=74]="F11",e[e.F12=75]="F12",e[e.PrintScreen=76]="PrintScreen",e[e.ScrollLock=77]="ScrollLock",e[e.Pause=78]="Pause",e[e.Insert=79]="Insert",e[e.Home=80]="Home",e[e.PageUp=81]="PageUp",e[e.Delete=82]="Delete",e[e.End=83]="End",e[e.PageDown=84]="PageDown",e[e.ArrowRight=85]="ArrowRight",e[e.ArrowLeft=86]="ArrowLeft",e[e.ArrowDown=87]="ArrowDown",e[e.ArrowUp=88]="ArrowUp",e[e.NumLock=89]="NumLock",e[e.NumpadDivide=90]="NumpadDivide",e[e.NumpadMultiply=91]="NumpadMultiply",e[e.NumpadSubtract=92]="NumpadSubtract",e[e.NumpadAdd=93]="NumpadAdd",e[e.NumpadEnter=94]="NumpadEnter",e[e.Numpad1=95]="Numpad1",e[e.Numpad2=96]="Numpad2",e[e.Numpad3=97]="Numpad3",e[e.Numpad4=98]="Numpad4",e[e.Numpad5=99]="Numpad5",e[e.Numpad6=100]="Numpad6",e[e.Numpad7=101]="Numpad7",e[e.Numpad8=102]="Numpad8",e[e.Numpad9=103]="Numpad9",e[e.Numpad0=104]="Numpad0",e[e.NumpadDecimal=105]="NumpadDecimal",e[e.IntlBackslash=106]="IntlBackslash",e[e.ContextMenu=107]="ContextMenu",e[e.Power=108]="Power",e[e.NumpadEqual=109]="NumpadEqual",e[e.F13=110]="F13",e[e.F14=111]="F14",e[e.F15=112]="F15",e[e.F16=113]="F16",e[e.F17=114]="F17",e[e.F18=115]="F18",e[e.F19=116]="F19",e[e.F20=117]="F20",e[e.F21=118]="F21",e[e.F22=119]="F22",e[e.F23=120]="F23",e[e.F24=121]="F24",e[e.Open=122]="Open",e[e.Help=123]="Help",e[e.Select=124]="Select",e[e.Again=125]="Again",e[e.Undo=126]="Undo",e[e.Cut=127]="Cut",e[e.Copy=128]="Copy",e[e.Paste=129]="Paste",e[e.Find=130]="Find",e[e.AudioVolumeMute=131]="AudioVolumeMute",e[e.AudioVolumeUp=132]="AudioVolumeUp",e[e.AudioVolumeDown=133]="AudioVolumeDown",e[e.NumpadComma=134]="NumpadComma",e[e.IntlRo=135]="IntlRo",e[e.KanaMode=136]="KanaMode",e[e.IntlYen=137]="IntlYen",e[e.Convert=138]="Convert",e[e.NonConvert=139]="NonConvert",e[e.Lang1=140]="Lang1",e[e.Lang2=141]="Lang2",e[e.Lang3=142]="Lang3",e[e.Lang4=143]="Lang4",e[e.Lang5=144]="Lang5",e[e.Abort=145]="Abort",e[e.Props=146]="Props",e[e.NumpadParenLeft=147]="NumpadParenLeft",e[e.NumpadParenRight=148]="NumpadParenRight",e[e.NumpadBackspace=149]="NumpadBackspace",e[e.NumpadMemoryStore=150]="NumpadMemoryStore",e[e.NumpadMemoryRecall=151]="NumpadMemoryRecall",e[e.NumpadMemoryClear=152]="NumpadMemoryClear",e[e.NumpadMemoryAdd=153]="NumpadMemoryAdd",e[e.NumpadMemorySubtract=154]="NumpadMemorySubtract",e[e.NumpadClear=155]="NumpadClear",e[e.NumpadClearEntry=156]="NumpadClearEntry",e[e.ControlLeft=157]="ControlLeft",e[e.ShiftLeft=158]="ShiftLeft",e[e.AltLeft=159]="AltLeft",e[e.MetaLeft=160]="MetaLeft",e[e.ControlRight=161]="ControlRight",e[e.ShiftRight=162]="ShiftRight",e[e.AltRight=163]="AltRight",e[e.MetaRight=164]="MetaRight",e[e.BrightnessUp=165]="BrightnessUp",e[e.BrightnessDown=166]="BrightnessDown",e[e.MediaPlay=167]="MediaPlay",e[e.MediaRecord=168]="MediaRecord",e[e.MediaFastForward=169]="MediaFastForward",e[e.MediaRewind=170]="MediaRewind",e[e.MediaTrackNext=171]="MediaTrackNext",e[e.MediaTrackPrevious=172]="MediaTrackPrevious",e[e.MediaStop=173]="MediaStop",e[e.Eject=174]="Eject",e[e.MediaPlayPause=175]="MediaPlayPause",e[e.MediaSelect=176]="MediaSelect",e[e.LaunchMail=177]="LaunchMail",e[e.LaunchApp2=178]="LaunchApp2",e[e.LaunchApp1=179]="LaunchApp1",e[e.SelectTask=180]="SelectTask",e[e.LaunchScreenSaver=181]="LaunchScreenSaver",e[e.BrowserSearch=182]="BrowserSearch",e[e.BrowserHome=183]="BrowserHome",e[e.BrowserBack=184]="BrowserBack",e[e.BrowserForward=185]="BrowserForward",e[e.BrowserStop=186]="BrowserStop",e[e.BrowserRefresh=187]="BrowserRefresh",e[e.BrowserFavorites=188]="BrowserFavorites",e[e.ZoomToggle=189]="ZoomToggle",e[e.MailReply=190]="MailReply",e[e.MailForward=191]="MailForward",e[e.MailSend=192]="MailSend",e[e.MAX_VALUE=193]="MAX_VALUE"}(On||(On={}));const Mn=[],Pn=Object.create(null),Un=Object.create(null),Ln=[],Nn=[];var xn,Bn,jn;function Fn(e,t,n,r){var i,s=arguments.length,o=s<3?t:null===r?r=Object.getOwnPropertyDescriptor(t,n):r;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)o=Reflect.decorate(e,t,n,r);else for(var a=e.length-1;a>=0;a--)(i=e[a])&&(o=(s<3?i(o):s>3?i(t,n,o):i(t,n))||o);return s>3&&o&&Object.defineProperty(t,n,o),o}!function(){function e(e,t){Mn[e]=t,Pn[t]=e,Un[t.toLowerCase()]=e}e(0,"None"),e(1,"Hyper"),e(2,"Super"),e(3,"Fn"),e(4,"FnLock"),e(5,"Suspend"),e(6,"Resume"),e(7,"Turbo"),e(8,"Sleep"),e(9,"WakeUp"),e(10,"KeyA"),e(11,"KeyB"),e(12,"KeyC"),e(13,"KeyD"),e(14,"KeyE"),e(15,"KeyF"),e(16,"KeyG"),e(17,"KeyH"),e(18,"KeyI"),e(19,"KeyJ"),e(20,"KeyK"),e(21,"KeyL"),e(22,"KeyM"),e(23,"KeyN"),e(24,"KeyO"),e(25,"KeyP"),e(26,"KeyQ"),e(27,"KeyR"),e(28,"KeyS"),e(29,"KeyT"),e(30,"KeyU"),e(31,"KeyV"),e(32,"KeyW"),e(33,"KeyX"),e(34,"KeyY"),e(35,"KeyZ"),e(36,"Digit1"),e(37,"Digit2"),e(38,"Digit3"),e(39,"Digit4"),e(40,"Digit5"),e(41,"Digit6"),e(42,"Digit7"),e(43,"Digit8"),e(44,"Digit9"),e(45,"Digit0"),e(46,"Enter"),e(47,"Escape"),e(48,"Backspace"),e(49,"Tab"),e(50,"Space"),e(51,"Minus"),e(52,"Equal"),e(53,"BracketLeft"),e(54,"BracketRight"),e(55,"Backslash"),e(56,"IntlHash"),e(57,"Semicolon"),e(58,"Quote"),e(59,"Backquote"),e(60,"Comma"),e(61,"Period"),e(62,"Slash"),e(63,"CapsLock"),e(64,"F1"),e(65,"F2"),e(66,"F3"),e(67,"F4"),e(68,"F5"),e(69,"F6"),e(70,"F7"),e(71,"F8"),e(72,"F9"),e(73,"F10"),e(74,"F11"),e(75,"F12"),e(76,"PrintScreen"),e(77,"ScrollLock"),e(78,"Pause"),e(79,"Insert"),e(80,"Home"),e(81,"PageUp"),e(82,"Delete"),e(83,"End"),e(84,"PageDown"),e(85,"ArrowRight"),e(86,"ArrowLeft"),e(87,"ArrowDown"),e(88,"ArrowUp"),e(89,"NumLock"),e(90,"NumpadDivide"),e(91,"NumpadMultiply"),e(92,"NumpadSubtract"),e(93,"NumpadAdd"),e(94,"NumpadEnter"),e(95,"Numpad1"),e(96,"Numpad2"),e(97,"Numpad3"),e(98,"Numpad4"),e(99,"Numpad5"),e(100,"Numpad6"),e(101,"Numpad7"),e(102,"Numpad8"),e(103,"Numpad9"),e(104,"Numpad0"),e(105,"NumpadDecimal"),e(106,"IntlBackslash"),e(107,"ContextMenu"),e(108,"Power"),e(109,"NumpadEqual"),e(110,"F13"),e(111,"F14"),e(112,"F15"),e(113,"F16"),e(114,"F17"),e(115,"F18"),e(116,"F19"),e(117,"F20"),e(118,"F21"),e(119,"F22"),e(120,"F23"),e(121,"F24"),e(122,"Open"),e(123,"Help"),e(124,"Select"),e(125,"Again"),e(126,"Undo"),e(127,"Cut"),e(128,"Copy"),e(129,"Paste"),e(130,"Find"),e(131,"AudioVolumeMute"),e(132,"AudioVolumeUp"),e(133,"AudioVolumeDown"),e(134,"NumpadComma"),e(135,"IntlRo"),e(136,"KanaMode"),e(137,"IntlYen"),e(138,"Convert"),e(139,"NonConvert"),e(140,"Lang1"),e(141,"Lang2"),e(142,"Lang3"),e(143,"Lang4"),e(144,"Lang5"),e(145,"Abort"),e(146,"Props"),e(147,"NumpadParenLeft"),e(148,"NumpadParenRight"),e(149,"NumpadBackspace"),e(150,"NumpadMemoryStore"),e(151,"NumpadMemoryRecall"),e(152,"NumpadMemoryClear"),e(153,"NumpadMemoryAdd"),e(154,"NumpadMemorySubtract"),e(155,"NumpadClear"),e(156,"NumpadClearEntry"),e(157,"ControlLeft"),e(158,"ShiftLeft"),e(159,"AltLeft"),e(160,"MetaLeft"),e(161,"ControlRight"),e(162,"ShiftRight"),e(163,"AltRight"),e(164,"MetaRight"),e(165,"BrightnessUp"),e(166,"BrightnessDown"),e(167,"MediaPlay"),e(168,"MediaRecord"),e(169,"MediaFastForward"),e(170,"MediaRewind"),e(171,"MediaTrackNext"),e(172,"MediaTrackPrevious"),e(173,"MediaStop"),e(174,"Eject"),e(175,"MediaPlayPause"),e(176,"MediaSelect"),e(177,"LaunchMail"),e(178,"LaunchApp2"),e(179,"LaunchApp1"),e(180,"SelectTask"),e(181,"LaunchScreenSaver"),e(182,"BrowserSearch"),e(183,"BrowserHome"),e(184,"BrowserBack"),e(185,"BrowserForward"),e(186,"BrowserStop"),e(187,"BrowserRefresh"),e(188,"BrowserFavorites"),e(189,"ZoomToggle"),e(190,"MailReply"),e(191,"MailForward"),e(192,"MailSend")}(),function(){for(let e=0;e<=193;e++)Ln[e]=-1;for(let e=0;e<=112;e++)Nn[e]=-1;function e(e,t){Ln[e]=t,0!==t&&3!==t&&5!==t&&4!==t&&6!==t&&57!==t&&(Nn[t]=e)}Nn[3]=46,e(0,0),e(1,0),e(2,0),e(3,0),e(4,0),e(5,0),e(6,0),e(7,0),e(8,0),e(9,0),e(46,3),e(47,9),e(48,1),e(49,2),e(50,10),e(63,8),e(64,59),e(65,60),e(66,61),e(67,62),e(68,63),e(69,64),e(70,65),e(71,66),e(72,67),e(73,68),e(74,69),e(75,70),e(76,0),e(77,79),e(78,7),e(79,19),e(80,14),e(81,11),e(82,20),e(83,13),e(84,12),e(85,17),e(86,15),e(87,18),e(88,16),e(89,78),e(90,108),e(91,103),e(92,106),e(93,104),e(94,3),e(95,94),e(96,95),e(97,96),e(98,97),e(99,98),e(100,99),e(101,100),e(102,101),e(103,102),e(104,93),e(105,107),e(107,58),e(108,0),e(109,0),e(110,71),e(111,72),e(112,73),e(113,74),e(114,75),e(115,76),e(116,77),e(117,0),e(118,0),e(119,0),e(120,0),e(121,0),e(122,0),e(123,0),e(124,0),e(125,0),e(126,0),e(127,0),e(128,0),e(129,0),e(130,0),e(131,0),e(132,0),e(133,0),e(134,105),e(136,0),e(138,0),e(139,0),e(140,0),e(141,0),e(142,0),e(143,0),e(144,0),e(145,0),e(146,0),e(147,0),e(148,0),e(149,0),e(150,0),e(151,0),e(152,0),e(153,0),e(154,0),e(155,0),e(156,0),e(157,5),e(158,4),e(159,6),e(160,57),e(161,5),e(162,4),e(163,6),e(164,57),e(165,0),e(166,0),e(167,0),e(168,0),e(169,0),e(170,0),e(171,0),e(172,0),e(173,0),e(174,0),e(175,0),e(176,0),e(177,0),e(178,0),e(179,0),e(180,0),e(181,0),e(182,0),e(183,0),e(184,0),e(185,0),e(186,0),e(187,0),e(188,0),e(189,0),e(190,0),e(191,0),e(192,0)}(),Object.create(null),function(e){e[e.TEXT=0]="TEXT",e[e.VARIABLE=1]="VARIABLE",e[e.SEPARATOR=2]="SEPARATOR"}(xn||(xn={}));Fn([Ut],class{constructor(e){this.nodes=e}toString(){return this.nodes.map((e=>"string"==typeof e?e:e.label)).join("")}}.prototype,"toString",null),function(e){e[e.Uri=1]="Uri",e[e.Regexp=2]="Regexp",e[e.ScmResource=3]="ScmResource",e[e.ScmResourceGroup=4]="ScmResourceGroup",e[e.ScmProvider=5]="ScmProvider",e[e.CommentController=6]="CommentController",e[e.CommentThread=7]="CommentThread",e[e.CommentThreadReply=8]="CommentThreadReply",e[e.CommentNode=9]="CommentNode",e[e.CommentThreadNode=10]="CommentThreadNode",e[e.TimelineActionContext=11]="TimelineActionContext",e[e.NotebookCellActionContext=12]="NotebookCellActionContext",e[e.TestItemContext=13]="TestItemContext"}(Bn||(Bn={})),function(e){e.text="text/plain",e.binary="application/octet-stream",e.unknown="application/unknown",e.markdown="text/markdown"}(jn||(jn={})),new qt(1e4);new qt(1e4);var Kn,qn,$n,Vn,Gn,Wn,Hn;!function(e){e[e.OK=0]="OK",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error",e[e.Fatal=4]="Fatal"}(Kn||(Kn={})),function(e){e[e.stdout=0]="stdout",e[e.stderr=1]="stderr"}(qn||(qn={})),function(e){e[e.Success=0]="Success",e[e.Unknown=1]="Unknown",e[e.AccessDenied=2]="AccessDenied",e[e.ProcessNotFound=3]="ProcessNotFound"}($n||($n={})),function(e){function t(e,t){if(e.start>=t.end||t.start>=e.end)return{start:0,end:0};const n=Math.max(e.start,t.start),r=Math.min(e.end,t.end);return r-n<=0?{start:0,end:0}:{start:n,end:r}}function n(e){return e.end-e.start<=0}e.intersect=t,e.isEmpty=n,e.intersects=function(e,r){return!n(t(e,r))},e.relativeComplement=function(e,t){const r=[],i={start:e.start,end:Math.min(t.start,e.end)},s={start:Math.max(t.end,e.start),end:e.end};return n(i)||r.push(i),n(s)||r.push(s),r}}(Vn||(Vn={}));Fn([Ut],class{constructor(e,t,n,r=void 0,i=void 0){this.uri=e,this.relativePath=t,this.context=n,this.element=r,this.parent=i,this._children=new Map}get childrenCount(){return this._children.size}get children(){return this._children.values()}get name(){return je.basename(this.relativePath)}get(e){return this._children.get(e)}set(e,t){this._children.set(e,t)}delete(e){this._children.delete(e)}clear(){this._children.clear()}}.prototype,"name",null),function(e){e[e.Auto=1]="Auto",e[e.Hidden=2]="Hidden",e[e.Visible=3]="Visible"}(Gn||(Gn={})),function(e){e[e.Ignore=0]="Ignore",e[e.Info=1]="Info",e[e.Warning=2]="Warning",e[e.Error=3]="Error"}(Wn||(Wn={})),function(e){const t="error",n="warning",r="info";e.fromValue=function(i){return i?ye(t,i)?e.Error:ye(n,i)||ye("warn",i)?e.Warning:ye(r,i)?e.Info:e.Ignore:e.Ignore},e.toString=function(i){switch(i){case e.Error:return t;case e.Warning:return n;case e.Info:return r;default:return"ignore"}}}(Wn||(Wn={})),Symbol.toStringTag,Symbol.iterator,function(e){e[e.MAX_SAFE_SMALL_INTEGER=1073741824]="MAX_SAFE_SMALL_INTEGER",e[e.MIN_SAFE_SMALL_INTEGER=-1073741824]="MIN_SAFE_SMALL_INTEGER",e[e.MAX_UINT_8=255]="MAX_UINT_8",e[e.MAX_UINT_16=65535]="MAX_UINT_16",e[e.MAX_UINT_32=4294967295]="MAX_UINT_32",e[e.UNICODE_SUPPLEMENTARY_PLANE_BEGIN=65536]="UNICODE_SUPPLEMENTARY_PLANE_BEGIN"}(Hn||(Hn={})),new class{transformIncoming(e){return e}transformOutgoing(e){return e}transformOutgoingURI(e){return e}transformOutgoingScheme(e){return e}},new Uint8Array(16);const Yn=[];for(let e=0;e<256;e++)Yn.push(e.toString(16).padStart(2,"0"));let zn;zn="object"==typeof crypto&&"function"==typeof crypto.getRandomValues?crypto.getRandomValues.bind(crypto):function(e){for(let t=0;t<e.length;t++)e[t]=Math.floor(256*Math.random());return e};const Jn=()=>new Map,Qn=e=>{const t=Jn();return e.forEach(((e,n)=>{t.set(n,e)})),t},Xn=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r},Zn=()=>new Set,er=e=>e[e.length-1],tr=(e,t)=>{for(let n=0;n<t.length;n++)e.push(t[n])},nr=Array.from,rr=Array.isArray;class ir{constructor(){this._observers=Jn()}on(e,t){Xn(this._observers,e,Zn).add(t)}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return nr((this._observers.get(e)||Jn()).values()).forEach((e=>e(...t)))}destroy(){this._observers=Jn()}}const sr=Math.floor,or=(Math.ceil,Math.abs),ar=(Math.imul,Math.round,Math.log10,Math.log2,Math.log,Math.sqrt,(e,t)=>e<t?e:t),cr=(e,t)=>e>t?e:t,lr=(Number.isNaN,Math.pow,Math.sign,e=>0!==e?e<0:1/e<0),dr=64,ur=128,hr=127,fr=Number.MAX_SAFE_INTEGER,gr=(Number.MIN_SAFE_INTEGER,Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&sr(e)===e)),pr=(Number.isNaN,Number.parseInt,String.fromCharCode),mr=(String.fromCodePoint,pr(65535),/^\s*/g),yr=/([A-Z])/g,vr=(e,t)=>(e=>e.replace(mr,""))(e.replace(yr,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),br="undefined"!=typeof TextEncoder?new TextEncoder:null,_r=br?e=>br.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let Er="undefined"==typeof TextDecoder?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});Er&&1===Er.decode(new Uint8Array).length&&(Er=null);class wr{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Sr=()=>new wr,Cr=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(new Uint8Array(e.cbuf.buffer,0,e.cpos),n),t},Tr=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},Rr=Tr,Ir=(e,t)=>{for(;t>hr;)Tr(e,ur|hr&t),t=sr(t/128);Tr(e,hr&t)},kr=(e,t)=>{const n=lr(t);for(n&&(t=-t),Tr(e,(t>63?ur:0)|(n?dr:0)|63&t),t=sr(t/64);t>0;)Tr(e,(t>hr?ur:0)|hr&t),t=sr(t/128)},Or=new Uint8Array(3e4),Ar=Or.length/3,Dr=br&&br.encodeInto?(e,t)=>{if(t.length<Ar){const n=br.encodeInto(t,Or).written||0;Ir(e,n);for(let t=0;t<n;t++)Tr(e,Or[t])}else Pr(e,_r(t))}:(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;Ir(e,r);for(let t=0;t<r;t++)Tr(e,n.codePointAt(t))},Mr=(e,t)=>{const n=e.cbuf.length,r=e.cpos,i=ar(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(cr(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)},Pr=(e,t)=>{Ir(e,t.byteLength),Mr(e,t)},Ur=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(new Uint8Array(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*cr(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Lr=new DataView(new ArrayBuffer(4)),Nr=(e,t)=>{switch(typeof t){case"string":Tr(e,119),Dr(e,t);break;case"number":gr(t)&&or(t)<=2147483647?(Tr(e,125),kr(e,t)):(n=t,Lr.setFloat32(0,n),Lr.getFloat32(0)===n?(Tr(e,124),((e,t)=>{Ur(e,4).setFloat32(0,t,!1)})(e,t)):(Tr(e,123),((e,t)=>{Ur(e,8).setFloat64(0,t,!1)})(e,t)));break;case"bigint":Tr(e,122),((e,t)=>{Ur(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)Tr(e,126);else if(rr(t)){Tr(e,117),Ir(e,t.length);for(let n=0;n<t.length;n++)Nr(e,t[n])}else if(t instanceof Uint8Array)Tr(e,116),Pr(e,t);else{Tr(e,118);const n=Object.keys(t);Ir(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];Dr(e,i),Nr(e,t[i])}}break;case"boolean":Tr(e,t?120:121);break;default:Tr(e,127)}var n};class xr extends wr{constructor(e){super(),this.w=e,this.s=null,this.count=0}write(e){this.s===e?this.count++:(this.count>0&&Ir(this,this.count-1),this.count=1,this.w(this,e),this.s=e)}}const Br=e=>{e.count>0&&(kr(e.encoder,1===e.count?e.s:-e.s),e.count>1&&Ir(e.encoder,e.count-2))};class jr{constructor(){this.encoder=new wr,this.s=0,this.count=0}write(e){this.s===e?this.count++:(Br(this),this.count=1,this.s=e)}toUint8Array(){return Br(this),Cr(this.encoder)}}const Fr=e=>{if(e.count>0){const t=2*e.diff+(1===e.count?0:1);kr(e.encoder,t),e.count>1&&Ir(e.encoder,e.count-2)}};class Kr{constructor(){this.encoder=new wr,this.s=0,this.count=0,this.diff=0}write(e){this.diff===e-this.s?(this.s=e,this.count++):(Fr(this),this.count=1,this.diff=e-this.s,this.s=e)}toUint8Array(){return Fr(this),Cr(this.encoder)}}class qr{constructor(){this.sarr=[],this.s="",this.lensE=new jr}write(e){this.s+=e,this.s.length>19&&(this.sarr.push(this.s),this.s=""),this.lensE.write(e.length)}toUint8Array(){const e=new wr;return this.sarr.push(this.s),this.s="",Dr(e,this.sarr.join("")),Mr(e,this.lensE.toUint8Array()),Cr(e)}}const $r=e=>new Error(e),Vr=()=>{throw $r("Method unimplemented")},Gr=()=>{throw $r("Unexpected case")},Wr=$r("Unexpected end of array"),Hr=$r("Integer out of Range");class Yr{constructor(e){this.arr=e,this.pos=0}}const zr=e=>new Yr(e),Jr=e=>e.pos!==e.arr.length,Qr=e=>((e,t)=>{const n=new Uint8Array(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Zr(e)),Xr=e=>e.arr[e.pos++],Zr=e=>{let t=0,n=1;const r=e.arr.length;for(;e.pos<r;){const r=e.arr[e.pos++];if(t+=(r&hr)*n,n*=128,r<ur)return t;if(t>fr)throw Hr}throw Wr},ei=e=>{let t=e.arr[e.pos++],n=63&t,r=64;const i=(t&dr)>0?-1:1;if(0==(t&ur))return i*n;const s=e.arr.length;for(;e.pos<s;){if(t=e.arr[e.pos++],n+=(t&hr)*r,r*=128,t<ur)return i*n;if(n>fr)throw Hr}throw Wr},ti=Er?e=>Er.decode(Qr(e)):e=>{let t=Zr(e);if(0===t)return"";{let n=String.fromCodePoint(Xr(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Xr(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},ni=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},ri=[e=>{},e=>null,ei,e=>ni(e,4).getFloat32(0,!1),e=>ni(e,8).getFloat64(0,!1),e=>ni(e,8).getBigInt64(0,!1),e=>!1,e=>!0,ti,e=>{const t=Zr(e),n={};for(let r=0;r<t;r++)n[ti(e)]=ii(e);return n},e=>{const t=Zr(e),n=[];for(let r=0;r<t;r++)n.push(ii(e));return n},Qr],ii=e=>ri[127-Xr(e)](e);class si extends Yr{constructor(e,t){super(e),this.reader=t,this.s=null,this.count=0}read(){return 0===this.count&&(this.s=this.reader(this),Jr(this)?this.count=Zr(this)+1:this.count=-1),this.count--,this.s}}class oi extends Yr{constructor(e){super(e),this.s=0,this.count=0}read(){if(0===this.count){this.s=ei(this);const e=lr(this.s);this.count=1,e&&(this.s=-this.s,this.count=Zr(this)+2)}return this.count--,this.s}}class ai extends Yr{constructor(e){super(e),this.s=0,this.count=0,this.diff=0}read(){if(0===this.count){const e=ei(this),t=1&e;this.diff=sr(e/2),this.count=1,t&&(this.count=Zr(this)+2)}return this.s+=this.diff,this.count--,this.s}}class ci{constructor(e){this.decoder=new oi(e),this.str=ti(this.decoder),this.spos=0}read(){const e=this.spos+this.decoder.read(),t=this.str.slice(this.spos,e);return this.spos=e,t}}crypto.subtle;const li=crypto.getRandomValues.bind(crypto),di=(Math.random,()=>li(new Uint32Array(1))[0]),ui=[1e7]+-1e3+-4e3+-8e3+-1e11,hi=()=>ui.replace(/[018]/g,(e=>(e^di()&15>>e/4).toString(16))),fi=e=>new Promise(e),gi=(Promise.all.bind(Promise),e=>void 0===e?null:e);let pi=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},mi=!0;try{"undefined"!=typeof localStorage&&localStorage&&(pi=localStorage,mi=!1)}catch(e){}const yi=pi,vi=(e,t,n=0)=>{try{for(;n<e.length;n++)e[n](...t)}finally{n<e.length&&vi(e,t,n+1)}},bi=e=>e,_i="undefined"!=typeof process&&process.release&&/node|io\.js/.test(process.release.name)&&"[object process]"===Object.prototype.toString.call("undefined"!=typeof process?process:0);let Ei;"undefined"!=typeof navigator&&/Mac/.test(navigator.platform);const wi=[],Si=e=>(()=>{if(void 0===Ei)if(_i){Ei=Jn();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&Ei.set(t,""),t=r):null!==t?(Ei.set(t,r),t=null):wi.push(r)}null!==t&&Ei.set(t,"")}else"object"==typeof location?(Ei=Jn(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");Ei.set(`--${vr(t,"-")}`,n),Ei.set(`-${vr(t,"-")}`,n)}}))):Ei=Jn();return Ei})().has(e),Ci=e=>gi(_i?process.env[e.toUpperCase()]:yi.getItem(e));Si("--"+"production")||Ci("production");const Ti=_i&&(Ri=process.env.FORCE_COLOR,["true","1","2"].includes(Ri));var Ri;const Ii=!Si("no-colors")&&(!_i||process.stdout.isTTY||Ti)&&(!_i||Si("color")||Ti||null!==Ci("COLORTERM")||(Ci("TERM")||"").includes("color"));class ki{constructor(e,t){this.left=e,this.right=t}}const Oi=(e,t)=>new ki(e,t),Ai="undefined"!=typeof document?document:{},Di=("undefined"!=typeof DOMParser&&new DOMParser,e=>((e,t)=>{const n=[];for(const[r,i]of e)n.push(t(i,r));return n})(e,((e,t)=>`${t}:${e};`)).join("")),Mi=(Ai.ELEMENT_NODE,Ai.TEXT_NODE,Ai.CDATA_SECTION_NODE,Ai.COMMENT_NODE,Ai.DOCUMENT_NODE,Ai.DOCUMENT_TYPE_NODE,Ai.DOCUMENT_FRAGMENT_NODE,Symbol),Pi=Date.now,Ui=Mi(),Li=Mi(),Ni=Mi(),xi=Mi(),Bi=Mi(),ji=Mi(),Fi=Mi(),Ki=Mi(),qi=Mi();Pi();const $i={[Ui]:Oi("font-weight","bold"),[Li]:Oi("font-weight","normal"),[Ni]:Oi("color","blue"),[Bi]:Oi("color","green"),[xi]:Oi("color","grey"),[ji]:Oi("color","red"),[Fi]:Oi("color","purple"),[Ki]:Oi("color","orange"),[qi]:Oi("color","black")},Vi=Ii?e=>{const t=[],n=[],r=Jn();let i=[],s=0;for(;s<e.length;s++){const i=e[s],o=$i[i];if(void 0!==o)r.set(o.left,o.right);else{if(i.constructor!==String&&i.constructor!==Number)break;{const e=Di(r);s>0||e.length>0?(t.push("%c"+i),n.push(e)):t.push(i)}}}for(s>0&&(i=n,i.unshift(t.join("")));s<e.length;s++){const t=e[s];t instanceof Symbol||i.push(t)}return i}:e=>{const t=[],n=[];let r=0;for(;r<e.length;r++){const i=e[r];i.constructor===String||i.constructor===Number?t.push(i):i.constructor===Object&&n.push(JSON.stringify(i))}return n},Gi=(...e)=>{console.log(...Vi(e)),Wi.forEach((t=>t.print(e)))},Wi=Zn(),Hi=e=>({[Symbol.iterator](){return this},next:e}),Yi=(e,t)=>Hi((()=>{const{done:n,value:r}=e.next();return{done:n,value:n?void 0:t(r)}})),zi=Object.assign,Ji=Object.keys,Qi=e=>Ji(e).length;class Xi extends ir{constructor(e,t){super(),this.doc=e,this.awareness=t}}class Zi{constructor(e,t){this.clock=e,this.len=t}}class es{constructor(){this.clients=new Map}}const ts=(e,t,n)=>t.clients.forEach(((t,r)=>{const i=e.doc.store.clients.get(r);for(let r=0;r<t.length;r++){const s=t[r];Ro(e,i,s.clock,s.len,n)}})),ns=(e,t)=>{const n=e.clients.get(t.client);return void 0!==n&&null!==((e,t)=>{let n=0,r=e.length-1;for(;n<=r;){const i=sr((n+r)/2),s=e[i],o=s.clock;if(o<=t){if(t<o+s.len)return i;n=i+1}else r=i-1}return null})(n,t.clock)},rs=e=>{e.clients.forEach((e=>{let t,n;for(e.sort(((e,t)=>e.clock-t.clock)),t=1,n=1;t<e.length;t++){const r=e[n-1],i=e[t];r.clock+r.len>=i.clock?r.len=cr(r.len,i.clock+i.len-r.clock):(n<t&&(e[n]=i),n++)}e.length=n}))},is=e=>{const t=new es;for(let n=0;n<e.length;n++)e[n].clients.forEach(((r,i)=>{if(!t.clients.has(i)){const s=r.slice();for(let t=n+1;t<e.length;t++)tr(s,e[t].clients.get(i)||[]);t.clients.set(i,s)}}));return rs(t),t},ss=(e,t,n,r)=>{Xn(e.clients,t,(()=>[])).push(new Zi(n,r))},os=()=>new es,as=e=>{const t=os();return e.clients.forEach(((e,n)=>{const r=[];for(let t=0;t<e.length;t++){const n=e[t];if(n.deleted){const i=n.id.clock;let s=n.length;if(t+1<e.length)for(let n=e[t+1];t+1<e.length&&n.deleted;n=e[1+ ++t])s+=n.length;r.push(new Zi(i,s))}}r.length>0&&t.clients.set(n,r)})),t},cs=(e,t)=>{Ir(e.restEncoder,t.clients.size),nr(t.clients.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{e.resetDsCurVal(),Ir(e.restEncoder,t);const r=n.length;Ir(e.restEncoder,r);for(let t=0;t<r;t++){const r=n[t];e.writeDsClock(r.clock),e.writeDsLen(r.len)}}))},ls=e=>{const t=new es,n=Zr(e.restDecoder);for(let r=0;r<n;r++){e.resetDsCurVal();const n=Zr(e.restDecoder),r=Zr(e.restDecoder);if(r>0){const i=Xn(t.clients,n,(()=>[]));for(let t=0;t<r;t++)i.push(new Zi(e.readDsClock(),e.readDsLen()))}}return t},ds=(e,t,n)=>{const r=new es,i=Zr(e.restDecoder);for(let s=0;s<i;s++){e.resetDsCurVal();const i=Zr(e.restDecoder),s=Zr(e.restDecoder),o=n.clients.get(i)||[],a=bo(n,i);for(let n=0;n<s;n++){const n=e.readDsClock(),s=n+e.readDsLen();if(n<a){a<s&&ss(r,i,a,s-a);let e=Eo(o,n),c=o[e];for(!c.deleted&&c.id.clock<n&&(o.splice(e+1,0,Uc(t,c,n-c.id.clock)),e++);e<o.length&&(c=o[e++],c.id.clock<s);)c.deleted||(s<c.id.clock+c.length&&o.splice(e,0,Uc(t,c,s-c.id.clock)),c.delete(t))}else ss(r,i,n,s-n)}}if(r.clients.size>0){const e=new Es;return Ir(e.restEncoder,0),cs(e,r),e.toUint8Array()}return null},us=(e,t)=>{if(e.clients.size!==t.clients.size)return!1;for(const[n,r]of e.clients.entries()){const e=t.clients.get(n);if(void 0===e||r.length!==e.length)return!1;for(let t=0;t<r.length;t++){const n=r[t],i=e[t];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0},hs=di;class fs extends ir{constructor({guid:e=hi(),collectionid:t=null,gc:n=!0,gcFilter:r=(()=>!0),meta:i=null,autoLoad:s=!1,shouldLoad:o=!0}={}){super(),this.gc=n,this.gcFilter=r,this.clientID=hs(),this.guid=e,this.collectionid=t,this.share=new Map,this.store=new yo,this._transaction=null,this._transactionCleanups=[],this.subdocs=new Set,this._item=null,this.shouldLoad=o,this.autoLoad=s,this.meta=i,this.isLoaded=!1,this.isSynced=!1,this.whenLoaded=fi((e=>{this.on("load",(()=>{this.isLoaded=!0,e(this)}))}));const a=()=>fi((e=>{const t=n=>{void 0!==n&&!0!==n||(this.off("sync",t),e())};this.on("sync",t)}));this.on("sync",(e=>{!1===e&&this.isSynced&&(this.whenSynced=a()),this.isSynced=void 0===e||!0===e,this.isSynced&&!this.isLoaded&&this.emit("load",[])})),this.whenSynced=a()}load(){const e=this._item;null===e||this.shouldLoad||Lo(e.parent.doc,(e=>{e.subdocsLoaded.add(this)}),null,!0),this.shouldLoad=!0}getSubdocs(){return this.subdocs}getSubdocGuids(){return new Set(nr(this.subdocs).map((e=>e.guid)))}transact(e,t=null){return Lo(this,e,t)}get(e,t=_a){const n=Xn(this.share,e,(()=>{const e=new t;return e._integrate(this,null),e})),r=n.constructor;if(t!==_a&&r!==t){if(r===_a){const r=new t;r._map=n._map,n._map.forEach((e=>{for(;null!==e;e=e.left)e.parent=r})),r._start=n._start;for(let e=r._start;null!==e;e=e.right)e.parent=r;return r._length=n._length,this.share.set(e,r),r._integrate(this,null),r}throw new Error(`Type with the name ${e} has already been defined with a different constructor`)}return n}getArray(e=""){return this.get(e,Ka)}getText(e=""){return this.get(e,sc)}getMap(e=""){return this.get(e,$a)}getXmlFragment(e=""){return this.get(e,ac)}toJSON(){const e={};return this.share.forEach(((t,n)=>{e[n]=t.toJSON()})),e}destroy(){nr(this.subdocs).forEach((e=>e.destroy()));const e=this._item;if(null!==e){this._item=null;const t=e.content;t.doc=new fs({guid:this.guid,...t.opts,shouldLoad:!1}),t.doc._item=e,Lo(e.parent.doc,(n=>{const r=t.doc;e.deleted||n.subdocsAdded.add(r),n.subdocsRemoved.add(this)}),null,!0)}this.emit("destroyed",[!0]),this.emit("destroy",[this]),super.destroy()}on(e,t){super.on(e,t)}off(e,t){super.off(e,t)}}class gs{constructor(e){this.restDecoder=e}resetDsCurVal(){}readDsClock(){return Zr(this.restDecoder)}readDsLen(){return Zr(this.restDecoder)}}class ps extends gs{readLeftID(){return Fs(Zr(this.restDecoder),Zr(this.restDecoder))}readRightID(){return Fs(Zr(this.restDecoder),Zr(this.restDecoder))}readClient(){return Zr(this.restDecoder)}readInfo(){return Xr(this.restDecoder)}readString(){return ti(this.restDecoder)}readParentInfo(){return 1===Zr(this.restDecoder)}readTypeRef(){return Zr(this.restDecoder)}readLen(){return Zr(this.restDecoder)}readAny(){return ii(this.restDecoder)}readBuf(){return(e=>{const t=(n=e.byteLength,new Uint8Array(n));var n;return t.set(e),t})(Qr(this.restDecoder))}readJSON(){return JSON.parse(ti(this.restDecoder))}readKey(){return ti(this.restDecoder)}}class ms{constructor(e){this.dsCurrVal=0,this.restDecoder=e}resetDsCurVal(){this.dsCurrVal=0}readDsClock(){return this.dsCurrVal+=Zr(this.restDecoder),this.dsCurrVal}readDsLen(){const e=Zr(this.restDecoder)+1;return this.dsCurrVal+=e,e}}class ys extends ms{constructor(e){super(e),this.keys=[],Zr(e),this.keyClockDecoder=new ai(Qr(e)),this.clientDecoder=new oi(Qr(e)),this.leftClockDecoder=new ai(Qr(e)),this.rightClockDecoder=new ai(Qr(e)),this.infoDecoder=new si(Qr(e),Xr),this.stringDecoder=new ci(Qr(e)),this.parentInfoDecoder=new si(Qr(e),Xr),this.typeRefDecoder=new oi(Qr(e)),this.lenDecoder=new oi(Qr(e))}readLeftID(){return new Bs(this.clientDecoder.read(),this.leftClockDecoder.read())}readRightID(){return new Bs(this.clientDecoder.read(),this.rightClockDecoder.read())}readClient(){return this.clientDecoder.read()}readInfo(){return this.infoDecoder.read()}readString(){return this.stringDecoder.read()}readParentInfo(){return 1===this.parentInfoDecoder.read()}readTypeRef(){return this.typeRefDecoder.read()}readLen(){return this.lenDecoder.read()}readAny(){return ii(this.restDecoder)}readBuf(){return Qr(this.restDecoder)}readJSON(){return ii(this.restDecoder)}readKey(){const e=this.keyClockDecoder.read();if(e<this.keys.length)return this.keys[e];{const e=this.stringDecoder.read();return this.keys.push(e),e}}}class vs{constructor(){this.restEncoder=Sr()}toUint8Array(){return Cr(this.restEncoder)}resetDsCurVal(){}writeDsClock(e){Ir(this.restEncoder,e)}writeDsLen(e){Ir(this.restEncoder,e)}}class bs extends vs{writeLeftID(e){Ir(this.restEncoder,e.client),Ir(this.restEncoder,e.clock)}writeRightID(e){Ir(this.restEncoder,e.client),Ir(this.restEncoder,e.clock)}writeClient(e){Ir(this.restEncoder,e)}writeInfo(e){Rr(this.restEncoder,e)}writeString(e){Dr(this.restEncoder,e)}writeParentInfo(e){Ir(this.restEncoder,e?1:0)}writeTypeRef(e){Ir(this.restEncoder,e)}writeLen(e){Ir(this.restEncoder,e)}writeAny(e){Nr(this.restEncoder,e)}writeBuf(e){Pr(this.restEncoder,e)}writeJSON(e){Dr(this.restEncoder,JSON.stringify(e))}writeKey(e){Dr(this.restEncoder,e)}}class _s{constructor(){this.restEncoder=Sr(),this.dsCurrVal=0}toUint8Array(){return Cr(this.restEncoder)}resetDsCurVal(){this.dsCurrVal=0}writeDsClock(e){const t=e-this.dsCurrVal;this.dsCurrVal=e,Ir(this.restEncoder,t)}writeDsLen(e){0===e&&Gr(),Ir(this.restEncoder,e-1),this.dsCurrVal+=e}}class Es extends _s{constructor(){super(),this.keyMap=new Map,this.keyClock=0,this.keyClockEncoder=new Kr,this.clientEncoder=new jr,this.leftClockEncoder=new Kr,this.rightClockEncoder=new Kr,this.infoEncoder=new xr(Rr),this.stringEncoder=new qr,this.parentInfoEncoder=new xr(Rr),this.typeRefEncoder=new jr,this.lenEncoder=new jr}toUint8Array(){const e=Sr();return Ir(e,0),Pr(e,this.keyClockEncoder.toUint8Array()),Pr(e,this.clientEncoder.toUint8Array()),Pr(e,this.leftClockEncoder.toUint8Array()),Pr(e,this.rightClockEncoder.toUint8Array()),Pr(e,Cr(this.infoEncoder)),Pr(e,this.stringEncoder.toUint8Array()),Pr(e,Cr(this.parentInfoEncoder)),Pr(e,this.typeRefEncoder.toUint8Array()),Pr(e,this.lenEncoder.toUint8Array()),Mr(e,Cr(this.restEncoder)),Cr(e)}writeLeftID(e){this.clientEncoder.write(e.client),this.leftClockEncoder.write(e.clock)}writeRightID(e){this.clientEncoder.write(e.client),this.rightClockEncoder.write(e.clock)}writeClient(e){this.clientEncoder.write(e)}writeInfo(e){this.infoEncoder.write(e)}writeString(e){this.stringEncoder.write(e)}writeParentInfo(e){this.parentInfoEncoder.write(e?1:0)}writeTypeRef(e){this.typeRefEncoder.write(e)}writeLen(e){this.lenEncoder.write(e)}writeAny(e){Nr(this.restEncoder,e)}writeBuf(e){Pr(this.restEncoder,e)}writeJSON(e){Nr(this.restEncoder,e)}writeKey(e){const t=this.keyMap.get(e);void 0===t?(this.keyClockEncoder.write(this.keyClock++),this.stringEncoder.write(e)):this.keyClockEncoder.write(t)}}const ws=(e,t,n)=>{const r=new Map;n.forEach(((e,n)=>{bo(t,n)>e&&r.set(n,e)})),vo(t).forEach(((e,t)=>{n.has(t)||r.set(t,0)})),Ir(e.restEncoder,r.size),nr(r.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([n,r])=>{((e,t,n,r)=>{r=cr(r,t[0].id.clock);const i=Eo(t,r);Ir(e.restEncoder,t.length-i),e.writeClient(n),Ir(e.restEncoder,r);const s=t[i];s.write(e,r-s.id.clock);for(let n=i+1;n<t.length;n++)t[n].write(e,0)})(e,t.clients.get(n),n,r)}))},Ss=(e,t,n,r=new ys(e))=>Lo(t,(e=>{e.local=!1;let t=!1;const n=e.doc,i=n.store,s=((e,t)=>{const n=Jn(),r=Zr(e.restDecoder);for(let i=0;i<r;i++){const r=Zr(e.restDecoder),i=new Array(r),s=e.readClient();let o=Zr(e.restDecoder);n.set(s,{i:0,refs:i});for(let n=0;n<r;n++){const r=e.readInfo();switch(31&r){case 0:{const t=e.readLen();i[n]=new fc(Fs(s,o),t),o+=t;break}case 10:{const t=Zr(e.restDecoder);i[n]=new Fc(Fs(s,o),t),o+=t;break}default:{const a=0==(192&r),c=new xc(Fs(s,o),null,(r&ur)===ur?e.readLeftID():null,null,(r&dr)===dr?e.readRightID():null,a?e.readParentInfo()?t.get(e.readString()):e.readLeftID():null,a&&32==(32&r)?e.readString():null,Bc(e,r));i[n]=c,o+=c.length}}}}return n})(r,n),o=((e,t,n)=>{const r=[];let i=nr(n.keys()).sort(((e,t)=>e-t));if(0===i.length)return null;const s=()=>{if(0===i.length)return null;let e=n.get(i[i.length-1]);for(;e.refs.length===e.i;){if(i.pop(),!(i.length>0))return null;e=n.get(i[i.length-1])}return e};let o=s();if(null===o)return null;const a=new yo,c=new Map,l=(e,t)=>{const n=c.get(e);(null==n||n>t)&&c.set(e,t)};let d=o.refs[o.i++];const u=new Map,h=()=>{for(const e of r){const t=e.id.client,r=n.get(t);r?(r.i--,a.clients.set(t,r.refs.slice(r.i)),n.delete(t),r.i=0,r.refs=[]):a.clients.set(t,[e]),i=i.filter((e=>e!==t))}r.length=0};for(;;){if(d.constructor!==Fc){const i=Xn(u,d.id.client,(()=>bo(t,d.id.client)))-d.id.clock;if(i<0)r.push(d),l(d.id.client,d.id.clock-1),h();else{const s=d.getMissing(e,t);if(null!==s){r.push(d);const e=n.get(s)||{refs:[],i:0};if(e.refs.length!==e.i){d=e.refs[e.i++];continue}l(s,bo(t,s)),h()}else(0===i||i<d.length)&&(d.integrate(e,i),u.set(d.id.client,d.id.clock+d.length))}}if(r.length>0)d=r.pop();else if(null!==o&&o.i<o.refs.length)d=o.refs[o.i++];else{if(o=s(),null===o)break;d=o.refs[o.i++]}}if(a.clients.size>0){const e=new Es;return ws(e,a,new Map),Ir(e.restEncoder,0),{missing:c,update:e.toUint8Array()}}return null})(e,i,s),a=i.pendingStructs;if(a){for(const[e,n]of a.missing)if(n<bo(i,e)){t=!0;break}if(o){for(const[e,t]of o.missing){const n=a.missing.get(e);(null==n||n>t)&&a.missing.set(e,t)}a.update=Xo([a.update,o.update])}}else i.pendingStructs=o;const c=ds(r,e,i);if(i.pendingDs){const t=new ys(zr(i.pendingDs));Zr(t.restDecoder);const n=ds(t,e,i);i.pendingDs=c&&n?Xo([c,n]):c||n}else i.pendingDs=c;if(t){const t=i.pendingStructs.update;i.pendingStructs=null,Ts(e.doc,t)}}),n,!1),Cs=(e,t,n)=>Ss(e,t,n,new ps(e)),Ts=(e,t,n,r=ys)=>{const i=zr(t);Ss(i,e,n,new r(i))},Rs=(e,t,n)=>Ts(e,t,n,ps),Is=(e,t=new Uint8Array([0]),n=new Es)=>{((e,t,n=new Map)=>{ws(e,t.store,n),cs(e,as(t.store))})(n,e,As(t));const r=[n.toUint8Array()];if(e.store.pendingDs&&r.push(e.store.pendingDs),e.store.pendingStructs&&r.push(Zo(e.store.pendingStructs.update,t)),r.length>1){if(n.constructor===bs)return Wo(r.map(((e,t)=>0===t?e:la(e))));if(n.constructor===Es)return Xo(r)}return r[0]},ks=(e,t)=>Is(e,t,new bs),Os=e=>{const t=new Map,n=Zr(e.restDecoder);for(let r=0;r<n;r++){const n=Zr(e.restDecoder),r=Zr(e.restDecoder);t.set(n,r)}return t},As=e=>Os(new gs(zr(e))),Ds=(e,t)=>(Ir(e.restEncoder,t.size),nr(t.entries()).sort(((e,t)=>t[0]-e[0])).forEach((([t,n])=>{Ir(e.restEncoder,t),Ir(e.restEncoder,n)})),e),Ms=e=>((e,t=new _s)=>(e instanceof Map?Ds(t,e):((e,t)=>{Ds(e,vo(t.store))})(t,e),t.toUint8Array()))(e,new vs);class Ps{constructor(){this.l=[]}}const Us=()=>new Ps,Ls=(e,t)=>e.l.push(t),Ns=(e,t)=>{const n=e.l,r=n.length;e.l=n.filter((e=>t!==e)),r===e.l.length&&console.error("[yjs] Tried to remove event handler that doesn't exist.")},xs=(e,t,n)=>vi(e.l,[t,n]);class Bs{constructor(e,t){this.client=e,this.clock=t}}const js=(e,t)=>e===t||null!==e&&null!==t&&e.client===t.client&&e.clock===t.clock,Fs=(e,t)=>new Bs(e,t),Ks=(e,t)=>{Ir(e,t.client),Ir(e,t.clock)},qs=e=>Fs(Zr(e),Zr(e)),$s=e=>{for(const[t,n]of e.doc.share.entries())if(n===e)return t;throw Gr()},Vs=(e,t)=>{for(;null!==t;){if(t.parent===e)return!0;t=t.parent._item}return!1},Gs=e=>{const t=[];let n=e._start;for(;n;)t.push(n),n=n.right;console.log("Children: ",t),console.log("Children content: ",t.filter((e=>!e.deleted)).map((e=>e.content)))};class Ws{constructor(e,t=e.getMap("users")){const n=new Map;this.yusers=t,this.doc=e,this.clients=new Map,this.dss=n;const r=(e,t)=>{const n=e.get("ds"),r=e.get("ids"),i=e=>this.clients.set(e,t);n.observe((e=>{e.changes.added.forEach((e=>{e.content.getContent().forEach((e=>{e instanceof Uint8Array&&this.dss.set(t,is([this.dss.get(t)||os(),ls(new gs(zr(e)))]))}))}))})),this.dss.set(t,is(n.map((e=>ls(new gs(zr(e))))))),r.observe((e=>e.changes.added.forEach((e=>e.content.getContent().forEach(i))))),r.forEach(i)};t.observe((e=>{e.keysChanged.forEach((e=>r(t.get(e),e)))})),t.forEach(r)}setUserMapping(e,t,n,{filter:r=(()=>!0)}={}){const i=this.yusers;let s=i.get(n);s||(s=new $a,s.set("ids",new Ka),s.set("ds",new Ka),i.set(n,s)),s.get("ids").push([t]),i.observe((e=>{setTimeout((()=>{const e=i.get(n);if(e!==s){s=e,this.clients.forEach(((e,t)=>{n===e&&s.get("ids").push([t])}));const t=new vs,r=this.dss.get(n);r&&(cs(t,r),s.get("ds").push([t.toUint8Array()]))}}),0)})),e.on("afterTransaction",(e=>{setTimeout((()=>{const t=s.get("ds"),n=e.deleteSet;if(e.local&&n.clients.size>0&&r(e,n)){const e=new vs;cs(e,n),t.push([e.toUint8Array()])}}))}))}getUserByClientId(e){return this.clients.get(e)||null}getUserByDeletedId(e){for(const[t,n]of this.dss.entries())if(ns(n,e))return t;return null}}class Hs{constructor(e,t,n,r=0){this.type=e,this.tname=t,this.item=n,this.assoc=r}}const Ys=e=>{const t={};return e.type&&(t.type=e.type),e.tname&&(t.tname=e.tname),e.item&&(t.item=e.item),null!=e.assoc&&(t.assoc=e.assoc),t},zs=e=>new Hs(null==e.type?null:Fs(e.type.client,e.type.clock),e.tname||null,null==e.item?null:Fs(e.item.client,e.item.clock),null==e.assoc?0:e.assoc);class Js{constructor(e,t,n=0){this.type=e,this.index=t,this.assoc=n}}const Qs=(e,t,n)=>{let r=null,i=null;return null===e._item?i=$s(e):r=Fs(e._item.id.client,e._item.id.clock),new Hs(r,i,t,n)},Xs=(e,t,n=0)=>{let r=e._start;if(n<0){if(0===t)return Qs(e,null,n);t--}for(;null!==r;){if(!r.deleted&&r.countable){if(r.length>t)return Qs(e,Fs(r.id.client,r.id.clock+t),n);t-=r.length}if(null===r.right&&n<0)return Qs(e,r.lastId,n);r=r.right}return Qs(e,null,n)},Zs=e=>{const t=Sr();return((e,t)=>{const{type:n,tname:r,item:i,assoc:s}=t;if(null!==i)Ir(e,0),Ks(e,i);else if(null!==r)Rr(e,1),Dr(e,r);else{if(null===n)throw Gr();Rr(e,2),Ks(e,n)}kr(e,s)})(t,e),Cr(t)},eo=e=>(e=>{let t=null,n=null,r=null;switch(Zr(e)){case 0:r=qs(e);break;case 1:n=ti(e);break;case 2:t=qs(e)}const i=Jr(e)?ei(e):0;return new Hs(t,n,r,i)})(zr(e)),to=(e,t)=>{const n=t.store,r=e.item,i=e.type,s=e.tname,o=e.assoc;let a=null,c=0;if(null!==r){if(bo(n,r.client)<=r.clock)return null;const e=Mc(n,r),t=e.item;if(!(t instanceof xc))return null;if(a=t.parent,null===a._item||!a._item.deleted){c=t.deleted||!t.countable?0:e.diff+(o>=0?0:1);let n=t.left;for(;null!==n;)!n.deleted&&n.countable&&(c+=n.length),n=n.left}}else{if(null!==s)a=t.get(s);else{if(null===i)throw Gr();{if(bo(n,i.client)<=i.clock)return null;const{item:e}=Mc(n,i);if(!(e instanceof xc&&e.content instanceof Dc))return null;a=e.content.type}}c=o>=0?a._length:0}return((e,t,n=0)=>new Js(e,t,n))(a,c,e.assoc)},no=(e,t)=>e===t||null!==e&&null!==t&&e.tname===t.tname&&js(e.item,t.item)&&js(e.type,t.type)&&e.assoc===t.assoc;class ro{constructor(e,t){this.ds=e,this.sv=t}}const io=(e,t)=>{const n=e.ds.clients,r=t.ds.clients,i=e.sv,s=t.sv;if(i.size!==s.size||n.size!==r.size)return!1;for(const[e,t]of i.entries())if(s.get(e)!==t)return!1;for(const[e,t]of n.entries()){const n=r.get(e)||[];if(t.length!==n.length)return!1;for(let e=0;e<t.length;e++){const r=t[e],i=n[e];if(r.clock!==i.clock||r.len!==i.len)return!1}}return!0},so=(e,t=new _s)=>(cs(t,e.ds),Ds(t,e.sv),t.toUint8Array()),oo=e=>so(e,new vs),ao=(e,t=new ms(zr(e)))=>new ro(ls(t),Os(t)),co=e=>ao(e,new gs(zr(e))),lo=(e,t)=>new ro(e,t),uo=lo(os(),new Map),ho=e=>lo(as(e.store),vo(e.store)),fo=(e,t)=>void 0===t?!e.deleted:t.sv.has(e.id.client)&&(t.sv.get(e.id.client)||0)>e.id.clock&&!ns(t.ds,e.id),go=(e,t)=>{const n=Xn(e.meta,go,Zn),r=e.doc.store;n.has(t)||(t.sv.forEach(((t,n)=>{t<bo(r,n)&&Co(e,Fs(n,t))})),ts(e,t.ds,(e=>{})),n.add(t))},po=(e,t,n=new fs)=>{if(e.gc)throw new Error("Garbage-collection must be disabled in `originDoc`!");const{sv:r,ds:i}=t,s=new Es;return e.transact((t=>{let n=0;r.forEach((e=>{e>0&&n++})),Ir(s.restEncoder,n);for(const[n,i]of r){if(0===i)continue;i<bo(e.store,n)&&Co(t,Fs(n,i));const r=e.store.clients.get(n)||[],o=Eo(r,i-1);Ir(s.restEncoder,o+1),s.writeClient(n),Ir(s.restEncoder,0);for(let e=0;e<=o;e++)r[e].write(s,0)}cs(s,i)})),Ts(n,s.toUint8Array(),"snapshot"),n},mo=(e,t)=>((e,t,n=ys)=>{const r=new n(zr(t)),i=new Fo(r,!1);for(let t=i.curr;null!==t;t=i.next())if((e.sv.get(t.id.client)||0)<t.id.clock+t.length)return!1;const s=is([e.ds,ls(r)]);return us(e.ds,s)})(e,t,ps);class yo{constructor(){this.clients=new Map,this.pendingStructs=null,this.pendingDs=null}}const vo=e=>{const t=new Map;return e.clients.forEach(((e,n)=>{const r=e[e.length-1];t.set(n,r.id.clock+r.length)})),t},bo=(e,t)=>{const n=e.clients.get(t);if(void 0===n)return 0;const r=n[n.length-1];return r.id.clock+r.length},_o=(e,t)=>{let n=e.clients.get(t.id.client);if(void 0===n)n=[],e.clients.set(t.id.client,n);else{const e=n[n.length-1];if(e.id.clock+e.length!==t.id.clock)throw Gr()}n.push(t)},Eo=(e,t)=>{let n=0,r=e.length-1,i=e[r],s=i.id.clock;if(s===t)return r;let o=sr(t/(s+i.length-1)*r);for(;n<=r;){if(i=e[o],s=i.id.clock,s<=t){if(t<s+i.length)return o;n=o+1}else r=o-1;o=sr((n+r)/2)}throw Gr()},wo=(e,t)=>{const n=e.clients.get(t.client);return n[Eo(n,t.clock)]},So=(e,t,n)=>{const r=Eo(t,n),i=t[r];return i.id.clock<n&&i instanceof xc?(t.splice(r+1,0,Uc(e,i,n-i.id.clock)),r+1):r},Co=(e,t)=>{const n=e.doc.store.clients.get(t.client);return n[So(e,n,t.clock)]},To=(e,t,n)=>{const r=t.clients.get(n.client),i=Eo(r,n.clock),s=r[i];return n.clock!==s.id.clock+s.length-1&&s.constructor!==fc&&r.splice(i+1,0,Uc(e,s,n.clock-s.id.clock+1)),s},Ro=(e,t,n,r,i)=>{if(0===r)return;const s=n+r;let o,a=So(e,t,n);do{o=t[a++],s<o.id.clock+o.length&&So(e,t,s),i(o)}while(a<t.length&&t[a].id.clock<s)};class Io{constructor(e,t,n){this.doc=e,this.deleteSet=new es,this.beforeState=vo(e.store),this.afterState=new Map,this.changed=new Map,this.changedParentTypes=new Map,this._mergeStructs=[],this.origin=t,this.meta=new Map,this.local=n,this.subdocsAdded=new Set,this.subdocsRemoved=new Set,this.subdocsLoaded=new Set,this._needFormattingCleanup=!1}}const ko=(e,t)=>!(0===t.deleteSet.clients.size&&!((e,n)=>{for(const[n,s]of e)if(r=s,i=n,t.beforeState.get(i)!==r)return!0;var r,i;return!1})(t.afterState)||(rs(t.deleteSet),((e,t)=>{ws(e,t.doc.store,t.beforeState)})(e,t),cs(e,t.deleteSet),0)),Oo=(e,t,n)=>{const r=t._item;(null===r||r.id.clock<(e.beforeState.get(r.id.client)||0)&&!r.deleted)&&Xn(e.changed,t,Zn).add(n)},Ao=(e,t)=>{let n=e[t],r=e[t-1],i=t;for(;i>0&&r.deleted===n.deleted&&r.constructor===n.constructor&&r.mergeWith(n);n=r,r=e[--i-1])n instanceof xc&&null!==n.parentSub&&n.parent._map.get(n.parentSub)===n&&n.parent._map.set(n.parentSub,r);const s=t-i;return s&&e.splice(t+1-s,s),s},Do=(e,t,n)=>{for(const[r,i]of e.clients.entries()){const e=t.clients.get(r);for(let r=i.length-1;r>=0;r--){const s=i[r],o=s.clock+s.len;for(let r=Eo(e,s.clock),i=e[r];r<e.length&&i.id.clock<o;i=e[++r]){const i=e[r];if(s.clock+s.len<=i.id.clock)break;i instanceof xc&&i.deleted&&!i.keep&&n(i)&&i.gc(t,!1)}}}},Mo=(e,t)=>{e.clients.forEach(((e,n)=>{const r=t.clients.get(n);for(let t=e.length-1;t>=0;t--){const n=e[t];for(let e=ar(r.length-1,1+Eo(r,n.clock+n.len-1)),t=r[e];e>0&&t.id.clock>=n.clock;t=r[e])e-=1+Ao(r,e)}}))},Po=(e,t,n)=>{Do(e,t,n),Mo(e,t)},Uo=(e,t)=>{if(t<e.length){const n=e[t],r=n.doc,i=r.store,s=n.deleteSet,o=n._mergeStructs;try{rs(s),n.afterState=vo(n.doc.store),r.emit("beforeObserverCalls",[n,r]);const e=[];n.changed.forEach(((t,r)=>e.push((()=>{null!==r._item&&r._item.deleted||r._callObserver(n,t)})))),e.push((()=>{n.changedParentTypes.forEach(((e,t)=>{t._dEH.l.length>0&&(null===t._item||!t._item.deleted)&&((e=e.filter((e=>null===e.target._item||!e.target._item.deleted))).forEach((e=>{e.currentTarget=t,e._path=null})),e.sort(((e,t)=>e.path.length-t.path.length)),xs(t._dEH,e,n))}))})),e.push((()=>r.emit("afterTransaction",[n,r]))),vi(e,[]),n._needFormattingCleanup&&nc(n)}finally{r.gc&&Do(s,i,r.gcFilter),Mo(s,i),n.afterState.forEach(((e,t)=>{const r=n.beforeState.get(t)||0;if(r!==e){const e=i.clients.get(t),n=cr(Eo(e,r),1);for(let t=e.length-1;t>=n;)t-=1+Ao(e,t)}}));for(let e=o.length-1;e>=0;e--){const{client:t,clock:n}=o[e].id,r=i.clients.get(t),s=Eo(r,n);s+1<r.length&&Ao(r,s+1)>1||s>0&&Ao(r,s)}if(n.local||n.afterState.get(r.clientID)===n.beforeState.get(r.clientID)||(Gi(Ki,Ui,"[yjs] ",Li,ji,"Changed the client-id because another client seems to be using it."),r.clientID=hs()),r.emit("afterTransactionCleanup",[n,r]),r._observers.has("update")){const e=new bs;ko(e,n)&&r.emit("update",[e.toUint8Array(),n.origin,r,n])}if(r._observers.has("updateV2")){const e=new Es;ko(e,n)&&r.emit("updateV2",[e.toUint8Array(),n.origin,r,n])}const{subdocsAdded:a,subdocsLoaded:c,subdocsRemoved:l}=n;(a.size>0||l.size>0||c.size>0)&&(a.forEach((e=>{e.clientID=r.clientID,null==e.collectionid&&(e.collectionid=r.collectionid),r.subdocs.add(e)})),l.forEach((e=>r.subdocs.delete(e))),r.emit("subdocs",[{loaded:c,added:a,removed:l},r,n]),l.forEach((e=>e.destroy()))),e.length<=t+1?(r._transactionCleanups=[],r.emit("afterAllTransactions",[r,e])):Uo(e,t+1)}}},Lo=(e,t,n=null,r=!0)=>{const i=e._transactionCleanups;let s=!1,o=null;null===e._transaction&&(s=!0,e._transaction=new Io(e,n,r),i.push(e._transaction),1===i.length&&e.emit("beforeAllTransactions",[e]),e.emit("beforeTransaction",[e._transaction,e]));try{o=t(e._transaction)}finally{if(s){const t=e._transaction===i[0];e._transaction=null,t&&Uo(i,0)}}return o};class No{constructor(e,t){this.insertions=t,this.deletions=e,this.meta=new Map}}const xo=(e,t,n)=>{ts(e,n.deletions,(e=>{e instanceof xc&&t.scope.some((t=>Vs(t,e)))&&Pc(e,!1)}))},Bo=(e,t,n)=>{let r=null,i=null;const s=e.doc,o=e.scope;if(Lo(s,(n=>{for(;t.length>0&&null===r;){const i=s.store,a=t.pop(),c=new Set,l=[];let d=!1;ts(n,a.insertions,(e=>{if(e instanceof xc){if(null!==e.redone){let{item:t,diff:r}=Mc(i,e.id);r>0&&(t=Co(n,Fs(t.id.client,t.id.clock+r))),e=t}!e.deleted&&o.some((t=>Vs(t,e)))&&l.push(e)}})),ts(n,a.deletions,(e=>{e instanceof xc&&o.some((t=>Vs(t,e)))&&!ns(a.insertions,e.id)&&c.add(e)})),c.forEach((t=>{d=null!==Nc(n,t,c,a.insertions,e.ignoreRemoteMapChanges,e)||d}));for(let t=l.length-1;t>=0;t--){const r=l[t];e.deleteFilter(r)&&(r.delete(n),d=!0)}r=d?a:null}n.changed.forEach(((e,t)=>{e.has(null)&&t._searchMarker&&(t._searchMarker.length=0)})),i=n}),e),null!=r){const t=i.changedParentTypes;e.emit("stack-item-popped",[{stackItem:r,type:n,changedParentTypes:t},e])}return r};class jo extends ir{constructor(e,{captureTimeout:t=500,captureTransaction:n=(e=>!0),deleteFilter:r=(()=>!0),trackedOrigins:i=new Set([null]),ignoreRemoteMapChanges:s=!1,doc:o=(rr(e)?e[0].doc:e.doc)}={}){super(),this.scope=[],this.doc=o,this.addToScope(e),this.deleteFilter=r,i.add(this),this.trackedOrigins=i,this.captureTransaction=n,this.undoStack=[],this.redoStack=[],this.undoing=!1,this.redoing=!1,this.lastChange=0,this.ignoreRemoteMapChanges=s,this.captureTimeout=t,this.afterTransactionHandler=e=>{if(!(this.captureTransaction(e)&&this.scope.some((t=>e.changedParentTypes.has(t)))&&(this.trackedOrigins.has(e.origin)||e.origin&&this.trackedOrigins.has(e.origin.constructor))))return;const t=this.undoing,n=this.redoing,r=t?this.redoStack:this.undoStack;t?this.stopCapturing():n||this.clear(!1,!0);const i=new es;e.afterState.forEach(((t,n)=>{const r=e.beforeState.get(n)||0,s=t-r;s>0&&ss(i,n,r,s)}));const s=Pi();let o=!1;if(this.lastChange>0&&s-this.lastChange<this.captureTimeout&&r.length>0&&!t&&!n){const t=r[r.length-1];t.deletions=is([t.deletions,e.deleteSet]),t.insertions=is([t.insertions,i])}else r.push(new No(e.deleteSet,i)),o=!0;t||n||(this.lastChange=s),ts(e,e.deleteSet,(e=>{e instanceof xc&&this.scope.some((t=>Vs(t,e)))&&Pc(e,!0)}));const a=[{stackItem:r[r.length-1],origin:e.origin,type:t?"redo":"undo",changedParentTypes:e.changedParentTypes},this];o?this.emit("stack-item-added",a):this.emit("stack-item-updated",a)},this.doc.on("afterTransaction",this.afterTransactionHandler),this.doc.on("destroy",(()=>{this.destroy()}))}addToScope(e){(e=rr(e)?e:[e]).forEach((e=>{this.scope.every((t=>t!==e))&&(e.doc!==this.doc&&((...e)=>{console.warn(...Vi(e)),e.unshift(Ki),Wi.forEach((t=>t.print(e)))})("[yjs#509] Not same Y.Doc"),this.scope.push(e))}))}addTrackedOrigin(e){this.trackedOrigins.add(e)}removeTrackedOrigin(e){this.trackedOrigins.delete(e)}clear(e=!0,t=!0){(e&&this.canUndo()||t&&this.canRedo())&&this.doc.transact((n=>{e&&(this.undoStack.forEach((e=>xo(n,this,e))),this.undoStack=[]),t&&(this.redoStack.forEach((e=>xo(n,this,e))),this.redoStack=[]),this.emit("stack-cleared",[{undoStackCleared:e,redoStackCleared:t}])}))}stopCapturing(){this.lastChange=0}undo(){let e;this.undoing=!0;try{e=Bo(this,this.undoStack,"undo")}finally{this.undoing=!1}return e}redo(){let e;this.redoing=!0;try{e=Bo(this,this.redoStack,"redo")}finally{this.redoing=!1}return e}canUndo(){return this.undoStack.length>0}canRedo(){return this.redoStack.length>0}destroy(){this.trackedOrigins.delete(this),this.doc.off("afterTransaction",this.afterTransactionHandler),super.destroy()}}class Fo{constructor(e,t){this.gen=function*(e){const t=Zr(e.restDecoder);for(let n=0;n<t;n++){const t=Zr(e.restDecoder),n=e.readClient();let r=Zr(e.restDecoder);for(let i=0;i<t;i++){const t=e.readInfo();if(10===t){const t=Zr(e.restDecoder);yield new Fc(Fs(n,r),t),r+=t}else if(0!=(31&t)){const i=0==(192&t),s=new xc(Fs(n,r),null,(t&ur)===ur?e.readLeftID():null,null,(t&dr)===dr?e.readRightID():null,i?e.readParentInfo()?e.readString():e.readLeftID():null,i&&32==(32&t)?e.readString():null,Bc(e,t));yield s,r+=s.length}else{const t=e.readLen();yield new fc(Fs(n,r),t),r+=t}}}}(e),this.curr=null,this.done=!1,this.filterSkips=t,this.next()}next(){do{this.curr=this.gen.next().value||null}while(this.filterSkips&&null!==this.curr&&this.curr.constructor===Fc);return this.curr}}const Ko=e=>qo(e,ps),qo=(e,t=ys)=>{const n=[],r=new t(zr(e)),i=new Fo(r,!1);for(let e=i.curr;null!==e;e=i.next())n.push(e);Gi("Structs: ",n);const s=ls(r);Gi("DeleteSet: ",s)},$o=e=>Vo(e,ps),Vo=(e,t=ys)=>{const n=[],r=new t(zr(e)),i=new Fo(r,!1);for(let e=i.curr;null!==e;e=i.next())n.push(e);return{structs:n,ds:ls(r)}};class Go{constructor(e){this.currClient=0,this.startClock=0,this.written=0,this.encoder=e,this.clientStructs=[]}}const Wo=e=>Xo(e,ps,bs),Ho=(e,t=_s,n=ys)=>{const r=new t,i=new Fo(new n(zr(e)),!1);let s=i.curr;if(null!==s){let e=0,t=s.id.client,n=0!==s.id.clock,o=n?0:s.id.clock+s.length;for(;null!==s;s=i.next())t!==s.id.client&&(0!==o&&(e++,Ir(r.restEncoder,t),Ir(r.restEncoder,o)),t=s.id.client,o=0,n=0!==s.id.clock),s.constructor===Fc&&(n=!0),n||(o=s.id.clock+s.length);0!==o&&(e++,Ir(r.restEncoder,t),Ir(r.restEncoder,o));const a=Sr();return Ir(a,e),((e,t)=>{Mr(e,Cr(t))})(a,r.restEncoder),r.restEncoder=a,r.toUint8Array()}return Ir(r.restEncoder,0),r.toUint8Array()},Yo=e=>Ho(e,vs,ps),zo=(e,t=ys)=>{const n=new Map,r=new Map,i=new Fo(new t(zr(e)),!1);let s=i.curr;if(null!==s){let e=s.id.client,t=s.id.clock;for(n.set(e,t);null!==s;s=i.next())e!==s.id.client&&(r.set(e,t),n.set(s.id.client,s.id.clock),e=s.id.client),t=s.id.clock+s.length;r.set(e,t)}return{from:n,to:r}},Jo=e=>zo(e,ps),Qo=(e,t)=>{if(e.constructor===fc){const{client:n,clock:r}=e.id;return new fc(Fs(n,r+t),e.length-t)}if(e.constructor===Fc){const{client:n,clock:r}=e.id;return new Fc(Fs(n,r+t),e.length-t)}{const n=e,{client:r,clock:i}=n.id;return new xc(Fs(r,i+t),null,Fs(r,i+t-1),null,n.rightOrigin,n.parent,n.parentSub,n.content.splice(t))}},Xo=(e,t=ys,n=Es)=>{if(1===e.length)return e[0];const r=e.map((e=>new t(zr(e))));let i=r.map((e=>new Fo(e,!0))),s=null;const o=new n,a=new Go(o);for(;i=i.filter((e=>null!==e.curr)),i.sort(((e,t)=>{if(e.curr.id.client===t.curr.id.client){const n=e.curr.id.clock-t.curr.id.clock;return 0===n?e.curr.constructor===t.curr.constructor?0:e.curr.constructor===Fc?1:-1:n}return t.curr.id.client-e.curr.id.client})),0!==i.length;){const e=i[0],t=e.curr.id.client;if(null!==s){let n=e.curr,r=!1;for(;null!==n&&n.id.clock+n.length<=s.struct.id.clock+s.struct.length&&n.id.client>=s.struct.id.client;)n=e.next(),r=!0;if(null===n||n.id.client!==t||r&&n.id.clock>s.struct.id.clock+s.struct.length)continue;if(t!==s.struct.id.client)na(a,s.struct,s.offset),s={struct:n,offset:0},e.next();else if(s.struct.id.clock+s.struct.length<n.id.clock)if(s.struct.constructor===Fc)s.struct.length=n.id.clock+n.length-s.struct.id.clock;else{na(a,s.struct,s.offset);const e=n.id.clock-s.struct.id.clock-s.struct.length;s={struct:new Fc(Fs(t,s.struct.id.clock+s.struct.length),e),offset:0}}else{const t=s.struct.id.clock+s.struct.length-n.id.clock;t>0&&(s.struct.constructor===Fc?s.struct.length-=t:n=Qo(n,t)),s.struct.mergeWith(n)||(na(a,s.struct,s.offset),s={struct:n,offset:0},e.next())}}else s={struct:e.curr,offset:0},e.next();for(let n=e.curr;null!==n&&n.id.client===t&&n.id.clock===s.struct.id.clock+s.struct.length&&n.constructor!==Fc;n=e.next())na(a,s.struct,s.offset),s={struct:n,offset:0}}null!==s&&(na(a,s.struct,s.offset),s=null),ra(a);const c=r.map((e=>ls(e))),l=is(c);return cs(o,l),o.toUint8Array()},Zo=(e,t,n=ys,r=Es)=>{const i=As(t),s=new r,o=new Go(s),a=new n(zr(e)),c=new Fo(a,!1);for(;c.curr;){const e=c.curr,t=e.id.client,n=i.get(t)||0;if(c.curr.constructor!==Fc)if(e.id.clock+e.length>n)for(na(o,e,cr(n-e.id.clock,0)),c.next();c.curr&&c.curr.id.client===t;)na(o,c.curr,0),c.next();else for(;c.curr&&c.curr.id.client===t&&c.curr.id.clock+c.curr.length<=n;)c.next();else c.next()}ra(o);const l=ls(a);return cs(s,l),s.toUint8Array()},ea=(e,t)=>Zo(e,t,ps,bs),ta=e=>{e.written>0&&(e.clientStructs.push({written:e.written,restEncoder:Cr(e.encoder.restEncoder)}),e.encoder.restEncoder=Sr(),e.written=0)},na=(e,t,n)=>{e.written>0&&e.currClient!==t.id.client&&ta(e),0===e.written&&(e.currClient=t.id.client,e.encoder.writeClient(t.id.client),Ir(e.encoder.restEncoder,t.id.clock+n)),t.write(e.encoder,n),e.written++},ra=e=>{ta(e);const t=e.encoder.restEncoder;Ir(t,e.clientStructs.length);for(let n=0;n<e.clientStructs.length;n++){const r=e.clientStructs[n];Ir(t,r.written),Mr(t,r.restEncoder)}},ia=(e,t,n,r)=>{const i=new n(zr(e)),s=new Fo(i,!1),o=new r,a=new Go(o);for(let e=s.curr;null!==e;e=s.next())na(a,t(e),0);ra(a);const c=ls(i);return cs(o,c),o.toUint8Array()},sa=({formatting:e=!0,subdocs:t=!0,yxml:n=!0}={})=>{let r=0;const i=Jn(),s=Jn(),o=Jn(),a=Jn();return a.set(null,null),c=>{switch(c.constructor){case fc:case Fc:return c;case xc:{const d=c,u=d.content;switch(u.constructor){case pc:break;case Dc:if(n){const e=u.type;e instanceof cc&&(e.nodeName=Xn(s,e.nodeName,(()=>"node-"+r))),e instanceof dc&&(e.hookName=Xn(s,e.hookName,(()=>"hook-"+r)))}break;case Ec:{const e=u;e.arr=e.arr.map((()=>r));break}case gc:u.content=new Uint8Array([r]);break;case yc:{const e=u;t&&(e.opts={},e.doc.guid=r+"");break}case vc:u.embed={};break;case bc:{const t=u;e&&(t.key=Xn(o,t.key,(()=>r+"")),t.value=Xn(a,t.value,(()=>({i:r}))));break}case _c:{const e=u;e.arr=e.arr.map((()=>r));break}case wc:{const e=u;e.str=(l=r%10+"",((e,t)=>{const n=new Array(e);for(let t=0;t<e;t++)n[t]=l;return n})(e.str.length).join(""));break}default:Gr()}return d.parentSub&&(d.parentSub=Xn(i,d.parentSub,(()=>r+""))),r++,c}default:Gr()}var l}},oa=(e,t)=>ia(e,sa(t),ps,bs),aa=(e,t)=>ia(e,sa(t),ys,Es),ca=e=>ia(e,bi,ps,Es),la=e=>ia(e,bi,ys,bs),da="You must not compute changes after the event-handler fired.";class ua{constructor(e,t){this.target=e,this.currentTarget=e,this.transaction=t,this._changes=null,this._keys=null,this._delta=null,this._path=null}get path(){return this._path||(this._path=ha(this.currentTarget,this.target))}deletes(e){return ns(this.transaction.deleteSet,e.id)}get keys(){if(null===this._keys){if(0===this.transaction.doc._transactionCleanups.length)throw $r(da);const e=new Map,t=this.target;this.transaction.changed.get(t).forEach((n=>{if(null!==n){const r=t._map.get(n);let i,s;if(this.adds(r)){let e=r.left;for(;null!==e&&this.adds(e);)e=e.left;if(this.deletes(r)){if(null===e||!this.deletes(e))return;i="delete",s=er(e.content.getContent())}else null!==e&&this.deletes(e)?(i="update",s=er(e.content.getContent())):(i="add",s=void 0)}else{if(!this.deletes(r))return;i="delete",s=er(r.content.getContent())}e.set(n,{action:i,oldValue:s})}})),this._keys=e}return this._keys}get delta(){return this.changes.delta}adds(e){return e.id.clock>=(this.transaction.beforeState.get(e.id.client)||0)}get changes(){let e=this._changes;if(null===e){if(0===this.transaction.doc._transactionCleanups.length)throw $r(da);const t=this.target,n=Zn(),r=Zn(),i=[];if(e={added:n,deleted:r,delta:i,keys:this.keys},this.transaction.changed.get(t).has(null)){let e=null;const s=()=>{e&&i.push(e)};for(let i=t._start;null!==i;i=i.right)i.deleted?this.deletes(i)&&!this.adds(i)&&(null!==e&&void 0!==e.delete||(s(),e={delete:0}),e.delete+=i.length,r.add(i)):this.adds(i)?(null!==e&&void 0!==e.insert||(s(),e={insert:[]}),e.insert=e.insert.concat(i.content.getContent()),n.add(i)):(null!==e&&void 0!==e.retain||(s(),e={retain:0}),e.retain+=i.length);null!==e&&void 0===e.retain&&s()}this._changes=e}return e}}const ha=(e,t)=>{const n=[];for(;null!==t._item&&t!==e;){if(null!==t._item.parentSub)n.unshift(t._item.parentSub);else{let e=0,r=t._item.parent._start;for(;r!==t._item&&null!==r;)r.deleted||e++,r=r.right;n.unshift(e)}t=t._item.parent}return n};let fa=0;class ga{constructor(e,t){e.marker=!0,this.p=e,this.index=t,this.timestamp=fa++}}const pa=(e,t,n)=>{e.p.marker=!1,e.p=t,t.marker=!0,e.index=n,e.timestamp=fa++},ma=(e,t)=>{if(null===e._start||0===t||null===e._searchMarker)return null;const n=0===e._searchMarker.length?null:e._searchMarker.reduce(((e,n)=>or(t-e.index)<or(t-n.index)?e:n));let r=e._start,i=0;for(null!==n&&(r=n.p,i=n.index,(e=>{e.timestamp=fa++})(n));null!==r.right&&i<t;){if(!r.deleted&&r.countable){if(t<i+r.length)break;i+=r.length}r=r.right}for(;null!==r.left&&i>t;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);for(;null!==r.left&&r.left.id.client===r.id.client&&r.left.id.clock+r.left.length===r.id.clock;)r=r.left,!r.deleted&&r.countable&&(i-=r.length);return null!==n&&or(n.index-i)<r.parent.length/80?(pa(n,r,i),n):((e,t,n)=>{if(e.length>=80){const r=e.reduce(((e,t)=>e.timestamp<t.timestamp?e:t));return pa(r,t,n),r}{const r=new ga(t,n);return e.push(r),r}})(e._searchMarker,r,i)},ya=(e,t,n)=>{for(let r=e.length-1;r>=0;r--){const i=e[r];if(n>0){let t=i.p;for(t.marker=!1;t&&(t.deleted||!t.countable);)t=t.left,t&&!t.deleted&&t.countable&&(i.index-=t.length);if(null===t||!0===t.marker){e.splice(r,1);continue}i.p=t,t.marker=!0}(t<i.index||n>0&&t===i.index)&&(i.index=cr(t,i.index+n))}},va=e=>{let t=e._start;const n=[];for(;t;)n.push(t),t=t.right;return n},ba=(e,t,n)=>{const r=e,i=t.changedParentTypes;for(;Xn(i,e,(()=>[])).push(n),null!==e._item;)e=e._item.parent;xs(r._eH,n,t)};class _a{constructor(){this._item=null,this._map=new Map,this._start=null,this.doc=null,this._length=0,this._eH=Us(),this._dEH=Us(),this._searchMarker=null}get parent(){return this._item?this._item.parent:null}_integrate(e,t){this.doc=e,this._item=t}_copy(){throw Vr()}clone(){throw Vr()}_write(e){}get _first(){let e=this._start;for(;null!==e&&e.deleted;)e=e.right;return e}_callObserver(e,t){!e.local&&this._searchMarker&&(this._searchMarker.length=0)}observe(e){Ls(this._eH,e)}observeDeep(e){Ls(this._dEH,e)}unobserve(e){Ns(this._eH,e)}unobserveDeep(e){Ns(this._dEH,e)}toJSON(){}}const Ea=(e,t,n)=>{t<0&&(t=e._length+t),n<0&&(n=e._length+n);let r=n-t;const i=[];let s=e._start;for(;null!==s&&r>0;){if(s.countable&&!s.deleted){const e=s.content.getContent();if(e.length<=t)t-=e.length;else{for(let n=t;n<e.length&&r>0;n++)i.push(e[n]),r--;t=0}}s=s.right}return i},wa=e=>{const t=[];let n=e._start;for(;null!==n;){if(n.countable&&!n.deleted){const e=n.content.getContent();for(let n=0;n<e.length;n++)t.push(e[n])}n=n.right}return t},Sa=(e,t)=>{const n=[];let r=e._start;for(;null!==r;){if(r.countable&&fo(r,t)){const e=r.content.getContent();for(let t=0;t<e.length;t++)n.push(e[t])}r=r.right}return n},Ca=(e,t)=>{let n=0,r=e._start;for(;null!==r;){if(r.countable&&!r.deleted){const i=r.content.getContent();for(let r=0;r<i.length;r++)t(i[r],n++,e)}r=r.right}},Ta=(e,t)=>{const n=[];return Ca(e,((r,i)=>{n.push(t(r,i,e))})),n},Ra=e=>{let t=e._start,n=null,r=0;return{[Symbol.iterator](){return this},next:()=>{if(null===n){for(;null!==t&&t.deleted;)t=t.right;if(null===t)return{done:!0,value:void 0};n=t.content.getContent(),r=0,t=t.right}const e=n[r++];return n.length<=r&&(n=null),{done:!1,value:e}}}},Ia=(e,t)=>{const n=ma(e,t);let r=e._start;for(null!==n&&(r=n.p,t-=n.index);null!==r;r=r.right)if(!r.deleted&&r.countable){if(t<r.length)return r.content.getContent()[t];t-=r.length}},ka=(e,t,n,r)=>{let i=n;const s=e.doc,o=s.clientID,a=s.store,c=null===n?t._start:n.right;let l=[];const d=()=>{l.length>0&&(i=new xc(Fs(o,bo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Ec(l)),i.integrate(e,0),l=[])};r.forEach((n=>{if(null===n)l.push(n);else switch(n.constructor){case Number:case Object:case Boolean:case Array:case String:l.push(n);break;default:switch(d(),n.constructor){case Uint8Array:case ArrayBuffer:i=new xc(Fs(o,bo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new gc(new Uint8Array(n))),i.integrate(e,0);break;case fs:i=new xc(Fs(o,bo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new yc(n)),i.integrate(e,0);break;default:if(!(n instanceof _a))throw new Error("Unexpected content type in insert operation");i=new xc(Fs(o,bo(a,o)),i,i&&i.lastId,c,c&&c.id,t,null,new Dc(n)),i.integrate(e,0)}}})),d()},Oa=()=>$r("Length exceeded!"),Aa=(e,t,n,r)=>{if(n>t._length)throw Oa();if(0===n)return t._searchMarker&&ya(t._searchMarker,n,r.length),ka(e,t,null,r);const i=n,s=ma(t,n);let o=t._start;for(null!==s&&(o=s.p,0==(n-=s.index)&&(o=o.prev,n+=o&&o.countable&&!o.deleted?o.length:0));null!==o;o=o.right)if(!o.deleted&&o.countable){if(n<=o.length){n<o.length&&Co(e,Fs(o.id.client,o.id.clock+n));break}n-=o.length}return t._searchMarker&&ya(t._searchMarker,i,r.length),ka(e,t,o,r)},Da=(e,t,n,r)=>{if(0===r)return;const i=n,s=r,o=ma(t,n);let a=t._start;for(null!==o&&(a=o.p,n-=o.index);null!==a&&n>0;a=a.right)!a.deleted&&a.countable&&(n<a.length&&Co(e,Fs(a.id.client,a.id.clock+n)),n-=a.length);for(;r>0&&null!==a;)a.deleted||(r<a.length&&Co(e,Fs(a.id.client,a.id.clock+r)),a.delete(e),r-=a.length),a=a.right;if(r>0)throw Oa();t._searchMarker&&ya(t._searchMarker,i,-s+r)},Ma=(e,t,n)=>{const r=t._map.get(n);void 0!==r&&r.delete(e)},Pa=(e,t,n,r)=>{const i=t._map.get(n)||null,s=e.doc,o=s.clientID;let a;if(null==r)a=new Ec([r]);else switch(r.constructor){case Number:case Object:case Boolean:case Array:case String:a=new Ec([r]);break;case Uint8Array:a=new gc(r);break;case fs:a=new yc(r);break;default:if(!(r instanceof _a))throw new Error("Unexpected content type");a=new Dc(r)}new xc(Fs(o,bo(s.store,o)),i,i&&i.lastId,null,null,t,n,a).integrate(e,0)},Ua=(e,t)=>{const n=e._map.get(t);return void 0===n||n.deleted?void 0:n.content.getContent()[n.length-1]},La=e=>{const t={};return e._map.forEach(((e,n)=>{e.deleted||(t[n]=e.content.getContent()[e.length-1])})),t},Na=(e,t)=>{const n=e._map.get(t);return void 0!==n&&!n.deleted},xa=(e,t,n)=>{let r=e._map.get(t)||null;for(;null!==r&&(!n.sv.has(r.id.client)||r.id.clock>=(n.sv.get(r.id.client)||0));)r=r.left;return null!==r&&fo(r,n)?r.content.getContent()[r.length-1]:void 0},Ba=(e,t)=>{const n={};return e._map.forEach(((e,r)=>{let i=e;for(;null!==i&&(!t.sv.has(i.id.client)||i.id.clock>=(t.sv.get(i.id.client)||0));)i=i.left;null!==i&&fo(i,t)&&(n[r]=i.content.getContent()[i.length-1])})),n},ja=e=>{return t=e.entries(),Hi((()=>{let e;do{e=t.next()}while(!e.done&&e.value[1].deleted);return e}));var t};class Fa extends ua{constructor(e,t){super(e,t),this._transaction=t}}class Ka extends _a{constructor(){super(),this._prelimContent=[],this._searchMarker=[]}static from(e){const t=new Ka;return t.push(e),t}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new Ka}clone(){const e=new Ka;return e.insert(0,this.toArray().map((e=>e instanceof _a?e.clone():e))),e}get length(){return null===this._prelimContent?this._length:this._prelimContent.length}_callObserver(e,t){super._callObserver(e,t),ba(this,e,new Fa(this,e))}insert(e,t){null!==this.doc?Lo(this.doc,(n=>{Aa(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}push(e){null!==this.doc?Lo(this.doc,(t=>{((e,t,n)=>{let r=(t._searchMarker||[]).reduce(((e,t)=>t.index>e.index?t:e),{index:0,p:t._start}).p;if(r)for(;r.right;)r=r.right;ka(e,t,r,n)})(t,this,e)})):this._prelimContent.push(...e)}unshift(e){this.insert(0,e)}delete(e,t=1){null!==this.doc?Lo(this.doc,(n=>{Da(n,this,e,t)})):this._prelimContent.splice(e,t)}get(e){return Ia(this,e)}toArray(){return wa(this)}slice(e=0,t=this.length){return Ea(this,e,t)}toJSON(){return this.map((e=>e instanceof _a?e.toJSON():e))}map(e){return Ta(this,e)}forEach(e){Ca(this,e)}[Symbol.iterator](){return Ra(this)}_write(e){e.writeTypeRef(Cc)}}class qa extends ua{constructor(e,t,n){super(e,t),this.keysChanged=n}}class $a extends _a{constructor(e){super(),this._prelimContent=null,this._prelimContent=void 0===e?new Map:new Map(e)}_integrate(e,t){super._integrate(e,t),this._prelimContent.forEach(((e,t)=>{this.set(t,e)})),this._prelimContent=null}_copy(){return new $a}clone(){const e=new $a;return this.forEach(((t,n)=>{e.set(n,t instanceof _a?t.clone():t)})),e}_callObserver(e,t){ba(this,e,new qa(this,e,t))}toJSON(){const e={};return this._map.forEach(((t,n)=>{if(!t.deleted){const r=t.content.getContent()[t.length-1];e[n]=r instanceof _a?r.toJSON():r}})),e}get size(){return[...ja(this._map)].length}keys(){return Yi(ja(this._map),(e=>e[0]))}values(){return Yi(ja(this._map),(e=>e[1].content.getContent()[e[1].length-1]))}entries(){return Yi(ja(this._map),(e=>[e[0],e[1].content.getContent()[e[1].length-1]]))}forEach(e){this._map.forEach(((t,n)=>{t.deleted||e(t.content.getContent()[t.length-1],n,this)}))}[Symbol.iterator](){return this.entries()}delete(e){null!==this.doc?Lo(this.doc,(t=>{Ma(t,this,e)})):this._prelimContent.delete(e)}set(e,t){return null!==this.doc?Lo(this.doc,(n=>{Pa(n,this,e,t)})):this._prelimContent.set(e,t),t}get(e){return Ua(this,e)}has(e){return Na(this,e)}clear(){null!==this.doc?Lo(this.doc,(e=>{this.forEach((function(t,n,r){Ma(e,r,n)}))})):this._prelimContent.clear()}_write(e){e.writeTypeRef(Tc)}}const Va=(e,t)=>e===t||"object"==typeof e&&"object"==typeof t&&e&&t&&((e,t)=>e===t||Qi(e)===Qi(t)&&((e,t)=>{for(const n in e)if(!t(e[n],n))return!1;return!0})(e,((e,n)=>(void 0!==e||((e,t)=>Object.prototype.hasOwnProperty.call(e,t))(t,n))&&t[n]===e)))(e,t);class Ga{constructor(e,t,n,r){this.left=e,this.right=t,this.index=n,this.currentAttributes=r}forward(){null===this.right&&Gr(),this.right.content.constructor===bc?this.right.deleted||za(this.currentAttributes,this.right.content):this.right.deleted||(this.index+=this.right.length),this.left=this.right,this.right=this.right.right}}const Wa=(e,t,n)=>{for(;null!==t.right&&n>0;)t.right.content.constructor===bc?t.right.deleted||za(t.currentAttributes,t.right.content):t.right.deleted||(n<t.right.length&&Co(e,Fs(t.right.id.client,t.right.id.clock+n)),t.index+=t.right.length,n-=t.right.length),t.left=t.right,t.right=t.right.right;return t},Ha=(e,t,n)=>{const r=new Map,i=ma(t,n);if(i){const t=new Ga(i.p.left,i.p,i.index,r);return Wa(e,t,n-i.index)}{const i=new Ga(null,t._start,0,r);return Wa(e,i,n)}},Ya=(e,t,n,r)=>{for(;null!==n.right&&(!0===n.right.deleted||n.right.content.constructor===bc&&Va(r.get(n.right.content.key),n.right.content.value));)n.right.deleted||r.delete(n.right.content.key),n.forward();const i=e.doc,s=i.clientID;r.forEach(((r,o)=>{const a=n.left,c=n.right,l=new xc(Fs(s,bo(i.store,s)),a,a&&a.lastId,c,c&&c.id,t,null,new bc(o,r));l.integrate(e,0),n.right=l,n.forward()}))},za=(e,t)=>{const{key:n,value:r}=t;null===r?e.delete(n):e.set(n,r)},Ja=(e,t)=>{for(;null!==e.right&&(e.right.deleted||e.right.content.constructor===bc&&Va(t[e.right.content.key]||null,e.right.content.value));)e.forward()},Qa=(e,t,n,r)=>{const i=e.doc,s=i.clientID,o=new Map;for(const a in r){const c=r[a],l=n.currentAttributes.get(a)||null;if(!Va(l,c)){o.set(a,l);const{left:r,right:d}=n;n.right=new xc(Fs(s,bo(i.store,s)),r,r&&r.lastId,d,d&&d.id,t,null,new bc(a,c)),n.right.integrate(e,0),n.forward()}}return o},Xa=(e,t,n,r,i)=>{n.currentAttributes.forEach(((e,t)=>{void 0===i[t]&&(i[t]=null)}));const s=e.doc,o=s.clientID;Ja(n,i);const a=Qa(e,t,n,i),c=r.constructor===String?new wc(r):r instanceof _a?new Dc(r):new vc(r);let{left:l,right:d,index:u}=n;t._searchMarker&&ya(t._searchMarker,n.index,c.getLength()),d=new xc(Fs(o,bo(s.store,o)),l,l&&l.lastId,d,d&&d.id,t,null,c),d.integrate(e,0),n.right=d,n.index=u,n.forward(),Ya(e,t,n,a)},Za=(e,t,n,r,i)=>{const s=e.doc,o=s.clientID;Ja(n,i);const a=Qa(e,t,n,i);e:for(;null!==n.right&&(r>0||a.size>0&&(n.right.deleted||n.right.content.constructor===bc));){if(!n.right.deleted)switch(n.right.content.constructor){case bc:{const{key:t,value:s}=n.right.content,o=i[t];if(void 0!==o){if(Va(o,s))a.delete(t);else{if(0===r)break e;a.set(t,s)}n.right.delete(e)}else n.currentAttributes.set(t,s);break}default:r<n.right.length&&Co(e,Fs(n.right.id.client,n.right.id.clock+r)),r-=n.right.length}n.forward()}if(r>0){let i="";for(;r>0;r--)i+="\n";n.right=new xc(Fs(o,bo(s.store,o)),n.left,n.left&&n.left.lastId,n.right,n.right&&n.right.id,t,null,new wc(i)),n.right.integrate(e,0),n.forward()}Ya(e,t,n,a)},ec=(e,t,n,r,i)=>{let s=t;const o=Jn();for(;s&&(!s.countable||s.deleted);){if(!s.deleted&&s.content.constructor===bc){const e=s.content;o.set(e.key,e)}s=s.right}let a=0,c=!1;for(;t!==s;){if(n===t&&(c=!0),!t.deleted){const n=t.content;switch(n.constructor){case bc:{const{key:s,value:l}=n,d=r.get(s)||null;o.get(s)===n&&d!==l||(t.delete(e),a++,c||(i.get(s)||null)!==l||d===l||(null===d?i.delete(s):i.set(s,d))),c||t.deleted||za(i,n);break}}}t=t.right}return a},tc=e=>{let t=0;return Lo(e.doc,(n=>{let r=e._start,i=e._start,s=Jn();const o=Qn(s);for(;i;)!1===i.deleted&&(i.content.constructor===bc?za(o,i.content):(t+=ec(n,r,i,s,o),s=Qn(o),r=i)),i=i.right})),t},nc=e=>{const t=new Set,n=e.doc;for(const[r,i]of e.afterState.entries()){const s=e.beforeState.get(r)||0;i!==s&&Ro(e,n.store.clients.get(r),s,i,(e=>{e.deleted||e.content.constructor!==bc||e.constructor===fc||t.add(e.parent)}))}Lo(n,(n=>{ts(e,e.deleteSet,(e=>{if(e instanceof fc||!e.parent._hasFormatting||t.has(e.parent))return;const r=e.parent;e.content.constructor===bc?t.add(r):((e,t)=>{for(;t&&t.right&&(t.right.deleted||!t.right.countable);)t=t.right;const n=new Set;for(;t&&(t.deleted||!t.countable);){if(!t.deleted&&t.content.constructor===bc){const r=t.content.key;n.has(r)?t.delete(e):n.add(r)}t=t.left}})(n,e)}));for(const e of t)tc(e)}))},rc=(e,t,n)=>{const r=n,i=Qn(t.currentAttributes),s=t.right;for(;n>0&&null!==t.right;){if(!1===t.right.deleted)switch(t.right.content.constructor){case Dc:case vc:case wc:n<t.right.length&&Co(e,Fs(t.right.id.client,t.right.id.clock+n)),n-=t.right.length,t.right.delete(e)}t.forward()}s&&ec(e,s,t.right,i,t.currentAttributes);const o=(t.left||t.right).parent;return o._searchMarker&&ya(o._searchMarker,t.index,-r+n),t};class ic extends ua{constructor(e,t,n){super(e,t),this.childListChanged=!1,this.keysChanged=new Set,n.forEach((e=>{null===e?this.childListChanged=!0:this.keysChanged.add(e)}))}get changes(){if(null===this._changes){const e={keys:this.keys,delta:this.delta,added:new Set,deleted:new Set};this._changes=e}return this._changes}get delta(){if(null===this._delta){const e=this.target.doc,t=[];Lo(e,(e=>{const n=new Map,r=new Map;let i=this.target._start,s=null;const o={};let a="",c=0,l=0;const d=()=>{if(null!==s){let e=null;switch(s){case"delete":l>0&&(e={delete:l}),l=0;break;case"insert":("object"==typeof a||a.length>0)&&(e={insert:a},n.size>0&&(e.attributes={},n.forEach(((t,n)=>{null!==t&&(e.attributes[n]=t)})))),a="";break;case"retain":c>0&&(e={retain:c},(e=>{for(const t in e)return!1;return!0})(o)||(e.attributes=zi({},o))),c=0}e&&t.push(e),s=null}};for(;null!==i;){switch(i.content.constructor){case Dc:case vc:this.adds(i)?this.deletes(i)||(d(),s="insert",a=i.content.getContent()[0],d()):this.deletes(i)?("delete"!==s&&(d(),s="delete"),l+=1):i.deleted||("retain"!==s&&(d(),s="retain"),c+=1);break;case wc:this.adds(i)?this.deletes(i)||("insert"!==s&&(d(),s="insert"),a+=i.content.str):this.deletes(i)?("delete"!==s&&(d(),s="delete"),l+=i.length):i.deleted||("retain"!==s&&(d(),s="retain"),c+=i.length);break;case bc:{const{key:t,value:a}=i.content;if(this.adds(i)){if(!this.deletes(i)){const c=n.get(t)||null;Va(c,a)?null!==a&&i.delete(e):("retain"===s&&d(),Va(a,r.get(t)||null)?delete o[t]:o[t]=a)}}else if(this.deletes(i)){r.set(t,a);const e=n.get(t)||null;Va(e,a)||("retain"===s&&d(),o[t]=e)}else if(!i.deleted){r.set(t,a);const n=o[t];void 0!==n&&(Va(n,a)?null!==n&&i.delete(e):("retain"===s&&d(),null===a?delete o[t]:o[t]=a))}i.deleted||("insert"===s&&d(),za(n,i.content));break}}i=i.right}for(d();t.length>0;){const e=t[t.length-1];if(void 0===e.retain||void 0!==e.attributes)break;t.pop()}})),this._delta=t}return this._delta}}class sc extends _a{constructor(e){super(),this._pending=void 0!==e?[()=>this.insert(0,e)]:[],this._searchMarker=[],this._hasFormatting=!1}get length(){return this._length}_integrate(e,t){super._integrate(e,t);try{this._pending.forEach((e=>e()))}catch(e){console.error(e)}this._pending=null}_copy(){return new sc}clone(){const e=new sc;return e.applyDelta(this.toDelta()),e}_callObserver(e,t){super._callObserver(e,t);const n=new ic(this,e,t);ba(this,e,n),!e.local&&this._hasFormatting&&(e._needFormattingCleanup=!0)}toString(){let e="",t=this._start;for(;null!==t;)!t.deleted&&t.countable&&t.content.constructor===wc&&(e+=t.content.str),t=t.right;return e}toJSON(){return this.toString()}applyDelta(e,{sanitize:t=!0}={}){null!==this.doc?Lo(this.doc,(n=>{const r=new Ga(null,this._start,0,new Map);for(let i=0;i<e.length;i++){const s=e[i];if(void 0!==s.insert){const o=t||"string"!=typeof s.insert||i!==e.length-1||null!==r.right||"\n"!==s.insert.slice(-1)?s.insert:s.insert.slice(0,-1);("string"!=typeof o||o.length>0)&&Xa(n,this,r,o,s.attributes||{})}else void 0!==s.retain?Za(n,this,r,s.retain,s.attributes||{}):void 0!==s.delete&&rc(n,r,s.delete)}})):this._pending.push((()=>this.applyDelta(e)))}toDelta(e,t,n){const r=[],i=new Map,s=this.doc;let o="",a=this._start;function c(){if(o.length>0){const e={};let t=!1;i.forEach(((n,r)=>{t=!0,e[r]=n}));const n={insert:o};t&&(n.attributes=e),r.push(n),o=""}}const l=()=>{for(;null!==a;){if(fo(a,e)||void 0!==t&&fo(a,t))switch(a.content.constructor){case wc:{const r=i.get("ychange");void 0===e||fo(a,e)?void 0===t||fo(a,t)?void 0!==r&&(c(),i.delete("ychange")):void 0!==r&&r.user===a.id.client&&"added"===r.type||(c(),i.set("ychange",n?n("added",a.id):{type:"added"})):void 0!==r&&r.user===a.id.client&&"removed"===r.type||(c(),i.set("ychange",n?n("removed",a.id):{type:"removed"})),o+=a.content.str;break}case Dc:case vc:{c();const e={insert:a.content.getContent()[0]};if(i.size>0){const t={};e.attributes=t,i.forEach(((e,n)=>{t[n]=e}))}r.push(e);break}case bc:fo(a,e)&&(c(),za(i,a.content))}a=a.right}c()};return e||t?Lo(s,(n=>{e&&go(n,e),t&&go(n,t),l()}),"cleanup"):l(),r}insert(e,t,n){if(t.length<=0)return;const r=this.doc;null!==r?Lo(r,(r=>{const i=Ha(r,this,e);n||(n={},i.currentAttributes.forEach(((e,t)=>{n[t]=e}))),Xa(r,this,i,t,n)})):this._pending.push((()=>this.insert(e,t,n)))}insertEmbed(e,t,n={}){const r=this.doc;null!==r?Lo(r,(r=>{const i=Ha(r,this,e);Xa(r,this,i,t,n)})):this._pending.push((()=>this.insertEmbed(e,t,n)))}delete(e,t){if(0===t)return;const n=this.doc;null!==n?Lo(n,(n=>{rc(n,Ha(n,this,e),t)})):this._pending.push((()=>this.delete(e,t)))}format(e,t,n){if(0===t)return;const r=this.doc;null!==r?Lo(r,(r=>{const i=Ha(r,this,e);null!==i.right&&Za(r,this,i,t,n)})):this._pending.push((()=>this.format(e,t,n)))}removeAttribute(e){null!==this.doc?Lo(this.doc,(t=>{Ma(t,this,e)})):this._pending.push((()=>this.removeAttribute(e)))}setAttribute(e,t){null!==this.doc?Lo(this.doc,(n=>{Pa(n,this,e,t)})):this._pending.push((()=>this.setAttribute(e,t)))}getAttribute(e){return Ua(this,e)}getAttributes(){return La(this)}_write(e){e.writeTypeRef(Rc)}}class oc{constructor(e,t=(()=>!0)){this._filter=t,this._root=e,this._currentNode=e._start,this._firstCall=!0}[Symbol.iterator](){return this}next(){let e=this._currentNode,t=e&&e.content&&e.content.type;if(null!==e&&(!this._firstCall||e.deleted||!this._filter(t)))do{if(t=e.content.type,e.deleted||t.constructor!==cc&&t.constructor!==ac||null===t._start)for(;null!==e;){if(null!==e.right){e=e.right;break}e=e.parent===this._root?null:e.parent._item}else e=t._start}while(null!==e&&(e.deleted||!this._filter(e.content.type)));return this._firstCall=!1,null===e?{value:void 0,done:!0}:(this._currentNode=e,{value:e.content.type,done:!1})}}class ac extends _a{constructor(){super(),this._prelimContent=[]}get firstChild(){const e=this._first;return e?e.content.getContent()[0]:null}_integrate(e,t){super._integrate(e,t),this.insert(0,this._prelimContent),this._prelimContent=null}_copy(){return new ac}clone(){const e=new ac;return e.insert(0,this.toArray().map((e=>e instanceof _a?e.clone():e))),e}get length(){return null===this._prelimContent?this._length:this._prelimContent.length}createTreeWalker(e){return new oc(this,e)}querySelector(e){e=e.toUpperCase();const t=new oc(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)).next();return t.done?null:t.value}querySelectorAll(e){return e=e.toUpperCase(),nr(new oc(this,(t=>t.nodeName&&t.nodeName.toUpperCase()===e)))}_callObserver(e,t){ba(this,e,new lc(this,t,e))}toString(){return Ta(this,(e=>e.toString())).join("")}toJSON(){return this.toString()}toDOM(e=document,t={},n){const r=e.createDocumentFragment();return void 0!==n&&n._createAssociation(r,this),Ca(this,(i=>{r.insertBefore(i.toDOM(e,t,n),null)})),r}insert(e,t){null!==this.doc?Lo(this.doc,(n=>{Aa(n,this,e,t)})):this._prelimContent.splice(e,0,...t)}insertAfter(e,t){if(null!==this.doc)Lo(this.doc,(n=>{const r=e&&e instanceof _a?e._item:e;ka(n,this,r,t)}));else{const n=this._prelimContent,r=null===e?0:n.findIndex((t=>t===e))+1;if(0===r&&null!==e)throw $r("Reference item not found");n.splice(r,0,...t)}}delete(e,t=1){null!==this.doc?Lo(this.doc,(n=>{Da(n,this,e,t)})):this._prelimContent.splice(e,t)}toArray(){return wa(this)}push(e){this.insert(this.length,e)}unshift(e){this.insert(0,e)}get(e){return Ia(this,e)}slice(e=0,t=this.length){return Ea(this,e,t)}forEach(e){Ca(this,e)}_write(e){e.writeTypeRef(kc)}}class cc extends ac{constructor(e="UNDEFINED"){super(),this.nodeName=e,this._prelimAttrs=new Map}get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_integrate(e,t){super._integrate(e,t),this._prelimAttrs.forEach(((e,t)=>{this.setAttribute(t,e)})),this._prelimAttrs=null}_copy(){return new cc(this.nodeName)}clone(){const e=new cc(this.nodeName);return((e,t)=>{for(const n in e)t(e[n],n)})(this.getAttributes(),((t,n)=>{"string"==typeof t&&e.setAttribute(n,t)})),e.insert(0,this.toArray().map((e=>e instanceof _a?e.clone():e))),e}toString(){const e=this.getAttributes(),t=[],n=[];for(const t in e)n.push(t);n.sort();const r=n.length;for(let i=0;i<r;i++){const r=n[i];t.push(r+'="'+e[r]+'"')}const i=this.nodeName.toLocaleLowerCase();return`<${i}${t.length>0?" "+t.join(" "):""}>${super.toString()}</${i}>`}removeAttribute(e){null!==this.doc?Lo(this.doc,(t=>{Ma(t,this,e)})):this._prelimAttrs.delete(e)}setAttribute(e,t){null!==this.doc?Lo(this.doc,(n=>{Pa(n,this,e,t)})):this._prelimAttrs.set(e,t)}getAttribute(e){return Ua(this,e)}hasAttribute(e){return Na(this,e)}getAttributes(e){return e?Ba(this,e):La(this)}toDOM(e=document,t={},n){const r=e.createElement(this.nodeName),i=this.getAttributes();for(const e in i){const t=i[e];"string"==typeof t&&r.setAttribute(e,t)}return Ca(this,(i=>{r.appendChild(i.toDOM(e,t,n))})),void 0!==n&&n._createAssociation(r,this),r}_write(e){e.writeTypeRef(Ic),e.writeKey(this.nodeName)}}class lc extends ua{constructor(e,t,n){super(e,n),this.childListChanged=!1,this.attributesChanged=new Set,t.forEach((e=>{null===e?this.childListChanged=!0:this.attributesChanged.add(e)}))}}class dc extends $a{constructor(e){super(),this.hookName=e}_copy(){return new dc(this.hookName)}clone(){const e=new dc(this.hookName);return this.forEach(((t,n)=>{e.set(n,t)})),e}toDOM(e=document,t={},n){const r=t[this.hookName];let i;return i=void 0!==r?r.createDom(this):document.createElement(this.hookName),i.setAttribute("data-yjs-hook",this.hookName),void 0!==n&&n._createAssociation(i,this),i}_write(e){e.writeTypeRef(Oc),e.writeKey(this.hookName)}}class uc extends sc{get nextSibling(){const e=this._item?this._item.next:null;return e?e.content.type:null}get prevSibling(){const e=this._item?this._item.prev:null;return e?e.content.type:null}_copy(){return new uc}clone(){const e=new uc;return e.applyDelta(this.toDelta()),e}toDOM(e=document,t,n){const r=e.createTextNode(this.toString());return void 0!==n&&n._createAssociation(r,this),r}toString(){return this.toDelta().map((e=>{const t=[];for(const n in e.attributes){const r=[];for(const t in e.attributes[n])r.push({key:t,value:e.attributes[n][t]});r.sort(((e,t)=>e.key<t.key?-1:1)),t.push({nodeName:n,attrs:r})}t.sort(((e,t)=>e.nodeName<t.nodeName?-1:1));let n="";for(let e=0;e<t.length;e++){const r=t[e];n+=`<${r.nodeName}`;for(let e=0;e<r.attrs.length;e++){const t=r.attrs[e];n+=` ${t.key}="${t.value}"`}n+=">"}n+=e.insert;for(let e=t.length-1;e>=0;e--)n+=`</${t[e].nodeName}>`;return n})).join("")}toJSON(){return this.toString()}_write(e){e.writeTypeRef(Ac)}}class hc{constructor(e,t){this.id=e,this.length=t}get deleted(){throw Vr()}mergeWith(e){return!1}write(e,t,n){throw Vr()}integrate(e,t){throw Vr()}}class fc extends hc{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){t>0&&(this.id.clock+=t,this.length-=t),_o(e.doc.store,this)}write(e,t){e.writeInfo(0),e.writeLen(this.length-t)}getMissing(e,t){return null}}class gc{constructor(e){this.content=e}getLength(){return 1}getContent(){return[this.content]}isCountable(){return!0}copy(){return new gc(this.content)}splice(e){throw Vr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeBuf(this.content)}getRef(){return 3}}class pc{constructor(e){this.len=e}getLength(){return this.len}getContent(){return[]}isCountable(){return!1}copy(){return new pc(this.len)}splice(e){const t=new pc(this.len-e);return this.len=e,t}mergeWith(e){return this.len+=e.len,!0}integrate(e,t){ss(e.deleteSet,t.id.client,t.id.clock,this.len),t.markDeleted()}delete(e){}gc(e){}write(e,t){e.writeLen(this.len-t)}getRef(){return 1}}const mc=(e,t)=>new fs({guid:e,...t,shouldLoad:t.shouldLoad||t.autoLoad||!1});class yc{constructor(e){e._item&&console.error("This document was already integrated as a sub-document. You should create a second instance instead with the same guid."),this.doc=e;const t={};this.opts=t,e.gc||(t.gc=!1),e.autoLoad&&(t.autoLoad=!0),null!==e.meta&&(t.meta=e.meta)}getLength(){return 1}getContent(){return[this.doc]}isCountable(){return!0}copy(){return new yc(mc(this.doc.guid,this.opts))}splice(e){throw Vr()}mergeWith(e){return!1}integrate(e,t){this.doc._item=t,e.subdocsAdded.add(this.doc),this.doc.shouldLoad&&e.subdocsLoaded.add(this.doc)}delete(e){e.subdocsAdded.has(this.doc)?e.subdocsAdded.delete(this.doc):e.subdocsRemoved.add(this.doc)}gc(e){}write(e,t){e.writeString(this.doc.guid),e.writeAny(this.opts)}getRef(){return 9}}class vc{constructor(e){this.embed=e}getLength(){return 1}getContent(){return[this.embed]}isCountable(){return!0}copy(){return new vc(this.embed)}splice(e){throw Vr()}mergeWith(e){return!1}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeJSON(this.embed)}getRef(){return 5}}class bc{constructor(e,t){this.key=e,this.value=t}getLength(){return 1}getContent(){return[]}isCountable(){return!1}copy(){return new bc(this.key,this.value)}splice(e){throw Vr()}mergeWith(e){return!1}integrate(e,t){const n=t.parent;n._searchMarker=null,n._hasFormatting=!0}delete(e){}gc(e){}write(e,t){e.writeKey(this.key),e.writeJSON(this.value)}getRef(){return 6}}class _c{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new _c(this.arr)}splice(e){const t=new _c(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeString(void 0===t?"undefined":JSON.stringify(t))}}getRef(){return 2}}class Ec{constructor(e){this.arr=e}getLength(){return this.arr.length}getContent(){return this.arr}isCountable(){return!0}copy(){return new Ec(this.arr)}splice(e){const t=new Ec(this.arr.slice(e));return this.arr=this.arr.slice(0,e),t}mergeWith(e){return this.arr=this.arr.concat(e.arr),!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){const n=this.arr.length;e.writeLen(n-t);for(let r=t;r<n;r++){const t=this.arr[r];e.writeAny(t)}}getRef(){return 8}}class wc{constructor(e){this.str=e}getLength(){return this.str.length}getContent(){return this.str.split("")}isCountable(){return!0}copy(){return new wc(this.str)}splice(e){const t=new wc(this.str.slice(e));this.str=this.str.slice(0,e);const n=this.str.charCodeAt(e-1);return n>=55296&&n<=56319&&(this.str=this.str.slice(0,e-1)+"<22>",t.str="<22>"+t.str.slice(1)),t}mergeWith(e){return this.str+=e.str,!0}integrate(e,t){}delete(e){}gc(e){}write(e,t){e.writeString(0===t?this.str:this.str.slice(t))}getRef(){return 4}}const Sc=[e=>new Ka,e=>new $a,e=>new sc,e=>new cc(e.readKey()),e=>new ac,e=>new dc(e.readKey()),e=>new uc],Cc=0,Tc=1,Rc=2,Ic=3,kc=4,Oc=5,Ac=6;class Dc{constructor(e){this.type=e}getLength(){return 1}getContent(){return[this.type]}isCountable(){return!0}copy(){return new Dc(this.type._copy())}splice(e){throw Vr()}mergeWith(e){return!1}integrate(e,t){this.type._integrate(e.doc,t)}delete(e){let t=this.type._start;for(;null!==t;)t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e),t=t.right;this.type._map.forEach((t=>{t.deleted?t.id.clock<(e.beforeState.get(t.id.client)||0)&&e._mergeStructs.push(t):t.delete(e)})),e.changed.delete(this.type)}gc(e){let t=this.type._start;for(;null!==t;)t.gc(e,!0),t=t.right;this.type._start=null,this.type._map.forEach((t=>{for(;null!==t;)t.gc(e,!0),t=t.left})),this.type._map=new Map}write(e,t){this.type._write(e)}getRef(){return 7}}const Mc=(e,t)=>{let n,r=t,i=0;do{i>0&&(r=Fs(r.client,r.clock+i)),n=wo(e,r),i=r.clock-n.id.clock,r=n.redone}while(null!==r&&n instanceof xc);return{item:n,diff:i}},Pc=(e,t)=>{for(;null!==e&&e.keep!==t;)e.keep=t,e=e.parent._item},Uc=(e,t,n)=>{const{client:r,clock:i}=t.id,s=new xc(Fs(r,i+n),t,Fs(r,i+n-1),t.right,t.rightOrigin,t.parent,t.parentSub,t.content.splice(n));return t.deleted&&s.markDeleted(),t.keep&&(s.keep=!0),null!==t.redone&&(s.redone=Fs(t.redone.client,t.redone.clock+n)),t.right=s,null!==s.right&&(s.right.left=s),e._mergeStructs.push(s),null!==s.parentSub&&null===s.right&&s.parent._map.set(s.parentSub,s),t.length=n,s},Lc=(e,t)=>((e,n)=>{for(let n=0;n<e.length;n++)if(r=e[n],ns(r.deletions,t))return!0;var r;return!1})(e),Nc=(e,t,n,r,i,s)=>{const o=e.doc,a=o.store,c=o.clientID,l=t.redone;if(null!==l)return Co(e,l);let d,u=t.parent._item,h=null;if(null!==u&&!0===u.deleted){if(null===u.redone&&(!n.has(u)||null===Nc(e,u,n,r,i,s)))return null;for(;null!==u.redone;)u=Co(e,u.redone)}const f=null===u?t.parent:u.content.type;if(null===t.parentSub){for(h=t.left,d=t;null!==h;){let t=h;for(;null!==t&&t.parent._item!==u;)t=null===t.redone?null:Co(e,t.redone);if(null!==t&&t.parent._item===u){h=t;break}h=h.left}for(;null!==d;){let t=d;for(;null!==t&&t.parent._item!==u;)t=null===t.redone?null:Co(e,t.redone);if(null!==t&&t.parent._item===u){d=t;break}d=d.right}}else if(d=null,t.right&&!i){for(h=t;null!==h&&null!==h.right&&(h.right.redone||ns(r,h.right.id)||Lc(s.undoStack,h.right.id)||Lc(s.redoStack,h.right.id));)for(h=h.right;h.redone;)h=Co(e,h.redone);if(h&&null!==h.right)return null}else h=f._map.get(t.parentSub)||null;const g=bo(a,c),p=Fs(c,g),m=new xc(p,h,h&&h.lastId,d,d&&d.id,f,t.parentSub,t.content.copy());return t.redone=p,Pc(m,!0),m.integrate(e,0),m};class xc extends hc{constructor(e,t,n,r,i,s,o,a){super(e,a.getLength()),this.origin=n,this.left=t,this.right=r,this.rightOrigin=i,this.parent=s,this.parentSub=o,this.redone=null,this.content=a,this.info=this.content.isCountable()?2:0}set marker(e){(8&this.info)>0!==e&&(this.info^=8)}get marker(){return(8&this.info)>0}get keep(){return(1&this.info)>0}set keep(e){this.keep!==e&&(this.info^=1)}get countable(){return(2&this.info)>0}get deleted(){return(4&this.info)>0}set deleted(e){this.deleted!==e&&(this.info^=4)}markDeleted(){this.info|=4}getMissing(e,t){if(this.origin&&this.origin.client!==this.id.client&&this.origin.clock>=bo(t,this.origin.client))return this.origin.client;if(this.rightOrigin&&this.rightOrigin.client!==this.id.client&&this.rightOrigin.clock>=bo(t,this.rightOrigin.client))return this.rightOrigin.client;if(this.parent&&this.parent.constructor===Bs&&this.id.client!==this.parent.client&&this.parent.clock>=bo(t,this.parent.client))return this.parent.client;if(this.origin&&(this.left=To(e,t,this.origin),this.origin=this.left.lastId),this.rightOrigin&&(this.right=Co(e,this.rightOrigin),this.rightOrigin=this.right.id),this.left&&this.left.constructor===fc||this.right&&this.right.constructor===fc)this.parent=null;else if(this.parent){if(this.parent.constructor===Bs){const e=wo(t,this.parent);e.constructor===fc?this.parent=null:this.parent=e.content.type}}else this.left&&this.left.constructor===xc&&(this.parent=this.left.parent,this.parentSub=this.left.parentSub),this.right&&this.right.constructor===xc&&(this.parent=this.right.parent,this.parentSub=this.right.parentSub);return null}integrate(e,t){if(t>0&&(this.id.clock+=t,this.left=To(e,e.doc.store,Fs(this.id.client,this.id.clock-1)),this.origin=this.left.lastId,this.content=this.content.splice(t),this.length-=t),this.parent){if(!this.left&&(!this.right||null!==this.right.left)||this.left&&this.left.right!==this.right){let t,n=this.left;if(null!==n)t=n.right;else if(null!==this.parentSub)for(t=this.parent._map.get(this.parentSub)||null;null!==t&&null!==t.left;)t=t.left;else t=this.parent._start;const r=new Set,i=new Set;for(;null!==t&&t!==this.right;){if(i.add(t),r.add(t),js(this.origin,t.origin)){if(t.id.client<this.id.client)n=t,r.clear();else if(js(this.rightOrigin,t.rightOrigin))break}else{if(null===t.origin||!i.has(wo(e.doc.store,t.origin)))break;r.has(wo(e.doc.store,t.origin))||(n=t,r.clear())}t=t.right}this.left=n}if(null!==this.left){const e=this.left.right;this.right=e,this.left.right=this}else{let e;if(null!==this.parentSub)for(e=this.parent._map.get(this.parentSub)||null;null!==e&&null!==e.left;)e=e.left;else e=this.parent._start,this.parent._start=this;this.right=e}null!==this.right?this.right.left=this:null!==this.parentSub&&(this.parent._map.set(this.parentSub,this),null!==this.left&&this.left.delete(e)),null===this.parentSub&&this.countable&&!this.deleted&&(this.parent._length+=this.length),_o(e.doc.store,this),this.content.integrate(e,this),Oo(e,this.parent,this.parentSub),(null!==this.parent._item&&this.parent._item.deleted||null!==this.parentSub&&null!==this.right)&&this.delete(e)}else new fc(this.id,this.length).integrate(e,0)}get next(){let e=this.right;for(;null!==e&&e.deleted;)e=e.right;return e}get prev(){let e=this.left;for(;null!==e&&e.deleted;)e=e.left;return e}get lastId(){return 1===this.length?this.id:Fs(this.id.client,this.id.clock+this.length-1)}mergeWith(e){if(this.constructor===e.constructor&&js(e.origin,this.lastId)&&this.right===e&&js(this.rightOrigin,e.rightOrigin)&&this.id.client===e.id.client&&this.id.clock+this.length===e.id.clock&&this.deleted===e.deleted&&null===this.redone&&null===e.redone&&this.content.constructor===e.content.constructor&&this.content.mergeWith(e.content)){const t=this.parent._searchMarker;return t&&t.forEach((t=>{t.p===e&&(t.p=this,!this.deleted&&this.countable&&(t.index-=this.length))})),e.keep&&(this.keep=!0),this.right=e.right,null!==this.right&&(this.right.left=this),this.length+=e.length,!0}return!1}delete(e){if(!this.deleted){const t=this.parent;this.countable&&null===this.parentSub&&(t._length-=this.length),this.markDeleted(),ss(e.deleteSet,this.id.client,this.id.clock,this.length),Oo(e,t,this.parentSub),this.content.delete(e)}}gc(e,t){if(!this.deleted)throw Gr();this.content.gc(e),t?((e,t,n)=>{const r=e.clients.get(t.id.client);r[Eo(r,t.id.clock)]=n})(e,this,new fc(this.id,this.length)):this.content=new pc(this.length)}write(e,t){const n=t>0?Fs(this.id.client,this.id.clock+t-1):this.origin,r=this.rightOrigin,i=this.parentSub,s=31&this.content.getRef()|(null===n?0:ur)|(null===r?0:dr)|(null===i?0:32);if(e.writeInfo(s),null!==n&&e.writeLeftID(n),null!==r&&e.writeRightID(r),null===n&&null===r){const t=this.parent;if(void 0!==t._item){const n=t._item;if(null===n){const n=$s(t);e.writeParentInfo(!0),e.writeString(n)}else e.writeParentInfo(!1),e.writeLeftID(n.id)}else t.constructor===String?(e.writeParentInfo(!0),e.writeString(t)):t.constructor===Bs?(e.writeParentInfo(!1),e.writeLeftID(t)):Gr();null!==i&&e.writeString(i)}this.content.write(e,t)}}const Bc=(e,t)=>jc[31&t](e),jc=[()=>{Gr()},e=>new pc(e.readLen()),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++){const t=e.readString();"undefined"===t?n.push(void 0):n.push(JSON.parse(t))}return new _c(n)},e=>new gc(e.readBuf()),e=>new wc(e.readString()),e=>new vc(e.readJSON()),e=>new bc(e.readKey(),e.readJSON()),e=>new Dc(Sc[e.readTypeRef()](e)),e=>{const t=e.readLen(),n=[];for(let r=0;r<t;r++)n.push(e.readAny());return new Ec(n)},e=>new yc(mc(e.readString(),e.readAny())),()=>{Gr()}];class Fc extends hc{get deleted(){return!0}delete(){}mergeWith(e){return this.constructor===e.constructor&&(this.length+=e.length,!0)}integrate(e,t){Gr()}write(e,t){e.writeInfo(10),Ir(e.restEncoder,this.length-t)}getMissing(e,t){return null}}const Kc="undefined"!=typeof globalThis?globalThis:"undefined"!=typeof window?window:"undefined"!=typeof global?global:{},qc="__ $YJS$ __";!0===Kc[qc]&&console.error("Yjs was already imported. This breaks constructor checks and will lead to issues! - https://github.com/yjs/yjs/issues/438"),Kc[qc]=!0;var $c=n(9141),Vc=n(8743),Gc=n(8853),Wc=Object.defineProperty,Hc=(e,t,n)=>(((e,t,n)=>{t in e?Wc(e,t,{enumerable:!0,configurable:!0,writable:!0,value:n}):e[t]=n})(e,"symbol"!=typeof t?t+"":t,n),n);function Yc(e){return Buffer.from(e).toString("base64")}function zc(e){return Buffer.from(e,"base64")}class Jc extends p{constructor(e,t){super(),Hc(this,"disposed",!1),Hc(this,"initialized",!1),Hc(this,"initializing",!1),Hc(this,"initializeOutdated",!1),Hc(this,"members",new Map),Hc(this,"powerLevels"),Hc(this,"processEvent",(e=>{if("m.room.power_levels"===e.type||"m.room.member"===e.type){if(this.initializing)return void(this.initializeOutdated=!0);if(this.initialized){if("m.room.power_levels"===e.type)return void(this.powerLevels=e.content);if("m.room.member"===e.type){if("join"===e.content.membership||"invite"===e.content.membership){const t={displayname:e.content.displayname,user_id:e.state_key};this.members.set(e.state_key,t)}else this.members.delete(e.state_key);return}throw new Error("unexpected")}}})),this.matrixClient=e,this.reader=t,this._register(this.reader.onEvents((e=>e.events.forEach((e=>this.processEvent(e))))))}hasWriteAccess(e,t="m.room.message"){if(!this.members.has(e))return!1;const n=this.powerLevels;let r=n.events[t];void 0===r&&(r=n.events_default);let i=n.users[e];if(void 0===i&&(i=n.users_default),"number"!=typeof i||"number"!=typeof r)throw new Error("unexpected");return i>=r}async initialize(){if(this.initializing||this.initialized)throw new Error("already initializing / initialized");if(!this.reader.isStarted)throw new Error("MatrixReader must have started before initializing MatrixMemberReader");this.initializing=!0;const[e,t]=await Promise.all([this.matrixClient.getStateEvent(this.reader.roomId,"m.room.power_levels",void 0),this.matrixClient.members(this.reader.roomId,void 0,["knock","leave","ban"])]);if(this.initializeOutdated)return this.initializing=!1,this.initializeOutdated=!1,this.initialize();this.powerLevels=e,t.chunk.filter((e=>"m.room.member"===e.type&&("join"===e.content.membership||"invite"===e.content.membership))).forEach((e=>{this.members.set(e.state_key,{displayname:e.content.displayname,user_id:e.state_key})})),this.initializing=!1,this.initialized=!0}dispose(){this.disposed=!0,super.dispose()}}const Qc={snapshotInterval:30};class Xc extends p{constructor(e,t,n,r={}){super(),Hc(this,"latestToken"),Hc(this,"disposed",!1),Hc(this,"polling",!1),Hc(this,"pendingPollRequest"),Hc(this,"pollRetryTimeout"),Hc(this,"messagesSinceSnapshot",0),Hc(this,"_onEvents",this._register(new ae.Emitter)),Hc(this,"onEvents",this._onEvents.event),Hc(this,"opts"),Hc(this,"matrixRoomListener",((e,t,n)=>{throw console.error("not expected; Room.timeline on MatrixClient"),new Error("unexpected, we don't use /sync calls for MatrixReader, startClient should not be used on the Matrix client")})),this.matrixClient=e,this.roomId=t,this.translator=n,this.opts={...Qc,...r},this.matrixClient.on(Vc.RoomEvent.Timeline,this.matrixRoomListener)}processIncomingEventsForSnapshot(e){let t=!1;for(let n of e)if(this.translator.isUpdateEvent(n)){if(n.room_id!==this.roomId)throw new Error("event received with invalid roomid");this.messagesSinceSnapshot++,this.messagesSinceSnapshot%this.opts.snapshotInterval==0&&n.user_id===this.matrixClient.credentials.userId&&(t=!0)}else this.translator.isSnapshotEvent(n)&&(this.messagesSinceSnapshot=0,t=!1);return t}async decryptRawEventsIfNecessary(e){return await Promise.all(e.map((async e=>"m.room.encrypted"===e.type?(await this.matrixClient.crypto.decryptEvent(new Vc.MatrixEvent(e))).clearEvent:e)))}async peekPoll(){if(!this.latestToken)throw new Error("polling but no pagination token");if(!this.disposed)try{this.pendingPollRequest=this.matrixClient.http.authedRequest(void 0,Vc.Method.Get,"/events",{room_id:this.roomId,timeout:"30000",from:this.latestToken},void 0,{localTimeoutMs:6e4});const e=await this.pendingPollRequest;if(this.pendingPollRequest=void 0,this.disposed)return;const t=await this.decryptRawEventsIfNecessary(e.chunk),n=this.processIncomingEventsForSnapshot(t);t.length&&this._onEvents.fire({events:t,shouldSendSnapshot:n}),this.latestToken=e.end,this.peekPoll()}catch(e){console.error("peek error",e),this.disposed||(this.pollRetryTimeout=setTimeout((()=>this.peekPoll()),3e4))}}async getInitialDocumentUpdateEvents(e){let t,n=[],r="",i=!0;for(;i;){const s=await this.matrixClient.createMessagesRequest(this.roomId,r,30,Vc.Direction.Backward),o=await this.decryptRawEventsIfNecessary(s.chunk);for(let r of o)if(e)r.type===e&&n.push(r);else if(this.translator.isSnapshotEvent(r))n.push(r),t=r.content.last_event_id;else if(this.translator.isUpdateEvent(r)){if(t&&t===r.event_id)return this.latestToken||(this.latestToken=s.start),n.reverse();this.messagesSinceSnapshot++,n.push(r)}r=s.end,this.latestToken||(this.latestToken=s.start),i=!(s.start===s.end||!s.end)}return n.reverse()}startPolling(){if(this.polling)throw new Error("already polling");this.polling=!0,this.peekPoll()}get isStarted(){return this.polling}dispose(){this.disposed=!0,super.dispose(),this.pollRetryTimeout&&clearTimeout(this.pollRetryTimeout),this.pendingPollRequest&&this.pendingPollRequest.abort(),this.matrixClient.off(Vc.RoomEvent.Timeline,this.matrixRoomListener)}}const Zc=String.fromCharCode,el=/^\s*/g,tl=/([A-Z])/g,nl=(e,t)=>(e=>e.replace(el,""))(e.replace(tl,(e=>`${t}${(e=>e.toLowerCase())(e)}`))),rl=typeof TextEncoder<"u"?new TextEncoder:null,il=rl?e=>rl.encode(e):e=>{const t=unescape(encodeURIComponent(e)),n=t.length,r=new Uint8Array(n);for(let e=0;e<n;e++)r[e]=t.codePointAt(e);return r};let sl=typeof TextDecoder>"u"?null:new TextDecoder("utf-8",{fatal:!0,ignoreBOM:!0});sl&&1===sl.decode(new Uint8Array).length&&(sl=null);const ol=()=>new Map,al=(e,t,n)=>{let r=e.get(t);return void 0===r&&e.set(t,r=n()),r};let cl=new class{constructor(){this.map=new Map}setItem(e,t){this.map.set(e,t)}getItem(e){return this.map.get(e)}},ll=!0;try{typeof localStorage<"u"&&(cl=localStorage,ll=!1)}catch{}const dl=cl,ul=typeof process<"u"&&process.release&&/node|io\.js/.test(process.release.name),hl=typeof window<"u"&&!ul;let fl;typeof navigator<"u"&&/Mac/.test(navigator.platform);const gl=e=>(e=>void 0===e?null:e)(ul?process.env[e.toUpperCase()]:dl.getItem(e));(e=>(()=>{if(void 0===fl)if(ul){fl=ol();const e=process.argv;let t=null;for(let n=0;n<e.length;n++){const r=e[n];"-"===r[0]?(null!==t&&fl.set(t,""),t=r):null!==t&&(fl.set(t,r),t=null)}null!==t&&fl.set(t,"")}else"object"==typeof location?(fl=ol(),(location.search||"?").slice(1).split("&").forEach((e=>{if(0!==e.length){const[t,n]=e.split("=");fl.set(`--${nl(t,"-")}`,n),fl.set(`-${nl(t,"-")}`,n)}}))):fl=ol();return fl})().has(e))("--"+"production")||gl("production");const pl=Math.floor,ml=Math.abs,yl=Math.log10,vl=(e,t)=>e<t?e:t,bl=(e,t)=>e>t?e:t,_l=128,El=127,wl=Number.isInteger||(e=>"number"==typeof e&&isFinite(e)&&pl(e)===e);class Sl{constructor(){this.cpos=0,this.cbuf=new Uint8Array(100),this.bufs=[]}}const Cl=()=>new Sl,Tl=e=>{const t=new Uint8Array((e=>{let t=e.cpos;for(let n=0;n<e.bufs.length;n++)t+=e.bufs[n].length;return t})(e));let n=0;for(let r=0;r<e.bufs.length;r++){const i=e.bufs[r];t.set(i,n),n+=i.length}return t.set(Ul(e.cbuf.buffer,0,e.cpos),n),t},Rl=(e,t)=>{const n=e.cbuf.length;e.cpos===n&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(2*n),e.cpos=0),e.cbuf[e.cpos++]=t},Il=Rl,kl=(e,t)=>{for(;t>El;)Rl(e,_l|El&t),t>>>=7;Rl(e,El&t)},Ol=(e,t)=>{const n=unescape(encodeURIComponent(t)),r=n.length;kl(e,r);for(let t=0;t<r;t++)Rl(e,n.codePointAt(t))},Al=(e,t)=>{kl(e,t.byteLength),((e,t)=>{const n=e.cbuf.length,r=e.cpos,i=vl(n-r,t.length),s=t.length-i;e.cbuf.set(t.subarray(0,i),r),e.cpos+=i,s>0&&(e.bufs.push(e.cbuf),e.cbuf=new Uint8Array(bl(2*n,s)),e.cbuf.set(t.subarray(i)),e.cpos=s)})(e,t)},Dl=(e,t)=>{((e,t)=>{const n=e.cbuf.length;n-e.cpos<t&&(e.bufs.push(Ul(e.cbuf.buffer,0,e.cpos)),e.cbuf=new Uint8Array(2*bl(n,t)),e.cpos=0)})(e,t);const n=new DataView(e.cbuf.buffer,e.cpos,t);return e.cpos+=t,n},Ml=new DataView(new ArrayBuffer(4)),Pl=(e,t)=>{switch(typeof t){case"string":Rl(e,119),Ol(e,t);break;case"number":wl(t)&&ml(t)<=2147483647?(Rl(e,125),((e,t)=>{const n=(e=>0!==e?e<0:1/e<0)(t);for(n&&(t=-t),Rl(e,(t>63?_l:0)|(n?64:0)|63&t),t>>>=6;t>0;)Rl(e,(t>El?_l:0)|El&t),t>>>=7})(e,t)):(e=>(Ml.setFloat32(0,e),Ml.getFloat32(0)===e))(t)?(Rl(e,124),((e,t)=>{Dl(e,4).setFloat32(0,t,!1)})(e,t)):(Rl(e,123),((e,t)=>{Dl(e,8).setFloat64(0,t,!1)})(e,t));break;case"bigint":Rl(e,122),((e,t)=>{Dl(e,8).setBigInt64(0,t,!1)})(e,t);break;case"object":if(null===t)Rl(e,126);else if(t instanceof Array){Rl(e,117),kl(e,t.length);for(let n=0;n<t.length;n++)Pl(e,t[n])}else if(t instanceof Uint8Array)Rl(e,116),Al(e,t);else{Rl(e,118);const n=Object.keys(t);kl(e,n.length);for(let r=0;r<n.length;r++){const i=n[r];Ol(e,i),Pl(e,t[i])}}break;case"boolean":Rl(e,t?120:121);break;default:Rl(e,127)}},Ul=(e,t,n)=>new Uint8Array(e,t,n),Ll=hl?e=>{let t="";for(let n=0;n<e.byteLength;n++)t+=Zc(e[n]);return btoa(t)}:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString("base64"),Nl=hl?e=>{const t=atob(e),n=(e=>new Uint8Array(e))(t.length);for(let e=0;e<t.length;e++)n[e]=t.charCodeAt(e);return n}:e=>{const t=Buffer.from(e,"base64");return new Uint8Array(t.buffer,t.byteOffset,t.byteLength)};class xl{constructor(e){this.arr=e,this.pos=0}}const Bl=e=>new xl(e),jl=e=>((e,t)=>{const n=Ul(e.arr.buffer,e.pos+e.arr.byteOffset,t);return e.pos+=t,n})(e,Kl(e)),Fl=e=>e.arr[e.pos++],Kl=e=>{let t=0,n=0;for(;;){const r=e.arr[e.pos++];if(t|=(r&El)<<n,n+=7,r<_l)return t>>>0;if(n>53)throw new Error("Integer out of range!")}},ql=e=>{let t=Kl(e);if(0===t)return"";{let n=String.fromCodePoint(Fl(e));if(--t<100)for(;t--;)n+=String.fromCodePoint(Fl(e));else for(;t>0;){const r=t<1e4?t:1e4,i=e.arr.subarray(e.pos,e.pos+r);e.pos+=r,n+=String.fromCodePoint.apply(null,i),t-=r}return decodeURIComponent(escape(n))}},$l=(e,t)=>{const n=new DataView(e.arr.buffer,e.arr.byteOffset+e.pos,t);return e.pos+=t,n},Vl=[e=>{},e=>null,e=>{let t=e.arr[e.pos++],n=63&t,r=6;const i=(64&t)>0?-1:1;if(0==(t&_l))return i*n;for(;;){if(t=e.arr[e.pos++],n|=(t&El)<<r,r+=7,t<_l)return i*(n>>>0);if(r>53)throw new Error("Integer out of range!")}},e=>$l(e,4).getFloat32(0,!1),e=>$l(e,8).getFloat64(0,!1),e=>$l(e,8).getBigInt64(0,!1),e=>!1,e=>!0,ql,e=>{const t=Kl(e),n={};for(let r=0;r<t;r++)n[ql(e)]=Gl(e);return n},e=>{const t=Kl(e),n=[];for(let r=0;r<t;r++)n.push(Gl(e));return n},jl],Gl=e=>Vl[127-Fl(e)](e),Wl=Date.now,Hl=()=>new Set,Yl=Array.from;class zl{constructor(){this._observers=ol()}on(e,t){al(this._observers,e,Hl).add(t)}once(e,t){const n=(...r)=>{this.off(e,n),t(...r)};this.on(e,n)}off(e,t){const n=this._observers.get(e);void 0!==n&&(n.delete(t),0===n.size&&this._observers.delete(e))}emit(e,t){return Yl((this._observers.get(e)||ol()).values()).forEach((e=>e(...t)))}destroy(){this._observers=ol()}}const Jl=Object.keys,Ql=e=>Jl(e).length,Xl=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),Zl=()=>{},ed=(e,t)=>{if(null==e||null==t)return((e,t)=>e===t)(e,t);if(e.constructor!==t.constructor)return!1;if(e===t)return!0;switch(e.constructor){case ArrayBuffer:e=new Uint8Array(e),t=new Uint8Array(t);case Uint8Array:if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.length;n++)if(e[n]!==t[n])return!1;break;case Set:if(e.size!==t.size)return!1;for(const n of e)if(!t.has(n))return!1;break;case Map:if(e.size!==t.size)return!1;for(const n of e.keys())if(!t.has(n)||!ed(e.get(n),t.get(n)))return!1;break;case Object:if(Ql(e)!==Ql(t))return!1;for(const n in e)if(!Xl(e,n)||!ed(e[n],t[n]))return!1;break;case Array:if(e.length!==t.length)return!1;for(let n=0;n<e.length;n++)if(!ed(e[n],t[n]))return!1;break;default:return!1}return!0};class td extends zl{constructor(e){super(),this.doc=e,this.clientID=e.clientID,this.states=new Map,this.meta=new Map,this._checkInterval=setInterval((()=>{const e=Wl();null!==this.getLocalState()&&15e3<=e-this.meta.get(this.clientID).lastUpdated&&this.setLocalState(this.getLocalState());const t=[];this.meta.forEach(((n,r)=>{r!==this.clientID&&3e4<=e-n.lastUpdated&&this.states.has(r)&&t.push(r)})),t.length>0&&nd(this,t,"timeout")}),pl(3e3)),e.on("destroy",(()=>{this.destroy()})),this.setLocalState({})}destroy(){this.emit("destroy",[this]),this.setLocalState(null),super.destroy(),clearInterval(this._checkInterval)}getLocalState(){return this.states.get(this.clientID)||null}setLocalState(e){const t=this.clientID,n=this.meta.get(t),r=void 0===n?0:n.clock+1,i=this.states.get(t);null===e?this.states.delete(t):this.states.set(t,e),this.meta.set(t,{clock:r,lastUpdated:Wl()});const s=[],o=[],a=[],c=[];null===e?c.push(t):null==i?null!=e&&s.push(t):(o.push(t),ed(i,e)||a.push(t)),(s.length>0||a.length>0||c.length>0)&&this.emit("change",[{added:s,updated:a,removed:c},"local"]),this.emit("update",[{added:s,updated:o,removed:c},"local"])}setLocalStateField(e,t){const n=this.getLocalState();null!==n&&this.setLocalState({...n,[e]:t})}getStates(){return this.states}}const nd=(e,t,n)=>{const r=[];for(let n=0;n<t.length;n++){const i=t[n];if(e.states.has(i)){if(e.states.delete(i),i===e.clientID){const t=e.meta.get(i);e.meta.set(i,{clock:t.clock+1,lastUpdated:Wl()})}r.push(i)}}r.length>0&&(e.emit("change",[{added:[],updated:[],removed:r},n]),e.emit("update",[{added:[],updated:[],removed:r},n]))},rd=(e,t,n=e.states)=>{const r=t.length,i=Cl();kl(i,r);for(let s=0;s<r;s++){const r=t[s],o=n.get(r)||null,a=e.meta.get(r).clock;kl(i,r),kl(i,a),Ol(i,JSON.stringify(o))}return Tl(i)},id=(e,t,n)=>{try{Rs(t,jl(e),n)}catch(e){console.error("Caught error while handling a Yjs update",e)}},sd=id,od=(e,t,n,r)=>{const i=Kl(e);switch(i){case 0:((e,t,n)=>{((e,t,n)=>{kl(e,1),Al(e,ks(t,n))})(t,n,jl(e))})(e,t,n);break;case 1:id(e,n,r);break;case 2:sd(e,n,r);break;default:throw new Error("Unknown message type")}return i},ad=Symbol;class cd{constructor(e,t){this.left=e,this.right=t}}const ld=(e,t)=>new cd(e,t),dd=typeof document<"u"?document:{};typeof DOMParser<"u"&&new DOMParser;const ud=e=>((e,t)=>{const n=[];for(const[r,i]of e)n.push(t(i,r));return n})(e,((e,t)=>`${t}:${e};`)).join("");dd.ELEMENT_NODE,dd.TEXT_NODE,dd.CDATA_SECTION_NODE,dd.COMMENT_NODE,dd.DOCUMENT_NODE,dd.DOCUMENT_TYPE_NODE,dd.DOCUMENT_FRAGMENT_NODE;const hd=ad(),fd=ad(),gd=ad(),pd=ad(),md=ad(),yd=ad(),vd=ad(),bd=ad(),_d=ad(),Ed={[hd]:ld("font-weight","bold"),[fd]:ld("font-weight","normal"),[gd]:ld("color","blue"),[md]:ld("color","green"),[pd]:ld("color","grey"),[yd]:ld("color","red"),[vd]:ld("color","purple"),[bd]:ld("color","orange"),[_d]:ld("color","black")},wd={[hd]:"[1m",[fd]:"[2m",[gd]:"[34m",[md]:"[32m",[pd]:"[37m",[yd]:"[31m",[vd]:"[35m",[bd]:"[38;5;208m",[_d]:"[0m"},Sd=ul?e=>{const t=[],n=[];let r=0;for(;r<e.length;r++){const n=e[r],i=wd[n];if(void 0!==i)t.push(i);else{if(n.constructor!==String&&n.constructor!==Number)break;t.push(n)}}for(r>0&&(t.push("[0m"),n.push(t.join("")));r<e.length;r++){const t=e[r];t instanceof Symbol||n.push(t)}return n}:e=>{const t=[],n=[],r=ol();let i=[],s=0;for(;s<e.length;s++){const i=e[s],o=Ed[i];if(void 0!==o)r.set(o.left,o.right);else{if(i.constructor!==String&&i.constructor!==Number)break;{const e=ud(r);s>0||e.length>0?(t.push("%c"+i),n.push(e)):t.push(i)}}}for(s>0&&(i=n,i.unshift(t.join("")));s<e.length;s++){const t=e[s];t instanceof Symbol||i.push(t)}return i},Cd=new Set,Td=[md,vd,bd,gd];let Rd=0,Id=Wl();const kd=e=>{const t=Td[Rd],n=gl("log"),r=null!==n&&("*"===n||"true"===n||new RegExp(n,"gi").test(e));return Rd=(Rd+1)%Td.length,e+=": ",r?(...n)=>{const r=Wl(),i=r-Id;Id=r,((...e)=>{console.log(...Sd(e)),Cd.forEach((t=>t.print(e)))})(t,e,_d,...n.map((e=>"string"==typeof e||"symbol"==typeof e?e:JSON.stringify(e))),t," +"+i+"ms")}:Zl},Od=e=>new Error(e),Ad=typeof crypto>"u"?null:crypto,Dd=null!==Ad?e=>{const t=new ArrayBuffer(e),n=new Uint8Array(t);return Ad.getRandomValues(n),t}:e=>{const t=new ArrayBuffer(e),n=new Uint8Array(t);for(let t=0;t<e;t++)n[t]=Math.ceil(4294967295*Math.random()>>>0);return t},Md=Math.random,Pd=[1e7]+-1e3+-4e3+-8e3+-1e11,Ud=async(e,t)=>{if(!t)return e;const n=crypto.getRandomValues(new Uint8Array(12));return crypto.subtle.encrypt({name:"AES-GCM",iv:n},t,e).then((e=>{const t=Cl();return Ol(t,"AES-GCM"),Al(t,n),Al(t,new Uint8Array(e)),Tl(t)}))},Ld=async(e,t)=>{if(!t)return e;const n=Bl(e);"AES-GCM"!==ql(n)&&(e=>{Promise.reject(e)})(Od("Unknown encryption algorithm"));const r=jl(n),i=jl(n);return crypto.subtle.decrypt({name:"AES-GCM",iv:r},t,i).then((e=>new Uint8Array(e)))},Nd=new Map,xd=new Map;function Bd(e){Nd.forEach((t=>{t.connected&&(t.send({type:"subscribe",topics:[e.name]}),e.webrtcConns.size<e.provider.maxConns&&t.publishSignalingMessage(e,{type:"announce",from:e.peerId}))}))}const jd=new Map,Fd=typeof BroadcastChannel>"u"?class{constructor(e){this.room=e,this.onmessage=null,(e=>{ll||addEventListener("storage",e)})((t=>t.key===e&&null!==this.onmessage&&this.onmessage({data:Nl(t.newValue||"")})))}postMessage(e){dl.setItem(this.room,Ll((e=>new Uint8Array(e))(e)))}}:BroadcastChannel,Kd=e=>al(jd,e,(()=>{const t=new Set,n=new Fd(e);return n.onmessage=e=>t.forEach((t=>t(e.data,"broadcastchannel"))),{bc:n,subs:t}})),qd=kd("y-webrtc");class $d{constructor(e,t,n,r,i){Hc(this,"peerId",Pd.replace(/[018]/g,(e=>(e^new Uint32Array(Dd(4))[0]&15>>e/4).toString(16)))),Hc(this,"synced",!1),Hc(this,"webrtcConns",new Map),Hc(this,"bcConns",new Set),Hc(this,"mux",(()=>{let e=!0;return(t,n)=>{if(e){e=!1;try{t()}finally{e=!0}}else void 0!==n&&n()}})()),Hc(this,"bcconnected",!1),Hc(this,"_bcSubscriber",(e=>Ld(new Uint8Array(e),this.key).then((e=>this.mux((()=>{this.readMessage(e,(e=>{this.broadcastBcMessage(Tl(e))}))})))))),Hc(this,"readMessage",((e,t)=>{const n=Bl(e),r=Cl(),i=e=>{kl(r,5),Al(r,e),t(r)};switch(Kl(n)){case 5:this.onCustomMessage(jl(n),i);break;case 4:{const e=1===Fl(n),t=ql(n);if(t!==this.peerId&&(this.bcConns.has(t)&&!e||!this.bcConns.has(t)&&e)){const n=[],r=[];e?(this.bcConns.add(t),r.push(t),this.onPeerConnected(i)):(this.bcConns.delete(t),n.push(t)),this.provider.emit("peers",[{added:r,removed:n,webrtcPeers:Array.from(this.webrtcConns.keys()),bcPeers:Array.from(this.bcConns)}]),this.broadcastBcPeerId()}break}default:return void console.error("Unable to compute message")}})),this.provider=e,this.onCustomMessage=t,this.onPeerConnected=n,this.name=r,this.key=i}broadcastBcPeerId(){if(this.provider.filterBcConns){const e=Cl();kl(e,4),Il(e,1),Ol(e,this.peerId),this.broadcastBcMessage(Tl(e))}}broadcastWebrtcConn(e){qd("broadcast message in ",hd,this.name,fd),this.webrtcConns.forEach((t=>{try{t.peer.send(e)}catch{}}))}broadcastRoomMessage(e){const t=Cl();kl(t,5),Al(t,e);const n=Tl(t);this.bcconnected&&this.broadcastBcMessage(n),this.broadcastWebrtcConn(n)}broadcastBcMessage(e){return Ud(e,this.key).then((e=>this.mux((()=>((e,t,n=null)=>{const r=Kd(e);r.bc.postMessage(t),r.subs.forEach((e=>e(t,n)))})(this.name,e)))))}connect(){Bd(this),((e,t)=>{Kd(e).subs.add(t)})(this.name,this._bcSubscriber),this.bcconnected=!0,this.broadcastBcPeerId()}disconnect(){Nd.forEach((e=>{e.connected&&e.send({type:"unsubscribe",topics:[this.name]})}));const e=Cl();kl(e,4),Il(e,0),Ol(e,this.peerId),this.broadcastBcMessage(Tl(e)),((e,t)=>{Kd(e).subs.delete(t)})(this.name,this._bcSubscriber),this.bcconnected=!1,this.webrtcConns.forEach((e=>e.destroy()))}destroy(){this.disconnect()}}const Vd=3e4,Gd=e=>{if(e.shouldConnect&&null===e.ws){const t=new WebSocket(e.url),n=e.binaryType;let r=null;n&&(t.binaryType=n),e.ws=t,e.connecting=!0,e.connected=!1,t.onmessage=t=>{e.lastMessageReceived=Wl();const n=t.data,i="string"==typeof n?JSON.parse(n):n;i&&"pong"===i.type&&(clearTimeout(r),r=setTimeout(s,Vd/2)),e.emit("message",[i,e])};const i=t=>{null!==e.ws&&(e.ws=null,e.connecting=!1,e.connected?(e.connected=!1,e.emit("disconnect",[{type:"disconnect",error:t},e])):e.unsuccessfulReconnects++,setTimeout(Gd,vl(1200*yl(e.unsuccessfulReconnects+1),2500),e)),clearTimeout(r)},s=()=>{e.ws===t&&e.send({type:"ping"})};t.onclose=()=>i(null),t.onerror=e=>i(e),t.onopen=()=>{e.lastMessageReceived=Wl(),e.connecting=!1,e.connected=!0,e.unsuccessfulReconnects=0,e.emit("connect",[{type:"connect"},e]),r=setTimeout(s,Vd/2)}}};class Wd extends zl{constructor(e,{binaryType:t}={}){super(),this.url=e,this.ws=null,this.binaryType=t||null,this.connected=!1,this.connecting=!1,this.unsuccessfulReconnects=0,this.lastMessageReceived=0,this.shouldConnect=!0,this._checkInterval=setInterval((()=>{this.connected&&Vd<Wl()-this.lastMessageReceived&&this.ws.close()}),Vd/2),Gd(this)}send(e){this.ws&&this.ws.send(JSON.stringify(e))}destroy(){clearInterval(this._checkInterval),this.disconnect(),super.destroy()}disconnect(){this.shouldConnect=!1,null!==this.ws&&this.ws.close()}connect(){this.shouldConnect=!0,!this.connected&&null===this.ws&&Gd(this)}}const Hd=kd("y-webrtc");class Yd{constructor(e,t,n,r){Hc(this,"closed",!1),Hc(this,"connected",!1),Hc(this,"synced",!1),Hc(this,"peer"),this.remotePeerId=n,this.room=r,Hd("establishing connection to ",hd,n),this.peer=new Gc({initiator:t,...r.provider.peerOpts}),this.peer.on("signal",(t=>{e.publishSignalingMessage(r,{to:n,from:r.peerId,type:"signal",signal:t})})),this.peer.on("connect",(()=>{Hd("connected to ",hd,n),this.connected=!0,r.onPeerConnected((e=>{const t=Cl();kl(t,5),Al(t,e),this.sendWebrtcConn(t)}))})),this.peer.on("close",(()=>{this.connected=!1,this.closed=!0,r.webrtcConns.has(this.remotePeerId)&&(r.webrtcConns.delete(this.remotePeerId),r.provider.emit("peers",[{removed:[this.remotePeerId],added:[],webrtcPeers:Array.from(r.webrtcConns.keys()),bcPeers:Array.from(r.bcConns)}])),this.peer.destroy(),Hd("closed connection to ",hd,n),Bd(r)})),this.peer.on("error",(e=>{Hd("Error in connection to ",hd,n,": ",e),Bd(r)})),this.peer.on("data",(e=>{Hd("received message from ",hd,this.remotePeerId,pd," (",r.name,")",fd,_d),this.room.readMessage(e,(e=>{this.sendWebrtcConn(e)}))}))}sendWebrtcConn(e){Hd("send message to ",hd,this.remotePeerId,fd,pd," (",this.room.name,")",_d);try{this.peer.send(Tl(e))}catch{}}destroy(){this.peer.destroy()}}const zd=kd("y-webrtc");class Jd extends Wd{constructor(e){super(e),Hc(this,"providers",new Set),Hc(this,"publishSignalingMessage",((e,t)=>{e.key?((e,t)=>{const n=Cl();return Pl(n,e),Ud(Tl(n),t)})(t,e.key).then((t=>{this.send({type:"publish",topic:e.name,data:Ll(t)})})):this.send({type:"publish",topic:e.name,data:t})})),this.on("connect",(()=>{zd(`connected (${e})`);const t=Array.from(xd.keys());this.send({type:"subscribe",topics:t}),xd.forEach((e=>this.publishSignalingMessage(e,{type:"announce",from:e.peerId})))})),this.on("message",(e=>{if("publish"===e.type){const t=e.topic,n=xd.get(t);if(null==n||"string"!=typeof t)return;const r=e=>{const t=n.webrtcConns,r=n.peerId;if(null==e||e.from===r||void 0!==e.to&&e.to!==r||n.bcConns.has(e.from))return;const i=t.has(e.from)?()=>{}:()=>n.provider.emit("peers",[{removed:[],added:[e.from],webrtcPeers:Array.from(n.webrtcConns.keys()),bcPeers:Array.from(n.bcConns)}]);switch(e.type){case"announce":t.size<n.provider.maxConns&&(al(t,e.from,(()=>new Yd(this,!0,e.from,n))),i());break;case"signal":e.to===r&&(al(t,e.from,(()=>new Yd(this,!1,e.from,n))).peer.signal(e.signal),i())}};n.key?"string"==typeof e.data&&((e,t)=>Ld(e,t).then((e=>Gl(Bl(new Uint8Array(e))))))(Nl(e.data),n.key).then(r):r(e.data)}})),this.on("disconnect",(()=>zd(`disconnect (${e})`)))}}kd("y-webrtc");class Qd extends zl{constructor(e,{signaling:t=["wss://signaling.yjs.dev","wss://y-webrtc-signaling-eu.herokuapp.com","wss://y-webrtc-signaling-us.herokuapp.com"],password:n,maxConns:r=20+pl(15*Md()),filterBcConns:i=!0,peerOpts:s={}}={}){super(),Hc(this,"shouldConnect",!1),Hc(this,"filterBcConns",!0),Hc(this,"signalingUrls"),Hc(this,"signalingConns"),Hc(this,"peerOpts"),Hc(this,"maxConns"),Hc(this,"key"),Hc(this,"room"),this.roomName=e,this.filterBcConns=i,this.shouldConnect=!1,this.signalingUrls=t,this.signalingConns=[],this.maxConns=r,this.peerOpts={iceServers:[]},this.key=n?((e,t)=>{const n=il(e).buffer,r=il(t).buffer;return crypto.subtle.importKey("raw",n,"PBKDF2",!1,["deriveKey"]).then((e=>crypto.subtle.deriveKey({name:"PBKDF2",salt:r,iterations:1e5,hash:"SHA-256"},e,{name:"AES-GCM",length:256},!0,["encrypt","decrypt"])))})(n,e):Promise.resolve(void 0),this.key.then((t=>{this.room=((e,t,n,r,i)=>{if(xd.has(r))throw Od(`A Yjs Doc connected to room "${r}" already exists!`);const s=new $d(e,t,n,r,i);return xd.set(r,s),s})(this,this.onCustomMessage,this.onPeerConnected,e,t),this.shouldConnect?this.room.connect():this.room.disconnect()})),this.connect()}get connected(){return null!==this.room&&this.shouldConnect}connect(){this.shouldConnect=!0,this.signalingUrls.forEach((e=>{const t=al(Nd,e,(()=>new Jd(e)));this.signalingConns.push(t),t.providers.add(this)})),this.room&&this.room.connect()}disconnect(){this.shouldConnect=!1,this.signalingConns.forEach((e=>{e.providers.delete(this),0===e.providers.size&&(e.destroy(),Nd.delete(e.url))})),this.room&&this.room.disconnect()}destroy(){this.key.then((()=>{var e;null==(e=this.room)||e.destroy(),xd.delete(this.roomName)})),super.destroy()}}const Xd=kd("y-webrtc");class Zd extends Qd{constructor(e,t,n,r,i,s,o=new td(e)){super(t,{password:n,...s}),Hc(this,"onCustomMessage",((e,t)=>{const n=Bl(e),r=Cl();switch(Kl(n)){case 0:{const e=Gl(n);this.verify(e).then((()=>{const t=zc(e.message),n=Bl(t);if(2!==od(n,r,this.doc,this))throw Xd("error: expect only updates"),new Error("error: only update messages expected")}),(e=>{console.error("couldn't verify message")}));break}case 1:((e,t,n)=>{const r=Bl(t),i=Wl(),s=[],o=[],a=[],c=[],l=Kl(r);for(let t=0;t<l;t++){const t=Kl(r);let n=Kl(r);const l=JSON.parse(ql(r)),d=e.meta.get(t),u=e.states.get(t),h=void 0===d?0:d.clock;(h<n||h===n&&null===l&&e.states.has(t))&&(null===l?t===e.clientID&&null!=e.getLocalState()?n++:e.states.delete(t):e.states.set(t,l),e.meta.set(t,{clock:n,lastUpdated:i}),void 0===d&&null!==l?s.push(t):void 0!==d&&null===l?c.push(t):null!==l&&(ed(l,u)||a.push(t),o.push(t)))}(s.length>0||a.length>0||c.length>0)&&e.emit("change",[{added:s,updated:a,removed:c},n]),(s.length>0||o.length>0||c.length>0)&&e.emit("update",[{added:s,updated:o,removed:c},n])})(this.awareness,jl(n),this)}})),Hc(this,"onPeerConnected",(e=>{const t=Cl(),n=this.awareness.getStates();n.size>0&&(kl(t,1),Al(t,rd(this.awareness,Array.from(n.keys()))),e(Tl(t)))})),Hc(this,"_docUpdateHandler",(async(e,t)=>{if(!this.room)return;const n=Cl();kl(n,0);const r=Cl();((e,t)=>{kl(e,2),Al(e,t)})(r,e);const i={message:Yc(Tl(r))};await this.sign(i),Pl(n,i),this.room.broadcastRoomMessage(Tl(n))})),Hc(this,"_awarenessUpdateHandler",(({added:e,updated:t,removed:n},r)=>{if(!this.room)return;const i=e.concat(t).concat(n);Xd("awareness change ",{added:e,updated:t,removed:n},"local",this.awareness.clientID);const s=Cl();kl(s,1),Al(s,rd(this.awareness,i)),this.room.broadcastRoomMessage(Tl(s))})),this.doc=e,this.roomPassword=n,this.sign=r,this.verify=i,this.awareness=o,e.on("destroy",this.destroy.bind(this)),this.doc.on("update",this._docUpdateHandler),this.awareness.on("update",this._awarenessUpdateHandler),window.addEventListener("beforeunload",(()=>{nd(this.awareness,[e.clientID],"window unload"),xd.forEach((e=>{e.disconnect()}))}))}destroy(){this.doc.off("update",this._docUpdateHandler),this.awareness.off("update",this._awarenessUpdateHandler),this.doc.off("destroy",this.destroy),super.destroy()}}var eu=typeof globalThis<"u"?globalThis:typeof window<"u"?window:typeof global<"u"?global:typeof self<"u"?self:{},tu=function(e){var t=typeof e;return null!=e&&("object"==t||"function"==t)},nu="object"==typeof eu&&eu&&eu.Object===Object&&eu,ru="object"==typeof self&&self&&self.Object===Object&&self,iu=nu||ru||Function("return this")(),su=iu,ou=/\s/,au=function(e){for(var t=e.length;t--&&ou.test(e.charAt(t)););return t},cu=/^\s+/,lu=iu.Symbol,du=lu,uu=Object.prototype,hu=uu.hasOwnProperty,fu=uu.toString,gu=du?du.toStringTag:void 0,pu=Object.prototype.toString,mu=function(e){var t=hu.call(e,gu),n=e[gu];try{e[gu]=void 0;var r=!0}catch{}var i=fu.call(e);return r&&(t?e[gu]=n:delete e[gu]),i},yu=function(e){return pu.call(e)},vu=lu?lu.toStringTag:void 0,bu=function(e){return null==e?void 0===e?"[object Undefined]":"[object Null]":vu&&vu in Object(e)?mu(e):yu(e)},_u=function(e){return null!=e&&"object"==typeof e},Eu=function(e){return e&&e.slice(0,au(e)+1).replace(cu,"")},wu=tu,Su=function(e){return"symbol"==typeof e||_u(e)&&"[object Symbol]"==bu(e)},Cu=/^[-+]0x[0-9a-f]+$/i,Tu=/^0b[01]+$/i,Ru=/^0o[0-7]+$/i,Iu=parseInt,ku=tu,Ou=function(){return su.Date.now()},Au=function(e){if("number"==typeof e)return e;if(Su(e))return NaN;if(wu(e)){var t="function"==typeof e.valueOf?e.valueOf():e;e=wu(t)?t+"":t}if("string"!=typeof e)return 0===e?e:+e;e=Eu(e);var n=Tu.test(e);return n||Ru.test(e)?Iu(e.slice(2),n?2:8):Cu.test(e)?NaN:+e},Du=Math.max,Mu=Math.min,Pu=function(e,t,n){var r,i,s,o,a,c,l=0,d=!1,u=!1,h=!0;if("function"!=typeof e)throw new TypeError("Expected a function");function f(t){var n=r,s=i;return r=i=void 0,l=t,o=e.apply(s,n)}function g(e){var n=e-c;return void 0===c||n>=t||n<0||u&&e-l>=s}function p(){var e=Ou();if(g(e))return m(e);a=setTimeout(p,function(e){var n=t-(e-c);return u?Mu(n,s-(e-l)):n}(e))}function m(e){return a=void 0,h&&r?f(e):(r=i=void 0,o)}function y(){var e=Ou(),n=g(e);if(r=arguments,i=this,c=e,n){if(void 0===a)return function(e){return l=e,a=setTimeout(p,t),d?f(e):o}(c);if(u)return clearTimeout(a),a=setTimeout(p,t),f(c)}return void 0===a&&(a=setTimeout(p,t)),o}return t=Au(t)||0,ku(n)&&(d=!!n.leading,s=(u="maxWait"in n)?Du(Au(n.maxWait)||0,t):s,h="trailing"in n?!!n.trailing:h),y.cancel=function(){void 0!==a&&clearTimeout(a),l=0,r=c=i=a=void 0},y.flush=function(){return void 0===a?o:m(Ou())},y},Uu=tu;const Lu={flushInterval:500,retryIfForbiddenInterval:3e4};class Nu extends p{constructor(e,t,n={}){super(),Hc(this,"pendingUpdates",[]),Hc(this,"isSendingUpdates",!1),Hc(this,"_canWrite",!0),Hc(this,"retryTimeoutHandler"),Hc(this,"roomId"),Hc(this,"_onCanWriteChanged",this._register(new ae.Emitter)),Hc(this,"onCanWriteChanged",this._onCanWriteChanged.event),Hc(this,"_onSentAllEvents",this._register(new ae.Emitter)),Hc(this,"onSentAllEvents",this._onSentAllEvents.event),Hc(this,"throttledFlushUpdatesToMatrix"),Hc(this,"opts"),Hc(this,"flushUpdatesToMatrix",(async()=>{if(this.isSendingUpdates||!this.pendingUpdates.length||!this.roomId)return;this.isSendingUpdates=!0;const e=Wo(this.pendingUpdates);this.pendingUpdates=[];let t=!1;try{console.log("Sending updates"),await this.translator.sendUpdate(this.matrixClient,this.roomId,e),this.setCanWrite(!0),console.log("sent updates")}catch(n){if("M_FORBIDDEN"===n.errcode){console.warn("not allowed to edit document",n),this.setCanWrite(!1);try{await this.matrixClient.joinRoom(this.roomId),console.log("joined room",this.roomId),t=!0}catch(e){console.warn("failed to join room",e)}}else console.error("error sending updates",n);this.pendingUpdates.unshift(e)}finally{this.isSendingUpdates=!1}this.pendingUpdates.length?this.retryTimeoutHandler=setTimeout((()=>{this.throttledFlushUpdatesToMatrix()}),t?0:this.canWrite?this.opts.flushInterval:this.opts.retryIfForbiddenInterval):(console.log("_onSentAllEvents"),this._onSentAllEvents.fire())})),this.matrixClient=e,this.translator=t,this.opts={...Lu,...n},this.throttledFlushUpdatesToMatrix=function(e,t,n){var r=!0,i=!0;if("function"!=typeof e)throw new TypeError("Expected a function");return Uu(n)&&(r="leading"in n?!!n.leading:r,i="trailing"in n?!!n.trailing:i),Pu(e,t,{leading:r,maxWait:t,trailing:i})}(this.flushUpdatesToMatrix,this.canWrite?this.opts.flushInterval:this.opts.retryIfForbiddenInterval)}setCanWrite(e){this._canWrite!==e&&(this._canWrite=e,this._onCanWriteChanged.fire())}async initialize(e){this.roomId=e,this.throttledFlushUpdatesToMatrix()}get canWrite(){return this._canWrite}writeUpdate(e){this.pendingUpdates.push(e),this.throttledFlushUpdatesToMatrix()}async waitForFlush(){!this.pendingUpdates.length&&!this.isSendingUpdates||await ae.Event.toPromise(this.onSentAllEvents)}dispose(){super.dispose(),clearTimeout(this.retryTimeoutHandler),this.throttledFlushUpdatesToMatrix.cancel()}}const xu="m.room.message",Bu={updatesAsRegularMessages:!1,updateEventType:"matrix-crdt.doc_update",snapshotEventType:"matrix-crdt.doc_snapshot"};class ju{constructor(e={}){Hc(this,"opts"),this.opts={...Bu,...e}}async sendUpdate(e,t,n){const r=Yc(n),i={update:r};if(this.opts.updatesAsRegularMessages){const n={body:this.opts.updateEventType+": "+r,msgtype:this.opts.updateEventType,...i};e.scheduler=void 0,await e.sendEvent(t,xu,n,"")}else await e.sendEvent(t,this.opts.updateEventType,i,"")}async sendSnapshot(e,t,n,r){const i=Yc(n),s={update:i,last_event_id:r};if(this.opts.updatesAsRegularMessages){const n={body:this.opts.snapshotEventType+": "+i,msgtype:this.opts.snapshotEventType,...s};e.scheduler=void 0,await e.sendEvent(t,xu,n,"")}else await e.sendEvent(t,this.opts.snapshotEventType,s,"")}isUpdateEvent(e){return this.opts.updatesAsRegularMessages?e.type===xu&&e.content.msgtype===this.opts.updateEventType:e.type===this.opts.updateEventType}isSnapshotEvent(e){return this.opts.updatesAsRegularMessages?e.type===xu&&e.content.msgtype===this.opts.snapshotEventType:e.type===this.opts.snapshotEventType}get WrappedEventType(){return this.opts.updatesAsRegularMessages?xu:this.opts.updateEventType}}const Fu={enableExperimentalWebrtcSync:!1,reader:{},writer:{},translator:{}};class Ku extends p{constructor(e,t,n,r,i={}){if(super(),Hc(this,"disposed",!1),Hc(this,"_roomId"),Hc(this,"initializeTimeoutHandler"),Hc(this,"initializedResolve"),Hc(this,"initializedPromise",new Promise((e=>{this.initializedResolve=e}))),Hc(this,"webrtcProvider"),Hc(this,"reader"),Hc(this,"throttledWriter"),Hc(this,"translator"),Hc(this,"_onDocumentAvailable",this._register(new ae.Emitter)),Hc(this,"_onDocumentUnavailable",this._register(new ae.Emitter)),Hc(this,"_onReceivedEvents",this._register(new ae.Emitter)),Hc(this,"opts"),Hc(this,"onDocumentAvailable",this._onDocumentAvailable.event),Hc(this,"onReceivedEvents",this._onReceivedEvents.event),Hc(this,"onDocumentUnavailable",this._onDocumentUnavailable.event),Hc(this,"totalEventsReceived",0),Hc(this,"documentUpdateListener",(async(e,t)=>{t===this||this.webrtcProvider&&t===this.webrtcProvider||null!=t&&t.provider||this.throttledWriter.writeUpdate(e)})),Hc(this,"processIncomingEvents",((e,t=!1)=>{e=e.filter((e=>!(!this.translator.isUpdateEvent(e)&&!this.translator.isSnapshotEvent(e)))),this.totalEventsReceived+=e.length;const n=e.map((e=>new Uint8Array(zc(e.content.update)))),r=Wo(n);if(!n.length)return r;if(Rs(this.doc,r,this),t){const t=e[e.length-1],n=ks(this.doc);this.translator.sendSnapshot(this.matrixClient,this._roomId,n,t.event_id).catch((e=>{console.error("failed to send snapshot")}))}return e.filter((e=>e.user_id!==this.matrixClient.credentials.userId)).length&&this._onReceivedEvents.fire(),r})),this.doc=e,this.matrixClient=t,this.room=n,this.awareness=r,r&&!i.enableExperimentalWebrtcSync)throw new Error("awareness is only supported when using enableExperimentalWebrtcSync=true");this.opts={...Fu,...i},this.translator=new ju(this.opts.translator),this.throttledWriter=new Nu(this.matrixClient,this.translator,this.opts.writer),e.on("update",this.documentUpdateListener)}get onCanWriteChanged(){return this.throttledWriter.onCanWriteChanged}get canWrite(){return this.throttledWriter.canWrite}get roomId(){return this._roomId}get matrixReader(){return this.reader}async initializeWebrtc(){if(!this._roomId)throw new Error("not initialized");if(!this.reader)throw new Error("needs reader to initialize webrtc");const e=this._register(new Jc(this.matrixClient,this.reader));await e.initialize(),this.webrtcProvider=new Zd(this.doc,this._roomId,this._roomId,(async e=>{await async function(e,t){await e.crypto.signObject(t)}(this.matrixClient,e)}),(async t=>{await async function(e,t,n,r){if(!n.signatures||1!==Object.keys(n.signatures).length)throw new Error("invalid signature");const i=Object.keys(n.signatures)[0];if(!t.hasWriteAccess(i,r))throw new Error("user doesn't have write access");const s=Object.keys(n.signatures[i])[0];if(!s.startsWith("ed25519:"))throw new Error("unexpected key");const o=s.substr(8);e.crypto.deviceList.startTrackingDeviceList(i);const a=(await e.crypto.deviceList.downloadKeys([i],!1))[i][o].keys[s];if(!a)throw new Error("key not found");await async function(e,t,n,r,i){const s="ed25519:"+r,o=((t.signatures||{})[n]||{})[s];if(!o)throw Error("No signature");const a=Object.assign({},t);delete a.unsigned,delete a.signatures;const c=$c.stringify(a);e.verifySignature(i,c,o)}(e.crypto.olmDevice,n,i,o,a)}(this.matrixClient,e,t,this.translator.WrappedEventType)}),void 0,this.awareness)}async initializeNoCatch(){const e="id"===this.room.type?this.room.id:this.room.alias;try{if("id"===this.room.type)this._roomId=this.room.id;else if("alias"===this.room.type){const e=await this.matrixClient.getRoomIdForAlias(this.room.alias);this._roomId=e.room_id}if(!this._roomId)throw new Error("error receiving room id");console.log("room resolved",this._roomId),await this.throttledWriter.initialize(this._roomId)}catch(t){let n=5e3;return"M_NOT_FOUND"===t.errcode?(console.log("room not found",e),this._onDocumentUnavailable.fire()):"ConnectionError"===t.name?console.log("room not found (offline)",e):(console.error("error retrieving room",e,t),n=3e4,this._onDocumentUnavailable.fire()),void(this.initializeTimeoutHandler=setTimeout((()=>{this.initialize()}),n))}let t=ks(this.doc);const n=Yo(t),r=ea(t,n);let i=ho(this.doc);const s=await this.initializeReader();this._onDocumentAvailable.fire();const o=Yo(s),a=ea(t,o);if(function(e,t){return function(e,t){if(e.byteLength!==t.byteLength)return!1;for(let n=0;n<e.byteLength;n++)if(e.getUint8(n)!==t.getUint8(n))return!1;return!0}(new DataView(e),new DataView(t))}(r.buffer,a.buffer)){let e=new fs;if(Rs(e,s),function(e,t){for(const[n,r]of t.ds.clients.entries()){const t=e.ds.clients.get(n)||[];if(r.length>t.length)return!1;for(let e=0;e<r.length;e++){const n=r[e],i=t[e];if(n.clock!==i.clock||n.len!==i.len)return!1}}return!0}(ho(e),i))return void this.initializedResolve()}a.length>2&&this.throttledWriter.writeUpdate(a),this.initializedResolve()}async initializeReader(){if(this.reader)throw new Error("already initialized reader");if(!this._roomId)throw new Error("no roomId");this.reader=this._register(new Xc(this.matrixClient,this._roomId,this.translator,this.opts.reader)),this._register(this.reader.onEvents((e=>this.processIncomingEvents(e.events,e.shouldSendSnapshot))));const e=await this.reader.getInitialDocumentUpdateEvents();return this.reader.startPolling(),this.processIncomingEvents(e)}async waitForFlush(){await this.initializedPromise,await this.throttledWriter.waitForFlush()}async initialize(){try{await this.initializeNoCatch(),await this.initializedPromise,!this.disposed&&this.opts.enableExperimentalWebrtcSync&&await this.initializeWebrtc()}catch(e){throw console.error(e),e}}dispose(){var e,t;super.dispose(),this.disposed=!0,null==(e=this.webrtcProvider)||e.destroy(),null==(t=this.reader)||t.dispose(),clearTimeout(this.initializeTimeoutHandler),this.doc.off("update",this.documentUpdateListener)}}kd("y-webrtc");var qu=n(8764)})(),r})()));window.matrix = (opts) => new Proxy({
|
||
|
||
el: null, // HTML element
|
||
|
||
profile:{
|
||
type: 'network',
|
||
name: '[Matrix]',
|
||
description: 'a standardized decentralized privacy-friendly protocol',
|
||
url: 'https://matrix.org',
|
||
protocol: 'matrix://',
|
||
video: false,
|
||
audio: false,
|
||
chat: true,
|
||
scene: true
|
||
},
|
||
|
||
useWebcam: false,
|
||
useChat: false,
|
||
useScene: false,
|
||
|
||
channel: '#xrfragment-test:matrix.org',
|
||
server: 'https://matrix.org',
|
||
username:'',
|
||
auth: 'via password',
|
||
authkey: '',
|
||
client: null,
|
||
roomid: '',
|
||
|
||
// Matrix-CRDT
|
||
ydoc: null,
|
||
yhref: null,
|
||
|
||
html: {
|
||
generic: (opts) => `<div>
|
||
<div target="_blank" class="badge ruler">matrix <a onclick="frontend.plugin.matrix.info()"><i class="gg-info right"></i></a></div>
|
||
<table id="matrix">
|
||
<tr>
|
||
<td>channel</td>
|
||
<td>
|
||
<input type="text" id="channel" placeholder="${opts.plugin.channel}" value="${opts.plugin.channel}"/>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<td>server</td>
|
||
<td>
|
||
<input type="text" id="server" placeholder="https://matrix.org" value="${opts.plugin.server}"/>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<td>user</td>
|
||
<td>
|
||
<input type="text" id="username" placeholder="@you:matrix.org" value="${opts.plugin.username}"/>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<td>auth</td>
|
||
<td>
|
||
<select id="auth">
|
||
<option>via password</option>
|
||
<option>via access token</option>
|
||
</select>
|
||
</td>
|
||
</tr>
|
||
<tr>
|
||
<td></td>
|
||
<td>
|
||
<input type="password" id="secret" placeholder="enter password"/>
|
||
</td>
|
||
</tr>
|
||
</table>
|
||
<br>
|
||
</div>
|
||
`
|
||
},
|
||
|
||
init(){
|
||
frontend.plugin['matrix'] = this
|
||
$connections.chatnetwork = $connections.chatnetwork.concat([this])
|
||
$connections.scene = $connections.scene.concat([this])
|
||
if( window.localStorage.getItem("username") ) this.username = window.localStorage.getItem("username")
|
||
this.reactToConnectionHrefs()
|
||
|
||
document.addEventListener('network.connect', (e) => this.connect(e.detail) )
|
||
document.addEventListener('network.init', () => {
|
||
let meeting = network.getMeetingFromUrl(document.location.href)
|
||
if( meeting.match(this.profile.protocol) ){
|
||
this.parseLink( meeting )
|
||
}
|
||
})
|
||
},
|
||
|
||
connect(opts){
|
||
if( opts.selectedWebcam == this.profile.name ) this.useWebcam = true
|
||
if( opts.selectedChatnetwork == this.profile.name ) this.useChat = true
|
||
if( opts.selectedScene == this.profile.name ) this.useScene = true
|
||
if( this.useWebcam || this.useScene || this.useChat ){
|
||
this.link = `matrix://r/${this.channel.replace(/^#/,'')}`
|
||
this.createLink() // ensure link
|
||
this.channel = document.querySelector("#matrix input#channel").value
|
||
this.server = document.querySelector("#matrix input#server").value
|
||
this.username = document.querySelector("#matrix input#username").value
|
||
this.auth = document.querySelector("#matrix select#auth").value
|
||
|
||
localStorage.setItem("matrix.username",this.username)
|
||
let secret = document.querySelector("#matrix input#secret").value
|
||
document.querySelector("#matrix input#secret").value = ''
|
||
|
||
let clientOpts = {
|
||
baseUrl: this.server.match(/^http/) ? this.server : `https://${this.server}`,
|
||
lazyLoadMembers: true,
|
||
}
|
||
|
||
if( this.auth == 'via access token'){
|
||
clientOpts.accessToken = secret
|
||
clientOpts.userId = this.username
|
||
}
|
||
|
||
this.client = Matrix.sdk.createClient(clientOpts)
|
||
// auth
|
||
if( this.auth == 'via password'){
|
||
//this.client.loginWithPassword(this.username, secret)
|
||
this.client.login("m.login.password",{"user": this.username, password: secret})
|
||
.then( () => this.onMatrixConnect() )
|
||
.catch( () => {
|
||
window.notify("authentication was not succesful 😞")
|
||
})
|
||
}else {
|
||
this.onMatrixConnect()
|
||
//this.client.loginWithToken(clientOpts.accessToken)
|
||
//.then( () => this.onMatrixConnect() )
|
||
//.catch( () => {
|
||
// window.notify("authentication was not succesful 😞")
|
||
//})
|
||
}
|
||
|
||
}
|
||
},
|
||
|
||
onMatrixConnect(){
|
||
// Extra configuration needed for certain matrix-js-sdk (we don't call start)
|
||
// calls to work without calling sync start functions
|
||
this.client.canSupportVoip = false;
|
||
this.client.clientOpts = {
|
||
lazyLoadMembers: true
|
||
}
|
||
//this.client.startClient({ initialSyncLimit: 4 }) // show last 4 messages?
|
||
//.then( () => {
|
||
//.catch( (e) => window.notify("could not start matrix client 😞"))
|
||
|
||
console.log("onmatrix connect")
|
||
// token: this.matrixclient.getAccessToken()
|
||
frontend.emit('network.info',{message:'🛰 syncing with Matrix (might take a while)',plugin:this})
|
||
//this.client.once("sync", function (state, prevState, res) { });
|
||
frontend.emit('network.connected',{plugin:this,username: this.username})
|
||
// get roomId of channel
|
||
this.client.getRoomIdForAlias(this.channel)
|
||
.then( (o) => {
|
||
console.log(`${this.channel} has id ${o.room_id}`)
|
||
this.roomId = o.room_id
|
||
// join room if we haven't already
|
||
this.client.joinRoom(this.roomId)
|
||
.then( () => this.setupListeners() )
|
||
.catch( () => this.setupListeners() )
|
||
})
|
||
.catch((e) => {
|
||
console.error(e)
|
||
frontend.emit('network.error',{plugin:this,message:`channel ${this.channel} cannot be joined: `+String(e)})
|
||
})
|
||
},
|
||
|
||
setupCRDT(){
|
||
// Create a new Y.Doc and connect the MatrixProvider
|
||
var Buffer = window.Buffer = Matrix.Buffer // expose to MatrixProvider
|
||
this.ydoc = new Matrix.Y.Doc();
|
||
const provider = new Matrix.MatrixProvider(this.ydoc, this.client, {
|
||
type: "alias",
|
||
alias: this.channel
|
||
});
|
||
provider.initialize();
|
||
|
||
this.ydoc.scene = this.ydoc.getMap('scene')
|
||
// observe changes of the sum
|
||
this.ydoc.scene.observe(ymapEvent => {
|
||
|
||
// Find out what changed:
|
||
// Option 1: A set of keys that changed
|
||
ymapEvent.keysChanged // => Set<strings>
|
||
// Option 2: Compute the differences
|
||
ymapEvent.changes.keys // => Map<string, { action: 'add'|'update'|'delete', oldValue: any}>
|
||
|
||
// sample code.
|
||
ymapEvent.changes.keys.forEach((change, key) => {
|
||
console.dir({key,change})
|
||
if ( key == 'href' && change.action != "delete" ){
|
||
let href = this.ydoc.scene.get('href')
|
||
if( href.match(/pos=/) ) return // no shared teleporting
|
||
xrf.hashbus.pub(href)
|
||
} else if (change.action === 'delete') {
|
||
console.log(`Property "${key}" was deleted. New value: undefined. Previous value: "${change.oldValue}".`)
|
||
}
|
||
})
|
||
})
|
||
|
||
},
|
||
|
||
getNormalizedName(){
|
||
return this.channel.replace(/(^#|:.*)/,'')
|
||
},
|
||
|
||
setupListeners(){
|
||
if( this.useChat ) this.setupChat()
|
||
if( this.useScene ) this.setupCRDT() /* throws weird errors, perhaps matrix-sdk-js is too new */
|
||
return this
|
||
},
|
||
|
||
setupChat(){
|
||
|
||
// receive receivemessages
|
||
this.client.on("Room.timeline", (event, room, toStartOfTimeline) => {
|
||
if (event.getType() !== "m.room.message") return // only print messages
|
||
if( room.roomId == this.roomId ){
|
||
$chat.send({message: event.getContent().body, from: event.getSender()})
|
||
}
|
||
});
|
||
|
||
// send chatmessages
|
||
document.addEventListener('network.send', (e) => {
|
||
let {message} = e.detail
|
||
let href = frontend.share({linkonly:true}) // get our meetinglink in there
|
||
// convert to absolute links
|
||
if( message.match(/href="#/) ){
|
||
message = message.replace(/href=['"]#.*?['"]/g, `href="${href}"`)
|
||
}else{
|
||
let pos = []
|
||
if( network.posName ){
|
||
pos.push(`<a href="${href}">#${network.posName}</a>`)
|
||
}
|
||
if( network.pos ){
|
||
pos.push(`<a href="${href}">#${`pos=${network.pos}`}</a>`)
|
||
}
|
||
if( pos.length ) message += `<br>📍 ${pos.join(' ')}`
|
||
}
|
||
let content = {
|
||
body: message,
|
||
format: "org.matrix.custom.html",
|
||
formatted_body: message,
|
||
msgtype:"m.text"
|
||
}
|
||
this.client.sendEvent( this.roomId, "m.room.message", content, "", (err,res) => console.error({err,res}) )
|
||
})
|
||
|
||
},
|
||
|
||
config(opts){
|
||
opts = {...opts, ...this.profile }
|
||
this.el = document.createElement('div')
|
||
let html = this.html.generic(opts)
|
||
for( let i in opts ){
|
||
if( this.html[i] ) html += this.html[i](opts)
|
||
}
|
||
this.el.innerHTML = html
|
||
this.el.querySelector('#auth').addEventListener('change', (e) => {
|
||
this.el.querySelector('#secret').setAttribute('placeholder', `enter ${e.target.value.replace(/.* /,'')}`)
|
||
})
|
||
return this.el
|
||
},
|
||
|
||
info(opts){
|
||
window.notify(`${this.profile.name} is ${this.profile.description}, it is the hottest internet technology available at this moment.<br>Read more about it <a href="${this.profile.url}" target="_blank">here</a>.<br>You can basically make up a new channelname or use an existing one`)
|
||
},
|
||
|
||
parseLink(url){
|
||
if( !url.match(this.profile.protocol) ) return
|
||
if( url.match('/r/') ){
|
||
this.link = url
|
||
let parts = url.split("/r/")
|
||
let channel = parts[1].replace(/:.*/,'')
|
||
let server = parts[1].replace(/.*:/,'')
|
||
$connections.show({
|
||
chatnetwork:this.profile.name,
|
||
scene: this.profile.name,
|
||
webcam: "No thanks"
|
||
})
|
||
this.el.querySelector('#channel').value = `#${channel}:${server}`
|
||
this.el.querySelector('#server').value = server
|
||
if( window.localStorage.getItem("matrix.username") ){
|
||
this.el.querySelector('#username').value = window.localStorage.getItem("matrix.username")
|
||
}
|
||
console.log("configured matrix")
|
||
return true
|
||
}
|
||
return false
|
||
},
|
||
|
||
createLink(opts){
|
||
if( !this.link ){
|
||
const meeting = network.getMeetingFromUrl(document.location.href)
|
||
this.link = network.meetingLink = meeting.match("matrix://") ? meeting : ''
|
||
}
|
||
if( !xrf.navigator.URI.hash.meet ) xrf.navigator.URI.hash.meet = this.link
|
||
},
|
||
|
||
reactToConnectionHrefs(){
|
||
xrf.addEventListener('href', (opts) => {
|
||
let {mesh} = opts
|
||
if( !opts.click ) return
|
||
let detected = this.parseLink(mesh.userData.href)
|
||
if( detected ) opts.promise() // don't resolve, ignore other listeners
|
||
let href = mesh.userData.href
|
||
let isLocal = href[0] == '#'
|
||
let isTeleport = href.match(/(pos=|http:)/)
|
||
if( isLocal && !isTeleport && this.client && this.useScene && this.ydoc ){
|
||
this.ydoc.scene.set('href',document.location.hash )
|
||
}
|
||
})
|
||
let hashvars = xrf.URI.parse( document.location.hash ).XRF
|
||
if( hashvars.meet ) this.parseLink(hashvars.meet.string)
|
||
}
|
||
},
|
||
{
|
||
// auto-trigger events on changes
|
||
get(data,k,receiver){ return data[k] },
|
||
set(data,k,v){
|
||
let from = data[k]
|
||
data[k] = v
|
||
//switch( k ){
|
||
// default: matrix.opts.scene.dispatchEvent({type:`matrix.${k}.change`, from, to:v})
|
||
//}
|
||
}
|
||
})
|
||
|
||
document.addEventListener('$connections:ready', (e) => {
|
||
matrix(e.detail).init()
|
||
})
|
||
|
||
}).apply({})
|