1bafe5a5569d58aa2446c60ef2a42f531d47698f jrobinso Sun Sep 21 21:56:30 2025 -0700 igv dialog position fixes. Misc minor cleanup diff --git src/hg/js/igv.min.js src/hg/js/igv.min.js index 080526c6042..f6ae0677afb 100644 --- src/hg/js/igv.min.js +++ src/hg/js/igv.min.js @@ -1,36 +1,36 @@ -!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?module.exports=t():"function"==typeof define&&define.amd?define(t):(e="undefined"!=typeof globalThis?globalThis:e||self).igv=t()}(this,(function(){"use strict";function e(e){const t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}function t(e){return i("div",e)}function i(e,t){const i=document.createElement(e);return t&&(t.class&&i.classList.add(t.class),t.id&&(i.id=t.id),t.style&&function(e,t){for(let i of Object.keys(t))e.style[i]=t[i]}(i,t.style)),i}function r(e){const t=getComputedStyle(e);"none"!==t.display&&(e._initialDisplay=t.display),e.style.display="none"}function s(e){const t=e._initialDisplay||"block";e.style.display=t}function o(e){if(e.type.startsWith("touch")){const t=e.touches[0];return{x:t.pageX,y:t.pageY}}return{x:e.pageX,y:e.pageY}}function n(){return("0000"+(Math.random()*Math.pow(36,4)|0).toString(36)).slice(-4)}function a(e,t){const{clientX:i,clientY:r}=e;return((e,{clientX:t,clientY:i})=>{const{left:r,top:s,width:o,height:n}=e.getBoundingClientRect(),a=t-r,c=i-s;return{x:a,y:c,xNormalized:a/o,yNormalized:c/n,width:o,height:n}})(t,{clientX:i,clientY:r})}class c{constructor(){this.elem=i("div",{class:"igv-ui-panel-column"})}add(e){if(e instanceof Node)this.elem.appendChild(e);else if("object"==typeof e)this.elem.appendChild(e.elem);else{const i=t();i.innerHTML=e,this.elem.appendChild(i),this.html=i}}}function l(e,t){return h(e,t)}function h(e,t){t=t||"currentColor";let i=d[e];i||(console.error(`No icon named: ${e}`),i=d.question);const r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttributeNS(null,"viewBox","0 0 "+i[0]+" "+i[1]);const s=document.createElementNS("http://www.w3.org/2000/svg","path");return s.setAttributeNS(null,"fill",t),s.setAttributeNS(null,"d",i[4]),r.appendChild(s),r}const d={check:[512,512,[],"f00c","M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"],cog:[512,512,[],"f013","M444.788 291.1l42.616 24.599c4.867 2.809 7.126 8.618 5.459 13.985-11.07 35.642-29.97 67.842-54.689 94.586a12.016 12.016 0 0 1-14.832 2.254l-42.584-24.595a191.577 191.577 0 0 1-60.759 35.13v49.182a12.01 12.01 0 0 1-9.377 11.718c-34.956 7.85-72.499 8.256-109.219.007-5.49-1.233-9.403-6.096-9.403-11.723v-49.184a191.555 191.555 0 0 1-60.759-35.13l-42.584 24.595a12.016 12.016 0 0 1-14.832-2.254c-24.718-26.744-43.619-58.944-54.689-94.586-1.667-5.366.592-11.175 5.459-13.985L67.212 291.1a193.48 193.48 0 0 1 0-70.199l-42.616-24.599c-4.867-2.809-7.126-8.618-5.459-13.985 11.07-35.642 29.97-67.842 54.689-94.586a12.016 12.016 0 0 1 14.832-2.254l42.584 24.595a191.577 191.577 0 0 1 60.759-35.13V25.759a12.01 12.01 0 0 1 9.377-11.718c34.956-7.85 72.499-8.256 109.219-.007 5.49 1.233 9.403 6.096 9.403 11.723v49.184a191.555 191.555 0 0 1 60.759 35.13l42.584-24.595a12.016 12.016 0 0 1 14.832 2.254c24.718 26.744 43.619 58.944 54.689 94.586 1.667 5.366-.592 11.175-5.459 13.985L444.788 220.9a193.485 193.485 0 0 1 0 70.2zM336 256c0-44.112-35.888-80-80-80s-80 35.888-80 80 35.888 80 80 80 80-35.888 80-80z"],exclamation:[192,512,[],"f12a","M176 432c0 44.112-35.888 80-80 80s-80-35.888-80-80 35.888-80 80-80 80 35.888 80 80zM25.26 25.199l13.6 272C39.499 309.972 50.041 320 62.83 320h66.34c12.789 0 23.331-10.028 23.97-22.801l13.6-272C167.425 11.49 156.496 0 142.77 0H49.23C35.504 0 24.575 11.49 25.26 25.199z"],"exclamation-circle":[512,512,[],"f06a","M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"],"exclamation-triangle":[576,512,[],"f071","M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"],minus:[448,512,[],"f068","M424 318.2c13.3 0 24-10.7 24-24v-76.4c0-13.3-10.7-24-24-24H24c-13.3 0-24 10.7-24 24v76.4c0 13.3 10.7 24 24 24h400z"],"minus-circle":[512,512,[],"f056","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zM124 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H124z"],"minus-square":[448,512,[],"f146","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM92 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H92z"],plus:[448,512,[],"f067","M448 294.2v-76.4c0-13.3-10.7-24-24-24H286.2V56c0-13.3-10.7-24-24-24h-76.4c-13.3 0-24 10.7-24 24v137.8H24c-13.3 0-24 10.7-24 24v76.4c0 13.3 10.7 24 24 24h137.8V456c0 13.3 10.7 24 24 24h76.4c13.3 0 24-10.7 24-24V318.2H424c13.3 0 24-10.7 24-24z"],"plus-circle":[512,512,[],"f055","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"],"plus-square":[448,512,[],"f0fe","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-32 252c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92H92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"],question:[384,512,[],"f128","M202.021 0C122.202 0 70.503 32.703 29.914 91.026c-7.363 10.58-5.093 25.086 5.178 32.874l43.138 32.709c10.373 7.865 25.132 6.026 33.253-4.148 25.049-31.381 43.63-49.449 82.757-49.449 30.764 0 68.816 19.799 68.816 49.631 0 22.552-18.617 34.134-48.993 51.164-35.423 19.86-82.299 44.576-82.299 106.405V320c0 13.255 10.745 24 24 24h72.471c13.255 0 24-10.745 24-24v-5.773c0-42.86 125.268-44.645 125.268-160.627C377.504 66.256 286.902 0 202.021 0zM192 373.459c-38.196 0-69.271 31.075-69.271 69.271 0 38.195 31.075 69.27 69.271 69.27s69.271-31.075 69.271-69.271-31.075-69.27-69.271-69.27z"],save:[448,512,[],"f0c7","M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z"],search:[512,512,[],"f002","M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"],share:[512,512,[],"f064","M503.691 189.836L327.687 37.851C312.281 24.546 288 35.347 288 56.015v80.053C127.371 137.907 0 170.1 0 322.326c0 61.441 39.581 122.309 83.333 154.132 13.653 9.931 33.111-2.533 28.077-18.631C66.066 312.814 132.917 274.316 288 272.085V360c0 20.7 24.3 31.453 39.687 18.164l176.004-152c11.071-9.562 11.086-26.753 0-36.328z"],spinner:[512,512,[],"f110","M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"],square:[448,512,[],"f0c8","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48z"],"square-full":[512,512,[],"f45c","M512 512H0V0h512v512z"],times:[384,512,[],"f00d","M323.1 441l53.9-53.9c9.4-9.4 9.4-24.5 0-33.9L279.8 256l97.2-97.2c9.4-9.4 9.4-24.5 0-33.9L323.1 71c-9.4-9.4-24.5-9.4-33.9 0L192 168.2 94.8 71c-9.4-9.4-24.5-9.4-33.9 0L7 124.9c-9.4 9.4-9.4 24.5 0 33.9l97.2 97.2L7 353.2c-9.4 9.4-9.4 24.5 0 33.9L60.9 441c9.4 9.4 24.5 9.4 33.9 0l97.2-97.2 97.2 97.2c9.3 9.3 24.5 9.3 33.9 0z"],"times-circle":[512,512,[],"f057","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z"],wrench:[512,512,[],"f0ad","M481.156 200c9.3 0 15.12 10.155 10.325 18.124C466.295 259.992 420.419 288 368 288c-79.222 0-143.501-63.974-143.997-143.079C223.505 65.469 288.548-.001 368.002 0c52.362.001 98.196 27.949 123.4 69.743C496.24 77.766 490.523 88 481.154 88H376l-40 56 40 56h105.156zm-171.649 93.003L109.255 493.255c-24.994 24.993-65.515 24.994-90.51 0-24.993-24.994-24.993-65.516 0-90.51L218.991 202.5c16.16 41.197 49.303 74.335 90.516 90.503zM104 432c0-13.255-10.745-24-24-24s-24 10.745-24 24 10.745 24 24 24 24-10.745 24-24z"]};function u(e,t){var i=document.createElement("div");e.appendChild(i),i.appendChild(l("times")),i.addEventListener("click",(function(e){e.preventDefault(),e.stopPropagation(),t()}))}let f;function p(e,t,i){t.addEventListener("mousedown",function(e){e.stopPropagation(),e.preventDefault();const t=g.bind(this),r=m.bind(this),s=getComputedStyle(this),o=this.getBoundingClientRect();f={constraint:i,dragFunction:t,dragEndFunction:r,screenX:e.screenX,screenY:e.screenY,minDy:-o.top,minDx:-o.left,top:parseInt(s.top.replace("px","")),left:parseInt(s.left.replace("px",""))},document.addEventListener("mousemove",t),document.addEventListener("mouseup",r),document.addEventListener("mouseleave",r),document.addEventListener("mouseexit",r)}.bind(e))}function g(e){if(!f)return void console.error("No drag data!");e.stopPropagation(),e.preventDefault();const t=Math.max(f.minDx,e.screenX-f.screenX),i=Math.max(f.minDy,e.screenY-f.screenY),r=f.left+t,s=f.top+i;this.style.left=`${r}px`,this.style.top=`${s}px`}function m(e){if(!f)return void console.error("No drag data!");e.stopPropagation(),e.preventDefault();const t=f.dragFunction,i=f.dragEndFunction;document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",i),document.removeEventListener("mouseleave",i),document.removeEventListener("mouseexit",i),f=void 0}class w{constructor({parent:e,label:i,content:r,okHandler:s,cancelHandler:o}){this.parent=e;const n=()=>{this.elem.style.display="none","function"==typeof o&&o(this)};this.elem=t(),this.elem.classList.add("igv-ui-generic-dialog-container","igv-ui-center-fixed");const a=t({class:"igv-ui-generic-dialog-header"});if(this.elem.appendChild(a),u(a,n),i){const e=t({class:"igv-ui-dialog-one-liner"});this.elem.appendChild(e),e.innerHTML=i}r.elem.style.margin="16px",this.elem.appendChild(r.elem),this.content=r;const c=t({class:"igv-ui-generic-dialog-ok-cancel"});this.elem.appendChild(c),this.ok=t(),c.appendChild(this.ok),this.ok.textContent="OK",this.cancel=t(),c.appendChild(this.cancel),this.cancel.textContent="Cancel",this.callback=void 0,this.ok.addEventListener("click",(e=>{this.elem.style.display="none","function"==typeof s?s(this):this.callback&&"function"==typeof this.callback&&this.callback(this)})),this.cancel.addEventListener("click",n),p(this.elem,a),this.elem.addEventListener("click",(e=>{e.preventDefault(),e.stopPropagation()}))}present(e,t){if(e.label&&this.label&&(this.label.textContent=e.label),e.html){this.content.html.innerHTML=e.html}if(e.text){this.content.html.innerText=e.text}e.value&&this.input&&(this.input.value=e.value),e.callback&&(this.callback=e.callback);const{top:i}=t.currentTarget.parentElement.getBoundingClientRect();this.elem.style.top=`${i}px`,this.elem.style.display="flex"}}function b(e){return"string"==typeof e||e instanceof String}function F(e){var t=String(e).split(/[.,]/);return t[0].split("").reverse().reduce((function(e,t,i){return i%3==0?e+","+t:e+t})).split("").reverse().join("")+(t[1]?"."+t[1]:"")}const v=function(e){return e.split(/\n|\r\n|\r/g)};function y(e,t){var i,r,s=[],o=e.length,n=0,a=!1;if(o>0)for(s[n]=e.charAt(0),i=1;i0?e.charAt(0).toUpperCase()+e.slice(1):e}function _(e){if(void 0!==e.name)return e.name;if(b(e)){let t=e.lastIndexOf("/"),i=t<0?e:e.substr(t+1);return t=i.indexOf("?"),t>0&&(i=i.substr(0,t)),i}throw Error("Expected File or string, got "+typeof e)}function x(e){return!!e&&("function"!=typeof e&&(e instanceof File||e.hasOwnProperty("name")&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer))}function k(e,t){const i=document.createElement("a");i.setAttribute("href",t),i.setAttribute("download",e),i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}function I(e){for(var t=S,i=t.parser.loose.exec(e),r={},s=14;s--;)r[t.key[s]]=i[s]||"";return r[t.q.name]={},r[t.key[12]].replace(t.q.parser,(function(e,i,s){i&&(r[t.q.name][i]=s)})),r}"object"==typeof process&&"undefined"==typeof window&&(global.atob=function(e){return Buffer.from(e,"base64").toString("binary")});const S={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};function E(e){let t=e.length;for(;--t>=0;)e[t]=0}const N=256,M=286,R=30,B=15,D=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),L=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),T=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),P=new Array(576);E(P);const H=new Array(60);E(H);const O=new Array(512);E(O);const V=new Array(256);E(V);const q=new Array(29);E(q);const U=new Array(R);function Q(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}let G,j,W;function $(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}E(U);const K=e=>e<256?O[e]:O[256+(e>>>7)],Z=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Y=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{Y(e,i[2*t],i[2*t+1])},J=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},ee=(e,t,i)=>{const r=new Array(16);let s,o,n=0;for(s=1;s<=B;s++)n=n+i[s-1]<<1,r[s]=n;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=J(r[t]++,t))}},te=e=>{let t;for(t=0;t{e.bi_valid>8?Z(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},re=(e,t,i,r)=>{const s=2*t,o=2*i;return e[s]{const r=e.heap[i];let s=i<<1;for(;s<=e.heap_len&&(s{let r,s,o,n,a=0;if(0!==e.sym_next)do{r=255&e.pending_buf[e.sym_buf+a++],r+=(255&e.pending_buf[e.sym_buf+a++])<<8,s=e.pending_buf[e.sym_buf+a++],0===r?X(e,s,t):(o=V[s],X(e,o+N+1,t),n=D[o],0!==n&&(s-=q[o],Y(e,s,n)),r--,o=K(r),X(e,o,i),n=L[o],0!==n&&(r-=U[o],Y(e,r,n)))}while(a{const i=t.dyn_tree,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.elems;let n,a,c,l=-1;for(e.heap_len=0,e.heap_max=573,n=0;n>1;n>=1;n--)se(e,i,n);c=o;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],se(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=a,i[2*c]=i[2*n]+i[2*a],e.depth[c]=(e.depth[n]>=e.depth[a]?e.depth[n]:e.depth[a])+1,i[2*n+1]=i[2*a+1]=c,e.heap[1]=c++,se(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,r=t.max_code,s=t.stat_desc.static_tree,o=t.stat_desc.has_stree,n=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let l,h,d,u,f,p,g=0;for(u=0;u<=B;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)h=e.heap[l],u=i[2*i[2*h+1]+1]+1,u>c&&(u=c,g++),i[2*h+1]=u,h>r||(e.bl_count[u]++,f=0,h>=a&&(f=n[h-a]),p=i[2*h],e.opt_len+=p*(u+f),o&&(e.static_len+=p*(s[2*h+1]+f)));if(0!==g){do{for(u=c-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[c]--,g-=2}while(g>0);for(u=c;0!==u;u--)for(h=e.bl_count[u];0!==h;)d=e.heap[--l],d>r||(i[2*d+1]!==u&&(e.opt_len+=(u-i[2*d+1])*i[2*d],i[2*d+1]=u),h--)}})(e,t),ee(i,l,e.bl_count)},ae=(e,t,i)=>{let r,s,o=-1,n=t[1],a=0,c=7,l=4;for(0===n&&(c=138,l=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=n,n=t[2*(r+1)+1],++a{let r,s,o=-1,n=t[1],a=0,c=7,l=4;for(0===n&&(c=138,l=3),r=0;r<=i;r++)if(s=n,n=t[2*(r+1)+1],!(++a{Y(e,0+(r?1:0),3),ie(e),Z(e,i),Z(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var de=(e,t,i,r)=>{let s,o,n=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t{let t;for(ae(e,e.dyn_ltree,e.l_desc.max_code),ae(e,e.dyn_dtree,e.d_desc.max_code),ne(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*z[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),s=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=s&&(s=o)):s=o=i+5,i+4<=s&&-1!==t?he(e,t,i,r):4===e.strategy||o===s?(Y(e,2+(r?1:0),3),oe(e,P,H)):(Y(e,4+(r?1:0),3),((e,t,i,r)=>{let s;for(Y(e,t-257,5),Y(e,i-1,5),Y(e,r-4,4),s=0;s{le||((()=>{let e,t,i,r,s;const o=new Array(16);for(i=0,r=0;r<28;r++)for(q[r]=i,e=0;e<1<>=7;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(V[i]+N+1)]++,e.dyn_dtree[2*K(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{Y(e,2,3),X(e,256,P),(e=>{16===e.bi_valid?(Z(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}};var fe=(e,t,i,r)=>{let s=65535&e,o=e>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+t[r++]|0,o=o+s|0}while(--n);s%=65521,o%=65521}return s|o<<16};const pe=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var ge=(e,t,i,r)=>{const s=pe,o=r+i;e^=-1;for(let i=r;i>>8^s[255&(e^t[i])];return-1^e},me={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},we={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:be,_tr_stored_block:Fe,_tr_flush_block:ve,_tr_tally:ye,_tr_align:Ae}=ue,{Z_NO_FLUSH:Ce,Z_PARTIAL_FLUSH:_e,Z_FULL_FLUSH:xe,Z_FINISH:ke,Z_BLOCK:Ie,Z_OK:Se,Z_STREAM_END:Ee,Z_STREAM_ERROR:Ne,Z_DATA_ERROR:Me,Z_BUF_ERROR:Re,Z_DEFAULT_COMPRESSION:Be,Z_FILTERED:De,Z_HUFFMAN_ONLY:Le,Z_RLE:Te,Z_FIXED:ze,Z_DEFAULT_STRATEGY:Pe,Z_UNKNOWN:He,Z_DEFLATED:Oe}=we,Ve=258,qe=262,Ue=42,Qe=113,Ge=666,je=(e,t)=>(e.msg=me[t],t),We=e=>2*e-(e>4?9:0),$e=e=>{let t=e.length;for(;--t>=0;)e[t]=0},Ke=e=>{let t,i,r,s=e.w_size;t=e.hash_size,r=t;do{i=e.head[--r],e.head[r]=i>=s?i-s:0}while(--t);t=s,r=t;do{i=e.prev[--r],e.prev[r]=i>=s?i-s:0}while(--t)};let Ze=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Xe=(e,t)=>{ve(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Ye(e.strm)},Je=(e,t)=>{e.pending_buf[e.pending++]=t},et=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},tt=(e,t,i,r)=>{let s=e.avail_in;return s>r&&(s=r),0===s?0:(e.avail_in-=s,t.set(e.input.subarray(e.next_in,e.next_in+s),i),1===e.state.wrap?e.adler=fe(e.adler,t,s,i):2===e.state.wrap&&(e.adler=ge(e.adler,t,s,i)),e.next_in+=s,e.total_in+=s,s)},it=(e,t)=>{let i,r,s=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-qe?e.strstart-(e.w_size-qe):0,l=e.window,h=e.w_mask,d=e.prev,u=e.strstart+Ve;let f=l[o+n-1],p=l[o+n];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,l[i+n]===p&&l[i+n-1]===f&&l[i]===l[o]&&l[++i]===l[o+1]){o+=2,i++;do{}while(l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&on){if(e.match_start=t,n=r,r>=a)break;f=l[o+n-1],p=l[o+n]}}}while((t=d[t&h])>c&&0!==--s);return n<=e.lookahead?n:e.lookahead},rt=e=>{const t=e.w_size;let i,r,s;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-qe)&&(e.window.set(e.window.subarray(t,t+t-r),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),Ke(e),r+=t),0===e.strm.avail_in)break;if(i=tt(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=i,e.lookahead+e.insert>=3)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=Ze(e,e.ins_h,e.window[s+1]);e.insert&&(e.ins_h=Ze(e,e.ins_h,e.window[s+3-1]),e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,r,s,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n=0,a=e.strm.avail_in;do{if(i=65535,s=e.bi_valid+42>>3,e.strm.avail_outr+e.strm.avail_in&&(i=r+e.strm.avail_in),i>s&&(i=s),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,Ye(e.strm),r&&(r>i&&(r=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+r),e.strm.next_out),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r,e.block_start+=r,i-=r),i&&(tt(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===n);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waters&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(tt(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,o=s>e.w_size?e.w_size:s,r=e.strstart-e.block_start,(r>=o||(r||t===ke)&&t!==Ce&&0===e.strm.avail_in&&r<=s)&&(i=r>s?s:r,n=t===ke&&0===e.strm.avail_in&&i===r?1:0,Fe(e,e.block_start,i,n),e.block_start+=i,Ye(e.strm)),n?3:1)},ot=(e,t)=>{let i,r;for(;;){if(e.lookahead=3&&(e.ins_h=Ze(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-qe&&(e.match_length=it(e,i)),e.match_length>=3)if(r=ye(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Ze(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Ze(e,e.ins_h,e.window[e.strstart+1]);else r=ye(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(Xe(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2},nt=(e,t)=>{let i,r,s;for(;;){if(e.lookahead=3&&(e.ins_h=Ze(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=ye(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=Ze(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(Xe(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(r=ye(e,0,e.window[e.strstart-1]),r&&Xe(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=ye(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2};function at(e,t,i,r,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=s}const ct=[new at(0,0,0,0,st),new at(4,4,8,4,ot),new at(4,5,16,8,ot),new at(4,6,32,32,ot),new at(4,4,16,16,nt),new at(8,16,32,32,nt),new at(8,16,128,128,nt),new at(8,32,128,256,nt),new at(32,128,258,1024,nt),new at(32,258,258,4096,nt)];function lt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Oe,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),$e(this.dyn_ltree),$e(this.dyn_dtree),$e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),$e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),$e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const ht=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Ue&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Qe&&t.status!==Ge?1:0},dt=e=>{if(ht(e))return je(e,Ne);e.total_in=e.total_out=0,e.data_type=He;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?Ue:Qe,e.adler=2===t.wrap?0:1,t.last_flush=-2,be(t),Se},ut=e=>{const t=dt(e);var i;return t===Se&&((i=e.state).window_size=2*i.w_size,$e(i.head),i.max_lazy_match=ct[i.level].max_lazy,i.good_match=ct[i.level].good_length,i.nice_match=ct[i.level].nice_length,i.max_chain_length=ct[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},ft=(e,t,i,r,s,o)=>{if(!e)return Ne;let n=1;if(t===Be&&(t=6),r<0?(n=0,r=-r):r>15&&(n=2,r-=16),s<1||s>9||i!==Oe||r<8||r>15||t<0||t>9||o<0||o>ze||8===r&&1!==n)return je(e,Ne);8===r&&(r=9);const a=new lt;return e.state=a,a.strm=e,a.status=Ue,a.wrap=n,a.gzhead=null,a.w_bits=r,a.w_size=1<{let i=t.length;if(ht(e))return Ne;const r=e.state,s=r.wrap;if(2===s||1===s&&r.status!==Ue||r.lookahead)return Ne;if(1===s&&(e.adler=fe(e.adler,t,i,0)),r.wrap=0,i>=r.w_size){0===s&&($e(r.head),r.strstart=0,r.block_start=0,r.insert=0);let e=new Uint8Array(r.w_size);e.set(t.subarray(i-r.w_size,i),0),t=e,i=r.w_size}const o=e.avail_in,n=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,rt(r);r.lookahead>=3;){let e=r.strstart,t=r.lookahead-2;do{r.ins_h=Ze(r,r.ins_h,r.window[e+3-1]),r.prev[e&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=e,e++}while(--t);r.strstart=e,r.lookahead=2,rt(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,e.next_in=n,e.input=a,e.avail_in=o,r.wrap=s,Se},gt={deflateInit:(e,t)=>ft(e,t,Oe,15,8,Pe),deflateInit2:ft,deflateReset:ut,deflateResetKeep:dt,deflateSetHeader:(e,t)=>ht(e)||2!==e.state.wrap?Ne:(e.state.gzhead=t,Se),deflate:(e,t)=>{if(ht(e)||t>Ie||t<0)return e?je(e,Ne):Ne;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Ge&&t!==ke)return je(e,0===e.avail_out?Re:Ne);const r=i.last_flush;if(i.last_flush=t,0!==i.pending){if(Ye(e),0===e.avail_out)return i.last_flush=-1,Se}else if(0===e.avail_in&&We(t)<=We(r)&&t!==ke)return je(e,Re);if(i.status===Ge&&0!==e.avail_in)return je(e,Re);if(i.status===Ue&&0===i.wrap&&(i.status=Qe),i.status===Ue){let t=Oe+(i.w_bits-8<<4)<<8,r=-1;if(r=i.strategy>=Le||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=r<<6,0!==i.strstart&&(t|=32),t+=31-t%31,et(i,t),0!==i.strstart&&(et(i,e.adler>>>16),et(i,65535&e.adler)),e.adler=1,i.status=Qe,Ye(e),0!==i.pending)return i.last_flush=-1,Se}if(57===i.status)if(e.adler=0,Je(i,31),Je(i,139),Je(i,8),i.gzhead)Je(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Je(i,255&i.gzhead.time),Je(i,i.gzhead.time>>8&255),Je(i,i.gzhead.time>>16&255),Je(i,i.gzhead.time>>24&255),Je(i,9===i.level?2:i.strategy>=Le||i.level<2?4:0),Je(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Je(i,255&i.gzhead.extra.length),Je(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=ge(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Je(i,0),Je(i,0),Je(i,0),Je(i,0),Je(i,0),Je(i,9===i.level?2:i.strategy>=Le||i.level<2?4:0),Je(i,3),i.status=Qe,Ye(e),0!==i.pending)return i.last_flush=-1,Se;if(69===i.status){if(i.gzhead.extra){let t=i.pending,r=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+r>i.pending_buf_size;){let s=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=ge(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=s,Ye(e),0!==i.pending)return i.last_flush=-1,Se;t=0,r-=s}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending+=r,i.gzhead.hcrc&&i.pending>t&&(e.adler=ge(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,r=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>r&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r)),Ye(e),0!==i.pending)return i.last_flush=-1,Se;r=0}t=i.gzindexr&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,r=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>r&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r)),Ye(e),0!==i.pending)return i.last_flush=-1,Se;r=0}t=i.gzindexr&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(Ye(e),0!==i.pending))return i.last_flush=-1,Se;Je(i,255&e.adler),Je(i,e.adler>>8&255),e.adler=0}if(i.status=Qe,Ye(e),0!==i.pending)return i.last_flush=-1,Se}if(0!==e.avail_in||0!==i.lookahead||t!==Ce&&i.status!==Ge){let r=0===i.level?st(i,t):i.strategy===Le?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(rt(e),0===e.lookahead)){if(t===Ce)return 1;break}if(e.match_length=0,i=ye(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Xe(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===Te?((e,t)=>{let i,r,s,o;const n=e.window;for(;;){if(e.lookahead<=Ve){if(rt(e),e.lookahead<=Ve&&t===Ce)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(s=e.strstart-1,r=n[s],r===n[++s]&&r===n[++s]&&r===n[++s])){o=e.strstart+Ve;do{}while(r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=ye(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=ye(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Xe(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2})(i,t):ct[i.level].func(i,t);if(3!==r&&4!==r||(i.status=Ge),1===r||3===r)return 0===e.avail_out&&(i.last_flush=-1),Se;if(2===r&&(t===_e?Ae(i):t!==Ie&&(Fe(i,0,0,!1),t===xe&&($e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Ye(e),0===e.avail_out))return i.last_flush=-1,Se}return t!==ke?Se:i.wrap<=0?Ee:(2===i.wrap?(Je(i,255&e.adler),Je(i,e.adler>>8&255),Je(i,e.adler>>16&255),Je(i,e.adler>>24&255),Je(i,255&e.total_in),Je(i,e.total_in>>8&255),Je(i,e.total_in>>16&255),Je(i,e.total_in>>24&255)):(et(i,e.adler>>>16),et(i,65535&e.adler)),Ye(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Se:Ee)},deflateEnd:e=>{if(ht(e))return Ne;const t=e.state.status;return e.state=null,t===Qe?je(e,Me):Se},deflateSetDictionary:pt,deflateInfo:"pako deflate (from Nodeca project)"};const mt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var wt=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)mt(i,t)&&(e[t]=i[t])}}return e},bt=e=>{let t=0;for(let i=0,r=e.length;i=252?6:by>=248?5:by>=240?4:by>=224?3:by>=192?2:1;vt[254]=vt[254]=1;var yt=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,r,s,o,n=e.length,a=0;for(s=0;s>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},At=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let r,s;const o=new Array(2*i);for(s=0,r=0;r4)o[s++]=65533,r+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&r1?o[s++]=65533:t<65536?o[s++]=t:(t-=65536,o[s++]=55296|t>>10&1023,o[s++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&Ft)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let r=0;r{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+vt[e[i]]>t?i:t};var _t=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const xt=Object.prototype.toString,{Z_NO_FLUSH:kt,Z_SYNC_FLUSH:It,Z_FULL_FLUSH:St,Z_FINISH:Et,Z_OK:Nt,Z_STREAM_END:Mt,Z_DEFAULT_COMPRESSION:Rt,Z_DEFAULT_STRATEGY:Bt,Z_DEFLATED:Dt}=we;function Lt(e){this.options=wt({level:Rt,method:Dt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Bt},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _t,this.strm.avail_out=0;let i=gt.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==Nt)throw new Error(me[i]);if(t.header&>.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?yt(t.dictionary):"[object ArrayBuffer]"===xt.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=gt.deflateSetDictionary(this.strm,e),i!==Nt)throw new Error(me[i]);this._dict_set=!0}}function Tt(e,t){const i=new Lt(t);if(i.push(e,!0),i.err)throw i.msg||me[i.err];return i.result}Lt.prototype.push=function(e,t){const i=this.strm,r=this.options.chunkSize;let s,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?Et:kt,"string"==typeof e?i.input=yt(e):"[object ArrayBuffer]"===xt.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(r),i.next_out=0,i.avail_out=r),(o===It||o===St)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(s=gt.deflate(i,o),s===Mt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),s=gt.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===Nt;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Lt.prototype.onData=function(e){this.chunks.push(e)},Lt.prototype.onEnd=function(e){e===Nt&&(this.result=bt(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var zt=function(e,t){return(t=t||{}).raw=!0,Tt(e,t)},Pt=function(e,t){return(t=t||{}).gzip=!0,Tt(e,t)},Ht={Deflate:Lt,deflate:Tt,deflateRaw:zt,gzip:Pt,constants:we};const Ot=16209;var Vt=function(e,t){let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_,x;const k=e.state;i=e.next_in,_=e.input,r=i+(e.avail_in-5),s=e.next_out,x=e.output,o=s-(t-e.avail_out),n=s+(e.avail_out-257),a=k.dmax,c=k.wsize,l=k.whave,h=k.wnext,d=k.window,u=k.hold,f=k.bits,p=k.lencode,g=k.distcode,m=(1<>>24,u>>>=F,f-=F,F=b>>>16&255,0===F)x[s++]=65535&b;else{if(!(16&F)){if(64&F){if(32&F){k.mode=16191;break e}e.msg="invalid literal/length code",k.mode=Ot;break e}b=p[(65535&b)+(u&(1<>>=F,f-=F),f<15&&(u+=_[i++]<>>24,u>>>=F,f-=F,F=b>>>16&255,16&F){if(y=65535&b,F&=15,fa){e.msg="invalid distance too far back",k.mode=Ot;break e}if(u>>>=F,f-=F,F=s-o,y>F){if(F=y-F,F>l&&k.sane){e.msg="invalid distance too far back",k.mode=Ot;break e}if(A=0,C=d,0===h){if(A+=c-F,F2;)x[s++]=C[A++],x[s++]=C[A++],x[s++]=C[A++],v-=3;v&&(x[s++]=C[A++],v>1&&(x[s++]=C[A++]))}else{A=s-y;do{x[s++]=x[A++],x[s++]=x[A++],x[s++]=x[A++],v-=3}while(v>2);v&&(x[s++]=x[A++],v>1&&(x[s++]=x[A++]))}break}if(64&F){e.msg="invalid distance code",k.mode=Ot;break e}b=g[(65535&b)+(u&(1<>3,i-=v,f-=v<<3,u&=(1<{const c=a.bits;let l,h,d,u,f,p,g=0,m=0,w=0,b=0,F=0,v=0,y=0,A=0,C=0,_=0,x=null;const k=new Uint16Array(16),I=new Uint16Array(16);let S,E,N,M=null;for(g=0;g<=qt;g++)k[g]=0;for(m=0;m=1&&0===k[b];b--);if(F>b&&(F=b),0===b)return s[o++]=20971520,s[o++]=20971520,a.bits=1,0;for(w=1;w0&&(0===e||1!==b))return-1;for(I[1]=0,g=1;g852||2===e&&C>592)return 1;for(;;){S=g-y,n[m]+1=p?(E=M[n[m]-p],N=x[n[m]-p]):(E=96,N=0),l=1<>y)+h]=S<<24|E<<16|N}while(0!==h);for(l=1<>=1;if(0!==l?(_&=l-1,_+=l):_=0,m++,0===--k[g]){if(g===b)break;g=t[i+n[m]]}if(g>F&&(_&u)!==d){for(0===y&&(y=F),f+=w,v=g-y,A=1<852||2===e&&C>592)return 1;d=_&u,s[d]=F<<24|v<<16|f-o}}return 0!==_&&(s[f+_]=g-y<<24|64<<16),a.bits=F,0};const{Z_FINISH:$t,Z_BLOCK:Kt,Z_TREES:Zt,Z_OK:Yt,Z_STREAM_END:Xt,Z_NEED_DICT:Jt,Z_STREAM_ERROR:ei,Z_DATA_ERROR:ti,Z_MEM_ERROR:ii,Z_BUF_ERROR:ri,Z_DEFLATED:si}=we,oi=16180,ni=16190,ai=16191,ci=16192,li=16194,hi=16199,di=16200,ui=16206,fi=16209,pi=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function gi(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const mi=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},wi=e=>{if(mi(e))return ei;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=oi,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Yt},bi=e=>{if(mi(e))return ei;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,wi(e)},Fi=(e,t)=>{let i;if(mi(e))return ei;const r=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?ei:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,bi(e))},vi=(e,t)=>{if(!e)return ei;const i=new gi;e.state=i,i.strm=e,i.window=null,i.mode=oi;const r=Fi(e,t);return r!==Yt&&(e.state=null),r};let yi,Ai,Ci=!0;const _i=e=>{if(Ci){yi=new Int32Array(512),Ai=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Wt(1,e.lens,0,288,yi,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Wt(2,e.lens,0,32,Ai,0,e.work,{bits:5}),Ci=!1}e.lencode=yi,e.lenbits=9,e.distcode=Ai,e.distbits=5},xi=(e,t,i,r)=>{let s;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(s=o.wsize-o.wnext,s>r&&(s=r),o.window.set(t.subarray(i-r,i-r+s),o.wnext),(r-=s)?(o.window.set(t.subarray(i-r,i),0),o.wnext=r,o.whave=o.wsize):(o.wnext+=s,o.wnext===o.wsize&&(o.wnext=0),o.whavevi(e,15),inflateInit2:vi,inflate:(e,t)=>{let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_=0;const x=new Uint8Array(4);let k,I;const S=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(mi(e)||!e.output||!e.input&&0!==e.avail_in)return ei;i=e.state,i.mode===ai&&(i.mode=ci),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,d=a,u=c,C=Yt;e:for(;;)switch(i.mode){case oi:if(0===i.wrap){i.mode=ci;break}for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=ge(i.check,x,2,0),l=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=fi;break}if((15&l)!==si){e.msg="unknown compression method",i.mode=fi;break}if(l>>>=4,h-=4,A=8+(15&l),0===i.wbits&&(i.wbits=A),A>15||A>i.wbits){e.msg="invalid window size",i.mode=fi;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(x[0]=255&l,x[1]=l>>>8&255,i.check=ge(i.check,x,2,0)),l=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>8&255,x[2]=l>>>16&255,x[3]=l>>>24&255,i.check=ge(i.check,x,4,0)),l=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>8),512&i.flags&&4&i.wrap&&(x[0]=255&l,x[1]=l>>>8&255,i.check=ge(i.check,x,2,0)),l=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=ge(i.check,x,2,0)),l=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(f=i.length,f>a&&(f=a),f&&(i.head&&(A=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(o,o+f),A)),512&i.flags&&4&i.wrap&&(i.check=ge(i.check,r,f,o)),a-=f,o+=f,i.length-=f),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;f=0;do{A=r[o+f++],i.head&&A&&i.length<65536&&(i.head.name+=String.fromCharCode(A))}while(A&&f>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ai;break;case 16189:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>=7&h,h-=7&h,i.mode=ui;break}for(;h<3;){if(0===a)break e;a--,l+=r[o++]<>>=1,h-=1,3&l){case 0:i.mode=16193;break;case 1:if(_i(i),i.mode=hi,t===Zt){l>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=fi}l>>>=2,h-=2;break;case 16193:for(l>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,l+=r[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=fi;break}if(i.length=65535&l,l=0,h=0,i.mode=li,t===Zt)break e;case li:i.mode=16195;case 16195:if(f=i.length,f){if(f>a&&(f=a),f>c&&(f=c),0===f)break e;s.set(r.subarray(o,o+f),n),a-=f,o+=f,c-=f,n+=f,i.length-=f;break}i.mode=ai;break;case 16196:for(;h<14;){if(0===a)break e;a--,l+=r[o++]<>>=5,h-=5,i.ndist=1+(31&l),l>>>=5,h-=5,i.ncode=4+(15&l),l>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=fi;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[S[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,k={bits:i.lenbits},C=Wt(0,i.lens,0,19,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid code lengths set",i.mode=fi;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=m,h-=m,i.lens[i.have++]=b;else{if(16===b){for(I=m+2;h>>=m,h-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=fi;break}A=i.lens[i.have-1],f=3+(3&l),l>>>=2,h-=2}else if(17===b){for(I=m+3;h>>=m,h-=m,A=0,f=3+(7&l),l>>>=3,h-=3}else{for(I=m+7;h>>=m,h-=m,A=0,f=11+(127&l),l>>>=7,h-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=fi;break}for(;f--;)i.lens[i.have++]=A}}if(i.mode===fi)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=fi;break}if(i.lenbits=9,k={bits:i.lenbits},C=Wt(1,i.lens,0,i.nlen,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid literal/lengths set",i.mode=fi;break}if(i.distbits=6,i.distcode=i.distdyn,k={bits:i.distbits},C=Wt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,k),i.distbits=k.bits,C){e.msg="invalid distances set",i.mode=fi;break}if(i.mode=hi,t===Zt)break e;case hi:i.mode=di;case di:if(a>=6&&c>=258){e.next_out=n,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=l,i.bits=h,Vt(e,u),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,i.mode===ai&&(i.back=-1);break}for(i.back=0;_=i.lencode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,i.length=b,0===w){i.mode=16205;break}if(32&w){i.back=-1,i.mode=ai;break}if(64&w){e.msg="invalid literal/length code",i.mode=fi;break}i.extra=15&w,i.mode=16201;case 16201:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;_=i.distcode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,64&w){e.msg="invalid distance code",i.mode=fi;break}i.offset=b,i.extra=15&w,i.mode=16203;case 16203:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=fi;break}i.mode=16204;case 16204:if(0===c)break e;if(f=u-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=fi;break}f>i.wnext?(f-=i.wnext,p=i.wsize-f):p=i.wnext-f,f>i.length&&(f=i.length),g=i.window}else g=s,p=n-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do{s[n++]=g[p++]}while(--f);0===i.length&&(i.mode=di);break;case 16205:if(0===c)break e;s[n++]=i.length,c--,i.mode=di;break;case ui:if(i.wrap){for(;h<32;){if(0===a)break e;a--,l|=r[o++]<{if(mi(e))return ei;let t=e.state;return t.window&&(t.window=null),e.state=null,Yt},inflateGetHeader:(e,t)=>{if(mi(e))return ei;const i=e.state;return 2&i.wrap?(i.head=t,t.done=!1,Yt):ei},inflateSetDictionary:(e,t)=>{const i=t.length;let r,s,o;return mi(e)?ei:(r=e.state,0!==r.wrap&&r.mode!==ni?ei:r.mode===ni&&(s=1,s=fe(s,t,i,0),s!==r.check)?ti:(o=xi(e,t,i,i),o?(r.mode=16210,ii):(r.havedict=1,Yt)))},inflateInfo:"pako inflate (from Nodeca project)"};var Ii=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const Si=Object.prototype.toString,{Z_NO_FLUSH:Ei,Z_FINISH:Ni,Z_OK:Mi,Z_STREAM_END:Ri,Z_NEED_DICT:Bi,Z_STREAM_ERROR:Di,Z_DATA_ERROR:Li,Z_MEM_ERROR:Ti}=we;function zi(e){this.options=wt({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _t,this.strm.avail_out=0;let i=ki.inflateInit2(this.strm,t.windowBits);if(i!==Mi)throw new Error(me[i]);if(this.header=new Ii,ki.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=yt(t.dictionary):"[object ArrayBuffer]"===Si.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=ki.inflateSetDictionary(this.strm,t.dictionary),i!==Mi)))throw new Error(me[i])}function Pi(e,t){const i=new zi(t);if(i.push(e),i.err)throw i.msg||me[i.err];return i.result}zi.prototype.push=function(e,t){const i=this.strm,r=this.options.chunkSize,s=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Ni:Ei,"[object ArrayBuffer]"===Si.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(r),i.next_out=0,i.avail_out=r),o=ki.inflate(i,n),o===Bi&&s&&(o=ki.inflateSetDictionary(i,s),o===Mi?o=ki.inflate(i,n):o===Li&&(o=Bi));i.avail_in>0&&o===Ri&&i.state.wrap>0&&0!==e[i.next_in];)ki.inflateReset(i),o=ki.inflate(i,n);switch(o){case Di:case Li:case Bi:case Ti:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===Ri))if("string"===this.options.to){let e=Ct(i.output,i.next_out),t=i.next_out-e,s=At(i.output,e);i.next_out=t,i.avail_out=r-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(s)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==Mi||0!==a){if(o===Ri)return o=ki.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},zi.prototype.onData=function(e){this.chunks.push(e)},zi.prototype.onEnd=function(e){e===Mi&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=bt(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Hi=function(e,t){return(t=t||{}).raw=!0,Pi(e,t)},Oi={Inflate:zi,inflate:Pi,inflateRaw:Hi,ungzip:Pi,constants:we};const{Deflate:Vi,deflate:qi,deflateRaw:Ui,gzip:Qi}=Ht,{Inflate:Gi,inflate:ji,inflateRaw:Wi,ungzip:$i}=Oi;var Ki=Ui,Zi=ji,Yi=Wi,Xi=$i;function Ji(e){const t=ArrayBuffer.isView(e)?e:new Uint8Array(e);return 31===t[0]&&139===t[1]}function er(e){const t=ArrayBuffer.isView(e)?e:new Uint8Array(e);return 0!==(4&t[3])&&66===t[12]&&67===t[13]?tr(t.buffer):Xi(t)}function tr(e,t){const i=[];let r=0,s=0;for(t=t||e.byteLength-18;r100?or(new Uint8Array(e.buffer,e.byteOffset+t,s),i,r):function(e,t,i,r,s){for(let o=0;o=0){s=atob(s);const e=new Uint8Array(s.length);for(let t=0;t0?Xi(e):e,i}return decodeURIComponent(s)}const ar=(e,t,i)=>(1-i)*e+i*t,cr=function(e,t,i){return Math.min(Math.max(e,t),i)},lr=function(e){return Math.log(e)/Math.LN2};function hr(){this.content=[]}function dr(e,t){return Math.random()*(t-e)+e}hr.prototype={push:function(e){this.content.push(e),this.bubbleUp(this.content.length-1)},pop:function(){var e=this.content[0],t=this.content.pop();return this.content.length>0&&(this.content[0]=t,this.sinkDown(0)),e},remove:function(e){for(var t=this.content.length,i=0;i0;){var r=Math.floor((e+1)/2)-1,s=this.content[r];if(i>=s)break;this.content[r]=t,this.content[e]=s,e=r}},sinkDown:function(e){for(var t=this.content.length,i=this.content[e],r=i;;){var s=2*(e+1),o=s-1,n=null;if(o{let e=[];for(let t=1;t>=.5;t-=.1)for(let i=0;i<1;i+=1/28){const r="rgb("+ur.hsvToRgb(i,1,t).join(",")+")";e.push(r)}return e.pop(),e.push(ur.rgbColor(16,16,16)),e},rgbToHex:function(e){return(e=e.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i))&&4===e.length?"#"+("0"+parseInt(e[1],10).toString(16)).slice(-2)+("0"+parseInt(e[2],10).toString(16)).slice(-2)+("0"+parseInt(e[3],10).toString(16)).slice(-2):""},hexToRgb:function(e){var t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(null!==t)return"rgb("+parseInt(t[1],16)+","+parseInt(t[2],16)+","+parseInt(t[3],16)+")"},hsvToRgb:function(e,t,i){var r,s,o,n=Math.floor(6*e),a=6*e-n,c=i*(1-t),l=i*(1-a*t),h=i*(1-(1-a)*t);switch(n%6){case 0:r=i,s=h,o=c;break;case 1:r=l,s=i,o=c;break;case 2:r=c,s=i,o=h;break;case 3:r=c,s=l,o=i;break;case 4:r=h,s=c,o=i;break;case 5:r=i,s=c,o=l}return[Math.floor(255*r),Math.floor(255*s),Math.floor(255*o)]},hslToRgb:function(e,t,i){var r,s,o;if(0===t)r=s=o=i;else{var n=i<.5?i*(1+t):i+t-i*t,a=2*i-n;r=ur.hue2rgb(a,n,e+1/3),s=ur.hue2rgb(a,n,e),o=ur.hue2rgb(a,n,e-1/3)}return[255*r,255*s,255*o]},hue2rgb:(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e),rgbaColor:function(e,t,i,r){return"rgba("+(e=cr(e,0,255))+","+(t=cr(t,0,255))+","+(i=cr(i,0,255))+","+(r=cr(r,0,1))+")"},rgbColor:function(e,t,i){return"rgb("+(e=cr(e,0,255))+","+(t=cr(t,0,255))+","+(i=cr(i,0,255))+")"},greyScale:function(e){var t=cr(e,0,255);return"rgb("+t+","+t+","+t+")"},randomGrey:function(e,t){e=cr(e,0,255),t=cr(t,0,255);var i=Math.round(dr(e,t)).toString(10);return"rgb("+i+","+i+","+i+")"},randomRGB:function(e,t){return e=cr(e,0,255),t=cr(t,0,255),"rgb("+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+")"},randomRGBConstantAlpha:function(e,t,i){return e=cr(e,0,255),t=cr(t,0,255),"rgba("+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+","+i+")"},addAlpha:function(e,t){if("0"===e||"."===e)e="rgb(0,0,0)";else{const t=this.colorNameToHex(e);t&&(e=t)}var i=/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(e);if(e.startsWith("rgba")){const i=e.lastIndexOf(",");return e.substring(0,i+1)+t.toString()+")"}return i&&(e=ur.hexToRgb(e)),e.startsWith("rgb")?e.replace("rgb","rgba").replace(")",", "+t+")"):(console.log(e+" is not an rgb style string"),e)},rgbComponents:function(e){if("0"===e||"."===e)return[0,0,0];if(/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(e))e=ur.hexToRgb(e);else if(!e.startsWith("rgb")){const t=this.colorNameToHex(e);e=this.hexToRgb(t)}if(e.startsWith("rgb("))return e.substring(4,e.length-1).split(",").map((e=>Number.parseInt(e.trim())));if(e.startsWith("rgba("))return e.substring(5,e.length-1).split(",").map(((e,t)=>(e=e.trim(),3===t?Number.parseFloat(e):Number.parseInt(e))));throw Error("Unrecognized color string: color")},getCompositeColor:function(e,t,i){return"rgb("+Math.floor(i*t[0]+(1-i)*e[0])+","+Math.floor(i*t[1]+(1-i)*e[1])+","+Math.floor(i*t[2]+(1-i)*e[2])+")"},createColorString:function(e){const t=this.createColorStringSafe(e);return t||e},createColorStringSafe:function(e){if((e=A(e)).startsWith("rgb(")&&e.endsWith(")"))return e;if(e.startsWith("#")&&e.length<8)return e;const t=this.colorNameToHex(e);if(t)return t;const i=e.split(",");return 3===i.length&&fr(i[0])&&fr(i[1])&&fr(i[2])?`rgb(${e})`:void 0},darkenLighten:function(e,t){let i,r=this.colorNameToHex(e);i=r?ur.hexToRgb(r):e.startsWith("rgb(")?e:ur.hexToRgb(e);const s=i.replace(")","").substring(4).split(","),o=Math.max(0,Math.min(255,Number.parseInt(s[0].trim())+t)),n=Math.max(0,Math.min(255,Number.parseInt(s[1].trim())+t)),a=Math.max(0,Math.min(255,Number.parseInt(s[2].trim())+t));return"rgb("+o.toString()+","+n.toString()+","+a.toString()+")"},colorNameToHex:function(e){return{aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4","indianred ":"#cd5c5c","indigo ":"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",darkgrey:"#a9a9a9",darkslategrey:"#2f4f4f",dimgrey:"#696969",grey:"#808080",lightgray:"#d3d3d3",lightslategrey:"#778899",slategrey:"#708090"}[e]}};function fr(e){const t=Number.parseInt(e);return!Number.isNaN(t)&&t>=0&&t<=255}const pr="googleapis";class gr{constructor(){this.oauthTokens={}}setToken(e,t){t=t||pr,this.oauthTokens[t]=e}getToken(e){let t;e=e||pr;for(let i of Object.keys(this.oauthTokens)){if(mr(i).test(e)){t=this.oauthTokens[i];break}}return t}removeToken(e){e=e||pr;for(let t of Object.keys(this.oauthTokens)){mr(t).test(e)&&(this.oauthTokens[t]=void 0)}}}function mr(e){return new RegExp("^"+e.split(/\*+/).map(wr).join(".*")+"$")}function wr(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&")}function br(e){return e.includes("googleapis")&&!e.includes("urlshortener")||Fr(e)||vr(e)}function Fr(e){return e.startsWith("gs://")||e.startsWith("https://www.googleapis.com/storage")||e.startsWith("https://storage.cloud.google.com")||e.startsWith("https://storage.googleapis.com")}function vr(e){return e.indexOf("drive.google.com")>=0||e.indexOf("www.googleapis.com/drive")>0}function yr(e){let{bucket:t,object:i}=function(e){let t,i;if(e.startsWith("gs://")){const r=e.indexOf("/",5);if(r>=0){t=e.substring(5,r);const s=e.indexOf("?");i=s<0?e.substring(r+1):e.substring(r+1,s)}}else if(e.startsWith("https://storage.googleapis.com")||e.startsWith("https://storage.cloud.google.com")){const r=e.indexOf("/v1/b/",8);if(r>0){const s=e.indexOf("/o/",r);if(s>0){const o=e.indexOf("?",s);t=e.substring(r+6,s),i=o>0?e.substring(s+3,o):e.substring(s+3)}}else{const r=e.indexOf("/",8),s=e.indexOf("/",r+1),o=e.indexOf("?",s);s>0&&(t=e.substring(r+1,s),i=o<0?e.substring(s+1):e.substring(s+1,o))}}else if(e.startsWith("https://www.googleapis.com/storage/v1/b")){const r=e.indexOf("/v1/b/",8),s=e.indexOf("/o/",r);if(s>0){const o=e.indexOf("?",s);t=e.substring(r+6,s),i=o>0?e.substring(s+3,o):e.substring(s+3)}}if(t&&i)return{bucket:t,object:i};throw Error(`Unrecognized Google Storage URI: ${e}`)}(e);i=function(e){let t="";return e.split("").forEach((function(e){Ar.has(e)?t+=Ar.get(e):t+=e})),t}(i);const r=e.indexOf("?");return`https://storage.googleapis.com/storage/v1/b/${t}/o/${i}${r>0?e.substring(r)+"&alt=media":"?alt=media"}`}const Ar=new Map;function Cr(){return window.google&&window.google.igv}let _r;async function xr(e){if(!Cr())throw Error("Google oAuth has not been initialized");if(google.igv.tokenResponse&&Date.now(){try{t.callback=e=>{void 0!==e.error&&r(e),google.igv.tokenResponse=e,google.igv.tokenExpiresAt=Date.now()+1e3*e.expires_in,console.log("Access token expires at "+new Date(google.igv.tokenExpiresAt)),i(e.access_token)},console.log("Requesting access token"),t.requestAccessToken({scope:e})}catch(e){console.log(e)}}))),_r}}function kr(){return google.igv.apiKey}function Ir(e){var t=Sr(e);return t?"https://www.googleapis.com/drive/v3/files/"+t+"?alt=media&supportsTeamDrives=true":e}function Sr(e){if(e.includes("/open?id=")){const t=e.indexOf("/open?id=")+9,i=e.indexOf("&");if(t>0&&i>t)return e.substring(t,i);if(t>0)return e.substring(t)}else{if(e.includes("/file/d/")){const t=e.indexOf("/file/d/")+8,i=e.lastIndexOf("/");return e.substring(t,i)}if(e.startsWith("https://www.googleapis.com/drive")){let t=e.indexOf("/files/");const i=e.indexOf("?");if(t>0)return t+=7,i>0?e.substring(t,i):e.substring(t)}}throw Error("Unknown Google Drive url format: "+e)}Ar.set("!","%21"),Ar.set("#","%23"),Ar.set("$","%24"),Ar.set("%","%25"),Ar.set("&","%26"),Ar.set("'","%27"),Ar.set("(","%28"),Ar.set(")","%29"),Ar.set("*","%2A"),Ar.set("+","%2B"),Ar.set(",","%2C"),Ar.set("/","%2F"),Ar.set(":","%3A"),Ar.set(";","%3B"),Ar.set("=","%3D"),Ar.set("?","%3F"),Ar.set("@","%40"),Ar.set("[","%5B"),Ar.set("]","%5D"),Ar.set(" ","%20");class Er{constructor(e){this.requestsPerSecond=e.requestsPerSecond||10,this.lastStartTime=0,this.queued=[]}add(e,t){var i=this;return new Promise((function(t,r){i.queued.push({resolve:t,reject:r,asyncFunction:e}),i.dequeue()}))}addAll(e,t){var i=e.map(function(e){return this.add(e,t)}.bind(this));return Promise.all(i)}dequeue(){if(this.queued.length>0){var e=new Date,t=1e3/this.requestsPerSecond+1,i=e-this.lastStartTime;i>=t?this._execute():setTimeout(function(){this.dequeue()}.bind(this),t-i)}}async _execute(){this.lastStartTime=new Date;var e=this.queued.shift();const t=e.asyncFunction;try{const i=await t();e.resolve(i)}catch(t){e.reject(t)}}}function Nr(){if(Cr()){return Cr()&&google.igv.tokenResponse&&Date.now()0)for(var n=0;nthis._loadURL(e,t))):this._loadURL(e,t)}throw Error(`url must be either a 'File', 'string', 'function', or 'Promise'. Actual type: ${i}`)}async _loadURL(e,t){const i=this,r=e;e=function(e){return e.startsWith("https://www.dropbox.com")?e.replace("//www.dropbox.com","//dl.dropboxusercontent.com"):e.startsWith("https://drive.google.com")?Ir(e):e.includes("//www.broadinstitute.org/igvdata")?e.replace("//www.broadinstitute.org/igvdata","//data.broadinstitute.org/igvdata"):e.includes("//igvdata.broadinstitute.org")?e.replace("//igvdata.broadinstitute.org","//s3.amazonaws.com/igv.broadinstitute.org"):e.includes("//igv.genepattern.org")?e.replace("//igv.genepattern.org","//igv-genepattern-org.s3.amazonaws.com"):e.startsWith("ftp://ftp.ncbi.nlm.nih.gov/geo")?e.replace("ftp://","https://"):e}(e);let s=(t=t||{}).oauthToken||this.getOauthToken(e);return s&&(s=await("function"==typeof s?s():s)),new Promise((function(o,n){br(e)&&!function(e){return e.indexOf("X-Goog-Signature")>-1}(e)&&(Fr(e)&&(e=yr(e)),vr(e=function(e){let t=Rr.apiKey;t||"undefined"==typeof gapi||(t=gapi.apiKey);if(void 0!==t&&!e.includes("key=")){const i=e.includes("?")?"&":"?";e=e+i+"key="+t}return e}(e))&&function(e){if(e.includes("supportsTeamDrive"))return e;{const t=e.includes("?")?"&":"?";e=e+t+"supportsTeamDrive=true"}}(e),s||(s=Nr()));const a=t.headers||{};s&&function(e,t){t&&(e["Cache-Control"]="no-cache",e.Authorization="Bearer "+t)}(a,s);const c=t.range,l=new XMLHttpRequest,h=t.sendData||t.body,d=t.method||(h?"POST":"GET"),u=t.responseType,f=t.contentType,p=t.mimeType;if(l.open(d,e),t.timeout&&(l.timeout=t.timeout),c){let e="";c.size&&(e=c.start+c.size-1),l.setRequestHeader("Range","bytes="+c.start+"-"+e)}if(f&&l.setRequestHeader("Content-Type",f),p&&l.overrideMimeType(p),u&&(l.responseType=u),a)for(let e of Object.keys(a)){const t=a[e];l.setRequestHeader(e,t)}!0===t.withCredentials&&(l.withCredentials=!0),l.onload=async function(r){if(0===l.status||l.status>=200&&l.status<=300)if("HEAD"===t.method){const e=t.requestedHeaders||["content-length"],i={};for(let t of e)i[t]=l.getResponseHeader(t);o(i)}else c&&206!==l.status&&0!==c.start?(l.response.length>1e5&&!i.RANGE_WARNING_GIVEN&&alert(`Warning: Range header ignored for URL: ${e}. This can have severe performance impacts.`),o(l.response.slice(c.start,c.start+c.size))):o(l.response);else 416===l.status?g(Error("416 Unsatisfiable Range")):!Cr()||404!==l.status&&401!==l.status&&403!==l.status||!br(e)||t.retries?403===l.status?g("Access forbidden: "+e):g(l.status):m()},l.onerror=function(i){br(e)&&!t.retries?m():g("Error accessing resource: "+e+" Status: "+l.status)},l.ontimeout=function(e){g("Timed out")},l.onabort=function(e){console.log("Aborted"),n(e)};try{l.send(h)}catch(i){br(e)&&!t.retries?m():g(i)}function g(e){if(!n)throw e;n(e)}async function m(){try{const e=await async function(e){if(Cr()){const t=function(e){return vr(e)?"https://www.googleapis.com/auth/drive.file":Fr(e)?"https://www.googleapis.com/auth/devstorage.read_only":"https://www.googleapis.com/auth/userinfo.profile"}(e);return await xr(t)}throw Error("Authorization is required, but Google oAuth has not been initalized. Contact your site administrator for assistance.")}(r);t.retries=1,t.oauthToken=e;const s=await i.load(r,t);o(s)}catch(e){if(e.error){const t=e.error.startsWith("popup_blocked")?"Google login popup blocked by browser.":e.error;alert(t)}else g(e)}}}))}async _loadFileSlice(e,t){let i=t&&t.range?await e.slice(t.range.start,t.range.start+t.range.size):e;const r=await i.arrayBuffer();return"arraybuffer"===t.responseType?r:Mr(r)}async _loadStringFromFile(e,t){const i=t.range?e.slice(t.range.start,t.range.start+t.range.size):e;return Mr(await i.arrayBuffer())}async _loadStringFromUrl(e,t){(t=t||{}).responseType="arraybuffer";return Mr(await this.load(e,t))}setOauthToken(e,t){this.oauth.setToken(e,t)}getOauthToken(e){const t=br(e)?void 0:I(e).host;let i=this.oauth.getToken(t);if(i)return i;if(void 0===t){const e=Nr();if(e&&e.expires_at>Date.now())return e.access_token}}async getContentLength(e,t){(t=t||{}).method="HEAD",t.requestedHeaders=["content-length"];const i=(await this._loadURL(e,t))["content-length"];return i?Number.parseInt(i):0}};var Br={color:1};Br.parent=Br,Br.left=Br,Br.right=Br;class Dr{constructor(){this.root=Br}insert(e,t,i){var r=new Or(new Hr(e,t,i));for(this.treeInsert(r),r.color=2;r!==this.root&&2===r.parent.color;)if(r.parent===r.parent.parent.left){let e=r.parent.parent.right;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.right&&(r=r.parent,Tr.call(this,r)),r.parent.color=1,r.parent.parent.color=2,zr.call(this,r.parent.parent))}else{let e=r.parent.parent.left;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.left&&(r=r.parent,zr.call(this,r)),r.parent.color=1,r.parent.parent.color=2,Tr.call(this,r.parent.parent))}this.root.color=1}findOverlapping(e,t){var i=new Hr(e,t,0);if(this.root===Br)return[];var r=Lr.call(this,i,this.root,[]);return r.length>1&&r.sort((function(e,t){return e.low-t.low})),r}logIntervals(){!function e(t,i){for(var r="",s=0;s=e.low&&Lr.call(this,e,t.left,i),t.right!==Br&&t.right.min<=e.high&&Lr.call(this,e,t.right,i),i}function Tr(e){var t=e.right;e.right=t.left,t.left!==Br&&(t.left.parent=e),t.parent=e.parent,e.parent===Br?this.root=t:e.parent.left===e?e.parent.left=t:e.parent.right=t,t.left=e,e.parent=t,Pr.call(this,e)}function zr(e){var t=e.left;e.left=t.right,t.right!==Br&&(t.right.parent=e),t.parent=e.parent,e.parent===Br?this.root=t:e.parent.right===e?e.parent.right=t:e.parent.left=t,t.right=e,e.parent=t,Pr.call(this,e)}function Pr(e){for(;e!==Br;){var t=e.left.max>e.right.max?e.left.max:e.right.max,i=e.interval.high;e.max=t>i?t:i;var r=e.left.mine.low?1:this.highe.high?1:0}overlaps(e){return this.low<=e.high&&e.low<=this.high}}function Or(e){this.parent=Br,this.left=Br,this.right=Br,this.interval=e,this.color=2}const Vr=function(e,t,i){if(e&&0!==e.length){const r=function(e){const t=new Dr,i=e.length,r=Math.max(10,Math.round(i/100));e.sort((function(e,t){return e.start===t.start?0:e.start>t.start?1:-1}));for(let s=0;si)break;o.end>t&&e.push(o)}})),e.sort((function(e,t){return e.start-t.start})),e)}return[]};function qr(e){if(3===(e=e.replace(/^#/,"")).length&&(e=e.split("").map((e=>e+e)).join("")),6!==e.length)throw new Error("Invalid HEX color.");let t=parseInt(e,16);return`rgb(${t>>16&255}, ${t>>8&255}, ${255&t})`}const Ur={licorice:"#000000",steel:"#6e6e6e",magnesium:"#b8b8b8",mercury:"#e8e8e8",cayenne:"#891100",mocha:"#894800",aspargus:"#888501",fern:"#458401",teal:"#008688",salmon:"#ff726e",tangerine:"#ff8802",cantaloupe:"#ffce6e",lemon:"#fffa03",lime:"#83f902",honeydew:"#cefa6e",ice:"#68fdff",aqua:"#008cff",blueberry:"#002eff",midnight:"#001888",grape:"#8931ff",lavender:"#d278ff",orchid:"#6e76ff",strawberry:"#ff2987",magenta:"#ff39ff",carnation:"#ff7fd3"},Qr={cantaloupe:{r:255,g:206,b:110},honeydew:{r:206,g:250,b:110},spindrift:{r:104,g:251,b:208},sky:{r:106,g:207,b:255},lavender:{r:210,g:120,b:255},carnation:{r:255,g:127,b:211},licorice:{r:0,g:0,b:0},snow:{r:255,g:255,b:255},salmon:{r:255,g:114,b:110},banana:{r:255,g:251,b:109},flora:{r:104,g:249,b:110},ice:{r:104,g:253,b:255},orchid:{r:110,g:118,b:255},bubblegum:{r:255,g:122,b:255},lead:{r:30,g:30,b:30},mercury:{r:232,g:232,b:232},tangerine:{r:255,g:136,b:2},lime:{r:131,g:249,b:2},sea_foam:{r:3,g:249,b:135},aqua:{r:0,g:140,b:255},grape:{r:137,g:49,b:255},strawberry:{r:255,g:41,b:135},tungsten:{r:58,g:58,b:58},silver:{r:208,g:208,b:208},maraschino:{r:255,g:33,b:1},lemon:{r:255,g:250,b:3},spring:{r:5,g:248,b:2},turquoise:{r:0,g:253,b:255},blueberry:{r:0,g:46,b:255},magenta:{r:255,g:57,b:255},iron:{r:84,g:84,b:83},magnesium:{r:184,g:184,b:184},mocha:{r:137,g:72,b:0},fern:{r:69,g:132,b:1},moss:{r:1,g:132,b:72},ocean:{r:0,g:74,b:136},eggplant:{r:73,g:26,b:136},maroon:{r:137,g:22,b:72},steel:{r:110,g:110,b:110},aluminum:{r:160,g:159,b:160},cayenne:{r:137,g:17,b:0},aspargus:{r:136,g:133,b:1},clover:{r:2,g:132,b:1},teal:{r:0,g:134,b:136},midnight:{r:0,g:24,b:136},plum:{r:137,g:30,b:136},tin:{r:135,g:134,b:135},nickel:{r:136,g:135,b:135}};function Gr(e){const{r:t,g:i,b:r}=Qr[e];return`rgb(${t},${i},${r})`}const jr={Set1:["rgb(228,26,28)","rgb(55,126,184)","rgb(77,175,74)","rgb(166,86,40)","rgb(152,78,163)","rgb(255,127,0)","rgb(247,129,191)","rgb(153,153,153)","rgb(255,255,51)"],Dark2:["rgb(27,158,119)","rgb(217,95,2)","rgb(117,112,179)","rgb(231,41,138)","rgb(102,166,30)","rgb(230,171,2)","rgb(166,118,29)","rgb(102,102,102)"],Set2:["rgb(102, 194,165)","rgb(252,141,98)","rgb(141,160,203)","rgb(231,138,195)","rgb(166,216,84)","rgb(255,217,47)","rgb(229,196,148)","rgb(179,179,179)"],Set3:["rgb(141,211,199)","rgb(255,255,179)","rgb(190,186,218)","rgb(251,128,114)","rgb(128,177,211)","rgb(253,180,98)","rgb(179,222,105)","rgb(252,205,229)","rgb(217,217,217)","rgb(188,128,189)","rgb(204,235,197)","rgb(255,237,111)"],Pastel1:["rgb(251,180,174)","rgb(179,205,227)","rgb(204,235,197)","rgb(222,203,228)","rgb(254,217,166)","rgb(255,255,204)","rgb(229,216,189)","rgb(253,218,236)"],Pastel2:["rgb(173,226,207)","rgb(253,205,172)","rgb(203,213,232)","rgb(244,202,228)","rgb(230,245,201)","rgb(255,242,174)","rgb(243,225,206)"],Accent:["rgb(127,201,127)","rgb(190,174,212)","rgb(253,192,134)","rgb(255,255,153)","rgb(56,108,176)","rgb(240,2,127)","rgb(191,91,23)"]};class Wr{constructor(e){this.colors=jr[e],Array.isArray(this.colors)||(this.colors=[]),this.colorTable=new Map,this.nextIdx=0,this.colorGenerator=new Kr}getColor(e){return this.colorTable.has(e)||(this.nextIdxparseInt(e)))}}Kr.prototype.hsvToRgb=function(e,t,i){var r=Math.floor(6*e),s=6*e-r,o=i*(1-t),n=i*(1-s*t),a=i*(1-(1-s)*t),c=255,l=255,h=255;switch(r){case 0:c=i,l=a,h=o;break;case 1:c=n,l=i,h=o;break;case 2:c=o,l=i,h=a;break;case 3:c=o,l=n,h=i;break;case 4:c=a,l=o,h=i;break;case 5:c=i,l=o,h=n}return[Math.floor(256*c),Math.floor(256*l),Math.floor(256*h)]},Kr.prototype.padHex=function(e){return e.length>this.hexwidth?e:new Array(this.hexwidth-e.length+1).join("0")+e},Kr.prototype.get=function(e,t){this.hue+=this.goldenRatio,this.hue%=1,"number"!=typeof e&&(e=.5),"number"!=typeof t&&(t=.95);var i=this.hsvToRgb(this.hue,e,t);return"#"+this.padHex(i[0].toString(16))+this.padHex(i[1].toString(16))+this.padHex(i[2].toString(16))},new Kr;function Jr(e,t,i){if(i<.005)return e;if(i>.995)return t;{let r,s,o,n,a,c;i<.5?(i/=.5,[r,s,o]=Xr(e),[n,a,c]=Xr(Gr("snow"))):(i=(i-.5)/.5,[r,s,o]=Xr(Gr("snow")),[n,a,c]=Xr(t));const[l,h,d]=[Math.floor(ar(r,n,i)),Math.floor(ar(s,a,i)),Math.floor(ar(o,c,i))];return function(e,t,i){return`rgb(${e=cr(e,0,255)}, ${t=cr(t,0,255)}, ${i=cr(i,0,255)})`}(l,h,d)}}function es(e){const t=new Set(["boolean","number","string","symbol"]),i=typeof e;return void 0!==e&&(t.has(i)||e.substring||e.toFixed)}function ts(e,t){var i={oauthToken:e.oauthToken,headers:e.headers,withCredentials:e.withCredentials,filename:e.filename};return Object.assign(i,t)}const is=function(e){var t,i;if(e&&e.length>0){t=Number.MAX_VALUE,i=-Number.MAX_VALUE;for(let r of e)Number.isNaN(r.value)||(t=Math.min(t,r.value),i=Math.max(i,r.value));i>0&&(t=Math.min(0,t)),i<0&&(i=0)}else t=0,i=100;return{min:t,max:i}},rs=function(e,t,i){let r=t.start,s=t.end;if(void 0===s)r-=i/2,s=r+i,s>e?(s=e,r=s-i):r<0&&(r=0,s=i);else if(s-re?(s=e,r=s-i):(r=t-i/2,s=r+i)}t.start=Math.ceil(r),t.end=Math.floor(s)},ss=function(e){return"number"==typeof e?e-e===0:"string"==typeof e&&""!==e.trim()&&Number.isFinite(+e)};async function os(e){if(b(e)&&e.startsWith("https://drive.google.com")){if(void 0===kr())throw Error("Google drive is referenced, but API key is not defined. An API key is required for Google Drive access");const t=await async function(e){let t="https://www.googleapis.com/drive/v3/files/"+Sr(e)+"?supportsTeamDrives=true";const i=kr();i&&(t+="&key="+i);const r=await fetch(t);let s=await r.json();if(s.error&&404===s.error.code){let e="https://www.googleapis.com/auth/drive.readonly";const i=await xr(e);if(!i)throw Error(s.error);{const e=await fetch(t,{headers:{Authorization:`Bearer ${i}`}});if(s=await e.json(),s.error)throw Error(s.error)}}return s}(e);return t.originalFileName||t.name}return _(e)}function ns(e){var t,i;return e>1e7?(t=" mb",i=e/1e6,Math.floor(i).toString()+t):e>1e4?(t=" kb",i=e/1e3,F(Math.floor(i))+t):F(e)+" bp"}function as(e){return b(e)&&e.startsWith("data:")}function cs(e,i){const r=t({class:i});return e.appendChild(r),r}function ls(e,t){t.parentNode.insertBefore(e,t)}function hs(e,t){t.parentNode.insertBefore(e,t.nextSibling)}function ds(){return"https:"===window.location.protocol||"localhost"===window.location.hostname}class us{constructor(e,i,r,s){this.parent=e,this.popover=t({class:"igv-ui-popover"}),e.appendChild(this.popover),this.popoverHeader=t(),this.popover.appendChild(this.popoverHeader);const o=t();this.popoverHeader.appendChild(o),r&&(o.textContent=r);const n=t();this.popoverHeader.appendChild(n),n.appendChild(l("times")),n.addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault(),s?s():this.dismiss()})),!0===i&&p(this.popover,this.popoverHeader,{minX:0,minY:0}),this.popoverContent=t(),this.popover.appendChild(this.popoverContent),this.popover.style.display="none"}configure(e){if(0===e.length)return;const t=ps(e,this.popover);for(const{element:e}of t)this.popoverContent.appendChild(e)}present(e){this.popover.style.display="block";const t=this.popover.parentNode,{x:i,y:r,width:s}=a(e,t);this.popover.style.top=`${r}px`;const{width:o}=this.popover.getBoundingClientRect(),n=i+o,c=n-s;this.popover.style.left=`${n>s?i-c:i}px`,this.popoverContent.style.maxWidth=`${Math.min(o,s)}px`}presentContentWithEvent(e,t){this.popover.style.display="block",this.popoverContent.innerHTML=t,fs(e,this.popover,this.popoverContent)}presentMenu(e,t){if(0===t.length)return;this.popover.style.display="block";const i=ps(t,this.popover);for(let e of i)this.popoverContent.appendChild(e.element);fs(e,this.popover,this.popoverContent)}dismiss(){this.popover.style.display="none"}hide(){this.popover.style.display="none",this.dispose()}dispose(){this.popover&&this.popover.parentNode.removeChild(this.popover);const e=Object.keys(this);for(let t of e)this[t]=void 0}}function fs(e,t,i){const{x:r,y:s,width:o}=a(e,t.parentNode);t.style.top=`${s}px`;const{width:n}=t.getBoundingClientRect(),c=r+n,l=c-o;t.style.left=`${c>o?r-l:r}px`,i.style.maxWidth=`${Math.min(n,o)}px`}function ps(e,i){const s=e.map((function(e,s){let o;if("string"==typeof e)o=t(),o.innerHTML=e;else if("Node"==typeof e)o=e;else if("function"==typeof e.init&&e.init(),"checkbox"===e.type?o=function(e,i){const r=t({class:"igv-ui-trackgear-popover-check-container"}),s=h("check",!0===i?"#444":"transparent");s.style.borderColor="gray",s.style.borderWidth="1px",s.style.borderStyle="solid",r.appendChild(s);let o=t();return o.textContent=e,r.appendChild(o),r}("Show all bases",e.value):(o=t(),"string"==typeof e.label&&(o.innerHTML=e.label)),e.click&&"color"!==e.type){function n(t){e.click(),r(i),t.preventDefault(),t.stopPropagation()}o.addEventListener("click",n),o.addEventListener("touchend",n),o.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}return{element:o,init:e.init}}));return s} -/*! @license DOMPurify 3.2.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.5/LICENSE */const{entries:gs,setPrototypeOf:ms,isFrozen:ws,getPrototypeOf:bs,getOwnPropertyDescriptor:Fs}=Object;let{freeze:vs,seal:ys,create:As}=Object,{apply:Cs,construct:_s}="undefined"!=typeof Reflect&&Reflect;vs||(vs=function(e){return e}),ys||(ys=function(e){return e}),Cs||(Cs=function(e,t,i){return e.apply(t,i)}),_s||(_s=function(e,t){return new e(...t)});const xs=Os(Array.prototype.forEach),ks=Os(Array.prototype.lastIndexOf),Is=Os(Array.prototype.pop),Ss=Os(Array.prototype.push),Es=Os(Array.prototype.splice),Ns=Os(String.prototype.toLowerCase),Ms=Os(String.prototype.toString),Rs=Os(String.prototype.match),Bs=Os(String.prototype.replace),Ds=Os(String.prototype.indexOf),Ls=Os(String.prototype.trim),Ts=Os(Object.prototype.hasOwnProperty),zs=Os(RegExp.prototype.test),Ps=(Hs=TypeError,function(){for(var e=arguments.length,t=new Array(e),i=0;i1?i-1:0),s=1;s2&&void 0!==arguments[2]?arguments[2]:Ns;ms&&ms(e,null);let r=t.length;for(;r--;){let s=t[r];if("string"==typeof s){const e=i(s);e!==s&&(ws(t)||(t[r]=e),s=e)}e[s]=!0}return e}function qs(e){for(let t=0;t/gm),so=ys(/\$\{[\w\W]*/gm),oo=ys(/^data-[\-\w.\u00B7-\uFFFF]+$/),no=ys(/^aria-[\-\w]+$/),ao=ys(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),co=ys(/^(?:\w+script|data):/i),lo=ys(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ho=ys(/^html$/i),uo=ys(/^[a-z][.\w]*(-[.\w]+)+$/i);var fo=Object.freeze({__proto__:null,ARIA_ATTR:no,ATTR_WHITESPACE:lo,CUSTOM_ELEMENT:uo,DATA_ATTR:oo,DOCTYPE_NAME:ho,ERB_EXPR:ro,IS_ALLOWED_URI:ao,IS_SCRIPT_OR_DATA:co,MUSTACHE_EXPR:io,TMPLIT_EXPR:so});const po=1,go=3,mo=7,wo=8,bo=9,Fo=function(){return"undefined"==typeof window?null:window};var vo=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fo();const i=t=>e(t);if(i.version="3.2.5",i.removed=[],!t||!t.document||t.document.nodeType!==bo||!t.Element)return i.isSupported=!1,i;let{document:r}=t;const s=r,o=s.currentScript,{DocumentFragment:n,HTMLTemplateElement:a,Node:c,Element:l,NodeFilter:h,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:u,DOMParser:f,trustedTypes:p}=t,g=l.prototype,m=Qs(g,"cloneNode"),w=Qs(g,"remove"),b=Qs(g,"nextSibling"),F=Qs(g,"childNodes"),v=Qs(g,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let y,A="";const{implementation:C,createNodeIterator:_,createDocumentFragment:x,getElementsByTagName:k}=r,{importNode:I}=s;let S={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};i.isSupported="function"==typeof gs&&"function"==typeof v&&C&&void 0!==C.createHTMLDocument;const{MUSTACHE_EXPR:E,ERB_EXPR:N,TMPLIT_EXPR:M,DATA_ATTR:R,ARIA_ATTR:B,IS_SCRIPT_OR_DATA:D,ATTR_WHITESPACE:L,CUSTOM_ELEMENT:T}=fo;let{IS_ALLOWED_URI:z}=fo,P=null;const H=Vs({},[...Gs,...js,...Ws,...Ks,...Ys]);let O=null;const V=Vs({},[...Xs,...Js,...eo,...to]);let q=Object.seal(As(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),U=null,Q=null,G=!0,j=!0,W=!1,$=!0,K=!1,Z=!0,Y=!1,X=!1,J=!1,ee=!1,te=!1,ie=!1,re=!0,se=!1,oe=!0,ne=!1,ae={},ce=null;const le=Vs({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let he=null;const de=Vs({},["audio","video","img","source","image","track"]);let ue=null;const fe=Vs({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pe="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",me="http://www.w3.org/1999/xhtml";let we=me,be=!1,Fe=null;const ve=Vs({},[pe,ge,me],Ms);let ye=Vs({},["mi","mo","mn","ms","mtext"]),Ae=Vs({},["annotation-xml"]);const Ce=Vs({},["title","style","font","a","script"]);let _e=null;const xe=["application/xhtml+xml","text/html"];let ke=null,Ie=null;const Se=r.createElement("form"),Ee=function(e){return e instanceof RegExp||e instanceof Function},Ne=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Ie||Ie!==e){if(e&&"object"==typeof e||(e={}),e=Us(e),_e=-1===xe.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ke="application/xhtml+xml"===_e?Ms:Ns,P=Ts(e,"ALLOWED_TAGS")?Vs({},e.ALLOWED_TAGS,ke):H,O=Ts(e,"ALLOWED_ATTR")?Vs({},e.ALLOWED_ATTR,ke):V,Fe=Ts(e,"ALLOWED_NAMESPACES")?Vs({},e.ALLOWED_NAMESPACES,Ms):ve,ue=Ts(e,"ADD_URI_SAFE_ATTR")?Vs(Us(fe),e.ADD_URI_SAFE_ATTR,ke):fe,he=Ts(e,"ADD_DATA_URI_TAGS")?Vs(Us(de),e.ADD_DATA_URI_TAGS,ke):de,ce=Ts(e,"FORBID_CONTENTS")?Vs({},e.FORBID_CONTENTS,ke):le,U=Ts(e,"FORBID_TAGS")?Vs({},e.FORBID_TAGS,ke):{},Q=Ts(e,"FORBID_ATTR")?Vs({},e.FORBID_ATTR,ke):{},ae=!!Ts(e,"USE_PROFILES")&&e.USE_PROFILES,G=!1!==e.ALLOW_ARIA_ATTR,j=!1!==e.ALLOW_DATA_ATTR,W=e.ALLOW_UNKNOWN_PROTOCOLS||!1,$=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,K=e.SAFE_FOR_TEMPLATES||!1,Z=!1!==e.SAFE_FOR_XML,Y=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,ie=e.RETURN_TRUSTED_TYPE||!1,J=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,se=e.SANITIZE_NAMED_PROPS||!1,oe=!1!==e.KEEP_CONTENT,ne=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||ao,we=e.NAMESPACE||me,ye=e.MATHML_TEXT_INTEGRATION_POINTS||ye,Ae=e.HTML_INTEGRATION_POINTS||Ae,q=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Ee(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Ee(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(q.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),K&&(j=!1),te&&(ee=!0),ae&&(P=Vs({},Ys),O=[],!0===ae.html&&(Vs(P,Gs),Vs(O,Xs)),!0===ae.svg&&(Vs(P,js),Vs(O,Js),Vs(O,to)),!0===ae.svgFilters&&(Vs(P,Ws),Vs(O,Js),Vs(O,to)),!0===ae.mathMl&&(Vs(P,Ks),Vs(O,eo),Vs(O,to))),e.ADD_TAGS&&(P===H&&(P=Us(P)),Vs(P,e.ADD_TAGS,ke)),e.ADD_ATTR&&(O===V&&(O=Us(O)),Vs(O,e.ADD_ATTR,ke)),e.ADD_URI_SAFE_ATTR&&Vs(ue,e.ADD_URI_SAFE_ATTR,ke),e.FORBID_CONTENTS&&(ce===le&&(ce=Us(ce)),Vs(ce,e.FORBID_CONTENTS,ke)),oe&&(P["#text"]=!0),Y&&Vs(P,["html","head","body"]),P.table&&(Vs(P,["tbody"]),delete U.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Ps('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Ps('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');y=e.TRUSTED_TYPES_POLICY,A=y.createHTML("")}else void 0===y&&(y=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let i=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(i=t.getAttribute(r));const s="dompurify"+(i?"#"+i:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(p,o)),null!==y&&"string"==typeof A&&(A=y.createHTML(""));vs&&vs(e),Ie=e}},Me=Vs({},[...js,...Ws,...$s]),Re=Vs({},[...Ks,...Zs]),Be=function(e){Ss(i.removed,{element:e});try{v(e).removeChild(e)}catch(t){w(e)}},De=function(e,t){try{Ss(i.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Ss(i.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Be(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Le=function(e){let t=null,i=null;if(J)e=""+e;else{const t=Rs(e,/^[\r\n\t ]+/);i=t&&t[0]}"application/xhtml+xml"===_e&&we===me&&(e=''+e+"");const s=y?y.createHTML(e):e;if(we===me)try{t=(new f).parseFromString(s,_e)}catch(e){}if(!t||!t.documentElement){t=C.createDocument(we,"template",null);try{t.documentElement.innerHTML=be?A:s}catch(e){}}const o=t.body||t.documentElement;return e&&i&&o.insertBefore(r.createTextNode(i),o.childNodes[0]||null),we===me?k.call(t,Y?"html":"body")[0]:Y?t.documentElement:o},Te=function(e){return _.call(e.ownerDocument||e,e,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},ze=function(e){return e instanceof u&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Pe=function(e){return"function"==typeof c&&e instanceof c};function He(e,t,r){xs(e,(e=>{e.call(i,t,r,Ie)}))}const Oe=function(e){let t=null;if(He(S.beforeSanitizeElements,e,null),ze(e))return Be(e),!0;const r=ke(e.nodeName);if(He(S.uponSanitizeElement,e,{tagName:r,allowedTags:P}),e.hasChildNodes()&&!Pe(e.firstElementChild)&&zs(/<[/\w!]/g,e.innerHTML)&&zs(/<[/\w!]/g,e.textContent))return Be(e),!0;if(e.nodeType===mo)return Be(e),!0;if(Z&&e.nodeType===wo&&zs(/<[/\w]/g,e.data))return Be(e),!0;if(!P[r]||U[r]){if(!U[r]&&qe(r)){if(q.tagNameCheck instanceof RegExp&&zs(q.tagNameCheck,r))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(r))return!1}if(oe&&!ce[r]){const t=v(e)||e.parentNode,i=F(e)||e.childNodes;if(i&&t){for(let r=i.length-1;r>=0;--r){const s=m(i[r],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,b(e))}}}return Be(e),!0}return e instanceof l&&!function(e){let t=v(e);t&&t.tagName||(t={namespaceURI:we,tagName:"template"});const i=Ns(e.tagName),r=Ns(t.tagName);return!!Fe[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===me?"svg"===i:t.namespaceURI===pe?"svg"===i&&("annotation-xml"===r||ye[r]):Boolean(Me[i]):e.namespaceURI===pe?t.namespaceURI===me?"math"===i:t.namespaceURI===ge?"math"===i&&Ae[r]:Boolean(Re[i]):e.namespaceURI===me?!(t.namespaceURI===ge&&!Ae[r])&&!(t.namespaceURI===pe&&!ye[r])&&!Re[i]&&(Ce[i]||!Me[i]):!("application/xhtml+xml"!==_e||!Fe[e.namespaceURI]))}(e)?(Be(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!zs(/<\/no(script|embed|frames)/i,e.innerHTML)?(K&&e.nodeType===go&&(t=e.textContent,xs([E,N,M],(e=>{t=Bs(t,e," ")})),e.textContent!==t&&(Ss(i.removed,{element:e.cloneNode()}),e.textContent=t)),He(S.afterSanitizeElements,e,null),!1):(Be(e),!0)},Ve=function(e,t,i){if(re&&("id"===t||"name"===t)&&(i in r||i in Se))return!1;if(j&&!Q[t]&&zs(R,t));else if(G&&zs(B,t));else if(!O[t]||Q[t]){if(!(qe(e)&&(q.tagNameCheck instanceof RegExp&&zs(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&zs(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&zs(q.tagNameCheck,i)||q.tagNameCheck instanceof Function&&q.tagNameCheck(i))))return!1}else if(ue[t]);else if(zs(z,Bs(i,L,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Ds(i,"data:")||!he[e]){if(W&&!zs(D,Bs(i,L,"")));else if(i)return!1}else;return!0},qe=function(e){return"annotation-xml"!==e&&Rs(e,T)},Ue=function(e){He(S.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||ze(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:O,forceKeepAttr:void 0};let s=t.length;for(;s--;){const o=t[s],{name:n,namespaceURI:a,value:c}=o,l=ke(n);let h="value"===n?c:Ls(c);if(r.attrName=l,r.attrValue=h,r.keepAttr=!0,r.forceKeepAttr=void 0,He(S.uponSanitizeAttribute,e,r),h=r.attrValue,!se||"id"!==l&&"name"!==l||(De(n,e),h="user-content-"+h),Z&&zs(/((--!?|])>)|<\/(style|title)/i,h)){De(n,e);continue}if(r.forceKeepAttr)continue;if(De(n,e),!r.keepAttr)continue;if(!$&&zs(/\/>/i,h)){De(n,e);continue}K&&xs([E,N,M],(e=>{h=Bs(h,e," ")}));const d=ke(e.nodeName);if(Ve(d,l,h)){if(y&&"object"==typeof p&&"function"==typeof p.getAttributeType)if(a);else switch(p.getAttributeType(d,l)){case"TrustedHTML":h=y.createHTML(h);break;case"TrustedScriptURL":h=y.createScriptURL(h)}try{a?e.setAttributeNS(a,n,h):e.setAttribute(n,h),ze(e)?Be(e):Is(i.removed)}catch(e){}}}He(S.afterSanitizeAttributes,e,null)},Qe=function e(t){let i=null;const r=Te(t);for(He(S.beforeSanitizeShadowDOM,t,null);i=r.nextNode();)He(S.uponSanitizeShadowNode,i,null),Oe(i),Ue(i),i.content instanceof n&&e(i.content);He(S.afterSanitizeShadowDOM,t,null)};return i.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,l=null;if(be=!e,be&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Pe(e)){if("function"!=typeof e.toString)throw Ps("toString is not a function");if("string"!=typeof(e=e.toString()))throw Ps("dirty is not a string, aborting")}if(!i.isSupported)return e;if(X||Ne(t),i.removed=[],"string"==typeof e&&(ne=!1),ne){if(e.nodeName){const t=ke(e.nodeName);if(!P[t]||U[t])throw Ps("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)r=Le("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),o.nodeType===po&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o);else{if(!ee&&!K&&!Y&&-1===e.indexOf("<"))return y&&ie?y.createHTML(e):e;if(r=Le(e),!r)return ee?null:ie?A:""}r&&J&&Be(r.firstChild);const h=Te(ne?e:r);for(;a=h.nextNode();)Oe(a),Ue(a),a.content instanceof n&&Qe(a.content);if(ne)return e;if(ee){if(te)for(l=x.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(O.shadowroot||O.shadowrootmode)&&(l=I.call(s,l,!0)),l}let d=Y?r.outerHTML:r.innerHTML;return Y&&P["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&zs(ho,r.ownerDocument.doctype.name)&&(d="\n"+d),K&&xs([E,N,M],(e=>{d=Bs(d,e," ")})),y&&ie?y.createHTML(d):d},i.setConfig=function(){Ne(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},i.clearConfig=function(){Ie=null,X=!1},i.isValidAttribute=function(e,t,i){Ie||Ne({});const r=ke(e),s=ke(t);return Ve(r,s,i)},i.addHook=function(e,t){"function"==typeof t&&Ss(S[e],t)},i.removeHook=function(e,t){if(void 0!==t){const i=ks(S[e],t);return-1===i?void 0:Es(S[e],i,1)[0]}return Is(S[e])},i.removeHooks=function(e){S[e]=[]},i.removeAllHooks=function(){S={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},i}();const yo={401:"Access unauthorized",403:"Access forbidden",404:"Not found"};class Ao{constructor(e,t){this.alertProps=Object.assign({shouldFocus:!0,preventScroll:!1},t),this.container=document.createElement("div"),this.container.className="igv-ui-alert-dialog-container",e.appendChild(this.container),this.container.setAttribute("tabIndex","-1");const i=document.createElement("div");this.container.appendChild(i),this.errorHeadline=document.createElement("div"),i.appendChild(this.errorHeadline),this.errorHeadline.textContent="";let r=document.createElement("div");r.className="igv-ui-alert-dialog-body",this.container.appendChild(r),this.body=document.createElement("div"),this.body.className="igv-ui-alert-dialog-body-copy",r.appendChild(this.body);let s=document.createElement("div");this.container.appendChild(s),this.ok=document.createElement("div"),s.appendChild(this.ok),this.ok.textContent="OK";const o=()=>{"function"==typeof this.callback&&(this.callback("OK"),this.callback=void 0),this.body.innerHTML="",this.container.style.display="none"};this.ok.addEventListener("click",(e=>{e.stopPropagation(),o()})),this.container.addEventListener("keypress",(e=>{e.stopPropagation(),"Enter"===e.key&&o()})),p(this.container,i),this.container.style.display="none"}present(e,t){this.errorHeadline.textContent=e.message?"ERROR":"";let i=e.message||e;yo.hasOwnProperty(i)&&(i=yo[i]),this.body.innerHTML=vo.sanitize(i),this.callback=t,this.container.style.display="flex",this.alertProps.shouldFocus&&this.container.focus({preventScroll:this.alertProps.preventScroll})}}const Co={configureHighDPICanvas:function(e,t,i){const r=window.devicePixelRatio;e.canvas.style.width=`${t}px`,e.canvas.width=Math.floor(r*t),e.canvas.style.height=`${i}px`,e.canvas.height=Math.floor(r*i),e.scale(r,r)},setProperties:function(e,t){for(var i in t)if(t.hasOwnProperty(i)){var r=t[i];e[i]=r}},strokeLine:function(e,t,i,r,s,o){t=Math.floor(t)+.5,i=Math.floor(i)+.5,r=Math.floor(r)+.5,s=Math.floor(s)+.5,o&&(e.save(),Co.setProperties(e,o)),e.beginPath(),e.moveTo(t,i),e.lineTo(r,s),e.stroke(),o&&e.restore()},fillRect:function(e,t,i,r,s,o){o&&(e.save(),Co.setProperties(e,o)),e.fillRect(t,i,r,s),o&&e.restore()},fillPolygon:function(e,t,i,r){r&&(e.save(),Co.setProperties(e,r)),_o(e,t,i),e.fill(),r&&e.restore()},strokePolygon:function(e,t,i,r){r&&(e.save(),Co.setProperties(e,r)),_o(e,t,i),e.stroke(),r&&e.restore()},fillText:function(e,t,i,r,s,o){if((s||o)&&e.save(),s&&Co.setProperties(e,s),o){for(var n in e.translate(i,r),o){var a=o[n];"translate"===n&&e.translate(a.x,a.y),"rotate"===n&&e.rotate(a.angle*Math.PI/180)}e.fillText(t,0,0)}else e.fillText(t,i,r);(s||o)&&e.restore()},strokeText:function(e,t,i,r,s,o){if((s||o)&&e.save(),s&&Co.setProperties(e,s),o){for(var n in e.translate(i,r),o){var a=o[n];"translate"===n&&e.translate(a.x,a.y),"rotate"===n&&e.rotate(a.angle*Math.PI/180)}e.strokeText(t,0,0)}else e.strokeText(t,i,r);(s||o)&&e.restore()},strokeCircle:function(e,t,i,r,s){s&&(e.save(),Co.setProperties(e,s)),e.beginPath(),e.arc(t,i,r,0,2*Math.PI),e.stroke(),s&&e.restore()},fillCircle:function(e,t,i,r,s){s&&(e.save(),Co.setProperties(e,s)),e.beginPath(),e.arc(t,i,r,0,2*Math.PI),e.fill(),s&&e.restore()},drawArrowhead:function(e,t,i,r,s){e.save(),r||(r=5),s&&(e.lineWidth=s),e.beginPath(),e.moveTo(t,i-r/2),e.lineTo(t,i+r/2),e.lineTo(t+r,i),e.lineTo(t,i-r/2),e.closePath(),e.fill(),e.restore()},dashedLine:function(e,t,i,r,s,o,n={}){void 0===o&&(o=2),e.setLineDash([o,o]),Co.strokeLine(e,t,i,r,s,n),e.setLineDash([])},roundRect:function(e,t,i,r,s,o,n,a){void 0===a&&(a=!0),void 0===o&&(o=5),e.beginPath(),e.moveTo(t+o,i),e.lineTo(t+r-o,i),e.quadraticCurveTo(t+r,i,t+r,i+o),e.lineTo(t+r,i+s-o),e.quadraticCurveTo(t+r,i+s,t+r-o,i+s),e.lineTo(t+o,i+s),e.quadraticCurveTo(t,i+s,t,i+s-o),e.lineTo(t,i+o),e.quadraticCurveTo(t,i,t+o,i),e.closePath(),a&&e.stroke(),n&&e.fill()},polygon:function(e,t,i,r,s){void 0===s&&(s=!0),e.beginPath();var o=t.length;e.moveTo(t[0],i[0]);for(var n=1;n{for(let t=0;t{e.translate(t,0),e.scale(-1,1),e.translate(-t,0)}};function _o(e,t,i){var r,s=t.length;for(e.beginPath(),e.moveTo(t[0],i[0]),r=1;r0;){const r=e[i];t+=ko.has(r)?ko.get(r):r}return t}class No{constructor(e,t,i,r){this.name=e,this.order=t,this.bpLength=i,this.altNames=r}getAltName(e){return this.altNames&&this.altNames.has(e)?this.altNames.get(e):this.name}}class Mo{constructor(e,t,i,r){this.chr=e,this.start=t,this.end=i,this.features=r}contains(e,t,i){return this.chr===e&&this.start<=t&&this.end>=i}containsRange(e){return this.chr===e.chr&&this.start<=e.start&&this.end>=e.end}get locusString(){return`${this.chr}:${this.start+1}-${this.end}`}}class Ro extends Mo{constructor(e,t,i,r){super(e,t,i,r)}getSequence(e,t){if(ethis.end)return null;const i=e-this.start,r=t-e;return this.features?this.features.substring(i,i+r):null}hasSequence(e,t){return e>=this.start&&t<=this.end}}const Bo=v,Do=new Set(["fastaURL","indexURL","cytobandURL","indexed"]);class Lo{#e;chromosomes=new Map;sequences=new Map;constructor(e){this.fastaURL=e.fastaURL,this.withCredentials=e.withCredentials;const t={};for(let i in e)e.hasOwnProperty(i)&&!Do.has(i)&&(t[i]=e[i]);this.config=t}async init(){return this.loadAll()}getSequenceRecord(e){return this.chromosomes.get(e)}get chromosomeNames(){return this.#e||(this.#e=Array.from(this.chromosomes.keys())),this.#e}getFirstChromosomeName(){return this.chromosomeNames[0]}async getSequence(e,t,i){if(0===this.sequences.size&&await this.loadAll(),!this.sequences.has(e))return;let r=this.sequences.get(e).find((e=>e.contains(t,i)));if(!r&&(r=this.sequences.get(e).find((e=>e.overlaps(t,i))),!r))return;t-=r.offset,i-=r.offset;let s="";if(t<0)for(let e=t;e{const r=e.length||e.offset+e.seq.length;if(i.has(e.chr)){const t=this.chromosomes.get(e.chr);t.bpLength=Math.max(t.bpLength,r)}else this.sequences.set(e.chr,[]),this.chromosomes.set(e.chr,new No(e.chr,t,r)),i.add(e.chr);this.sequences.get(e.chr).push(new To(e.offset,e.seq))};let t;if(as(this.fastaURL)){let e=nr(this.fastaURL);t="";for(let i of e)t+=String.fromCharCode(i)}else t=await Rr.load(this.fastaURL,ts(this.config));const i=new Set,r=Bo(t);let s=0,o={};for(let t of r)if(t.startsWith("#")||0===t.length);else if(t.startsWith(">")){o.seq&&o.seq.length>0&&e(o,s++),o.seq="";const i=t.substr(1).split(/\s+/);if(t.includes("@len=")){const e=i[0].split(":");if(o.chr=e[0],e.length>1&&e[1].indexOf("-")>0){const r=e[1].split("-");2===r.length&&/^[0-9]+$/.test(r[0])&&/^[0-9]+$/.test(r[1]);const s=Number.parseInt(r[0]);if(Number.parseInt(r[1]),o.offset=s-1,i.length>1&&i[1].startsWith("@len="))try{o.length=parseInt(i[1].trim().substring(5))}catch(e){o.length=void 0,console.error(`Error parsing sequence length for ${t}`)}else o.length=void 0}}else o.chr=i[0],o.offset=0}else o.seq+=t;o.seq&&o.seq.length>0&&e(o,s)}getSequenceInterval(e,t,i){const r=this.sequences.get(e);if(r)for(let s of r){const r=s.sequence,o=s.offset,n=o+r.length;if(o<=t&&n>=i)return new Ro(e,o,n,r)}}}class To{constructor(e,t){this.offset=e,this.sequence=t}contains(e,t){return this.offset<=e&&this.end>=t}overlaps(e,t){return this.offsete}get end(){return this.offset+this.sequence.length}}const zo=v,Po=new Set(["fastaURL","indexURL","compressedIndexURL","cytobandURL","indexed"]);class Ho{#e;chromosomes=new Map;constructor(e){this.file=e.fastaURL,this.indexFile=e.indexURL,this.compressedIndexFile=e.compressedIndexURL,this.withCredentials=e.withCredentials;const t={};for(let i in e)e.hasOwnProperty(i)&&!Po.has(i)&&(t[i]=e[i]);this.config=t}getSequenceRecord(e){return this.chromosomes.get(e)}async init(){return this.getIndex()}get chromosomeNames(){return this.#e||(this.#e=Array.from(this.chromosomes.keys())),this.#e}getFirstChromosomeName(){return this.chromosomeNames[0]}async getIndex(){if(this.index)return this.index;{const e=await Rr.load(this.indexFile,ts(this.config)),t=zo(e),i=t.length;let r=0,s=0;for(this.index={};rthis.compressedIndex[r][1])return[r];let s=0,o=r,n=Math.floor(this.compressedIndex.length/2),a=this.compressedIndex.length+1,c=!1;for(let t=0;te){c=!0;break}t=t)break}const l=i[i.length-1];return l===this.compressedIndex.length-1&&this.compressedIndex[l][1]0&&(w=Math.min(o-s,a-u),b+=m.substr(F,w),F+=w+l);F1){const e=Number.parseInt(t[1]),r=new No(t[0],i++,e);this.chromosomes.set(t[0],r)}}}}class qo{constructor(e,t=!0){this.littleEndian=t,this.position=0,this.view=e,this.length=e.byteLength}dumpBytes(e=100){const t=this.position,i=[];for(let t=0;t<=e;t++)i.push(this.getByte());console.log(i.join(" ")),this.setPosition(t)}setPosition(e){this.position=e}available(){return this.length-this.position}remLength(){return this.length-this.position}hasNext(){return this.position=0;i--)t=256*t+e[i];else for(let i=0;i0&&(t+=String.fromCharCode(e))}return t}getFloat(){var e=this.view.getFloat32(this.position,this.littleEndian);return this.position+=4,e}getDouble(){var e=this.view.getFloat64(this.position,this.littleEndian);return this.position+=8,e}skip(e){return this.position+=e,this.position}getVPointer(){var e=this.position,t=this.view.getUint8(e+1)<<8|this.view.getUint8(e),i=4294967296*(255&this.view.getUint8(e+6))+16777216*(255&this.view.getUint8(e+5))+65536*(255&this.view.getUint8(e+4))+256*(255&this.view.getUint8(e+3))+(255&this.view.getUint8(e+2));return this.position+=8,new Uo(i,t)}}class Uo{constructor(e,t){this.block=e,this.offset=t}isLessThan(e){return this.blocke.block||this.block===e.block&&this.offset>e.offset}isEqualTo(e){return this.block===e.block&&this.offset===e.offset}print(){return this.block+":"+this.offset}}class Qo{static magic=2026540177;littleEndian=!0;type="BPTree";nodeCache=new Map;static async loadBpTree(e,t,i,r,s){return new Qo(e,t,i,r,s).init()}constructor(e,t,i,r,s){this.path=e,this.config=t,this.startOffset=i,r&&(this.type=r),this.loader=s||Rr}async init(){const e=await this.#t(this.startOffset,32);let t=e.getInt();if(t!==Qo.magic&&(e.setPosition(0),this.littleEndian=!this.littleEndian,e.littleEndian=this.littleEndian,t=e.getInt(),t!==Qo.magic))throw Error(`Bad magic number ${t}`);const i=e.getInt(),r=e.getInt(),s=e.getInt(),o=e.getLong(),n=e.getLong(),a=this.startOffset+32;return this.header={magic:t,blockSize:i,keySize:r,valSize:s,itemCount:o,reserved:n,nodeOffset:a},this}getItemCount(){if(!this.header)throw Error("Header not initialized");return this.header.itemCount}async search(e){this.header||await this.init();const t=async i=>{const r=await this.readTreeNode(i);if(1!==r.type){let i=r.items[0].offset;for(let t=1;t{const{left:r,top:s,width:o,height:n}=e.getBoundingClientRect(),a=t-r,c=i-s;return{x:a,y:c,xNormalized:a/o,yNormalized:c/n,width:o,height:n}})(t,{clientX:i,clientY:r})}class c{constructor(){this.elem=i("div",{class:"igv-ui-panel-column"})}add(e){if(e instanceof Node)this.elem.appendChild(e);else if("object"==typeof e)this.elem.appendChild(e.elem);else{const i=t();i.innerHTML=e,this.elem.appendChild(i),this.html=i}}}function l(e,t){return h(e,t)}function h(e,t){t=t||"currentColor";let i=d[e];i||(console.error(`No icon named: ${e}`),i=d.question);const r=document.createElementNS("http://www.w3.org/2000/svg","svg");r.setAttributeNS(null,"viewBox","0 0 "+i[0]+" "+i[1]);const s=document.createElementNS("http://www.w3.org/2000/svg","path");return s.setAttributeNS(null,"fill",t),s.setAttributeNS(null,"d",i[4]),r.appendChild(s),r}const d={check:[512,512,[],"f00c","M173.898 439.404l-166.4-166.4c-9.997-9.997-9.997-26.206 0-36.204l36.203-36.204c9.997-9.998 26.207-9.998 36.204 0L192 312.69 432.095 72.596c9.997-9.997 26.207-9.997 36.204 0l36.203 36.204c9.997 9.997 9.997 26.206 0 36.204l-294.4 294.401c-9.998 9.997-26.207 9.997-36.204-.001z"],cog:[512,512,[],"f013","M444.788 291.1l42.616 24.599c4.867 2.809 7.126 8.618 5.459 13.985-11.07 35.642-29.97 67.842-54.689 94.586a12.016 12.016 0 0 1-14.832 2.254l-42.584-24.595a191.577 191.577 0 0 1-60.759 35.13v49.182a12.01 12.01 0 0 1-9.377 11.718c-34.956 7.85-72.499 8.256-109.219.007-5.49-1.233-9.403-6.096-9.403-11.723v-49.184a191.555 191.555 0 0 1-60.759-35.13l-42.584 24.595a12.016 12.016 0 0 1-14.832-2.254c-24.718-26.744-43.619-58.944-54.689-94.586-1.667-5.366.592-11.175 5.459-13.985L67.212 291.1a193.48 193.48 0 0 1 0-70.199l-42.616-24.599c-4.867-2.809-7.126-8.618-5.459-13.985 11.07-35.642 29.97-67.842 54.689-94.586a12.016 12.016 0 0 1 14.832-2.254l42.584 24.595a191.577 191.577 0 0 1 60.759-35.13V25.759a12.01 12.01 0 0 1 9.377-11.718c34.956-7.85 72.499-8.256 109.219-.007 5.49 1.233 9.403 6.096 9.403 11.723v49.184a191.555 191.555 0 0 1 60.759 35.13l42.584-24.595a12.016 12.016 0 0 1 14.832 2.254c24.718 26.744 43.619 58.944 54.689 94.586 1.667 5.366-.592 11.175-5.459 13.985L444.788 220.9a193.485 193.485 0 0 1 0 70.2zM336 256c0-44.112-35.888-80-80-80s-80 35.888-80 80 35.888 80 80 80 80-35.888 80-80z"],exclamation:[192,512,[],"f12a","M176 432c0 44.112-35.888 80-80 80s-80-35.888-80-80 35.888-80 80-80 80 35.888 80 80zM25.26 25.199l13.6 272C39.499 309.972 50.041 320 62.83 320h66.34c12.789 0 23.331-10.028 23.97-22.801l13.6-272C167.425 11.49 156.496 0 142.77 0H49.23C35.504 0 24.575 11.49 25.26 25.199z"],"exclamation-circle":[512,512,[],"f06a","M504 256c0 136.997-111.043 248-248 248S8 392.997 8 256C8 119.083 119.043 8 256 8s248 111.083 248 248zm-248 50c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"],"exclamation-triangle":[576,512,[],"f071","M569.517 440.013C587.975 472.007 564.806 512 527.94 512H48.054c-36.937 0-59.999-40.055-41.577-71.987L246.423 23.985c18.467-32.009 64.72-31.951 83.154 0l239.94 416.028zM288 354c-25.405 0-46 20.595-46 46s20.595 46 46 46 46-20.595 46-46-20.595-46-46-46zm-43.673-165.346l7.418 136c.347 6.364 5.609 11.346 11.982 11.346h48.546c6.373 0 11.635-4.982 11.982-11.346l7.418-136c.375-6.874-5.098-12.654-11.982-12.654h-63.383c-6.884 0-12.356 5.78-11.981 12.654z"],minus:[448,512,[],"f068","M424 318.2c13.3 0 24-10.7 24-24v-76.4c0-13.3-10.7-24-24-24H24c-13.3 0-24 10.7-24 24v76.4c0 13.3 10.7 24 24 24h400z"],"minus-circle":[512,512,[],"f056","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zM124 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H124z"],"minus-square":[448,512,[],"f146","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zM92 296c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h264c6.6 0 12 5.4 12 12v56c0 6.6-5.4 12-12 12H92z"],plus:[448,512,[],"f067","M448 294.2v-76.4c0-13.3-10.7-24-24-24H286.2V56c0-13.3-10.7-24-24-24h-76.4c-13.3 0-24 10.7-24 24v137.8H24c-13.3 0-24 10.7-24 24v76.4c0 13.3 10.7 24 24 24h137.8V456c0 13.3 10.7 24 24 24h76.4c13.3 0 24-10.7 24-24V318.2H424c13.3 0 24-10.7 24-24z"],"plus-circle":[512,512,[],"f055","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm144 276c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92h-92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"],"plus-square":[448,512,[],"f0fe","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48zm-32 252c0 6.6-5.4 12-12 12h-92v92c0 6.6-5.4 12-12 12h-56c-6.6 0-12-5.4-12-12v-92H92c-6.6 0-12-5.4-12-12v-56c0-6.6 5.4-12 12-12h92v-92c0-6.6 5.4-12 12-12h56c6.6 0 12 5.4 12 12v92h92c6.6 0 12 5.4 12 12v56z"],question:[384,512,[],"f128","M202.021 0C122.202 0 70.503 32.703 29.914 91.026c-7.363 10.58-5.093 25.086 5.178 32.874l43.138 32.709c10.373 7.865 25.132 6.026 33.253-4.148 25.049-31.381 43.63-49.449 82.757-49.449 30.764 0 68.816 19.799 68.816 49.631 0 22.552-18.617 34.134-48.993 51.164-35.423 19.86-82.299 44.576-82.299 106.405V320c0 13.255 10.745 24 24 24h72.471c13.255 0 24-10.745 24-24v-5.773c0-42.86 125.268-44.645 125.268-160.627C377.504 66.256 286.902 0 202.021 0zM192 373.459c-38.196 0-69.271 31.075-69.271 69.271 0 38.195 31.075 69.27 69.271 69.27s69.271-31.075 69.271-69.271-31.075-69.27-69.271-69.27z"],save:[448,512,[],"f0c7","M433.941 129.941l-83.882-83.882A48 48 0 0 0 316.118 32H48C21.49 32 0 53.49 0 80v352c0 26.51 21.49 48 48 48h352c26.51 0 48-21.49 48-48V163.882a48 48 0 0 0-14.059-33.941zM224 416c-35.346 0-64-28.654-64-64 0-35.346 28.654-64 64-64s64 28.654 64 64c0 35.346-28.654 64-64 64zm96-304.52V212c0 6.627-5.373 12-12 12H76c-6.627 0-12-5.373-12-12V108c0-6.627 5.373-12 12-12h228.52c3.183 0 6.235 1.264 8.485 3.515l3.48 3.48A11.996 11.996 0 0 1 320 111.48z"],search:[512,512,[],"f002","M505 442.7L405.3 343c-4.5-4.5-10.6-7-17-7H372c27.6-35.3 44-79.7 44-128C416 93.1 322.9 0 208 0S0 93.1 0 208s93.1 208 208 208c48.3 0 92.7-16.4 128-44v16.3c0 6.4 2.5 12.5 7 17l99.7 99.7c9.4 9.4 24.6 9.4 33.9 0l28.3-28.3c9.4-9.4 9.4-24.6.1-34zM208 336c-70.7 0-128-57.2-128-128 0-70.7 57.2-128 128-128 70.7 0 128 57.2 128 128 0 70.7-57.2 128-128 128z"],share:[512,512,[],"f064","M503.691 189.836L327.687 37.851C312.281 24.546 288 35.347 288 56.015v80.053C127.371 137.907 0 170.1 0 322.326c0 61.441 39.581 122.309 83.333 154.132 13.653 9.931 33.111-2.533 28.077-18.631C66.066 312.814 132.917 274.316 288 272.085V360c0 20.7 24.3 31.453 39.687 18.164l176.004-152c11.071-9.562 11.086-26.753 0-36.328z"],spinner:[512,512,[],"f110","M304 48c0 26.51-21.49 48-48 48s-48-21.49-48-48 21.49-48 48-48 48 21.49 48 48zm-48 368c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zm208-208c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.49-48-48-48zM96 256c0-26.51-21.49-48-48-48S0 229.49 0 256s21.49 48 48 48 48-21.49 48-48zm12.922 99.078c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.491-48-48-48zm294.156 0c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48c0-26.509-21.49-48-48-48zM108.922 60.922c-26.51 0-48 21.49-48 48s21.49 48 48 48 48-21.49 48-48-21.491-48-48-48z"],square:[448,512,[],"f0c8","M400 32H48C21.5 32 0 53.5 0 80v352c0 26.5 21.5 48 48 48h352c26.5 0 48-21.5 48-48V80c0-26.5-21.5-48-48-48z"],"square-full":[512,512,[],"f45c","M512 512H0V0h512v512z"],times:[384,512,[],"f00d","M323.1 441l53.9-53.9c9.4-9.4 9.4-24.5 0-33.9L279.8 256l97.2-97.2c9.4-9.4 9.4-24.5 0-33.9L323.1 71c-9.4-9.4-24.5-9.4-33.9 0L192 168.2 94.8 71c-9.4-9.4-24.5-9.4-33.9 0L7 124.9c-9.4 9.4-9.4 24.5 0 33.9l97.2 97.2L7 353.2c-9.4 9.4-9.4 24.5 0 33.9L60.9 441c9.4 9.4 24.5 9.4 33.9 0l97.2-97.2 97.2 97.2c9.3 9.3 24.5 9.3 33.9 0z"],"times-circle":[512,512,[],"f057","M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm121.6 313.1c4.7 4.7 4.7 12.3 0 17L338 377.6c-4.7 4.7-12.3 4.7-17 0L256 312l-65.1 65.6c-4.7 4.7-12.3 4.7-17 0L134.4 338c-4.7-4.7-4.7-12.3 0-17l65.6-65-65.6-65.1c-4.7-4.7-4.7-12.3 0-17l39.6-39.6c4.7-4.7 12.3-4.7 17 0l65 65.7 65.1-65.6c4.7-4.7 12.3-4.7 17 0l39.6 39.6c4.7 4.7 4.7 12.3 0 17L312 256l65.6 65.1z"],wrench:[512,512,[],"f0ad","M481.156 200c9.3 0 15.12 10.155 10.325 18.124C466.295 259.992 420.419 288 368 288c-79.222 0-143.501-63.974-143.997-143.079C223.505 65.469 288.548-.001 368.002 0c52.362.001 98.196 27.949 123.4 69.743C496.24 77.766 490.523 88 481.154 88H376l-40 56 40 56h105.156zm-171.649 93.003L109.255 493.255c-24.994 24.993-65.515 24.994-90.51 0-24.993-24.994-24.993-65.516 0-90.51L218.991 202.5c16.16 41.197 49.303 74.335 90.516 90.503zM104 432c0-13.255-10.745-24-24-24s-24 10.745-24 24 10.745 24 24 24 24-10.745 24-24z"]};function u(e,t){var i=document.createElement("div");e.appendChild(i),i.appendChild(l("times")),i.addEventListener("click",(function(e){e.preventDefault(),e.stopPropagation(),t()}))}let f;function p(e,t,i){t.addEventListener("mousedown",function(e){e.stopPropagation(),e.preventDefault();const t=g.bind(this),r=m.bind(this),s=getComputedStyle(this),o=this.getBoundingClientRect();f={constraint:i,dragFunction:t,dragEndFunction:r,screenX:e.screenX,screenY:e.screenY,minDy:-o.top,minDx:-o.left,top:parseInt(s.top.replace("px","")),left:parseInt(s.left.replace("px",""))},document.addEventListener("mousemove",t),document.addEventListener("mouseup",r),document.addEventListener("mouseleave",r),document.addEventListener("mouseexit",r)}.bind(e))}function g(e){if(!f)return void console.error("No drag data!");e.stopPropagation(),e.preventDefault();const t=Math.max(f.minDx,e.screenX-f.screenX),i=Math.max(f.minDy,e.screenY-f.screenY),r=f.left+t,s=f.top+i;this.style.left=`${r}px`,this.style.top=`${s}px`}function m(e){if(!f)return void console.error("No drag data!");e.stopPropagation(),e.preventDefault();const t=f.dragFunction,i=f.dragEndFunction;document.removeEventListener("mousemove",t),document.removeEventListener("mouseup",i),document.removeEventListener("mouseleave",i),document.removeEventListener("mouseexit",i),f=void 0}class w{constructor({parent:e,label:i,content:r,okHandler:s,cancelHandler:o}){this.parent=e;const n=()=>{this.elem.style.display="none","function"==typeof o&&o(this)};this.elem=t(),this.elem.classList.add("igv-ui-generic-dialog-container","igv-ui-center-fixed");const a=t({class:"igv-ui-generic-dialog-header"});if(this.elem.appendChild(a),u(a,n),i){const e=t({class:"igv-ui-dialog-one-liner"});this.elem.appendChild(e),e.innerHTML=i}r.elem.style.margin="16px",this.elem.appendChild(r.elem),this.content=r;const c=t({class:"igv-ui-generic-dialog-ok-cancel"});this.elem.appendChild(c),this.ok=t(),c.appendChild(this.ok),this.ok.textContent="OK",this.cancel=t(),c.appendChild(this.cancel),this.cancel.textContent="Cancel",this.callback=void 0,this.ok.addEventListener("click",(e=>{this.elem.style.display="none","function"==typeof s?s(this):this.callback&&"function"==typeof this.callback&&this.callback(this)})),this.cancel.addEventListener("click",n),p(this.elem,a),this.elem.addEventListener("click",(e=>{e.preventDefault(),e.stopPropagation()}))}present(e,t){if(e.label&&this.label&&(this.label.textContent=e.label),e.html){this.content.html.innerHTML=e.html}if(e.text){this.content.html.innerText=e.text}e.value&&this.input&&(this.input.value=e.value),e.callback&&(this.callback=e.callback);const{top:i}=t.currentTarget.parentElement.getBoundingClientRect();this.elem.style.top=`${i}px`,this.elem.style.display="flex"}}function b(e){return"string"==typeof e||e instanceof String}function F(e){var t=String(e).split(/[.,]/);return t[0].split("").reverse().reduce((function(e,t,i){return i%3==0?e+","+t:e+t})).split("").reverse().join("")+(t[1]?"."+t[1]:"")}const v=function(e){return e.split(/\n|\r\n|\r/g)};function y(e,t){var i,r,s=[],o=e.length,n=0,a=!1;if(o>0)for(s[n]=e.charAt(0),i=1;i0?e.charAt(0).toUpperCase()+e.slice(1):e}function _(e){if(void 0!==e.name)return e.name;if(b(e)){let t=e.lastIndexOf("/"),i=t<0?e:e.substr(t+1);return t=i.indexOf("?"),t>0&&(i=i.substr(0,t)),i}throw Error("Expected File or string, got "+typeof e)}function x(e){return!!e&&("function"!=typeof e&&(e instanceof File||e.hasOwnProperty("name")&&"function"==typeof e.slice&&"function"==typeof e.arrayBuffer))}function k(e,t){const i=document.createElement("a");i.setAttribute("href",t),i.setAttribute("download",e),i.style.display="none",document.body.appendChild(i),i.click(),document.body.removeChild(i)}function I(e){for(var t=S,i=t.parser.loose.exec(e),r={},s=14;s--;)r[t.key[s]]=i[s]||"";return r[t.q.name]={},r[t.key[12]].replace(t.q.parser,(function(e,i,s){i&&(r[t.q.name][i]=s)})),r}"object"==typeof process&&"undefined"==typeof window&&(global.atob=function(e){return Buffer.from(e,"base64").toString("binary")});const S={strictMode:!1,key:["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],q:{name:"queryKey",parser:/(?:^|&)([^&=]*)=?([^&]*)/g},parser:{strict:/^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,loose:/^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*)(?::([^:@]*))?)?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/}};function E(e){let t=e.length;for(;--t>=0;)e[t]=0}const N=256,M=286,R=30,B=15,D=new Uint8Array([0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0]),L=new Uint8Array([0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13]),T=new Uint8Array([0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7]),z=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]),P=new Array(576);E(P);const H=new Array(60);E(H);const O=new Array(512);E(O);const V=new Array(256);E(V);const q=new Array(29);E(q);const U=new Array(R);function Q(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}let G,j,W;function $(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}E(U);const K=e=>e<256?O[e]:O[256+(e>>>7)],Y=(e,t)=>{e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255},Z=(e,t,i)=>{e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<{Z(e,i[2*t],i[2*t+1])},J=(e,t)=>{let i=0;do{i|=1&e,e>>>=1,i<<=1}while(--t>0);return i>>>1},ee=(e,t,i)=>{const r=new Array(16);let s,o,n=0;for(s=1;s<=B;s++)n=n+i[s-1]<<1,r[s]=n;for(o=0;o<=t;o++){let t=e[2*o+1];0!==t&&(e[2*o]=J(r[t]++,t))}},te=e=>{let t;for(t=0;t{e.bi_valid>8?Y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0},re=(e,t,i,r)=>{const s=2*t,o=2*i;return e[s]{const r=e.heap[i];let s=i<<1;for(;s<=e.heap_len&&(s{let r,s,o,n,a=0;if(0!==e.sym_next)do{r=255&e.pending_buf[e.sym_buf+a++],r+=(255&e.pending_buf[e.sym_buf+a++])<<8,s=e.pending_buf[e.sym_buf+a++],0===r?X(e,s,t):(o=V[s],X(e,o+N+1,t),n=D[o],0!==n&&(s-=q[o],Z(e,s,n)),r--,o=K(r),X(e,o,i),n=L[o],0!==n&&(r-=U[o],Z(e,r,n)))}while(a{const i=t.dyn_tree,r=t.stat_desc.static_tree,s=t.stat_desc.has_stree,o=t.stat_desc.elems;let n,a,c,l=-1;for(e.heap_len=0,e.heap_max=573,n=0;n>1;n>=1;n--)se(e,i,n);c=o;do{n=e.heap[1],e.heap[1]=e.heap[e.heap_len--],se(e,i,1),a=e.heap[1],e.heap[--e.heap_max]=n,e.heap[--e.heap_max]=a,i[2*c]=i[2*n]+i[2*a],e.depth[c]=(e.depth[n]>=e.depth[a]?e.depth[n]:e.depth[a])+1,i[2*n+1]=i[2*a+1]=c,e.heap[1]=c++,se(e,i,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],((e,t)=>{const i=t.dyn_tree,r=t.max_code,s=t.stat_desc.static_tree,o=t.stat_desc.has_stree,n=t.stat_desc.extra_bits,a=t.stat_desc.extra_base,c=t.stat_desc.max_length;let l,h,d,u,f,p,g=0;for(u=0;u<=B;u++)e.bl_count[u]=0;for(i[2*e.heap[e.heap_max]+1]=0,l=e.heap_max+1;l<573;l++)h=e.heap[l],u=i[2*i[2*h+1]+1]+1,u>c&&(u=c,g++),i[2*h+1]=u,h>r||(e.bl_count[u]++,f=0,h>=a&&(f=n[h-a]),p=i[2*h],e.opt_len+=p*(u+f),o&&(e.static_len+=p*(s[2*h+1]+f)));if(0!==g){do{for(u=c-1;0===e.bl_count[u];)u--;e.bl_count[u]--,e.bl_count[u+1]+=2,e.bl_count[c]--,g-=2}while(g>0);for(u=c;0!==u;u--)for(h=e.bl_count[u];0!==h;)d=e.heap[--l],d>r||(i[2*d+1]!==u&&(e.opt_len+=(u-i[2*d+1])*i[2*d],i[2*d+1]=u),h--)}})(e,t),ee(i,l,e.bl_count)},ae=(e,t,i)=>{let r,s,o=-1,n=t[1],a=0,c=7,l=4;for(0===n&&(c=138,l=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=n,n=t[2*(r+1)+1],++a{let r,s,o=-1,n=t[1],a=0,c=7,l=4;for(0===n&&(c=138,l=3),r=0;r<=i;r++)if(s=n,n=t[2*(r+1)+1],!(++a{Z(e,0+(r?1:0),3),ie(e),Y(e,i),Y(e,~i),i&&e.pending_buf.set(e.window.subarray(t,t+i),e.pending),e.pending+=i};var de=(e,t,i,r)=>{let s,o,n=0;e.level>0?(2===e.strm.data_type&&(e.strm.data_type=(e=>{let t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t{let t;for(ae(e,e.dyn_ltree,e.l_desc.max_code),ae(e,e.dyn_dtree,e.d_desc.max_code),ne(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*z[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t})(e),s=e.opt_len+3+7>>>3,o=e.static_len+3+7>>>3,o<=s&&(s=o)):s=o=i+5,i+4<=s&&-1!==t?he(e,t,i,r):4===e.strategy||o===s?(Z(e,2+(r?1:0),3),oe(e,P,H)):(Z(e,4+(r?1:0),3),((e,t,i,r)=>{let s;for(Z(e,t-257,5),Z(e,i-1,5),Z(e,r-4,4),s=0;s{le||((()=>{let e,t,i,r,s;const o=new Array(16);for(i=0,r=0;r<28;r++)for(q[r]=i,e=0;e<1<>=7;r(e.pending_buf[e.sym_buf+e.sym_next++]=t,e.pending_buf[e.sym_buf+e.sym_next++]=t>>8,e.pending_buf[e.sym_buf+e.sym_next++]=i,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(V[i]+N+1)]++,e.dyn_dtree[2*K(t)]++),e.sym_next===e.sym_end),_tr_align:e=>{Z(e,2,3),X(e,256,P),(e=>{16===e.bi_valid?(Y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)})(e)}};var fe=(e,t,i,r)=>{let s=65535&e,o=e>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+t[r++]|0,o=o+s|0}while(--n);s%=65521,o%=65521}return s|o<<16};const pe=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})());var ge=(e,t,i,r)=>{const s=pe,o=r+i;e^=-1;for(let i=r;i>>8^s[255&(e^t[i])];return-1^e},me={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},we={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8};const{_tr_init:be,_tr_stored_block:Fe,_tr_flush_block:ve,_tr_tally:ye,_tr_align:Ae}=ue,{Z_NO_FLUSH:Ce,Z_PARTIAL_FLUSH:_e,Z_FULL_FLUSH:xe,Z_FINISH:ke,Z_BLOCK:Ie,Z_OK:Se,Z_STREAM_END:Ee,Z_STREAM_ERROR:Ne,Z_DATA_ERROR:Me,Z_BUF_ERROR:Re,Z_DEFAULT_COMPRESSION:Be,Z_FILTERED:De,Z_HUFFMAN_ONLY:Le,Z_RLE:Te,Z_FIXED:ze,Z_DEFAULT_STRATEGY:Pe,Z_UNKNOWN:He,Z_DEFLATED:Oe}=we,Ve=258,qe=262,Ue=42,Qe=113,Ge=666,je=(e,t)=>(e.msg=me[t],t),We=e=>2*e-(e>4?9:0),$e=e=>{let t=e.length;for(;--t>=0;)e[t]=0},Ke=e=>{let t,i,r,s=e.w_size;t=e.hash_size,r=t;do{i=e.head[--r],e.head[r]=i>=s?i-s:0}while(--t);t=s,r=t;do{i=e.prev[--r],e.prev[r]=i>=s?i-s:0}while(--t)};let Ye=(e,t,i)=>(t<{const t=e.state;let i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(e.output.set(t.pending_buf.subarray(t.pending_out,t.pending_out+i),e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))},Xe=(e,t)=>{ve(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,Ze(e.strm)},Je=(e,t)=>{e.pending_buf[e.pending++]=t},et=(e,t)=>{e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t},tt=(e,t,i,r)=>{let s=e.avail_in;return s>r&&(s=r),0===s?0:(e.avail_in-=s,t.set(e.input.subarray(e.next_in,e.next_in+s),i),1===e.state.wrap?e.adler=fe(e.adler,t,s,i):2===e.state.wrap&&(e.adler=ge(e.adler,t,s,i)),e.next_in+=s,e.total_in+=s,s)},it=(e,t)=>{let i,r,s=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match;const c=e.strstart>e.w_size-qe?e.strstart-(e.w_size-qe):0,l=e.window,h=e.w_mask,d=e.prev,u=e.strstart+Ve;let f=l[o+n-1],p=l[o+n];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(i=t,l[i+n]===p&&l[i+n-1]===f&&l[i]===l[o]&&l[++i]===l[o+1]){o+=2,i++;do{}while(l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&on){if(e.match_start=t,n=r,r>=a)break;f=l[o+n-1],p=l[o+n]}}}while((t=d[t&h])>c&&0!==--s);return n<=e.lookahead?n:e.lookahead},rt=e=>{const t=e.w_size;let i,r,s;do{if(r=e.window_size-e.lookahead-e.strstart,e.strstart>=t+(t-qe)&&(e.window.set(e.window.subarray(t,t+t-r),0),e.match_start-=t,e.strstart-=t,e.block_start-=t,e.insert>e.strstart&&(e.insert=e.strstart),Ke(e),r+=t),0===e.strm.avail_in)break;if(i=tt(e.strm,e.window,e.strstart+e.lookahead,r),e.lookahead+=i,e.lookahead+e.insert>=3)for(s=e.strstart-e.insert,e.ins_h=e.window[s],e.ins_h=Ye(e,e.ins_h,e.window[s+1]);e.insert&&(e.ins_h=Ye(e,e.ins_h,e.window[s+3-1]),e.prev[s&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=s,s++,e.insert--,!(e.lookahead+e.insert<3)););}while(e.lookahead{let i,r,s,o=e.pending_buf_size-5>e.w_size?e.w_size:e.pending_buf_size-5,n=0,a=e.strm.avail_in;do{if(i=65535,s=e.bi_valid+42>>3,e.strm.avail_outr+e.strm.avail_in&&(i=r+e.strm.avail_in),i>s&&(i=s),i>8,e.pending_buf[e.pending-2]=~i,e.pending_buf[e.pending-1]=~i>>8,Ze(e.strm),r&&(r>i&&(r=i),e.strm.output.set(e.window.subarray(e.block_start,e.block_start+r),e.strm.next_out),e.strm.next_out+=r,e.strm.avail_out-=r,e.strm.total_out+=r,e.block_start+=r,i-=r),i&&(tt(e.strm,e.strm.output,e.strm.next_out,i),e.strm.next_out+=i,e.strm.avail_out-=i,e.strm.total_out+=i)}while(0===n);return a-=e.strm.avail_in,a&&(a>=e.w_size?(e.matches=2,e.window.set(e.strm.input.subarray(e.strm.next_in-e.w_size,e.strm.next_in),0),e.strstart=e.w_size,e.insert=e.strstart):(e.window_size-e.strstart<=a&&(e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,e.insert>e.strstart&&(e.insert=e.strstart)),e.window.set(e.strm.input.subarray(e.strm.next_in-a,e.strm.next_in),e.strstart),e.strstart+=a,e.insert+=a>e.w_size-e.insert?e.w_size-e.insert:a),e.block_start=e.strstart),e.high_waters&&e.block_start>=e.w_size&&(e.block_start-=e.w_size,e.strstart-=e.w_size,e.window.set(e.window.subarray(e.w_size,e.w_size+e.strstart),0),e.matches<2&&e.matches++,s+=e.w_size,e.insert>e.strstart&&(e.insert=e.strstart)),s>e.strm.avail_in&&(s=e.strm.avail_in),s&&(tt(e.strm,e.window,e.strstart,s),e.strstart+=s,e.insert+=s>e.w_size-e.insert?e.w_size-e.insert:s),e.high_water>3,s=e.pending_buf_size-s>65535?65535:e.pending_buf_size-s,o=s>e.w_size?e.w_size:s,r=e.strstart-e.block_start,(r>=o||(r||t===ke)&&t!==Ce&&0===e.strm.avail_in&&r<=s)&&(i=r>s?s:r,n=t===ke&&0===e.strm.avail_in&&i===r?1:0,Fe(e,e.block_start,i,n),e.block_start+=i,Ze(e.strm)),n?3:1)},ot=(e,t)=>{let i,r;for(;;){if(e.lookahead=3&&(e.ins_h=Ye(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),0!==i&&e.strstart-i<=e.w_size-qe&&(e.match_length=it(e,i)),e.match_length>=3)if(r=ye(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=Ye(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart}while(0!==--e.match_length);e.strstart++}else e.strstart+=e.match_length,e.match_length=0,e.ins_h=e.window[e.strstart],e.ins_h=Ye(e,e.ins_h,e.window[e.strstart+1]);else r=ye(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++;if(r&&(Xe(e,!1),0===e.strm.avail_out))return 1}return e.insert=e.strstart<2?e.strstart:2,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2},nt=(e,t)=>{let i,r,s;for(;;){if(e.lookahead=3&&(e.ins_h=Ye(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart),e.prev_length=e.match_length,e.prev_match=e.match_start,e.match_length=2,0!==i&&e.prev_length4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=ye(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=Ye(e,e.ins_h,e.window[e.strstart+3-1]),i=e.prev[e.strstart&e.w_mask]=e.head[e.ins_h],e.head[e.ins_h]=e.strstart)}while(0!==--e.prev_length);if(e.match_available=0,e.match_length=2,e.strstart++,r&&(Xe(e,!1),0===e.strm.avail_out))return 1}else if(e.match_available){if(r=ye(e,0,e.window[e.strstart-1]),r&&Xe(e,!1),e.strstart++,e.lookahead--,0===e.strm.avail_out)return 1}else e.match_available=1,e.strstart++,e.lookahead--}return e.match_available&&(r=ye(e,0,e.window[e.strstart-1]),e.match_available=0),e.insert=e.strstart<2?e.strstart:2,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2};function at(e,t,i,r,s){this.good_length=e,this.max_lazy=t,this.nice_length=i,this.max_chain=r,this.func=s}const ct=[new at(0,0,0,0,st),new at(4,4,8,4,ot),new at(4,5,16,8,ot),new at(4,6,32,32,ot),new at(4,4,16,16,nt),new at(8,16,32,32,nt),new at(8,16,128,128,nt),new at(8,32,128,256,nt),new at(32,128,258,1024,nt),new at(32,258,258,4096,nt)];function lt(){this.strm=null,this.status=0,this.pending_buf=null,this.pending_buf_size=0,this.pending_out=0,this.pending=0,this.wrap=0,this.gzhead=null,this.gzindex=0,this.method=Oe,this.last_flush=-1,this.w_size=0,this.w_bits=0,this.w_mask=0,this.window=null,this.window_size=0,this.prev=null,this.head=null,this.ins_h=0,this.hash_size=0,this.hash_bits=0,this.hash_mask=0,this.hash_shift=0,this.block_start=0,this.match_length=0,this.prev_match=0,this.match_available=0,this.strstart=0,this.match_start=0,this.lookahead=0,this.prev_length=0,this.max_chain_length=0,this.max_lazy_match=0,this.level=0,this.strategy=0,this.good_match=0,this.nice_match=0,this.dyn_ltree=new Uint16Array(1146),this.dyn_dtree=new Uint16Array(122),this.bl_tree=new Uint16Array(78),$e(this.dyn_ltree),$e(this.dyn_dtree),$e(this.bl_tree),this.l_desc=null,this.d_desc=null,this.bl_desc=null,this.bl_count=new Uint16Array(16),this.heap=new Uint16Array(573),$e(this.heap),this.heap_len=0,this.heap_max=0,this.depth=new Uint16Array(573),$e(this.depth),this.sym_buf=0,this.lit_bufsize=0,this.sym_next=0,this.sym_end=0,this.opt_len=0,this.static_len=0,this.matches=0,this.insert=0,this.bi_buf=0,this.bi_valid=0}const ht=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.status!==Ue&&57!==t.status&&69!==t.status&&73!==t.status&&91!==t.status&&103!==t.status&&t.status!==Qe&&t.status!==Ge?1:0},dt=e=>{if(ht(e))return je(e,Ne);e.total_in=e.total_out=0,e.data_type=He;const t=e.state;return t.pending=0,t.pending_out=0,t.wrap<0&&(t.wrap=-t.wrap),t.status=2===t.wrap?57:t.wrap?Ue:Qe,e.adler=2===t.wrap?0:1,t.last_flush=-2,be(t),Se},ut=e=>{const t=dt(e);var i;return t===Se&&((i=e.state).window_size=2*i.w_size,$e(i.head),i.max_lazy_match=ct[i.level].max_lazy,i.good_match=ct[i.level].good_length,i.nice_match=ct[i.level].nice_length,i.max_chain_length=ct[i.level].max_chain,i.strstart=0,i.block_start=0,i.lookahead=0,i.insert=0,i.match_length=i.prev_length=2,i.match_available=0,i.ins_h=0),t},ft=(e,t,i,r,s,o)=>{if(!e)return Ne;let n=1;if(t===Be&&(t=6),r<0?(n=0,r=-r):r>15&&(n=2,r-=16),s<1||s>9||i!==Oe||r<8||r>15||t<0||t>9||o<0||o>ze||8===r&&1!==n)return je(e,Ne);8===r&&(r=9);const a=new lt;return e.state=a,a.strm=e,a.status=Ue,a.wrap=n,a.gzhead=null,a.w_bits=r,a.w_size=1<{let i=t.length;if(ht(e))return Ne;const r=e.state,s=r.wrap;if(2===s||1===s&&r.status!==Ue||r.lookahead)return Ne;if(1===s&&(e.adler=fe(e.adler,t,i,0)),r.wrap=0,i>=r.w_size){0===s&&($e(r.head),r.strstart=0,r.block_start=0,r.insert=0);let e=new Uint8Array(r.w_size);e.set(t.subarray(i-r.w_size,i),0),t=e,i=r.w_size}const o=e.avail_in,n=e.next_in,a=e.input;for(e.avail_in=i,e.next_in=0,e.input=t,rt(r);r.lookahead>=3;){let e=r.strstart,t=r.lookahead-2;do{r.ins_h=Ye(r,r.ins_h,r.window[e+3-1]),r.prev[e&r.w_mask]=r.head[r.ins_h],r.head[r.ins_h]=e,e++}while(--t);r.strstart=e,r.lookahead=2,rt(r)}return r.strstart+=r.lookahead,r.block_start=r.strstart,r.insert=r.lookahead,r.lookahead=0,r.match_length=r.prev_length=2,r.match_available=0,e.next_in=n,e.input=a,e.avail_in=o,r.wrap=s,Se},gt={deflateInit:(e,t)=>ft(e,t,Oe,15,8,Pe),deflateInit2:ft,deflateReset:ut,deflateResetKeep:dt,deflateSetHeader:(e,t)=>ht(e)||2!==e.state.wrap?Ne:(e.state.gzhead=t,Se),deflate:(e,t)=>{if(ht(e)||t>Ie||t<0)return e?je(e,Ne):Ne;const i=e.state;if(!e.output||0!==e.avail_in&&!e.input||i.status===Ge&&t!==ke)return je(e,0===e.avail_out?Re:Ne);const r=i.last_flush;if(i.last_flush=t,0!==i.pending){if(Ze(e),0===e.avail_out)return i.last_flush=-1,Se}else if(0===e.avail_in&&We(t)<=We(r)&&t!==ke)return je(e,Re);if(i.status===Ge&&0!==e.avail_in)return je(e,Re);if(i.status===Ue&&0===i.wrap&&(i.status=Qe),i.status===Ue){let t=Oe+(i.w_bits-8<<4)<<8,r=-1;if(r=i.strategy>=Le||i.level<2?0:i.level<6?1:6===i.level?2:3,t|=r<<6,0!==i.strstart&&(t|=32),t+=31-t%31,et(i,t),0!==i.strstart&&(et(i,e.adler>>>16),et(i,65535&e.adler)),e.adler=1,i.status=Qe,Ze(e),0!==i.pending)return i.last_flush=-1,Se}if(57===i.status)if(e.adler=0,Je(i,31),Je(i,139),Je(i,8),i.gzhead)Je(i,(i.gzhead.text?1:0)+(i.gzhead.hcrc?2:0)+(i.gzhead.extra?4:0)+(i.gzhead.name?8:0)+(i.gzhead.comment?16:0)),Je(i,255&i.gzhead.time),Je(i,i.gzhead.time>>8&255),Je(i,i.gzhead.time>>16&255),Je(i,i.gzhead.time>>24&255),Je(i,9===i.level?2:i.strategy>=Le||i.level<2?4:0),Je(i,255&i.gzhead.os),i.gzhead.extra&&i.gzhead.extra.length&&(Je(i,255&i.gzhead.extra.length),Je(i,i.gzhead.extra.length>>8&255)),i.gzhead.hcrc&&(e.adler=ge(e.adler,i.pending_buf,i.pending,0)),i.gzindex=0,i.status=69;else if(Je(i,0),Je(i,0),Je(i,0),Je(i,0),Je(i,0),Je(i,9===i.level?2:i.strategy>=Le||i.level<2?4:0),Je(i,3),i.status=Qe,Ze(e),0!==i.pending)return i.last_flush=-1,Se;if(69===i.status){if(i.gzhead.extra){let t=i.pending,r=(65535&i.gzhead.extra.length)-i.gzindex;for(;i.pending+r>i.pending_buf_size;){let s=i.pending_buf_size-i.pending;if(i.pending_buf.set(i.gzhead.extra.subarray(i.gzindex,i.gzindex+s),i.pending),i.pending=i.pending_buf_size,i.gzhead.hcrc&&i.pending>t&&(e.adler=ge(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex+=s,Ze(e),0!==i.pending)return i.last_flush=-1,Se;t=0,r-=s}let s=new Uint8Array(i.gzhead.extra);i.pending_buf.set(s.subarray(i.gzindex,i.gzindex+r),i.pending),i.pending+=r,i.gzhead.hcrc&&i.pending>t&&(e.adler=ge(e.adler,i.pending_buf,i.pending-t,t)),i.gzindex=0}i.status=73}if(73===i.status){if(i.gzhead.name){let t,r=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>r&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r)),Ze(e),0!==i.pending)return i.last_flush=-1,Se;r=0}t=i.gzindexr&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r)),i.gzindex=0}i.status=91}if(91===i.status){if(i.gzhead.comment){let t,r=i.pending;do{if(i.pending===i.pending_buf_size){if(i.gzhead.hcrc&&i.pending>r&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r)),Ze(e),0!==i.pending)return i.last_flush=-1,Se;r=0}t=i.gzindexr&&(e.adler=ge(e.adler,i.pending_buf,i.pending-r,r))}i.status=103}if(103===i.status){if(i.gzhead.hcrc){if(i.pending+2>i.pending_buf_size&&(Ze(e),0!==i.pending))return i.last_flush=-1,Se;Je(i,255&e.adler),Je(i,e.adler>>8&255),e.adler=0}if(i.status=Qe,Ze(e),0!==i.pending)return i.last_flush=-1,Se}if(0!==e.avail_in||0!==i.lookahead||t!==Ce&&i.status!==Ge){let r=0===i.level?st(i,t):i.strategy===Le?((e,t)=>{let i;for(;;){if(0===e.lookahead&&(rt(e),0===e.lookahead)){if(t===Ce)return 1;break}if(e.match_length=0,i=ye(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(Xe(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2})(i,t):i.strategy===Te?((e,t)=>{let i,r,s,o;const n=e.window;for(;;){if(e.lookahead<=Ve){if(rt(e),e.lookahead<=Ve&&t===Ce)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(s=e.strstart-1,r=n[s],r===n[++s]&&r===n[++s]&&r===n[++s])){o=e.strstart+Ve;do{}while(r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&r===n[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=ye(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=ye(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(Xe(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,t===ke?(Xe(e,!0),0===e.strm.avail_out?3:4):e.sym_next&&(Xe(e,!1),0===e.strm.avail_out)?1:2})(i,t):ct[i.level].func(i,t);if(3!==r&&4!==r||(i.status=Ge),1===r||3===r)return 0===e.avail_out&&(i.last_flush=-1),Se;if(2===r&&(t===_e?Ae(i):t!==Ie&&(Fe(i,0,0,!1),t===xe&&($e(i.head),0===i.lookahead&&(i.strstart=0,i.block_start=0,i.insert=0))),Ze(e),0===e.avail_out))return i.last_flush=-1,Se}return t!==ke?Se:i.wrap<=0?Ee:(2===i.wrap?(Je(i,255&e.adler),Je(i,e.adler>>8&255),Je(i,e.adler>>16&255),Je(i,e.adler>>24&255),Je(i,255&e.total_in),Je(i,e.total_in>>8&255),Je(i,e.total_in>>16&255),Je(i,e.total_in>>24&255)):(et(i,e.adler>>>16),et(i,65535&e.adler)),Ze(e),i.wrap>0&&(i.wrap=-i.wrap),0!==i.pending?Se:Ee)},deflateEnd:e=>{if(ht(e))return Ne;const t=e.state.status;return e.state=null,t===Qe?je(e,Me):Se},deflateSetDictionary:pt,deflateInfo:"pako deflate (from Nodeca project)"};const mt=(e,t)=>Object.prototype.hasOwnProperty.call(e,t);var wt=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)mt(i,t)&&(e[t]=i[t])}}return e},bt=e=>{let t=0;for(let i=0,r=e.length;i=252?6:Fy>=248?5:Fy>=240?4:Fy>=224?3:Fy>=192?2:1;vt[254]=vt[254]=1;var yt=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,r,s,o,n=e.length,a=0;for(s=0;s>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},At=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let r,s;const o=new Array(2*i);for(s=0,r=0;r4)o[s++]=65533,r+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&r1?o[s++]=65533:t<65536?o[s++]=t:(t-=65536,o[s++]=55296|t>>10&1023,o[s++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&Ft)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let r=0;r{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+vt[e[i]]>t?i:t};var _t=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0};const xt=Object.prototype.toString,{Z_NO_FLUSH:kt,Z_SYNC_FLUSH:It,Z_FULL_FLUSH:St,Z_FINISH:Et,Z_OK:Nt,Z_STREAM_END:Mt,Z_DEFAULT_COMPRESSION:Rt,Z_DEFAULT_STRATEGY:Bt,Z_DEFLATED:Dt}=we;function Lt(e){this.options=wt({level:Rt,method:Dt,chunkSize:16384,windowBits:15,memLevel:8,strategy:Bt},e||{});let t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _t,this.strm.avail_out=0;let i=gt.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(i!==Nt)throw new Error(me[i]);if(t.header&>.deflateSetHeader(this.strm,t.header),t.dictionary){let e;if(e="string"==typeof t.dictionary?yt(t.dictionary):"[object ArrayBuffer]"===xt.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,i=gt.deflateSetDictionary(this.strm,e),i!==Nt)throw new Error(me[i]);this._dict_set=!0}}function Tt(e,t){const i=new Lt(t);if(i.push(e,!0),i.err)throw i.msg||me[i.err];return i.result}Lt.prototype.push=function(e,t){const i=this.strm,r=this.options.chunkSize;let s,o;if(this.ended)return!1;for(o=t===~~t?t:!0===t?Et:kt,"string"==typeof e?i.input=yt(e):"[object ArrayBuffer]"===xt.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;)if(0===i.avail_out&&(i.output=new Uint8Array(r),i.next_out=0,i.avail_out=r),(o===It||o===St)&&i.avail_out<=6)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else{if(s=gt.deflate(i,o),s===Mt)return i.next_out>0&&this.onData(i.output.subarray(0,i.next_out)),s=gt.deflateEnd(this.strm),this.onEnd(s),this.ended=!0,s===Nt;if(0!==i.avail_out){if(o>0&&i.next_out>0)this.onData(i.output.subarray(0,i.next_out)),i.avail_out=0;else if(0===i.avail_in)break}else this.onData(i.output)}return!0},Lt.prototype.onData=function(e){this.chunks.push(e)},Lt.prototype.onEnd=function(e){e===Nt&&(this.result=bt(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var zt=function(e,t){return(t=t||{}).raw=!0,Tt(e,t)},Pt=function(e,t){return(t=t||{}).gzip=!0,Tt(e,t)},Ht={Deflate:Lt,deflate:Tt,deflateRaw:zt,gzip:Pt,constants:we};const Ot=16209;var Vt=function(e,t){let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_,x;const k=e.state;i=e.next_in,_=e.input,r=i+(e.avail_in-5),s=e.next_out,x=e.output,o=s-(t-e.avail_out),n=s+(e.avail_out-257),a=k.dmax,c=k.wsize,l=k.whave,h=k.wnext,d=k.window,u=k.hold,f=k.bits,p=k.lencode,g=k.distcode,m=(1<>>24,u>>>=F,f-=F,F=b>>>16&255,0===F)x[s++]=65535&b;else{if(!(16&F)){if(64&F){if(32&F){k.mode=16191;break e}e.msg="invalid literal/length code",k.mode=Ot;break e}b=p[(65535&b)+(u&(1<>>=F,f-=F),f<15&&(u+=_[i++]<>>24,u>>>=F,f-=F,F=b>>>16&255,16&F){if(y=65535&b,F&=15,fa){e.msg="invalid distance too far back",k.mode=Ot;break e}if(u>>>=F,f-=F,F=s-o,y>F){if(F=y-F,F>l&&k.sane){e.msg="invalid distance too far back",k.mode=Ot;break e}if(A=0,C=d,0===h){if(A+=c-F,F2;)x[s++]=C[A++],x[s++]=C[A++],x[s++]=C[A++],v-=3;v&&(x[s++]=C[A++],v>1&&(x[s++]=C[A++]))}else{A=s-y;do{x[s++]=x[A++],x[s++]=x[A++],x[s++]=x[A++],v-=3}while(v>2);v&&(x[s++]=x[A++],v>1&&(x[s++]=x[A++]))}break}if(64&F){e.msg="invalid distance code",k.mode=Ot;break e}b=g[(65535&b)+(u&(1<>3,i-=v,f-=v<<3,u&=(1<{const c=a.bits;let l,h,d,u,f,p,g=0,m=0,w=0,b=0,F=0,v=0,y=0,A=0,C=0,_=0,x=null;const k=new Uint16Array(16),I=new Uint16Array(16);let S,E,N,M=null;for(g=0;g<=qt;g++)k[g]=0;for(m=0;m=1&&0===k[b];b--);if(F>b&&(F=b),0===b)return s[o++]=20971520,s[o++]=20971520,a.bits=1,0;for(w=1;w0&&(0===e||1!==b))return-1;for(I[1]=0,g=1;g852||2===e&&C>592)return 1;for(;;){S=g-y,n[m]+1=p?(E=M[n[m]-p],N=x[n[m]-p]):(E=96,N=0),l=1<>y)+h]=S<<24|E<<16|N}while(0!==h);for(l=1<>=1;if(0!==l?(_&=l-1,_+=l):_=0,m++,0===--k[g]){if(g===b)break;g=t[i+n[m]]}if(g>F&&(_&u)!==d){for(0===y&&(y=F),f+=w,v=g-y,A=1<852||2===e&&C>592)return 1;d=_&u,s[d]=F<<24|v<<16|f-o}}return 0!==_&&(s[f+_]=g-y<<24|64<<16),a.bits=F,0};const{Z_FINISH:$t,Z_BLOCK:Kt,Z_TREES:Yt,Z_OK:Zt,Z_STREAM_END:Xt,Z_NEED_DICT:Jt,Z_STREAM_ERROR:ei,Z_DATA_ERROR:ti,Z_MEM_ERROR:ii,Z_BUF_ERROR:ri,Z_DEFLATED:si}=we,oi=16180,ni=16190,ai=16191,ci=16192,li=16194,hi=16199,di=16200,ui=16206,fi=16209,pi=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function gi(){this.strm=null,this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}const mi=e=>{if(!e)return 1;const t=e.state;return!t||t.strm!==e||t.mode16211?1:0},wi=e=>{if(mi(e))return ei;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=oi,t.last=0,t.havedict=0,t.flags=-1,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Zt},bi=e=>{if(mi(e))return ei;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,wi(e)},Fi=(e,t)=>{let i;if(mi(e))return ei;const r=e.state;return t<0?(i=0,t=-t):(i=5+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?ei:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,bi(e))},vi=(e,t)=>{if(!e)return ei;const i=new gi;e.state=i,i.strm=e,i.window=null,i.mode=oi;const r=Fi(e,t);return r!==Zt&&(e.state=null),r};let yi,Ai,Ci=!0;const _i=e=>{if(Ci){yi=new Int32Array(512),Ai=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(Wt(1,e.lens,0,288,yi,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;Wt(2,e.lens,0,32,Ai,0,e.work,{bits:5}),Ci=!1}e.lencode=yi,e.lenbits=9,e.distcode=Ai,e.distbits=5},xi=(e,t,i,r)=>{let s;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(s=o.wsize-o.wnext,s>r&&(s=r),o.window.set(t.subarray(i-r,i-r+s),o.wnext),(r-=s)?(o.window.set(t.subarray(i-r,i),0),o.wnext=r,o.whave=o.wsize):(o.wnext+=s,o.wnext===o.wsize&&(o.wnext=0),o.whavevi(e,15),inflateInit2:vi,inflate:(e,t)=>{let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_=0;const x=new Uint8Array(4);let k,I;const S=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(mi(e)||!e.output||!e.input&&0!==e.avail_in)return ei;i=e.state,i.mode===ai&&(i.mode=ci),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,d=a,u=c,C=Zt;e:for(;;)switch(i.mode){case oi:if(0===i.wrap){i.mode=ci;break}for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=ge(i.check,x,2,0),l=0,h=0,i.mode=16181;break}if(i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=fi;break}if((15&l)!==si){e.msg="unknown compression method",i.mode=fi;break}if(l>>>=4,h-=4,A=8+(15&l),0===i.wbits&&(i.wbits=A),A>15||A>i.wbits){e.msg="invalid window size",i.mode=fi;break}i.dmax=1<>8&1),512&i.flags&&4&i.wrap&&(x[0]=255&l,x[1]=l>>>8&255,i.check=ge(i.check,x,2,0)),l=0,h=0,i.mode=16182;case 16182:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>8&255,x[2]=l>>>16&255,x[3]=l>>>24&255,i.check=ge(i.check,x,4,0)),l=0,h=0,i.mode=16183;case 16183:for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>8),512&i.flags&&4&i.wrap&&(x[0]=255&l,x[1]=l>>>8&255,i.check=ge(i.check,x,2,0)),l=0,h=0,i.mode=16184;case 16184:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=ge(i.check,x,2,0)),l=0,h=0}else i.head&&(i.head.extra=null);i.mode=16185;case 16185:if(1024&i.flags&&(f=i.length,f>a&&(f=a),f&&(i.head&&(A=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(o,o+f),A)),512&i.flags&&4&i.wrap&&(i.check=ge(i.check,r,f,o)),a-=f,o+=f,i.length-=f),i.length))break e;i.length=0,i.mode=16186;case 16186:if(2048&i.flags){if(0===a)break e;f=0;do{A=r[o+f++],i.head&&A&&i.length<65536&&(i.head.name+=String.fromCharCode(A))}while(A&&f>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=ai;break;case 16189:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>=7&h,h-=7&h,i.mode=ui;break}for(;h<3;){if(0===a)break e;a--,l+=r[o++]<>>=1,h-=1,3&l){case 0:i.mode=16193;break;case 1:if(_i(i),i.mode=hi,t===Yt){l>>>=2,h-=2;break e}break;case 2:i.mode=16196;break;case 3:e.msg="invalid block type",i.mode=fi}l>>>=2,h-=2;break;case 16193:for(l>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,l+=r[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=fi;break}if(i.length=65535&l,l=0,h=0,i.mode=li,t===Yt)break e;case li:i.mode=16195;case 16195:if(f=i.length,f){if(f>a&&(f=a),f>c&&(f=c),0===f)break e;s.set(r.subarray(o,o+f),n),a-=f,o+=f,c-=f,n+=f,i.length-=f;break}i.mode=ai;break;case 16196:for(;h<14;){if(0===a)break e;a--,l+=r[o++]<>>=5,h-=5,i.ndist=1+(31&l),l>>>=5,h-=5,i.ncode=4+(15&l),l>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=fi;break}i.have=0,i.mode=16197;case 16197:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[S[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,k={bits:i.lenbits},C=Wt(0,i.lens,0,19,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid code lengths set",i.mode=fi;break}i.have=0,i.mode=16198;case 16198:for(;i.have>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=m,h-=m,i.lens[i.have++]=b;else{if(16===b){for(I=m+2;h>>=m,h-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=fi;break}A=i.lens[i.have-1],f=3+(3&l),l>>>=2,h-=2}else if(17===b){for(I=m+3;h>>=m,h-=m,A=0,f=3+(7&l),l>>>=3,h-=3}else{for(I=m+7;h>>=m,h-=m,A=0,f=11+(127&l),l>>>=7,h-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=fi;break}for(;f--;)i.lens[i.have++]=A}}if(i.mode===fi)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=fi;break}if(i.lenbits=9,k={bits:i.lenbits},C=Wt(1,i.lens,0,i.nlen,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid literal/lengths set",i.mode=fi;break}if(i.distbits=6,i.distcode=i.distdyn,k={bits:i.distbits},C=Wt(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,k),i.distbits=k.bits,C){e.msg="invalid distances set",i.mode=fi;break}if(i.mode=hi,t===Yt)break e;case hi:i.mode=di;case di:if(a>=6&&c>=258){e.next_out=n,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=l,i.bits=h,Vt(e,u),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,i.mode===ai&&(i.back=-1);break}for(i.back=0;_=i.lencode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,i.length=b,0===w){i.mode=16205;break}if(32&w){i.back=-1,i.mode=ai;break}if(64&w){e.msg="invalid literal/length code",i.mode=fi;break}i.extra=15&w,i.mode=16201;case 16201:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=16202;case 16202:for(;_=i.distcode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,64&w){e.msg="invalid distance code",i.mode=fi;break}i.offset=b,i.extra=15&w,i.mode=16203;case 16203:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=fi;break}i.mode=16204;case 16204:if(0===c)break e;if(f=u-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=fi;break}f>i.wnext?(f-=i.wnext,p=i.wsize-f):p=i.wnext-f,f>i.length&&(f=i.length),g=i.window}else g=s,p=n-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do{s[n++]=g[p++]}while(--f);0===i.length&&(i.mode=di);break;case 16205:if(0===c)break e;s[n++]=i.length,c--,i.mode=di;break;case ui:if(i.wrap){for(;h<32;){if(0===a)break e;a--,l|=r[o++]<{if(mi(e))return ei;let t=e.state;return t.window&&(t.window=null),e.state=null,Zt},inflateGetHeader:(e,t)=>{if(mi(e))return ei;const i=e.state;return 2&i.wrap?(i.head=t,t.done=!1,Zt):ei},inflateSetDictionary:(e,t)=>{const i=t.length;let r,s,o;return mi(e)?ei:(r=e.state,0!==r.wrap&&r.mode!==ni?ei:r.mode===ni&&(s=1,s=fe(s,t,i,0),s!==r.check)?ti:(o=xi(e,t,i,i),o?(r.mode=16210,ii):(r.havedict=1,Zt)))},inflateInfo:"pako inflate (from Nodeca project)"};var Ii=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1};const Si=Object.prototype.toString,{Z_NO_FLUSH:Ei,Z_FINISH:Ni,Z_OK:Mi,Z_STREAM_END:Ri,Z_NEED_DICT:Bi,Z_STREAM_ERROR:Di,Z_DATA_ERROR:Li,Z_MEM_ERROR:Ti}=we;function zi(e){this.options=wt({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new _t,this.strm.avail_out=0;let i=ki.inflateInit2(this.strm,t.windowBits);if(i!==Mi)throw new Error(me[i]);if(this.header=new Ii,ki.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=yt(t.dictionary):"[object ArrayBuffer]"===Si.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=ki.inflateSetDictionary(this.strm,t.dictionary),i!==Mi)))throw new Error(me[i])}function Pi(e,t){const i=new zi(t);if(i.push(e),i.err)throw i.msg||me[i.err];return i.result}zi.prototype.push=function(e,t){const i=this.strm,r=this.options.chunkSize,s=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Ni:Ei,"[object ArrayBuffer]"===Si.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(r),i.next_out=0,i.avail_out=r),o=ki.inflate(i,n),o===Bi&&s&&(o=ki.inflateSetDictionary(i,s),o===Mi?o=ki.inflate(i,n):o===Li&&(o=Bi));i.avail_in>0&&o===Ri&&i.state.wrap>0&&0!==e[i.next_in];)ki.inflateReset(i),o=ki.inflate(i,n);switch(o){case Di:case Li:case Bi:case Ti:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===Ri))if("string"===this.options.to){let e=Ct(i.output,i.next_out),t=i.next_out-e,s=At(i.output,e);i.next_out=t,i.avail_out=r-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(s)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==Mi||0!==a){if(o===Ri)return o=ki.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},zi.prototype.onData=function(e){this.chunks.push(e)},zi.prototype.onEnd=function(e){e===Mi&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=bt(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var Hi=function(e,t){return(t=t||{}).raw=!0,Pi(e,t)},Oi={Inflate:zi,inflate:Pi,inflateRaw:Hi,ungzip:Pi,constants:we};const{Deflate:Vi,deflate:qi,deflateRaw:Ui,gzip:Qi}=Ht,{Inflate:Gi,inflate:ji,inflateRaw:Wi,ungzip:$i}=Oi;var Ki=Ui,Yi=ji,Zi=Wi,Xi=$i;function Ji(e){const t=ArrayBuffer.isView(e)?e:new Uint8Array(e);return 31===t[0]&&139===t[1]}function er(e){const t=ArrayBuffer.isView(e)?e:new Uint8Array(e);return 0!==(4&t[3])&&66===t[12]&&67===t[13]?tr(t.buffer):Xi(t)}function tr(e,t){const i=[];let r=0,s=0;for(t=t||e.byteLength-18;r100?or(new Uint8Array(e.buffer,e.byteOffset+t,s),i,r):function(e,t,i,r,s){for(let o=0;o=0){s=atob(s);const e=new Uint8Array(s.length);for(let t=0;t0?Xi(e):e,i}return decodeURIComponent(s)}const ar=(e,t,i)=>(1-i)*e+i*t,cr=function(e,t,i){return Math.min(Math.max(e,t),i)},lr=function(e){return Math.log(e)/Math.LN2};function hr(){this.content=[]}function dr(e,t){return Math.random()*(t-e)+e}hr.prototype={push:function(e){this.content.push(e),this.bubbleUp(this.content.length-1)},pop:function(){var e=this.content[0],t=this.content.pop();return this.content.length>0&&(this.content[0]=t,this.sinkDown(0)),e},remove:function(e){for(var t=this.content.length,i=0;i0;){var r=Math.floor((e+1)/2)-1,s=this.content[r];if(i>=s)break;this.content[r]=t,this.content[e]=s,e=r}},sinkDown:function(e){for(var t=this.content.length,i=this.content[e],r=i;;){var s=2*(e+1),o=s-1,n=null;if(o{let e=[];for(let t=1;t>=.5;t-=.1)for(let i=0;i<1;i+=1/28){const r="rgb("+ur.hsvToRgb(i,1,t).join(",")+")";e.push(r)}return e.pop(),e.push(ur.rgbColor(16,16,16)),e},rgbToHex:function(e){return(e=e.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i))&&4===e.length?"#"+("0"+parseInt(e[1],10).toString(16)).slice(-2)+("0"+parseInt(e[2],10).toString(16)).slice(-2)+("0"+parseInt(e[3],10).toString(16)).slice(-2):""},hexToRgb:function(e){var t=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(e);if(null!==t)return"rgb("+parseInt(t[1],16)+","+parseInt(t[2],16)+","+parseInt(t[3],16)+")"},hsvToRgb:function(e,t,i){var r,s,o,n=Math.floor(6*e),a=6*e-n,c=i*(1-t),l=i*(1-a*t),h=i*(1-(1-a)*t);switch(n%6){case 0:r=i,s=h,o=c;break;case 1:r=l,s=i,o=c;break;case 2:r=c,s=i,o=h;break;case 3:r=c,s=l,o=i;break;case 4:r=h,s=c,o=i;break;case 5:r=i,s=c,o=l}return[Math.floor(255*r),Math.floor(255*s),Math.floor(255*o)]},hslToRgb:function(e,t,i){var r,s,o;if(0===t)r=s=o=i;else{var n=i<.5?i*(1+t):i+t-i*t,a=2*i-n;r=ur.hue2rgb(a,n,e+1/3),s=ur.hue2rgb(a,n,e),o=ur.hue2rgb(a,n,e-1/3)}return[255*r,255*s,255*o]},hue2rgb:(e,t,i)=>(i<0&&(i+=1),i>1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e),rgbaColor:function(e,t,i,r){return"rgba("+(e=cr(e,0,255))+","+(t=cr(t,0,255))+","+(i=cr(i,0,255))+","+(r=cr(r,0,1))+")"},rgbColor:function(e,t,i){return"rgb("+(e=cr(e,0,255))+","+(t=cr(t,0,255))+","+(i=cr(i,0,255))+")"},greyScale:function(e){var t=cr(e,0,255);return"rgb("+t+","+t+","+t+")"},randomGrey:function(e,t){e=cr(e,0,255),t=cr(t,0,255);var i=Math.round(dr(e,t)).toString(10);return"rgb("+i+","+i+","+i+")"},randomRGB:function(e,t){return e=cr(e,0,255),t=cr(t,0,255),"rgb("+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+")"},randomRGBConstantAlpha:function(e,t,i){return e=cr(e,0,255),t=cr(t,0,255),"rgba("+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+","+Math.round(dr(e,t)).toString(10)+","+i+")"},addAlpha:function(e,t){if("0"===e||"."===e)e="rgb(0,0,0)";else{const t=this.colorNameToHex(e);t&&(e=t)}var i=/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(e);if(e.startsWith("rgba")){const i=e.lastIndexOf(",");return e.substring(0,i+1)+t.toString()+")"}return i&&(e=ur.hexToRgb(e)),e.startsWith("rgb")?e.replace("rgb","rgba").replace(")",", "+t+")"):(console.log(e+" is not an rgb style string"),e)},rgbComponents:function(e){if("0"===e||"."===e)return[0,0,0];if(/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(e))e=ur.hexToRgb(e);else if(!e.startsWith("rgb")){const t=this.colorNameToHex(e);e=this.hexToRgb(t)}if(e.startsWith("rgb("))return e.substring(4,e.length-1).split(",").map((e=>Number.parseInt(e.trim())));if(e.startsWith("rgba("))return e.substring(5,e.length-1).split(",").map(((e,t)=>(e=e.trim(),3===t?Number.parseFloat(e):Number.parseInt(e))));throw Error("Unrecognized color string: color")},getCompositeColor:function(e,t,i){return"rgb("+Math.floor(i*t[0]+(1-i)*e[0])+","+Math.floor(i*t[1]+(1-i)*e[1])+","+Math.floor(i*t[2]+(1-i)*e[2])+")"},createColorString:function(e){const t=this.createColorStringSafe(e);return t||e},createColorStringSafe:function(e){if((e=A(e)).startsWith("rgb(")&&e.endsWith(")"))return e;if(e.startsWith("#")&&e.length<8)return e;const t=this.colorNameToHex(e);if(t)return t;const i=e.split(",");return 3===i.length&&fr(i[0])&&fr(i[1])&&fr(i[2])?`rgb(${e})`:void 0},darkenLighten:function(e,t){let i,r=this.colorNameToHex(e);i=r?ur.hexToRgb(r):e.startsWith("rgb(")?e:ur.hexToRgb(e);const s=i.replace(")","").substring(4).split(","),o=Math.max(0,Math.min(255,Number.parseInt(s[0].trim())+t)),n=Math.max(0,Math.min(255,Number.parseInt(s[1].trim())+t)),a=Math.max(0,Math.min(255,Number.parseInt(s[2].trim())+t));return"rgb("+o.toString()+","+n.toString()+","+a.toString()+")"},colorNameToHex:function(e){return{aliceblue:"#f0f8ff",antiquewhite:"#faebd7",aqua:"#00ffff",aquamarine:"#7fffd4",azure:"#f0ffff",beige:"#f5f5dc",bisque:"#ffe4c4",black:"#000000",blanchedalmond:"#ffebcd",blue:"#0000ff",blueviolet:"#8a2be2",brown:"#a52a2a",burlywood:"#deb887",cadetblue:"#5f9ea0",chartreuse:"#7fff00",chocolate:"#d2691e",coral:"#ff7f50",cornflowerblue:"#6495ed",cornsilk:"#fff8dc",crimson:"#dc143c",cyan:"#00ffff",darkblue:"#00008b",darkcyan:"#008b8b",darkgoldenrod:"#b8860b",darkgray:"#a9a9a9",darkgreen:"#006400",darkkhaki:"#bdb76b",darkmagenta:"#8b008b",darkolivegreen:"#556b2f",darkorange:"#ff8c00",darkorchid:"#9932cc",darkred:"#8b0000",darksalmon:"#e9967a",darkseagreen:"#8fbc8f",darkslateblue:"#483d8b",darkslategray:"#2f4f4f",darkturquoise:"#00ced1",darkviolet:"#9400d3",deeppink:"#ff1493",deepskyblue:"#00bfff",dimgray:"#696969",dodgerblue:"#1e90ff",firebrick:"#b22222",floralwhite:"#fffaf0",forestgreen:"#228b22",fuchsia:"#ff00ff",gainsboro:"#dcdcdc",ghostwhite:"#f8f8ff",gold:"#ffd700",goldenrod:"#daa520",gray:"#808080",green:"#008000",greenyellow:"#adff2f",honeydew:"#f0fff0",hotpink:"#ff69b4","indianred ":"#cd5c5c","indigo ":"#4b0082",ivory:"#fffff0",khaki:"#f0e68c",lavender:"#e6e6fa",lavenderblush:"#fff0f5",lawngreen:"#7cfc00",lemonchiffon:"#fffacd",lightblue:"#add8e6",lightcoral:"#f08080",lightcyan:"#e0ffff",lightgoldenrodyellow:"#fafad2",lightgrey:"#d3d3d3",lightgreen:"#90ee90",lightpink:"#ffb6c1",lightsalmon:"#ffa07a",lightseagreen:"#20b2aa",lightskyblue:"#87cefa",lightslategray:"#778899",lightsteelblue:"#b0c4de",lightyellow:"#ffffe0",lime:"#00ff00",limegreen:"#32cd32",linen:"#faf0e6",magenta:"#ff00ff",maroon:"#800000",mediumaquamarine:"#66cdaa",mediumblue:"#0000cd",mediumorchid:"#ba55d3",mediumpurple:"#9370d8",mediumseagreen:"#3cb371",mediumslateblue:"#7b68ee",mediumspringgreen:"#00fa9a",mediumturquoise:"#48d1cc",mediumvioletred:"#c71585",midnightblue:"#191970",mintcream:"#f5fffa",mistyrose:"#ffe4e1",moccasin:"#ffe4b5",navajowhite:"#ffdead",navy:"#000080",oldlace:"#fdf5e6",olive:"#808000",olivedrab:"#6b8e23",orange:"#ffa500",orangered:"#ff4500",orchid:"#da70d6",palegoldenrod:"#eee8aa",palegreen:"#98fb98",paleturquoise:"#afeeee",palevioletred:"#d87093",papayawhip:"#ffefd5",peachpuff:"#ffdab9",peru:"#cd853f",pink:"#ffc0cb",plum:"#dda0dd",powderblue:"#b0e0e6",purple:"#800080",red:"#ff0000",rosybrown:"#bc8f8f",royalblue:"#4169e1",saddlebrown:"#8b4513",salmon:"#fa8072",sandybrown:"#f4a460",seagreen:"#2e8b57",seashell:"#fff5ee",sienna:"#a0522d",silver:"#c0c0c0",skyblue:"#87ceeb",slateblue:"#6a5acd",slategray:"#708090",snow:"#fffafa",springgreen:"#00ff7f",steelblue:"#4682b4",tan:"#d2b48c",teal:"#008080",thistle:"#d8bfd8",tomato:"#ff6347",turquoise:"#40e0d0",violet:"#ee82ee",wheat:"#f5deb3",white:"#ffffff",whitesmoke:"#f5f5f5",yellow:"#ffff00",yellowgreen:"#9acd32",darkgrey:"#a9a9a9",darkslategrey:"#2f4f4f",dimgrey:"#696969",grey:"#808080",lightgray:"#d3d3d3",lightslategrey:"#778899",slategrey:"#708090"}[e]}};function fr(e){const t=Number.parseInt(e);return!Number.isNaN(t)&&t>=0&&t<=255}const pr="googleapis";class gr{constructor(){this.oauthTokens={}}setToken(e,t){t=t||pr,this.oauthTokens[t]=e}getToken(e){let t;e=e||pr;for(let i of Object.keys(this.oauthTokens)){if(mr(i).test(e)){t=this.oauthTokens[i];break}}return t}removeToken(e){e=e||pr;for(let t of Object.keys(this.oauthTokens)){mr(t).test(e)&&(this.oauthTokens[t]=void 0)}}}function mr(e){return new RegExp("^"+e.split(/\*+/).map(wr).join(".*")+"$")}function wr(e){return e.replace(/[|\\{}()[\]^$+*?.]/g,"\\$&")}function br(e){return e.includes("googleapis")&&!e.includes("urlshortener")||Fr(e)||vr(e)}function Fr(e){return e.startsWith("gs://")||e.startsWith("https://www.googleapis.com/storage")||e.startsWith("https://storage.cloud.google.com")||e.startsWith("https://storage.googleapis.com")}function vr(e){return e.indexOf("drive.google.com")>=0||e.indexOf("www.googleapis.com/drive")>0}function yr(e){let{bucket:t,object:i}=function(e){let t,i;if(e.startsWith("gs://")){const r=e.indexOf("/",5);if(r>=0){t=e.substring(5,r);const s=e.indexOf("?");i=s<0?e.substring(r+1):e.substring(r+1,s)}}else if(e.startsWith("https://storage.googleapis.com")||e.startsWith("https://storage.cloud.google.com")){const r=e.indexOf("/v1/b/",8);if(r>0){const s=e.indexOf("/o/",r);if(s>0){const o=e.indexOf("?",s);t=e.substring(r+6,s),i=o>0?e.substring(s+3,o):e.substring(s+3)}}else{const r=e.indexOf("/",8),s=e.indexOf("/",r+1),o=e.indexOf("?",s);s>0&&(t=e.substring(r+1,s),i=o<0?e.substring(s+1):e.substring(s+1,o))}}else if(e.startsWith("https://www.googleapis.com/storage/v1/b")){const r=e.indexOf("/v1/b/",8),s=e.indexOf("/o/",r);if(s>0){const o=e.indexOf("?",s);t=e.substring(r+6,s),i=o>0?e.substring(s+3,o):e.substring(s+3)}}if(t&&i)return{bucket:t,object:i};throw Error(`Unrecognized Google Storage URI: ${e}`)}(e);i=function(e){let t="";return e.split("").forEach((function(e){Ar.has(e)?t+=Ar.get(e):t+=e})),t}(i);const r=e.indexOf("?");return`https://storage.googleapis.com/storage/v1/b/${t}/o/${i}${r>0?e.substring(r)+"&alt=media":"?alt=media"}`}const Ar=new Map;function Cr(){return window.google&&window.google.igv}let _r;async function xr(e){if(!Cr())throw Error("Google oAuth has not been initialized");if(google.igv.tokenResponse&&Date.now(){try{t.callback=e=>{void 0!==e.error&&r(e),google.igv.tokenResponse=e,google.igv.tokenExpiresAt=Date.now()+1e3*e.expires_in,console.log("Access token expires at "+new Date(google.igv.tokenExpiresAt)),i(e.access_token)},console.log("Requesting access token"),t.requestAccessToken({scope:e})}catch(e){console.log(e)}}))),_r}}function kr(){return google.igv.apiKey}function Ir(e){var t=Sr(e);return t?"https://www.googleapis.com/drive/v3/files/"+t+"?alt=media&supportsTeamDrives=true":e}function Sr(e){if(e.includes("/open?id=")){const t=e.indexOf("/open?id=")+9,i=e.indexOf("&");if(t>0&&i>t)return e.substring(t,i);if(t>0)return e.substring(t)}else{if(e.includes("/file/d/")){const t=e.indexOf("/file/d/")+8,i=e.lastIndexOf("/");return e.substring(t,i)}if(e.startsWith("https://www.googleapis.com/drive")){let t=e.indexOf("/files/");const i=e.indexOf("?");if(t>0)return t+=7,i>0?e.substring(t,i):e.substring(t)}}throw Error("Unknown Google Drive url format: "+e)}Ar.set("!","%21"),Ar.set("#","%23"),Ar.set("$","%24"),Ar.set("%","%25"),Ar.set("&","%26"),Ar.set("'","%27"),Ar.set("(","%28"),Ar.set(")","%29"),Ar.set("*","%2A"),Ar.set("+","%2B"),Ar.set(",","%2C"),Ar.set("/","%2F"),Ar.set(":","%3A"),Ar.set(";","%3B"),Ar.set("=","%3D"),Ar.set("?","%3F"),Ar.set("@","%40"),Ar.set("[","%5B"),Ar.set("]","%5D"),Ar.set(" ","%20");class Er{constructor(e){this.requestsPerSecond=e.requestsPerSecond||10,this.lastStartTime=0,this.queued=[]}add(e,t){var i=this;return new Promise((function(t,r){i.queued.push({resolve:t,reject:r,asyncFunction:e}),i.dequeue()}))}addAll(e,t){var i=e.map(function(e){return this.add(e,t)}.bind(this));return Promise.all(i)}dequeue(){if(this.queued.length>0){var e=new Date,t=1e3/this.requestsPerSecond+1,i=e-this.lastStartTime;i>=t?this._execute():setTimeout(function(){this.dequeue()}.bind(this),t-i)}}async _execute(){this.lastStartTime=new Date;var e=this.queued.shift();const t=e.asyncFunction;try{const i=await t();e.resolve(i)}catch(t){e.reject(t)}}}function Nr(){if(Cr()){return Cr()&&google.igv.tokenResponse&&Date.now()0)for(var n=0;nthis._loadURL(e,t))):this._loadURL(e,t)}throw Error(`url must be either a 'File', 'string', 'function', or 'Promise'. Actual type: ${i}`)}async _loadURL(e,t){const i=this,r=e;e=function(e){return e.startsWith("https://www.dropbox.com")?e.replace("//www.dropbox.com","//dl.dropboxusercontent.com"):e.startsWith("https://drive.google.com")?Ir(e):e.includes("//www.broadinstitute.org/igvdata")?e.replace("//www.broadinstitute.org/igvdata","//data.broadinstitute.org/igvdata"):e.includes("//igvdata.broadinstitute.org")?e.replace("//igvdata.broadinstitute.org","//s3.amazonaws.com/igv.broadinstitute.org"):e.includes("//igv.genepattern.org")?e.replace("//igv.genepattern.org","//igv-genepattern-org.s3.amazonaws.com"):e.startsWith("ftp://ftp.ncbi.nlm.nih.gov/geo")?e.replace("ftp://","https://"):e}(e);let s=(t=t||{}).oauthToken||this.getOauthToken(e);return s&&(s=await("function"==typeof s?s():s)),new Promise((function(o,n){br(e)&&!function(e){return e.indexOf("X-Goog-Signature")>-1}(e)&&(Fr(e)&&(e=yr(e)),vr(e=function(e){let t=Rr.apiKey;t||"undefined"==typeof gapi||(t=gapi.apiKey);if(void 0!==t&&!e.includes("key=")){const i=e.includes("?")?"&":"?";e=e+i+"key="+t}return e}(e))&&function(e){if(e.includes("supportsTeamDrive"))return e;{const t=e.includes("?")?"&":"?";e=e+t+"supportsTeamDrive=true"}}(e),s||(s=Nr()));const a=t.headers||{};s&&function(e,t){t&&(e["Cache-Control"]="no-cache",e.Authorization="Bearer "+t)}(a,s);const c=t.range,l=new XMLHttpRequest,h=t.sendData||t.body,d=t.method||(h?"POST":"GET"),u=t.responseType,f=t.contentType,p=t.mimeType;if(l.open(d,e),t.timeout&&(l.timeout=t.timeout),c){let e="";c.size&&(e=c.start+c.size-1),l.setRequestHeader("Range","bytes="+c.start+"-"+e)}if(f&&l.setRequestHeader("Content-Type",f),p&&l.overrideMimeType(p),u&&(l.responseType=u),a)for(let e of Object.keys(a)){const t=a[e];l.setRequestHeader(e,t)}!0===t.withCredentials&&(l.withCredentials=!0),l.onload=async function(r){if(0===l.status||l.status>=200&&l.status<=300)if("HEAD"===t.method){const e=t.requestedHeaders||["content-length"],i={};for(let t of e)i[t]=l.getResponseHeader(t);o(i)}else c&&206!==l.status&&0!==c.start?(l.response.length>1e5&&!i.RANGE_WARNING_GIVEN&&alert(`Warning: Range header ignored for URL: ${e}. This can have severe performance impacts.`),o(l.response.slice(c.start,c.start+c.size))):o(l.response);else 416===l.status?g(Error("416 Unsatisfiable Range")):!Cr()||404!==l.status&&401!==l.status&&403!==l.status||!br(e)||t.retries?403===l.status?g("Access forbidden: "+e):g(l.status):m()},l.onerror=function(i){br(e)&&!t.retries?m():g("Error accessing resource: "+e+" Status: "+l.status)},l.ontimeout=function(e){g("Timed out")},l.onabort=function(e){console.log("Aborted"),n(e)};try{l.send(h)}catch(i){br(e)&&!t.retries?m():g(i)}function g(e){if(!n)throw e;n(e)}async function m(){try{const e=await async function(e){if(Cr()){const t=function(e){return vr(e)?"https://www.googleapis.com/auth/drive.file":Fr(e)?"https://www.googleapis.com/auth/devstorage.read_only":"https://www.googleapis.com/auth/userinfo.profile"}(e);return await xr(t)}throw Error("Authorization is required, but Google oAuth has not been initalized. Contact your site administrator for assistance.")}(r);t.retries=1,t.oauthToken=e;const s=await i.load(r,t);o(s)}catch(e){if(e.error){const t=e.error.startsWith("popup_blocked")?"Google login popup blocked by browser.":e.error;alert(t)}else g(e)}}}))}async _loadFileSlice(e,t){let i=t&&t.range?await e.slice(t.range.start,t.range.start+t.range.size):e;const r=await i.arrayBuffer();return"arraybuffer"===t.responseType?r:Mr(r)}async _loadStringFromFile(e,t){const i=t.range?e.slice(t.range.start,t.range.start+t.range.size):e;return Mr(await i.arrayBuffer())}async _loadStringFromUrl(e,t){(t=t||{}).responseType="arraybuffer";return Mr(await this.load(e,t))}setOauthToken(e,t){this.oauth.setToken(e,t)}getOauthToken(e){const t=br(e)?void 0:I(e).host;let i=this.oauth.getToken(t);if(i)return i;if(void 0===t){const e=Nr();if(e&&e.expires_at>Date.now())return e.access_token}}async getContentLength(e,t){(t=t||{}).method="HEAD",t.requestedHeaders=["content-length"];const i=(await this._loadURL(e,t))["content-length"];return i?Number.parseInt(i):0}};var Br={color:1};Br.parent=Br,Br.left=Br,Br.right=Br;class Dr{constructor(){this.root=Br}insert(e,t,i){var r=new Or(new Hr(e,t,i));for(this.treeInsert(r),r.color=2;r!==this.root&&2===r.parent.color;)if(r.parent===r.parent.parent.left){let e=r.parent.parent.right;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.right&&(r=r.parent,Tr.call(this,r)),r.parent.color=1,r.parent.parent.color=2,zr.call(this,r.parent.parent))}else{let e=r.parent.parent.left;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.left&&(r=r.parent,zr.call(this,r)),r.parent.color=1,r.parent.parent.color=2,Tr.call(this,r.parent.parent))}this.root.color=1}findOverlapping(e,t){var i=new Hr(e,t,0);if(this.root===Br)return[];var r=Lr.call(this,i,this.root,[]);return r.length>1&&r.sort((function(e,t){return e.low-t.low})),r}logIntervals(){!function e(t,i){for(var r="",s=0;s=e.low&&Lr.call(this,e,t.left,i),t.right!==Br&&t.right.min<=e.high&&Lr.call(this,e,t.right,i),i}function Tr(e){var t=e.right;e.right=t.left,t.left!==Br&&(t.left.parent=e),t.parent=e.parent,e.parent===Br?this.root=t:e.parent.left===e?e.parent.left=t:e.parent.right=t,t.left=e,e.parent=t,Pr.call(this,e)}function zr(e){var t=e.left;e.left=t.right,t.right!==Br&&(t.right.parent=e),t.parent=e.parent,e.parent===Br?this.root=t:e.parent.right===e?e.parent.right=t:e.parent.left=t,t.right=e,e.parent=t,Pr.call(this,e)}function Pr(e){for(;e!==Br;){var t=e.left.max>e.right.max?e.left.max:e.right.max,i=e.interval.high;e.max=t>i?t:i;var r=e.left.mine.low?1:this.highe.high?1:0}overlaps(e){return this.low<=e.high&&e.low<=this.high}}function Or(e){this.parent=Br,this.left=Br,this.right=Br,this.interval=e,this.color=2}const Vr=function(e,t,i){if(e&&0!==e.length){const r=function(e){const t=new Dr,i=e.length,r=Math.max(10,Math.round(i/100));e.sort((function(e,t){return e.start===t.start?0:e.start>t.start?1:-1}));for(let s=0;si)break;o.end>t&&e.push(o)}})),e.sort((function(e,t){return e.start-t.start})),e)}return[]};function qr(e){if(3===(e=e.replace(/^#/,"")).length&&(e=e.split("").map((e=>e+e)).join("")),6!==e.length)throw new Error("Invalid HEX color.");let t=parseInt(e,16);return`rgb(${t>>16&255}, ${t>>8&255}, ${255&t})`}const Ur={licorice:"#000000",steel:"#6e6e6e",magnesium:"#b8b8b8",mercury:"#e8e8e8",cayenne:"#891100",mocha:"#894800",aspargus:"#888501",fern:"#458401",teal:"#008688",salmon:"#ff726e",tangerine:"#ff8802",cantaloupe:"#ffce6e",lemon:"#fffa03",lime:"#83f902",honeydew:"#cefa6e",ice:"#68fdff",aqua:"#008cff",blueberry:"#002eff",midnight:"#001888",grape:"#8931ff",lavender:"#d278ff",orchid:"#6e76ff",strawberry:"#ff2987",magenta:"#ff39ff",carnation:"#ff7fd3"},Qr={cantaloupe:{r:255,g:206,b:110},honeydew:{r:206,g:250,b:110},spindrift:{r:104,g:251,b:208},sky:{r:106,g:207,b:255},lavender:{r:210,g:120,b:255},carnation:{r:255,g:127,b:211},licorice:{r:0,g:0,b:0},snow:{r:255,g:255,b:255},salmon:{r:255,g:114,b:110},banana:{r:255,g:251,b:109},flora:{r:104,g:249,b:110},ice:{r:104,g:253,b:255},orchid:{r:110,g:118,b:255},bubblegum:{r:255,g:122,b:255},lead:{r:30,g:30,b:30},mercury:{r:232,g:232,b:232},tangerine:{r:255,g:136,b:2},lime:{r:131,g:249,b:2},sea_foam:{r:3,g:249,b:135},aqua:{r:0,g:140,b:255},grape:{r:137,g:49,b:255},strawberry:{r:255,g:41,b:135},tungsten:{r:58,g:58,b:58},silver:{r:208,g:208,b:208},maraschino:{r:255,g:33,b:1},lemon:{r:255,g:250,b:3},spring:{r:5,g:248,b:2},turquoise:{r:0,g:253,b:255},blueberry:{r:0,g:46,b:255},magenta:{r:255,g:57,b:255},iron:{r:84,g:84,b:83},magnesium:{r:184,g:184,b:184},mocha:{r:137,g:72,b:0},fern:{r:69,g:132,b:1},moss:{r:1,g:132,b:72},ocean:{r:0,g:74,b:136},eggplant:{r:73,g:26,b:136},maroon:{r:137,g:22,b:72},steel:{r:110,g:110,b:110},aluminum:{r:160,g:159,b:160},cayenne:{r:137,g:17,b:0},aspargus:{r:136,g:133,b:1},clover:{r:2,g:132,b:1},teal:{r:0,g:134,b:136},midnight:{r:0,g:24,b:136},plum:{r:137,g:30,b:136},tin:{r:135,g:134,b:135},nickel:{r:136,g:135,b:135}};function Gr(e){const{r:t,g:i,b:r}=Qr[e];return`rgb(${t},${i},${r})`}const jr={Set1:["rgb(228,26,28)","rgb(55,126,184)","rgb(77,175,74)","rgb(166,86,40)","rgb(152,78,163)","rgb(255,127,0)","rgb(247,129,191)","rgb(153,153,153)","rgb(255,255,51)"],Dark2:["rgb(27,158,119)","rgb(217,95,2)","rgb(117,112,179)","rgb(231,41,138)","rgb(102,166,30)","rgb(230,171,2)","rgb(166,118,29)","rgb(102,102,102)"],Set2:["rgb(102, 194,165)","rgb(252,141,98)","rgb(141,160,203)","rgb(231,138,195)","rgb(166,216,84)","rgb(255,217,47)","rgb(229,196,148)","rgb(179,179,179)"],Set3:["rgb(141,211,199)","rgb(255,255,179)","rgb(190,186,218)","rgb(251,128,114)","rgb(128,177,211)","rgb(253,180,98)","rgb(179,222,105)","rgb(252,205,229)","rgb(217,217,217)","rgb(188,128,189)","rgb(204,235,197)","rgb(255,237,111)"],Pastel1:["rgb(251,180,174)","rgb(179,205,227)","rgb(204,235,197)","rgb(222,203,228)","rgb(254,217,166)","rgb(255,255,204)","rgb(229,216,189)","rgb(253,218,236)"],Pastel2:["rgb(173,226,207)","rgb(253,205,172)","rgb(203,213,232)","rgb(244,202,228)","rgb(230,245,201)","rgb(255,242,174)","rgb(243,225,206)"],Accent:["rgb(127,201,127)","rgb(190,174,212)","rgb(253,192,134)","rgb(255,255,153)","rgb(56,108,176)","rgb(240,2,127)","rgb(191,91,23)"]};class Wr{constructor(e){this.colors=jr[e],Array.isArray(this.colors)||(this.colors=[]),this.colorTable=new Map,this.nextIdx=0,this.colorGenerator=new Kr}getColor(e){return this.colorTable.has(e)||(this.nextIdxparseInt(e)))}}Kr.prototype.hsvToRgb=function(e,t,i){var r=Math.floor(6*e),s=6*e-r,o=i*(1-t),n=i*(1-s*t),a=i*(1-(1-s)*t),c=255,l=255,h=255;switch(r){case 0:c=i,l=a,h=o;break;case 1:c=n,l=i,h=o;break;case 2:c=o,l=i,h=a;break;case 3:c=o,l=n,h=i;break;case 4:c=a,l=o,h=i;break;case 5:c=i,l=o,h=n}return[Math.floor(256*c),Math.floor(256*l),Math.floor(256*h)]},Kr.prototype.padHex=function(e){return e.length>this.hexwidth?e:new Array(this.hexwidth-e.length+1).join("0")+e},Kr.prototype.get=function(e,t){this.hue+=this.goldenRatio,this.hue%=1,"number"!=typeof e&&(e=.5),"number"!=typeof t&&(t=.95);var i=this.hsvToRgb(this.hue,e,t);return"#"+this.padHex(i[0].toString(16))+this.padHex(i[1].toString(16))+this.padHex(i[2].toString(16))},new Kr;function Jr(e,t,i){if(i<.005)return e;if(i>.995)return t;{let r,s,o,n,a,c;i<.5?(i/=.5,[r,s,o]=Xr(e),[n,a,c]=Xr(Gr("snow"))):(i=(i-.5)/.5,[r,s,o]=Xr(Gr("snow")),[n,a,c]=Xr(t));const[l,h,d]=[Math.floor(ar(r,n,i)),Math.floor(ar(s,a,i)),Math.floor(ar(o,c,i))];return function(e,t,i){return`rgb(${e=cr(e,0,255)}, ${t=cr(t,0,255)}, ${i=cr(i,0,255)})`}(l,h,d)}}function es(e){const t=new Set(["boolean","number","string","symbol"]),i=typeof e;return void 0!==e&&(t.has(i)||e.substring||e.toFixed)}function ts(e,t){var i={oauthToken:e.oauthToken,headers:e.headers,withCredentials:e.withCredentials,filename:e.filename};return Object.assign(i,t)}const is=function(e){var t,i;if(e&&e.length>0){t=Number.MAX_VALUE,i=-Number.MAX_VALUE;for(let r of e)Number.isNaN(r.value)||(t=Math.min(t,r.value),i=Math.max(i,r.value));i>0&&(t=Math.min(0,t)),i<0&&(i=0)}else t=0,i=100;return{min:t,max:i}},rs=function(e,t,i){let r=t.start,s=t.end;if(void 0===s)r-=i/2,s=r+i,s>e?(s=e,r=s-i):r<0&&(r=0,s=i);else if(s-re?(s=e,r=s-i):(r=t-i/2,s=r+i)}t.start=Math.ceil(r),t.end=Math.floor(s)},ss=function(e){return"number"==typeof e?e-e===0:"string"==typeof e&&""!==e.trim()&&Number.isFinite(+e)};async function os(e){if(b(e)&&e.startsWith("https://drive.google.com")){if(void 0===kr())throw Error("Google drive is referenced, but API key is not defined. An API key is required for Google Drive access");const t=await async function(e){let t="https://www.googleapis.com/drive/v3/files/"+Sr(e)+"?supportsTeamDrives=true";const i=kr();i&&(t+="&key="+i);const r=await fetch(t);let s=await r.json();if(s.error&&404===s.error.code){let e="https://www.googleapis.com/auth/drive.readonly";const i=await xr(e);if(!i)throw Error(s.error);{const e=await fetch(t,{headers:{Authorization:`Bearer ${i}`}});if(s=await e.json(),s.error)throw Error(s.error)}}return s}(e);return t.originalFileName||t.name}return _(e)}function ns(e){var t,i;return e>1e7?(t=" mb",i=e/1e6,Math.floor(i).toString()+t):e>1e4?(t=" kb",i=e/1e3,F(Math.floor(i))+t):F(e)+" bp"}function as(e){return b(e)&&e.startsWith("data:")}function cs(e,i){const r=t({class:i});return e.appendChild(r),r}function ls(e,t){t.parentNode.insertBefore(e,t)}function hs(e,t){t.parentNode.insertBefore(e,t.nextSibling)}function ds(){return"https:"===window.location.protocol||"localhost"===window.location.hostname}class us{constructor(e,i,r,s){this.parent=e,this.popover=t({class:"igv-ui-popover"}),e.appendChild(this.popover),this.popoverHeader=t(),this.popover.appendChild(this.popoverHeader);const o=t();this.popoverHeader.appendChild(o),r&&(o.textContent=r);const n=t();this.popoverHeader.appendChild(n),n.appendChild(l("times")),n.addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault(),s?s():this.dismiss()})),!0===i&&p(this.popover,this.popoverHeader,{minX:0,minY:0}),this.popoverContent=t(),this.popover.appendChild(this.popoverContent),this.popover.style.display="none"}configure(e){if(0===e.length)return;const t=ps(e,this.popover);for(const{element:e}of t)this.popoverContent.appendChild(e)}present(e){this.popover.style.display="block";const t=this.popover.parentNode,{x:i,y:r,width:s}=a(e,t);this.popover.style.top=`${r}px`;const{width:o}=this.popover.getBoundingClientRect(),n=i+o,c=n-s;this.popover.style.left=`${n>s?i-c:i}px`,this.popoverContent.style.maxWidth=`${Math.min(o,s)}px`}presentContentWithEvent(e,t){this.popover.style.display="block",this.popoverContent.innerHTML=t,fs(e,this.popover,this.popoverContent)}presentMenu(e,t){if(0===t.length)return;this.popover.style.display="block";const i=ps(t,this.popover);for(let e of i)this.popoverContent.appendChild(e.element);fs(e,this.popover,this.popoverContent)}dismiss(){this.popover.style.display="none"}hide(){this.popover.style.display="none",this.dispose()}dispose(){this.popover&&this.popover.parentNode.removeChild(this.popover);const e=Object.keys(this);for(let t of e)this[t]=void 0}}function fs(e,t,i){const{x:r,y:s,width:o}=a(e,t.parentNode);t.style.top=`${s}px`;const{width:n}=t.getBoundingClientRect(),c=r+n,l=c-o;t.style.left=`${c>o?r-l:r}px`,i.style.maxWidth=`${Math.min(n,o)}px`}function ps(e,i){const s=e.map((function(e,s){let o;if("string"==typeof e)o=t(),o.innerHTML=e;else if("Node"==typeof e)o=e;else if("function"==typeof e.init&&e.init(),"checkbox"===e.type?o=function(e,i){const r=t({class:"igv-ui-trackgear-popover-check-container"}),s=h("check",!0===i?"#444":"transparent");s.style.borderColor="gray",s.style.borderWidth="1px",s.style.borderStyle="solid",r.appendChild(s);let o=t();return o.textContent=e,r.appendChild(o),r}("Show all bases",e.value):(o=t(),"string"==typeof e.label&&(o.innerHTML=e.label)),e.click&&"color"!==e.type){function n(t){e.click(),r(i),t.preventDefault(),t.stopPropagation()}o.addEventListener("click",n),o.addEventListener("touchend",n),o.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}return{element:o,init:e.init}}));return s} +/*! @license DOMPurify 3.2.5 | (c) Cure53 and other contributors | Released under the Apache license 2.0 and Mozilla Public License 2.0 | github.com/cure53/DOMPurify/blob/3.2.5/LICENSE */const{entries:gs,setPrototypeOf:ms,isFrozen:ws,getPrototypeOf:bs,getOwnPropertyDescriptor:Fs}=Object;let{freeze:vs,seal:ys,create:As}=Object,{apply:Cs,construct:_s}="undefined"!=typeof Reflect&&Reflect;vs||(vs=function(e){return e}),ys||(ys=function(e){return e}),Cs||(Cs=function(e,t,i){return e.apply(t,i)}),_s||(_s=function(e,t){return new e(...t)});const xs=Os(Array.prototype.forEach),ks=Os(Array.prototype.lastIndexOf),Is=Os(Array.prototype.pop),Ss=Os(Array.prototype.push),Es=Os(Array.prototype.splice),Ns=Os(String.prototype.toLowerCase),Ms=Os(String.prototype.toString),Rs=Os(String.prototype.match),Bs=Os(String.prototype.replace),Ds=Os(String.prototype.indexOf),Ls=Os(String.prototype.trim),Ts=Os(Object.prototype.hasOwnProperty),zs=Os(RegExp.prototype.test),Ps=(Hs=TypeError,function(){for(var e=arguments.length,t=new Array(e),i=0;i1?i-1:0),s=1;s2&&void 0!==arguments[2]?arguments[2]:Ns;ms&&ms(e,null);let r=t.length;for(;r--;){let s=t[r];if("string"==typeof s){const e=i(s);e!==s&&(ws(t)||(t[r]=e),s=e)}e[s]=!0}return e}function qs(e){for(let t=0;t/gm),so=ys(/\$\{[\w\W]*/gm),oo=ys(/^data-[\-\w.\u00B7-\uFFFF]+$/),no=ys(/^aria-[\-\w]+$/),ao=ys(/^(?:(?:(?:f|ht)tps?|mailto|tel|callto|sms|cid|xmpp):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i),co=ys(/^(?:\w+script|data):/i),lo=ys(/[\u0000-\u0020\u00A0\u1680\u180E\u2000-\u2029\u205F\u3000]/g),ho=ys(/^html$/i),uo=ys(/^[a-z][.\w]*(-[.\w]+)+$/i);var fo=Object.freeze({__proto__:null,ARIA_ATTR:no,ATTR_WHITESPACE:lo,CUSTOM_ELEMENT:uo,DATA_ATTR:oo,DOCTYPE_NAME:ho,ERB_EXPR:ro,IS_ALLOWED_URI:ao,IS_SCRIPT_OR_DATA:co,MUSTACHE_EXPR:io,TMPLIT_EXPR:so});const po=1,go=3,mo=7,wo=8,bo=9,Fo=function(){return"undefined"==typeof window?null:window};var vo=function e(){let t=arguments.length>0&&void 0!==arguments[0]?arguments[0]:Fo();const i=t=>e(t);if(i.version="3.2.5",i.removed=[],!t||!t.document||t.document.nodeType!==bo||!t.Element)return i.isSupported=!1,i;let{document:r}=t;const s=r,o=s.currentScript,{DocumentFragment:n,HTMLTemplateElement:a,Node:c,Element:l,NodeFilter:h,NamedNodeMap:d=t.NamedNodeMap||t.MozNamedAttrMap,HTMLFormElement:u,DOMParser:f,trustedTypes:p}=t,g=l.prototype,m=Qs(g,"cloneNode"),w=Qs(g,"remove"),b=Qs(g,"nextSibling"),F=Qs(g,"childNodes"),v=Qs(g,"parentNode");if("function"==typeof a){const e=r.createElement("template");e.content&&e.content.ownerDocument&&(r=e.content.ownerDocument)}let y,A="";const{implementation:C,createNodeIterator:_,createDocumentFragment:x,getElementsByTagName:k}=r,{importNode:I}=s;let S={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]};i.isSupported="function"==typeof gs&&"function"==typeof v&&C&&void 0!==C.createHTMLDocument;const{MUSTACHE_EXPR:E,ERB_EXPR:N,TMPLIT_EXPR:M,DATA_ATTR:R,ARIA_ATTR:B,IS_SCRIPT_OR_DATA:D,ATTR_WHITESPACE:L,CUSTOM_ELEMENT:T}=fo;let{IS_ALLOWED_URI:z}=fo,P=null;const H=Vs({},[...Gs,...js,...Ws,...Ks,...Zs]);let O=null;const V=Vs({},[...Xs,...Js,...eo,...to]);let q=Object.seal(As(null,{tagNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},attributeNameCheck:{writable:!0,configurable:!1,enumerable:!0,value:null},allowCustomizedBuiltInElements:{writable:!0,configurable:!1,enumerable:!0,value:!1}})),U=null,Q=null,G=!0,j=!0,W=!1,$=!0,K=!1,Y=!0,Z=!1,X=!1,J=!1,ee=!1,te=!1,ie=!1,re=!0,se=!1,oe=!0,ne=!1,ae={},ce=null;const le=Vs({},["annotation-xml","audio","colgroup","desc","foreignobject","head","iframe","math","mi","mn","mo","ms","mtext","noembed","noframes","noscript","plaintext","script","style","svg","template","thead","title","video","xmp"]);let he=null;const de=Vs({},["audio","video","img","source","image","track"]);let ue=null;const fe=Vs({},["alt","class","for","id","label","name","pattern","placeholder","role","summary","title","value","style","xmlns"]),pe="http://www.w3.org/1998/Math/MathML",ge="http://www.w3.org/2000/svg",me="http://www.w3.org/1999/xhtml";let we=me,be=!1,Fe=null;const ve=Vs({},[pe,ge,me],Ms);let ye=Vs({},["mi","mo","mn","ms","mtext"]),Ae=Vs({},["annotation-xml"]);const Ce=Vs({},["title","style","font","a","script"]);let _e=null;const xe=["application/xhtml+xml","text/html"];let ke=null,Ie=null;const Se=r.createElement("form"),Ee=function(e){return e instanceof RegExp||e instanceof Function},Ne=function(){let e=arguments.length>0&&void 0!==arguments[0]?arguments[0]:{};if(!Ie||Ie!==e){if(e&&"object"==typeof e||(e={}),e=Us(e),_e=-1===xe.indexOf(e.PARSER_MEDIA_TYPE)?"text/html":e.PARSER_MEDIA_TYPE,ke="application/xhtml+xml"===_e?Ms:Ns,P=Ts(e,"ALLOWED_TAGS")?Vs({},e.ALLOWED_TAGS,ke):H,O=Ts(e,"ALLOWED_ATTR")?Vs({},e.ALLOWED_ATTR,ke):V,Fe=Ts(e,"ALLOWED_NAMESPACES")?Vs({},e.ALLOWED_NAMESPACES,Ms):ve,ue=Ts(e,"ADD_URI_SAFE_ATTR")?Vs(Us(fe),e.ADD_URI_SAFE_ATTR,ke):fe,he=Ts(e,"ADD_DATA_URI_TAGS")?Vs(Us(de),e.ADD_DATA_URI_TAGS,ke):de,ce=Ts(e,"FORBID_CONTENTS")?Vs({},e.FORBID_CONTENTS,ke):le,U=Ts(e,"FORBID_TAGS")?Vs({},e.FORBID_TAGS,ke):{},Q=Ts(e,"FORBID_ATTR")?Vs({},e.FORBID_ATTR,ke):{},ae=!!Ts(e,"USE_PROFILES")&&e.USE_PROFILES,G=!1!==e.ALLOW_ARIA_ATTR,j=!1!==e.ALLOW_DATA_ATTR,W=e.ALLOW_UNKNOWN_PROTOCOLS||!1,$=!1!==e.ALLOW_SELF_CLOSE_IN_ATTR,K=e.SAFE_FOR_TEMPLATES||!1,Y=!1!==e.SAFE_FOR_XML,Z=e.WHOLE_DOCUMENT||!1,ee=e.RETURN_DOM||!1,te=e.RETURN_DOM_FRAGMENT||!1,ie=e.RETURN_TRUSTED_TYPE||!1,J=e.FORCE_BODY||!1,re=!1!==e.SANITIZE_DOM,se=e.SANITIZE_NAMED_PROPS||!1,oe=!1!==e.KEEP_CONTENT,ne=e.IN_PLACE||!1,z=e.ALLOWED_URI_REGEXP||ao,we=e.NAMESPACE||me,ye=e.MATHML_TEXT_INTEGRATION_POINTS||ye,Ae=e.HTML_INTEGRATION_POINTS||Ae,q=e.CUSTOM_ELEMENT_HANDLING||{},e.CUSTOM_ELEMENT_HANDLING&&Ee(e.CUSTOM_ELEMENT_HANDLING.tagNameCheck)&&(q.tagNameCheck=e.CUSTOM_ELEMENT_HANDLING.tagNameCheck),e.CUSTOM_ELEMENT_HANDLING&&Ee(e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck)&&(q.attributeNameCheck=e.CUSTOM_ELEMENT_HANDLING.attributeNameCheck),e.CUSTOM_ELEMENT_HANDLING&&"boolean"==typeof e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements&&(q.allowCustomizedBuiltInElements=e.CUSTOM_ELEMENT_HANDLING.allowCustomizedBuiltInElements),K&&(j=!1),te&&(ee=!0),ae&&(P=Vs({},Zs),O=[],!0===ae.html&&(Vs(P,Gs),Vs(O,Xs)),!0===ae.svg&&(Vs(P,js),Vs(O,Js),Vs(O,to)),!0===ae.svgFilters&&(Vs(P,Ws),Vs(O,Js),Vs(O,to)),!0===ae.mathMl&&(Vs(P,Ks),Vs(O,eo),Vs(O,to))),e.ADD_TAGS&&(P===H&&(P=Us(P)),Vs(P,e.ADD_TAGS,ke)),e.ADD_ATTR&&(O===V&&(O=Us(O)),Vs(O,e.ADD_ATTR,ke)),e.ADD_URI_SAFE_ATTR&&Vs(ue,e.ADD_URI_SAFE_ATTR,ke),e.FORBID_CONTENTS&&(ce===le&&(ce=Us(ce)),Vs(ce,e.FORBID_CONTENTS,ke)),oe&&(P["#text"]=!0),Z&&Vs(P,["html","head","body"]),P.table&&(Vs(P,["tbody"]),delete U.tbody),e.TRUSTED_TYPES_POLICY){if("function"!=typeof e.TRUSTED_TYPES_POLICY.createHTML)throw Ps('TRUSTED_TYPES_POLICY configuration option must provide a "createHTML" hook.');if("function"!=typeof e.TRUSTED_TYPES_POLICY.createScriptURL)throw Ps('TRUSTED_TYPES_POLICY configuration option must provide a "createScriptURL" hook.');y=e.TRUSTED_TYPES_POLICY,A=y.createHTML("")}else void 0===y&&(y=function(e,t){if("object"!=typeof e||"function"!=typeof e.createPolicy)return null;let i=null;const r="data-tt-policy-suffix";t&&t.hasAttribute(r)&&(i=t.getAttribute(r));const s="dompurify"+(i?"#"+i:"");try{return e.createPolicy(s,{createHTML:e=>e,createScriptURL:e=>e})}catch(e){return console.warn("TrustedTypes policy "+s+" could not be created."),null}}(p,o)),null!==y&&"string"==typeof A&&(A=y.createHTML(""));vs&&vs(e),Ie=e}},Me=Vs({},[...js,...Ws,...$s]),Re=Vs({},[...Ks,...Ys]),Be=function(e){Ss(i.removed,{element:e});try{v(e).removeChild(e)}catch(t){w(e)}},De=function(e,t){try{Ss(i.removed,{attribute:t.getAttributeNode(e),from:t})}catch(e){Ss(i.removed,{attribute:null,from:t})}if(t.removeAttribute(e),"is"===e)if(ee||te)try{Be(t)}catch(e){}else try{t.setAttribute(e,"")}catch(e){}},Le=function(e){let t=null,i=null;if(J)e=""+e;else{const t=Rs(e,/^[\r\n\t ]+/);i=t&&t[0]}"application/xhtml+xml"===_e&&we===me&&(e=''+e+"");const s=y?y.createHTML(e):e;if(we===me)try{t=(new f).parseFromString(s,_e)}catch(e){}if(!t||!t.documentElement){t=C.createDocument(we,"template",null);try{t.documentElement.innerHTML=be?A:s}catch(e){}}const o=t.body||t.documentElement;return e&&i&&o.insertBefore(r.createTextNode(i),o.childNodes[0]||null),we===me?k.call(t,Z?"html":"body")[0]:Z?t.documentElement:o},Te=function(e){return _.call(e.ownerDocument||e,e,h.SHOW_ELEMENT|h.SHOW_COMMENT|h.SHOW_TEXT|h.SHOW_PROCESSING_INSTRUCTION|h.SHOW_CDATA_SECTION,null)},ze=function(e){return e instanceof u&&("string"!=typeof e.nodeName||"string"!=typeof e.textContent||"function"!=typeof e.removeChild||!(e.attributes instanceof d)||"function"!=typeof e.removeAttribute||"function"!=typeof e.setAttribute||"string"!=typeof e.namespaceURI||"function"!=typeof e.insertBefore||"function"!=typeof e.hasChildNodes)},Pe=function(e){return"function"==typeof c&&e instanceof c};function He(e,t,r){xs(e,(e=>{e.call(i,t,r,Ie)}))}const Oe=function(e){let t=null;if(He(S.beforeSanitizeElements,e,null),ze(e))return Be(e),!0;const r=ke(e.nodeName);if(He(S.uponSanitizeElement,e,{tagName:r,allowedTags:P}),e.hasChildNodes()&&!Pe(e.firstElementChild)&&zs(/<[/\w!]/g,e.innerHTML)&&zs(/<[/\w!]/g,e.textContent))return Be(e),!0;if(e.nodeType===mo)return Be(e),!0;if(Y&&e.nodeType===wo&&zs(/<[/\w]/g,e.data))return Be(e),!0;if(!P[r]||U[r]){if(!U[r]&&qe(r)){if(q.tagNameCheck instanceof RegExp&&zs(q.tagNameCheck,r))return!1;if(q.tagNameCheck instanceof Function&&q.tagNameCheck(r))return!1}if(oe&&!ce[r]){const t=v(e)||e.parentNode,i=F(e)||e.childNodes;if(i&&t){for(let r=i.length-1;r>=0;--r){const s=m(i[r],!0);s.__removalCount=(e.__removalCount||0)+1,t.insertBefore(s,b(e))}}}return Be(e),!0}return e instanceof l&&!function(e){let t=v(e);t&&t.tagName||(t={namespaceURI:we,tagName:"template"});const i=Ns(e.tagName),r=Ns(t.tagName);return!!Fe[e.namespaceURI]&&(e.namespaceURI===ge?t.namespaceURI===me?"svg"===i:t.namespaceURI===pe?"svg"===i&&("annotation-xml"===r||ye[r]):Boolean(Me[i]):e.namespaceURI===pe?t.namespaceURI===me?"math"===i:t.namespaceURI===ge?"math"===i&&Ae[r]:Boolean(Re[i]):e.namespaceURI===me?!(t.namespaceURI===ge&&!Ae[r])&&!(t.namespaceURI===pe&&!ye[r])&&!Re[i]&&(Ce[i]||!Me[i]):!("application/xhtml+xml"!==_e||!Fe[e.namespaceURI]))}(e)?(Be(e),!0):"noscript"!==r&&"noembed"!==r&&"noframes"!==r||!zs(/<\/no(script|embed|frames)/i,e.innerHTML)?(K&&e.nodeType===go&&(t=e.textContent,xs([E,N,M],(e=>{t=Bs(t,e," ")})),e.textContent!==t&&(Ss(i.removed,{element:e.cloneNode()}),e.textContent=t)),He(S.afterSanitizeElements,e,null),!1):(Be(e),!0)},Ve=function(e,t,i){if(re&&("id"===t||"name"===t)&&(i in r||i in Se))return!1;if(j&&!Q[t]&&zs(R,t));else if(G&&zs(B,t));else if(!O[t]||Q[t]){if(!(qe(e)&&(q.tagNameCheck instanceof RegExp&&zs(q.tagNameCheck,e)||q.tagNameCheck instanceof Function&&q.tagNameCheck(e))&&(q.attributeNameCheck instanceof RegExp&&zs(q.attributeNameCheck,t)||q.attributeNameCheck instanceof Function&&q.attributeNameCheck(t))||"is"===t&&q.allowCustomizedBuiltInElements&&(q.tagNameCheck instanceof RegExp&&zs(q.tagNameCheck,i)||q.tagNameCheck instanceof Function&&q.tagNameCheck(i))))return!1}else if(ue[t]);else if(zs(z,Bs(i,L,"")));else if("src"!==t&&"xlink:href"!==t&&"href"!==t||"script"===e||0!==Ds(i,"data:")||!he[e]){if(W&&!zs(D,Bs(i,L,"")));else if(i)return!1}else;return!0},qe=function(e){return"annotation-xml"!==e&&Rs(e,T)},Ue=function(e){He(S.beforeSanitizeAttributes,e,null);const{attributes:t}=e;if(!t||ze(e))return;const r={attrName:"",attrValue:"",keepAttr:!0,allowedAttributes:O,forceKeepAttr:void 0};let s=t.length;for(;s--;){const o=t[s],{name:n,namespaceURI:a,value:c}=o,l=ke(n);let h="value"===n?c:Ls(c);if(r.attrName=l,r.attrValue=h,r.keepAttr=!0,r.forceKeepAttr=void 0,He(S.uponSanitizeAttribute,e,r),h=r.attrValue,!se||"id"!==l&&"name"!==l||(De(n,e),h="user-content-"+h),Y&&zs(/((--!?|])>)|<\/(style|title)/i,h)){De(n,e);continue}if(r.forceKeepAttr)continue;if(De(n,e),!r.keepAttr)continue;if(!$&&zs(/\/>/i,h)){De(n,e);continue}K&&xs([E,N,M],(e=>{h=Bs(h,e," ")}));const d=ke(e.nodeName);if(Ve(d,l,h)){if(y&&"object"==typeof p&&"function"==typeof p.getAttributeType)if(a);else switch(p.getAttributeType(d,l)){case"TrustedHTML":h=y.createHTML(h);break;case"TrustedScriptURL":h=y.createScriptURL(h)}try{a?e.setAttributeNS(a,n,h):e.setAttribute(n,h),ze(e)?Be(e):Is(i.removed)}catch(e){}}}He(S.afterSanitizeAttributes,e,null)},Qe=function e(t){let i=null;const r=Te(t);for(He(S.beforeSanitizeShadowDOM,t,null);i=r.nextNode();)He(S.uponSanitizeShadowNode,i,null),Oe(i),Ue(i),i.content instanceof n&&e(i.content);He(S.afterSanitizeShadowDOM,t,null)};return i.sanitize=function(e){let t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{},r=null,o=null,a=null,l=null;if(be=!e,be&&(e="\x3c!--\x3e"),"string"!=typeof e&&!Pe(e)){if("function"!=typeof e.toString)throw Ps("toString is not a function");if("string"!=typeof(e=e.toString()))throw Ps("dirty is not a string, aborting")}if(!i.isSupported)return e;if(X||Ne(t),i.removed=[],"string"==typeof e&&(ne=!1),ne){if(e.nodeName){const t=ke(e.nodeName);if(!P[t]||U[t])throw Ps("root node is forbidden and cannot be sanitized in-place")}}else if(e instanceof c)r=Le("\x3c!----\x3e"),o=r.ownerDocument.importNode(e,!0),o.nodeType===po&&"BODY"===o.nodeName||"HTML"===o.nodeName?r=o:r.appendChild(o);else{if(!ee&&!K&&!Z&&-1===e.indexOf("<"))return y&&ie?y.createHTML(e):e;if(r=Le(e),!r)return ee?null:ie?A:""}r&&J&&Be(r.firstChild);const h=Te(ne?e:r);for(;a=h.nextNode();)Oe(a),Ue(a),a.content instanceof n&&Qe(a.content);if(ne)return e;if(ee){if(te)for(l=x.call(r.ownerDocument);r.firstChild;)l.appendChild(r.firstChild);else l=r;return(O.shadowroot||O.shadowrootmode)&&(l=I.call(s,l,!0)),l}let d=Z?r.outerHTML:r.innerHTML;return Z&&P["!doctype"]&&r.ownerDocument&&r.ownerDocument.doctype&&r.ownerDocument.doctype.name&&zs(ho,r.ownerDocument.doctype.name)&&(d="\n"+d),K&&xs([E,N,M],(e=>{d=Bs(d,e," ")})),y&&ie?y.createHTML(d):d},i.setConfig=function(){Ne(arguments.length>0&&void 0!==arguments[0]?arguments[0]:{}),X=!0},i.clearConfig=function(){Ie=null,X=!1},i.isValidAttribute=function(e,t,i){Ie||Ne({});const r=ke(e),s=ke(t);return Ve(r,s,i)},i.addHook=function(e,t){"function"==typeof t&&Ss(S[e],t)},i.removeHook=function(e,t){if(void 0!==t){const i=ks(S[e],t);return-1===i?void 0:Es(S[e],i,1)[0]}return Is(S[e])},i.removeHooks=function(e){S[e]=[]},i.removeAllHooks=function(){S={afterSanitizeAttributes:[],afterSanitizeElements:[],afterSanitizeShadowDOM:[],beforeSanitizeAttributes:[],beforeSanitizeElements:[],beforeSanitizeShadowDOM:[],uponSanitizeAttribute:[],uponSanitizeElement:[],uponSanitizeShadowNode:[]}},i}();const yo={401:"Access unauthorized",403:"Access forbidden",404:"Not found"};class Ao{constructor(e,t){this.alertProps=Object.assign({shouldFocus:!0,preventScroll:!1},t),this.container=document.createElement("div"),this.container.className="igv-ui-alert-dialog-container",e.appendChild(this.container),this.container.setAttribute("tabIndex","-1");const i=document.createElement("div");this.container.appendChild(i),this.errorHeadline=document.createElement("div"),i.appendChild(this.errorHeadline),this.errorHeadline.textContent="";let r=document.createElement("div");r.className="igv-ui-alert-dialog-body",this.container.appendChild(r),this.body=document.createElement("div"),this.body.className="igv-ui-alert-dialog-body-copy",r.appendChild(this.body);let s=document.createElement("div");this.container.appendChild(s),this.ok=document.createElement("div"),s.appendChild(this.ok),this.ok.textContent="OK";const o=()=>{"function"==typeof this.callback&&(this.callback("OK"),this.callback=void 0),this.body.innerHTML="",this.container.style.display="none"};this.ok.addEventListener("click",(e=>{e.stopPropagation(),o()})),this.container.addEventListener("keypress",(e=>{e.stopPropagation(),"Enter"===e.key&&o()})),p(this.container,i),this.container.style.display="none"}present(e,t){this.errorHeadline.textContent=e.message?"ERROR":"";let i=e.message||e;yo.hasOwnProperty(i)&&(i=yo[i]),this.body.innerHTML=vo.sanitize(i),this.callback=t,this.container.style.display="flex",this.alertProps.shouldFocus&&this.container.focus({preventScroll:this.alertProps.preventScroll})}}const Co={configureHighDPICanvas:function(e,t,i){const r=window.devicePixelRatio;e.canvas.style.width=`${t}px`,e.canvas.width=Math.floor(r*t),e.canvas.style.height=`${i}px`,e.canvas.height=Math.floor(r*i),e.scale(r,r)},setProperties:function(e,t){for(var i in t)if(t.hasOwnProperty(i)){var r=t[i];e[i]=r}},strokeLine:function(e,t,i,r,s,o){t=Math.floor(t)+.5,i=Math.floor(i)+.5,r=Math.floor(r)+.5,s=Math.floor(s)+.5,o&&(e.save(),Co.setProperties(e,o)),e.beginPath(),e.moveTo(t,i),e.lineTo(r,s),e.stroke(),o&&e.restore()},fillRect:function(e,t,i,r,s,o){o&&(e.save(),Co.setProperties(e,o)),e.fillRect(t,i,r,s),o&&e.restore()},fillPolygon:function(e,t,i,r){r&&(e.save(),Co.setProperties(e,r)),_o(e,t,i),e.fill(),r&&e.restore()},strokePolygon:function(e,t,i,r){r&&(e.save(),Co.setProperties(e,r)),_o(e,t,i),e.stroke(),r&&e.restore()},fillText:function(e,t,i,r,s,o){if((s||o)&&e.save(),s&&Co.setProperties(e,s),o){for(var n in e.translate(i,r),o){var a=o[n];"translate"===n&&e.translate(a.x,a.y),"rotate"===n&&e.rotate(a.angle*Math.PI/180)}e.fillText(t,0,0)}else e.fillText(t,i,r);(s||o)&&e.restore()},strokeText:function(e,t,i,r,s,o){if((s||o)&&e.save(),s&&Co.setProperties(e,s),o){for(var n in e.translate(i,r),o){var a=o[n];"translate"===n&&e.translate(a.x,a.y),"rotate"===n&&e.rotate(a.angle*Math.PI/180)}e.strokeText(t,0,0)}else e.strokeText(t,i,r);(s||o)&&e.restore()},strokeCircle:function(e,t,i,r,s){s&&(e.save(),Co.setProperties(e,s)),e.beginPath(),e.arc(t,i,r,0,2*Math.PI),e.stroke(),s&&e.restore()},fillCircle:function(e,t,i,r,s){s&&(e.save(),Co.setProperties(e,s)),e.beginPath(),e.arc(t,i,r,0,2*Math.PI),e.fill(),s&&e.restore()},drawArrowhead:function(e,t,i,r,s){e.save(),r||(r=5),s&&(e.lineWidth=s),e.beginPath(),e.moveTo(t,i-r/2),e.lineTo(t,i+r/2),e.lineTo(t+r,i),e.lineTo(t,i-r/2),e.closePath(),e.fill(),e.restore()},dashedLine:function(e,t,i,r,s,o,n={}){void 0===o&&(o=2),e.setLineDash([o,o]),Co.strokeLine(e,t,i,r,s,n),e.setLineDash([])},roundRect:function(e,t,i,r,s,o,n,a){void 0===a&&(a=!0),void 0===o&&(o=5),e.beginPath(),e.moveTo(t+o,i),e.lineTo(t+r-o,i),e.quadraticCurveTo(t+r,i,t+r,i+o),e.lineTo(t+r,i+s-o),e.quadraticCurveTo(t+r,i+s,t+r-o,i+s),e.lineTo(t+o,i+s),e.quadraticCurveTo(t,i+s,t,i+s-o),e.lineTo(t,i+o),e.quadraticCurveTo(t,i,t+o,i),e.closePath(),a&&e.stroke(),n&&e.fill()},polygon:function(e,t,i,r,s){void 0===s&&(s=!0),e.beginPath();var o=t.length;e.moveTo(t[0],i[0]);for(var n=1;n{for(let t=0;t{e.translate(t,0),e.scale(-1,1),e.translate(-t,0)}};function _o(e,t,i){var r,s=t.length;for(e.beginPath(),e.moveTo(t[0],i[0]),r=1;r0;){const r=e[i];t+=ko.has(r)?ko.get(r):r}return t}class No{constructor(e,t,i,r){this.name=e,this.order=t,this.bpLength=i,this.altNames=r}getAltName(e){return this.altNames&&this.altNames.has(e)?this.altNames.get(e):this.name}}class Mo{constructor(e,t,i,r){this.chr=e,this.start=t,this.end=i,this.features=r}contains(e,t,i){return this.chr===e&&this.start<=t&&this.end>=i}containsRange(e){return this.chr===e.chr&&this.start<=e.start&&this.end>=e.end}get locusString(){return`${this.chr}:${this.start+1}-${this.end}`}}class Ro extends Mo{constructor(e,t,i,r){super(e,t,i,r)}getSequence(e,t){if(ethis.end)return null;const i=e-this.start,r=t-e;return this.features?this.features.substring(i,i+r):null}hasSequence(e,t){return e>=this.start&&t<=this.end}}const Bo=v,Do=new Set(["fastaURL","indexURL","cytobandURL","indexed"]);class Lo{#e;chromosomes=new Map;sequences=new Map;constructor(e){this.fastaURL=e.fastaURL,this.withCredentials=e.withCredentials;const t={};for(let i in e)e.hasOwnProperty(i)&&!Do.has(i)&&(t[i]=e[i]);this.config=t}async init(){return this.loadAll()}getSequenceRecord(e){return this.chromosomes.get(e)}get chromosomeNames(){return this.#e||(this.#e=Array.from(this.chromosomes.keys())),this.#e}getFirstChromosomeName(){return this.chromosomeNames[0]}async getSequence(e,t,i){if(0===this.sequences.size&&await this.loadAll(),!this.sequences.has(e))return;let r=this.sequences.get(e).find((e=>e.contains(t,i)));if(!r&&(r=this.sequences.get(e).find((e=>e.overlaps(t,i))),!r))return;t-=r.offset,i-=r.offset;let s="";if(t<0)for(let e=t;e{const r=e.length||e.offset+e.seq.length;if(i.has(e.chr)){const t=this.chromosomes.get(e.chr);t.bpLength=Math.max(t.bpLength,r)}else this.sequences.set(e.chr,[]),this.chromosomes.set(e.chr,new No(e.chr,t,r)),i.add(e.chr);this.sequences.get(e.chr).push(new To(e.offset,e.seq))};let t;if(as(this.fastaURL)){let e=nr(this.fastaURL);t="";for(let i of e)t+=String.fromCharCode(i)}else t=await Rr.load(this.fastaURL,ts(this.config));const i=new Set,r=Bo(t);let s=0,o={};for(let t of r)if(t.startsWith("#")||0===t.length);else if(t.startsWith(">")){o.seq&&o.seq.length>0&&e(o,s++),o.seq="";const i=t.substr(1).split(/\s+/);if(t.includes("@len=")){const e=i[0].split(":");if(o.chr=e[0],e.length>1&&e[1].indexOf("-")>0){const r=e[1].split("-");2===r.length&&/^[0-9]+$/.test(r[0])&&/^[0-9]+$/.test(r[1]);const s=Number.parseInt(r[0]);if(Number.parseInt(r[1]),o.offset=s-1,i.length>1&&i[1].startsWith("@len="))try{o.length=parseInt(i[1].trim().substring(5))}catch(e){o.length=void 0,console.error(`Error parsing sequence length for ${t}`)}else o.length=void 0}}else o.chr=i[0],o.offset=0}else o.seq+=t;o.seq&&o.seq.length>0&&e(o,s)}getSequenceInterval(e,t,i){const r=this.sequences.get(e);if(r)for(let s of r){const r=s.sequence,o=s.offset,n=o+r.length;if(o<=t&&n>=i)return new Ro(e,o,n,r)}}}class To{constructor(e,t){this.offset=e,this.sequence=t}contains(e,t){return this.offset<=e&&this.end>=t}overlaps(e,t){return this.offsete}get end(){return this.offset+this.sequence.length}}const zo=v,Po=new Set(["fastaURL","indexURL","compressedIndexURL","cytobandURL","indexed"]);class Ho{#e;chromosomes=new Map;constructor(e){this.file=e.fastaURL,this.indexFile=e.indexURL,this.compressedIndexFile=e.compressedIndexURL,this.withCredentials=e.withCredentials;const t={};for(let i in e)e.hasOwnProperty(i)&&!Po.has(i)&&(t[i]=e[i]);this.config=t}getSequenceRecord(e){return this.chromosomes.get(e)}async init(){return this.getIndex()}get chromosomeNames(){return this.#e||(this.#e=Array.from(this.chromosomes.keys())),this.#e}getFirstChromosomeName(){return this.chromosomeNames[0]}async getIndex(){if(this.index)return this.index;{const e=await Rr.load(this.indexFile,ts(this.config)),t=zo(e),i=t.length;let r=0,s=0;for(this.index={};rthis.compressedIndex[r][1])return[r];let s=0,o=r,n=Math.floor(this.compressedIndex.length/2),a=this.compressedIndex.length+1,c=!1;for(let t=0;te){c=!0;break}t=t)break}const l=i[i.length-1];return l===this.compressedIndex.length-1&&this.compressedIndex[l][1]0&&(w=Math.min(o-s,a-u),b+=m.substr(F,w),F+=w+l);F1){const e=Number.parseInt(t[1]),r=new No(t[0],i++,e);this.chromosomes.set(t[0],r)}}}}class qo{constructor(e,t=!0){this.littleEndian=t,this.position=0,this.view=e,this.length=e.byteLength}dumpBytes(e=100){const t=this.position,i=[];for(let t=0;t<=e;t++)i.push(this.getByte());console.log(i.join(" ")),this.setPosition(t)}setPosition(e){this.position=e}available(){return this.length-this.position}remLength(){return this.length-this.position}hasNext(){return this.position=0;i--)t=256*t+e[i];else for(let i=0;i0&&(t+=String.fromCharCode(e))}return t}getFloat(){var e=this.view.getFloat32(this.position,this.littleEndian);return this.position+=4,e}getDouble(){var e=this.view.getFloat64(this.position,this.littleEndian);return this.position+=8,e}skip(e){return this.position+=e,this.position}getVPointer(){var e=this.position,t=this.view.getUint8(e+1)<<8|this.view.getUint8(e),i=4294967296*(255&this.view.getUint8(e+6))+16777216*(255&this.view.getUint8(e+5))+65536*(255&this.view.getUint8(e+4))+256*(255&this.view.getUint8(e+3))+(255&this.view.getUint8(e+2));return this.position+=8,new Uo(i,t)}}class Uo{constructor(e,t){this.block=e,this.offset=t}isLessThan(e){return this.blocke.block||this.block===e.block&&this.offset>e.offset}isEqualTo(e){return this.block===e.block&&this.offset===e.offset}print(){return this.block+":"+this.offset}}class Qo{static magic=2026540177;littleEndian=!0;type="BPTree";nodeCache=new Map;static async loadBpTree(e,t,i,r,s){return new Qo(e,t,i,r,s).init()}constructor(e,t,i,r,s){this.path=e,this.config=t,this.startOffset=i,r&&(this.type=r),this.loader=s||Rr}async init(){const e=await this.#t(this.startOffset,32);let t=e.getInt();if(t!==Qo.magic&&(e.setPosition(0),this.littleEndian=!this.littleEndian,e.littleEndian=this.littleEndian,t=e.getInt(),t!==Qo.magic))throw Error(`Bad magic number ${t}`);const i=e.getInt(),r=e.getInt(),s=e.getInt(),o=e.getLong(),n=e.getLong(),a=this.startOffset+32;return this.header={magic:t,blockSize:i,keySize:r,valSize:s,itemCount:o,reserved:n,nodeOffset:a},this}getItemCount(){if(!this.header)throw Error("Header not initialized");return this.header.itemCount}async search(e){this.header||await this.init();const t=async i=>{const r=await this.readTreeNode(i);if(1!==r.type){let i=r.items[0].offset;for(let t=1;t>6&3]+Go[Ay>>4&3]+Go[Ay>>2&3]+Go[3&Ay]);const Wo=jo.map((e=>e.toLowerCase()));class $o{littleEndian;metaIndex=new Map;chromosomeNames;constructor(e){this.url=e.twoBitURL||e.fastaURL,this.config=e,e.twoBitBptURL&&(this.bptURL=e.twoBitBptURL)}async init(){if(this.bptURL)this.index=await Qo.loadBpTree(this.bptURL,this.config,0);else{const e=await this._readIndex();this.index={search:async t=>e.has(t)?{offset:e.get(t)}:void 0}}}async readSequence(e,t,i){this.index||await this.init();const r=await this.getSequenceRecord(e);if(!r)return null;if(t<0)throw new TypeError("regionStart cannot be less than 0");(void 0===i||i>r.dnaSize)&&(i=r.dnaSize);const s=this._getOverlappingBlocks(t,i,r.nBlocks),o=this._getOverlappingBlocks(t,i,r.maskBlocks),n=Math.floor(t/4),a=r.packedPos+n,c=Math.floor(i/4)-n+1,l=await Rr.loadArrayBuffer(this.url,{range:{start:a,size:c}}),h=new Uint8Array(l);let d="";for(let e=t;ee;if(s[0]&&e>=s[0].start&&et)break;s.endr.contains(e,t,i)));if(r||(r=await this.#n(e,t,i),this.#a(r),this.#s.push(r)),r){const e=t-r.start,s=i-t;return r.features?r.features.substring(e,e+s):null}}#a(e){this.#s=this.#s.filter((t=>!e.contains(t))),this.#s.length===this.#o&&this.#s.shift(),this.browser&&this.browser.referenceFrameList.length<100&&(this.#s=this.#s.filter((e=>void 0!==this.browser.referenceFrameList.find((t=>t.overlaps(e))))))}getSequenceInterval(e,t,i){return this.#s.find((r=>r.contains(e,t,i)))}async#n(e,t,i){let r=t,s=i;if(i-t{o.features=await this.sequenceReader.readSequence(e,r,s),t(o)}));return this.#r=[o,t],t}}async init(){return this.sequenceReader.init()}get chromosomeNames(){return this.sequenceReader.chromosomeNames}getFirstChromosomeName(){return"function"==typeof this.sequenceReader.getFirstChromosomeName?this.sequenceReader.getFirstChromosomeName():void 0}#c(e){this.browser.referenceFrameList}}async function Yo(e,t){let i;return"chromsizes"===e.format?i=new Vo(e.fastaURL||e.url):"2bit"===e.format||e.twoBitURL?i=new Zo(new $o(e),t):as(e.fastaURL)||!e.indexURL?i=new Lo(e):"gbk"===e.format||e.gbkURL||(i=new Zo(new Ho(e),t)),await i.init(),i}const Xo={A:"rgb( 0, 200, 0)",C:"rgb( 0,0,200)",T:"rgb(255,0,0)",G:"rgb(209,113, 5)",N:"rgb(80,80,80)"};var Jo={color:1};Jo.parent=Jo,Jo.left=Jo,Jo.right=Jo;class en{constructor(){this.root=Jo}insert(e,t,i){var r=new an(new nn(e,t,i));for(this.treeInsert(r),r.color=2;r!==this.root&&2===r.parent.color;)if(r.parent===r.parent.parent.left){let e=r.parent.parent.right;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.right&&(r=r.parent,rn.call(this,r)),r.parent.color=1,r.parent.parent.color=2,sn.call(this,r.parent.parent))}else{let e=r.parent.parent.left;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.left&&(r=r.parent,sn.call(this,r)),r.parent.color=1,r.parent.parent.color=2,rn.call(this,r.parent.parent))}this.root.color=1}findOverlapping(e,t){var i=new nn(e,t,0);if(this.root===Jo)return[];var r=tn.call(this,i,this.root,[]);return r.length>1&&r.sort((function(e,t){return e.low-t.low})),r}logIntervals(){!function e(t,i){for(var r="",s=0;s=e.low&&tn.call(this,e,t.left,i),t.right!==Jo&&t.right.min<=e.high&&tn.call(this,e,t.right,i),i}function rn(e){var t=e.right;e.right=t.left,t.left!==Jo&&(t.left.parent=e),t.parent=e.parent,e.parent===Jo?this.root=t:e.parent.left===e?e.parent.left=t:e.parent.right=t,t.left=e,e.parent=t,on.call(this,e)}function sn(e){var t=e.left;e.left=t.right,t.right!==Jo&&(t.right.parent=e),t.parent=e.parent,e.parent===Jo?this.root=t:e.parent.right===e?e.parent.right=t:e.parent.left=t,t.right=e,e.parent=t,on.call(this,e)}function on(e){for(;e!==Jo;){var t=e.left.max>e.right.max?e.left.max:e.right.max,i=e.interval.high;e.max=t>i?t:i;var r=e.left.mine.low?1:this.highe.high?1:0}overlaps(e){return this.low<=e.high&&e.low<=this.high}}function an(e){this.parent=Jo,this.left=Jo,this.right=Jo,this.interval=e,this.color=2}class cn{constructor(e,t){e=e||[],this.treeMap=this.buildTreeMap(e),this.range=t,this.count=e.length}containsRange(e){return void 0===this.range||this.range.contains(e.chr,e.start,e.end)}findFeatures(e){const t=[];for(let i of Object.values(this.allFeatures))for(let r of i)e(r)&&t.push(r);return t}queryFeatures(e,t,i){const r=this.treeMap[e];if(!r)return[];const s=r.findOverlapping(t,i);if(0===s.length)return[];{const r=[],o=this.allFeatures[e];if(o){for(let e of s){const s=e.value;for(let e=s.start;ei)break;s.end>=t&&r.push(s)}}r.sort((function(e,t){return e.start-t.start}))}return r}}getAllFeatures(){return this.allFeatures}buildTreeMap(e){const t={},i=[];if(this.allFeatures={},e){for(let t of e){const e=t.chr;let r=this.allFeatures[e];r||(i.push(e),r=[],this.allFeatures[e]=r),r.push(t)}for(let e of i){const i=this.allFeatures[e];i.sort((function(e,t){return e.start===t.start?0:e.start>t.start?1:-1})),t[e]=ln(i)}}return t}}function ln(e){const t=new en,i=e.length,r=Math.max(10,Math.round(i/10));for(let s=0;s6&&"."!==e[6]&&(i.name=e[6]),e.length>7&&"."!==e[7]&&(i.score=Number(e[7])),e.length>8&&"."!==e[8]&&(i.strand1=e[8]),e.length>9&&"."!==e[9]&&(i.strand2=e[9])),t){const r=t.colorColumn;r&&rs&&t.columnNames&&t.columnNames.length===e.length&&(i.extras=e.slice(s))}return i.chr1===i.chr2&&(i.chr=i.chr1,i.start=Math.min(i.start1,i.start2),i.end=Math.max(i.end1,i.end2)),i}function un(e,t){if(!(e.length<8))return{chr:e[0],start:Number.parseInt(e[1]),end:Number.parseInt(e[2]),color:ur.createColorString(e[6]),value:Number(e[7])}}function fn(e){return e&&(e.includes("fdrDonut")||e.includes("fdr_donut"))}function pn(e,t){if(!(e.length<6))return{chr:e[0],start:Number.parseInt(e[1]),end:Number.parseInt(e[2]),chr1:e[8],start1:Number.parseInt(e[9]),end1:Number.parseInt(e[10]),chr2:e[13],start2:Number.parseInt(e[14]),end2:Number.parseInt(e[15]),name:e[3],score:Number(e[4]),value:Number(e[5]),color:"."===e[7]?void 0:"0"===e[7]?"rgb(0,0,0)":e[7]};console.log("Skipping line: "+e.join(" "))}class gn{constructor(e){this.message=e}}const mn=new Map([["%09","\t"],["%0A","\n"],["%0D","\r"],["%25","%"],["%3B",";"],["%3D","="],["%26","&"],["%2C",","]]);function wn(e){if(!e.includes("%"))return e;let t="";for(let i=0;i0&&e"),this.name&&t.push({name:"Name",value:this.name}),t.push({name:"Type",value:this.type}),t.push({name:"Source",value:this.source}),void 0!==this.score&&t.push({name:"Score",value:this.score}),t.push({name:"Phase",value:this.phase}),this.attributeString){const e=bn(this.attributeString,this.delim);for(let[i,r]of e)void 0!==r&&r.length>0&&!Mn.has(i.toLowerCase())&&t.push({name:i+":",value:r})}return t.push({name:"Location",value:`${this.chr}:${F(this.start+1)}-${F(this.end)}`}),t}getAttributeValue(e){if(this.hasOwnProperty(e))return this[e];if(this._attributeCache||(this._attributeCache=new Map),this._attributeCache.has(e))return this._attributeCache.get(e);{const t=bn(this.attributeString,this.delim);let i;for(let[r,s]of t)if(r===e){i=s;break}return this._attributeCache.set(e,i),i}}}class Bn extends Rn{constructor(e){super(e),this.exons=[],this.parts=[]}addExon(e){this.exons.push(e),this.start=Math.min(this.start,e.start),this.end=Math.max(this.end,e.end)}addPart(e){this.parts.push(e)}assembleParts(){if(0===this.parts.length)return;this.parts.sort((function(e,t){return e.start-t.start}));let e=this.parts[0].start,t=this.parts[0].end;for(let i=1;i=t&&i.start<=e)return i}addCDS(e){let t;const i=this.exons;for(let r of i)if(r.start<=e.start&&r.end>=e.end){t=r;break}t?(t.cdStart=t.cdStart?Math.min(e.start,t.cdStart):e.start,t.cdEnd=t.cdEnd?Math.max(e.end,t.cdEnd):e.end,t.readingFrame=e.readingFrame):console.error("No exon found spanning "+e.start+"-"+e.end),this.cdStart=this.cdStart?Math.min(e.start,this.cdStart):e.start,this.cdEnd=this.cdEnd?Math.max(e.end,this.cdEnd):e.end}addUTR(e){let t;const i=this.exons;for(let r=0;r=e.end){t=i[r];break}t?e.start===t.start&&e.end===t.end?t.utr=!0:(e.endt.start&&(t.cdEnd=e.start)):console.error("No exon found spanning "+cds.start+"-"+cds.end)}finish(){this.assembleParts();var e=this.cdStart,t=this.cdEnd;this.exons.sort((function(e,t){return e.start-t.start})),e&&this.exons.forEach((function(i){(i.endt)&&(i.utr=!0)}))}popupData(e){const t=super.popupData(e);for(let i of this.exons)if(!i.pseudo&&e>=i.start&&e");const r=i.popupData(e);for(let e of r)t.push(e)}for(let i of this.parts)if(e>=i.start&&e");const r=i.popupData(e);for(let e of r)t.push(e)}return t}}class Dn{static gffNameFields=new Set(["Name","transcript_id","gene_name","gene","gene_id","alias","locus","name"]);constructor(e){this.format=e.format,this.nameField=e.nameField,this.filterTypes=void 0===e.filterTypes?new Set(["chromosome"]):new Set(e.filterTypes)}combineFeatures(e,t){let i;const r=this.filterTypes;if(e=e.filter((e=>void 0===r||!r.has(e.type))),"gff3"===this.format){const t=this.combineFeaturesById(e);i=this.combineFeaturesByType(t)}else i=this.combineFeaturesByType(e);return this.numberExons(i,t),this.nameFeatures(i),i}combineFeaturesById(e){const t=new Map,i=[];for(let r of e)if(Nn(r.type)||En(r.type)||!r.id)i.push(r);else{let e=t.get(r.chr);e||(e=new Map,t.set(r.chr,e));let i=e.get(r.id);i?i.push(r):e.set(r.id,[r])}for(let e of t.values())for(let t of e.values())if(t.length>1){const e=t[0];e.exons=[];for(let i of t)e.start=Math.min(e.start,i.start),e.end=Math.max(e.end,i.end),e.exons.push({start:i.start,end:i.end});i.push(e)}else i.push(t[0]);return i}combineFeaturesByType(e){const t=e.filter((e=>"gene"===e.type||e.type.endsWith("_gene"))),i=Object.create(null);for(let e of t)i[e.id]=e;const r=Object.create(null),s=[],o=new Set,n=this.filterTypes;e=e.filter((e=>void 0===n||!n.has(e.type)));for(let t of e)if(En(t.type)){const e=t.id;if(void 0!==e){const n=new Bn(t);r[e]=n,s.push(n),o.add(t);const a=i[t.parent];a&&(n.geneObject=a,o.add(a))}}for(let t of e)if(Nn(t.type)){const e=l(t);if(e)for(let i of e){let n=r[i];if(!n&&"gtf"===this.format){const e=Object.assign({},t);e.type="transcript",n=new Bn(e),r[i]=n,s.push(n)}if(void 0!==n){if(a=t.type,_n.has(a))if(e.length>1){const e=new Rn(t);n.addExon(e)}else n.addExon(t);else n.addPart(t);o.add(t)}}}var a;s.forEach((function(e){"function"==typeof e.finish&&e.finish()}));const c=e.filter((e=>!o.has(e)));for(let e of c)s.push(e);return s;function l(e){return e.parent&&""!==e.parent.trim()?e.parent.trim().split(","):null}}numberExons(e,t){for(let i of e)if(i.exons&&(!t||i.end<=t.end&&i.start>t.start))for(let e=0;e2?parseInt(e[2]):o+1;if(isNaN(o)||isNaN(n))return new gn("Unparsable bed record.");const a=new Zn({chr:s,start:o,end:n,score:1e3});let c=3;try{if(e.length>3&&c++0&&e[3].indexOf("=")>0){const i=bn(e[3],"=");a.attributes={};for(let e of i)a.attributes[e[0]]=e[1],r&&(null!=t.nameField&&e[0]===t.nameField||!a.name&&Dn.gffNameFields.has(e[0]))&&(a.name=e[1])}a.name||r||(a.name="."===e[3]?"":e[3])}if(e.length>4&&c++5&&c++6&&c++7&&c++8&&c++11&&c++1e3)return a;const i=e[10].replace(/,$/,"").split(","),r=e[11].replace(/,$/,"").split(",");if(i.length!==r.length||t!==i.length)return a;const s=[];for(let e=0;e0&&(Qn(s,a.cdStart,a.cdEnd),a.exons=s)}if(t){let i=t.thicknessColumn,r=t.colorColumn;r&&r14&&(i.signal=Number(e[12]),i.pValue=Number(e[13]),i.qValue=Number(e[14])),i}function zn(e,t){const i=Ln(e,t,9);if(i){const t=["Coverage","% Showing Methylation","N-mod","N-canonical","N-other mod","N-delete","N-fail","N-dff","N-nocall"];for(let r=9;ri?r.utr=!0:(t>=s&&t<=e&&(r.cdStart=t),i>=s&&i<=e&&(r.cdEnd=i))}}function Gn(e,t){var i,r,s,o,n,a,c;if(!(e.length<9))return i=e[0],r=parseInt(e[1]),s=parseInt(e[2]),n=e[3],a=Number(e[4]),o=e[5].trim(),c=Number(e[6]),0===a&&(a=c),{chr:i,start:r,end:s,name:n,score:a,strand:o,signal:c,pValue:Number(e[7]),qValue:Number(e[8])}}function jn(e,t){const i=Gn(e);return e.length>9&&(i.peak=Number(e[9])),i}function Wn(e,t){if(e.length<=3)return;const i={chr:e[0],start:parseInt(e[1]),end:parseInt(e[2]),value:Number(e[3])};if(t){let r=t.colorColumn;r&&r0)for(var u=c.split(","),f=0;fd&&(d=m),l.spanning_frag_coords.push({left:g,right:m})}return l.start=h,l.end=d,l}}function ia(e,t){if(e.length<7)return null;const i={chr:e[0],start:parseInt(e[1])-1,end:parseInt(e[2]),"Strongest SNP-risk allele":e[3],"Disease/Phenotype":e[4],"P-value":e[5],"Odds ratio or beta":e[6]};return e.length>6&&(i.PUBMEDID=`${e[7]}`),i}function ra(e,t){const i=t.customFormat;if(e.length1&&(t=e)}else{this.config.decode||this.setDecoder(r.format);const e=i.split(this.delimiter||"\t");try{const i=Object.assign({columnNames:t},r);let s;if(s=this.decode(e,i)){r.firstFeature=s;break}e.length>1&&(t=e)}catch(i){e.length>1&&(t=e)}}}if(t){r.columnNames=t;for(let e=0;e0&&console.error(`Error parsing line '${o}': ${c.message}`)):c&&t.push(c)}return i===dn&&function(e){if(0==e.length)return;const t=e[0];if(void 0===t.score&&void 0!==t.name){for(let t of e)if(!ss(t.name)&&"."!==t.name)return;for(let t of e)t.score=Number(t.name),delete t.name}const i=e.filter((e=>e.chr1!==e.chr2));for(let t of i){const i=Object.assign({},t);i.dup=!0,e.push(i),t.chr=t.chr1,t.start=t.start1,t.end=t.end1,i.chr=i.chr2,i.start=i.start2,i.end=i.end2}}(t),"gtf"!==this.config.format&&"gff3"!==this.config.format&&"gff"!==this.config.format||!1===this.config.assembleGFF?t:new Dn(this.config).combineFeatures(t)}setDecoder(e){switch(e){case"broadpeak":case"regionpeak":case"peaks":this.decode=Gn,this.delimiter=this.config.delimiter||/\s+/;break;case"narrowpeak":this.decode=jn,this.delimiter=this.config.delimiter||/\s+/;break;case"bedgraph":this.decode=Wn,this.delimiter=/\s+/;break;case"wig":this.decode=$n,this.delimiter=this.config.delimiter||/\s+/;break;case"gff3":case"gff":this.decode=Jn,this.delimiter="\t";break;case"gtf":this.decode=ea,this.delimiter="\t";break;case"fusionjuncspan":this.decode=ta,this.delimiter=this.config.delimiter||/\s+/;break;case"gtexgwas":this.skipRows=1,this.decode=ia,this.delimiter="\t";break;case"refflat":this.decode=Vn,this.delimiter=this.config.delimiter||/\s+/;break;case"genepred":this.decode=Hn,this.delimiter=this.config.delimiter||/\s+/;break;case"genepredext":this.decode=On,this.delimiter=this.config.delimiter||/\s+/;break;case"ensgene":this.decode=Hn,this.header.shift=1,this.delimiter=this.config.delimiter||/\s+/;break;case"refgene":this.decode=On,this.delimiter=this.config.delimiter||/\s+/,this.header.shift=1;break;case"bed":this.decode=Ln,this.delimiter=this.config.delimiter||/\s+/;break;case"gappedpeak":this.decode=Tn,this.delimiter=this.config.delimiter||/\s+/;break;case"bedmethyl":this.decode=zn,this.delimiter=this.config.delimiter||/\s+/;break;case"bedpe":case"hiccups":this.decode=dn,this.delimiter=this.config.delimiter||"\t";break;case"bedpe-domain":this.decode=un,this.headerLine=!0,this.delimiter=this.config.delimiter||"\t";break;case"bedpe-loop":this.decode=dn,this.delimiter=this.config.delimiter||"\t",this.header={colorColumn:7};break;case"interact":this.decode=pn,this.delimiter=this.config.delimiter||/\s+/;break;case"snp":this.decode=Kn,this.delimiter="\t";break;case"rmsk":this.decode=Pn,this.delimiter="\t";break;case"gcnv":this.decode=sa,this.delimiter="\t";break;case"shoebox":this.decode=oa,this.delimiter="\t";break;default:const t=function(e){return na&&na[e]?function(e){const t=e.fields,i=["chr","start","end"];for(let r=0;r4?parseInt(t[4].split("=")[1],10):1,index:0}}function da(e){const t=e.split(/\s+/);return{format:"variableStep",chrom:t[1].split("=")[1],span:t.length>2?parseInt(t[2].split("=")[1],10):1}}function ua(e,i){const r=t({class:"igv-menu-popup-check-container"}),s=t();r.appendChild(s);const o=l("check",!0===i?"#444":"transparent");s.appendChild(o);const n=t();return n.innerText=e,r.appendChild(n),r}function fa(e,t){t=t||Number.MAX_SAFE_INTEGER;const i=[];e.sort((function(e,t){return e.start-t.start})),i.push(-1e3);for(let r of e){let e=0;const s=Math.min(i.length,t);for(e=0;e=i[e]){r.row=e,i[e]=r.end;break}r.row=e,i[e]=r.end}}async function pa(e,t,i,r){const s=new Map,o=new Map,n=e=>{const i=Object.assign({},e);if(i.chr="all",e.chr2&&e.end2){const r=s.get(e.chr1)||e.chr1,o=s.get(e.chr2)||e.chr2;i.start=t.getGenomeCoordinate(r,e.start1),i.end=t.getGenomeCoordinate(o,e.end2)}else{const r=s.get(e.chr)||e.chr;i.start=t.getGenomeCoordinate(r,e.start),i.end=t.getGenomeCoordinate(r,e.end)}return i._f=e,i.exons&&delete i.exons,i},a=new Set(t.wgChromosomeNames);if(i)for(let e of t.wgChromosomeNames){const t=await i.getAliasName(e);s.set(e,t),o.set(t,e)}const c=[];let l=0;for(let i of t.wgChromosomeNames){if(Array.isArray(e)){const i={};for(let r of e){const e=t.getChromosomeName(r.chr);i.hasOwnProperty(e)||(i[e]=[]),i[e].push(r)}e=i}const h=e[s.get(i)||i];if(h){const e=r||1e4;for(let t of h){if(t.dup)continue;const i=o.get(t.chr)||t.chr,r=t.chr2?o.get(t.chr2)||t.chr2:i;if(a.has(i)&&a.has(r))if(c.length0&&!i.startsWith("rgb(")&&!i.startsWith("rgba(")?`rgb(${i})`:i);var i;e.name||e.label?this.name=e.name||e.label:x(e.url)?this.name=e.url.name:b(e.url)&&!e.url.startsWith("data:")&&(this.name=_(e.url)),this.url=e.url,this.config.type&&(this.type=this.config.type),this.id=void 0===this.config.id?this.name:this.config.id,this.order=e.order,this.autoscaleGroup=e.autoscaleGroup,this.removable=void 0===e.removable||e.removable,this.minHeight=e.minHeight||Math.min(25,this.height),this.maxHeight=e.maxHeight||Math.max(1e3,this.height),e.onclick&&(this.onclick=e.onclick,e.onclick=void 0),e.description&&("function"==typeof e.description?this.description=e.description:this.description=()=>e.description)}async postInit(){return this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get name(){return this._name}set name(e){this._name=e,this.trackView&&this.trackView.setTrackLabelName(e)}clearCachedFeatures(){this.trackView&&this.trackView.clearCachedFeatures()}updateViews(){this.trackView&&this.trackView.updateViews()}repaintViews(){this.trackView&&this.trackView.repaintViews()}getState(){const e={},t=Object.keys(this.config).filter((e=>{return!(void 0===(t=this.config[e])||"function"==typeof t||t instanceof Promise);var t}));for(const i of t)i.startsWith("_")||(e[i]=this.config[i]);for(let t of Object.keys(e)){if(t.startsWith("_"))continue;const i=this[t];void 0===i||!es(i)&&"boolean"!=typeof i&&"metadata"!==t||(e[t]=i)}const i=Object.assign({},ma.defaults);if(this.constructor.defaults)for(let e of Object.keys(this.constructor.defaults))i[e]=this.constructor.defaults[e];for(let t of Object.keys(i))void 0!==this[t]&&i[t]!==this[t]&&(e[t]=this[t]);return!this.autoscale&&this.dataRange&&(e.min=this.dataRange.min,e.max=this.dataRange.max),this.autoscaleGroup&&(e.autoscaleGroup=this.autoscaleGroup),e}get supportsWholeGenome(){return!0===this.config.supportsWholeGenome}hasSamples(){return!1}getGenomeId(){return this.browser.genome?this.browser.genome.id:void 0}setTrackProperties(e){if(this.disposed)return;const t={};let i;for(let r of Object.keys(e))switch(r.toLowerCase()){case"usescore":t.useScore=1===e[r]||"1"===e[r]||"on"===e[r]||!0===e[r];break;case"visibility":switch(e[r]){case"2":case"3":case"pack":case"full":t.displayMode="EXPANDED";break;case"4":case"squish":t.displayMode="SQUISHED";break;case"1":case"dense":t.displayMode="COLLAPSED"}break;case"color":case"altcolor":t[r]=e[r].startsWith("rgb(")?e[r]:"rgb("+e[r]+")";break;case"featurevisiblitywindow":case"visibilitywindow":t.visibilityWindow=Number.parseInt(e[r]);break;case"maxheightpixels":i=e[r].split(":"),3===i.length&&(t.minHeight=Number.parseInt(i[2]),t.height=Number.parseInt(i[1]),t.maxHeight=Number.parseInt(i[0]));break;case"viewlimits":if(!this.config.autoscale&&!this.config.max){i=e[r].split(":");let s,o=0;1==i.length?s=Number(i[0]):2==i.length&&(o=Number(i[0]),s=Number(i[1])),Number.isNaN(s)||Number.isNaN(o)?console.warn(`Unexpected viewLimits value in track line: ${e.viewLimits}`):(t.autoscale=!1,t.dataRange={min:o,max:s},this.viewLimitMin=o,this.viewLimitMax=s)}case"name":t[r]=e[r];break;case"url":t.infoURL=e[r];break;case"type":const s=e[r];wa.has(s)?t[r]=wa.get(s):t[r]=s;break;case"graphtype":t.graphType=e[r];break;default:t[r]=e[r]}for(let e of Object.keys(t))if(!this.config.hasOwnProperty(e)||"name"===e&&this.config._derivedName){let i=t[e];if("true"===i&&(i=!0),"false"===i&&(i=!1),this[e]=i,"height"===e&&this.trackView)try{const e=Number.parseInt(i);this.trackView.setTrackHeight(e)}catch(e){console.error(e)}}}clickedFeatures(e){const t=e.viewport.cachedFeatures;if(!t||!Array.isArray(t)||0===t.length)return[];const i=e.genomicLocation,r=e.referenceFrame.bpPerPixel>.2?3*e.referenceFrame.bpPerPixel:.2;return Vr(t,i-r,i+r)}extractPopupData(e,t){const i=new Set(["row","color","chr","start","end","cdStart","cdEnd","strand","alpha"]),r=[];let s,o;for(let t in e)if(e.hasOwnProperty(t)&&!i.has(t)&&es(e[t])){let i=e[t];r.push({name:C(t),value:i}),"alleles"===t?s=e[t]:"alleleFreqs"===t&&(o=e[t])}if(s&&o){s.endsWith(",")&&(s=s.substr(0,s.length-1)),o.endsWith(",")&&(o=o.substr(0,o.length-1));let i=s.split(","),n=o.split(",");if(n.length>1){let s=[];for(let e=0;e=0;i--){let n=s[i].a;if(1===n.length){t||(t=this.getGenomeId());const i=ma.getCravatLink(e.chr,e.start+1,o,n,t);console.log(i),i&&(r.push("
"),r.push({html:i}),r.push("
"))}}}}if(e.attributes)for(let t of Object.keys(e.attributes))r.push({name:t,value:e.attributes[t]});let n=`${e.chr}:${F(e.start+1)}-${F(e.end)}`;return e.strand&&(n+=` (${e.strand})`),r.push({name:"Location",value:n}),r}description(){const e=(e,t)=>{const i=document.createElement("div");i.className="igv-track-label-popover__row";const r=document.createElement("span");r.className="igv-track-label-popover__key",r.textContent=e+":";const s=document.createElement("span");return s.className="igv-track-label-popover__value",s.textContent=t,i.appendChild(r),i.appendChild(s),i},t=document.createDocumentFragment();if(!this.url){const e=document.createElement("div");return e.className="igv-track-label-popover__row",e.textContent=this.name,t.appendChild(e),t}if(x(this.url)?t.appendChild(e("Filename",this.url.name)):t.appendChild(e("URL",this.url)),this.config){if(this.config.metadata)for(let i of Object.keys(this.config.metadata)){const r=this.config.metadata[i];t.appendChild(e(i,r))}for(let i of Object.keys(this.config)){if(i.startsWith("_"))continue;let r=i.substr(0,1);if(r!==r.toLowerCase()){const r=this.config[i];r&&es(r)&&t.appendChild(e(i,r))}}}return t}getColorForFeature(e){return"function"==typeof this.color?this.color(feature):this.color}numericDataMenuItems(){const e=[];if("heatmap"!==this.graphType){function t(e){this.trackView.track.selected?this.browser.dataRangeDialog.configure(this.trackView.browser.getSelectedTrackViews()):this.browser.dataRangeDialog.configure(this.trackView),this.browser.dataRangeDialog.present(e)}if(e.push("
"),e.push({label:"Set data range",dialog:t}),void 0!==this.logScale){function r(){this.logScale=!this.logScale,this.trackView.repaintViews()}e.push({element:ua("Log scale",this.logScale),click:r})}function i(){this.autoscaleGroup=void 0,this.autoscale=!this.autoscale,this.browser.updateViews()}e.push({element:ua("Autoscale",this.autoscale),click:i})}return e}setDataRange({min:e,max:t}){this.dataRange={min:e,max:t},this.autoscale=!1,this.autoscaleGroup=void 0,this.trackView.repaintViews()}async nextFeatureAfter(e,t,i){let r=this.trackView.viewports[0].cachedFeatures;if(r&&Array.isArray(r)&&r.length>0){if(this.browser.genome.getChromosomeName(r[0].chr)===e){const e=function(e,t,i=!0){const r=e=>(e.start+e.end)/2,s=i?(e,t)=>e.start-t.start+e.end-t.end:(e,t)=>t.start-e.start+t.end-e.end,o=Array.from(e);o.sort(s);let n=0,a=o.length;for(;n=t?n=e+1:a=e}return o[n]}(r,t,i);if(e)return e}}if("function"==typeof this.featureSource.nextFeature)return this.featureSource.nextFeature(e,t,i,this.visibilityWindow)}dispose(){this.disposed=!0;for(let e of Object.keys(this))this[e]=void 0}static getCravatLink(e,t,i,r,s){if("hg38"===s||"GRCh38"===s){return`Cravat ${i}->${r}`}}static localFileInspection(e){const t=Object.assign({},e),i={url:"file",indexURL:"indexFile"};for(const e of["url","indexURL"])t[e]&&t[e]instanceof File&&(t[i[e]]=t[e].name,delete t[e]);return t}set filter(e){this._filter=e,this.trackView.repaintViews()}getInViewFeatures(){const e=[];for(let t of this.trackView.viewports)if(t.isVisible()){const i=t.referenceFrame;i.chr;const r=i.start,s=r+i.toBP(t.getWidth());if(t.cachedFeatures){const i=Vr(t.cachedFeatures,r,s);for(let t of i)this._filter&&!this._filter(t)||e.push(t)}}return e}getFilterableAttributes(){return{}}}const wa=new Map([["wiggle_0","wig"],["bed","bed"],["bigBed","bigBed"],["bigWig","bigWig"]]);class ba{constructor(e){switch(this.type=e||"seg",this.type){case"mut":this.sampleColumn=3,this.chrColumn=0,this.startColumn=1,this.endColumn=2,this.dataColumn=4;break;case"maf":this.sampleColumn=15,this.chrColumn=4,this.startColumn=5,this.endColumn=6,this.dataColumn=8;break;default:this.sampleColumn=0,this.chrColumn=1,this.startColumn=2,this.endColumn=3}}async parseHeader(e){let t;for(;void 0!==(t=await e.nextLine());)if(!t.startsWith("#")){const e=t.split("\t");this.header={headings:e};break}return this.header}async parseFeatures(e){const t=[];let i;this.header||(this.header=await this.parseHeader(e)),"seg"===this.type&&(this.dataColumn=this.header.headings.length-1),this.header.headings.length>5&&(i=this.extractExtraColumns(this.header.headings));const r=this.header.headings[this.dataColumn];let s;for(;void 0!==(s=await e.nextLine());){const e=s.split("\t"),o="seg"===this.type?Number(e[this.dataColumn]):e[this.dataColumn];if(e.length>this.dataColumn){const s=new Fa({sample:e[this.sampleColumn],chr:e[this.chrColumn],start:parseInt(e[this.startColumn])-1,end:parseInt(e[this.endColumn]),value:o,valueColumnName:r});if(i){const t=this.extractExtraColumns(e);s.setAttributes({names:i,values:t})}t.push(s)}}return t}extractExtraColumns(e){const t=[];for(let i=0;i=0)return this.attributeValues[t]}}popupData(e,t){const i=new Set(["chr","start","end","sample","value","row","color","sampleKey","uniqueSampleKey","sampleId","chromosome","uniquePatientKey"]),r=this.chr+":"+F(this.start+1)+"-"+F(this.end),s=[{name:"Sample",value:this.sample},{name:"Location",value:r},{name:this.valueColumnName?C(this.valueColumnName):"Value",value:this.value}];if("mut"===e&&"hg38"===t){const e=this.extractCravatLink(t);e&&(s.push("
"),s.push({html:e}),s.push("
"))}if(this.attributeNames&&this.attributeNames.length>0)for(let e=0;e0)for(let r=0;r"===t||"<*>"===t||"."===t)return"NONVARIANT";{const e=t.split(",").map((function(e){return 1===i&&1===e.length?"SNP":""===e?"NONVARIANT":e.length>i&&xa(e)?"INSERTION":e.lengthe.length>0));this.alleles=[],this.start=void 0,this.end=void 0;for(let t of i)if(this.alleles.push(t),"SV"!==this.type&&xa(t)){let i=t.length,r=e.length;const s=Math.min(i,r);let o=0;for(;o0&&r>0;){const s=o+i-1,n=o+r-1;if(t.charCodeAt(s)!==e.charCodeAt(n))break;i--,r--}for(;i>0&&r>0;){const s=o,n=o;if(t.charCodeAt(s)!==e.charCodeAt(n))break;o++,i--,r--}const n=this.pos+o-1,a=n+r;this.start=void 0===this.start?n:Math.min(this.start,n),this.end=void 0===this.end?a:Math.max(this.end,a)}void 0===this.start&&(this.start=this.pos-1,this.end=this.pos),this.start===this.end&&(this.start-=.5,this.end+=.5)}}popupData(e,t){const i=`${F(this.pos)}`,r=this.start===this.end?`${F(this.start)} | ${F(this.start+1)}`:`${F(this.start+1)}-${F(this.end)}`,s=[{name:"Chr",value:this.chr},{name:"Pos",value:i},{name:"Loc",value:r},{name:"ID",value:this.names?this.names:""},{name:"Ref",value:this.referenceBases},{name:"Alt",value:this.alternateBases.replace("<","<")},{name:"Qual",value:this.quality},{name:"Filter",value:this.filter}];if(this.type&&s.push({name:"Type",value:this.type}),"SNP"===this.type){let e=this.referenceBases;if(1===e.length){let i=this.alternateBases.split(",");for(let r of i)if(1===r.length){let i=ma.getCravatLink(this.chr,this.pos,e,r,t);i&&(s.push("
"),s.push({html:i}))}}}const o=Object.keys(this.info);if(this.info&&o.length>0){s.push({html:'
'});for(let e of o)s.push({name:e,value:ka(decodeURIComponent(this.info[e]))})}return s}getInfo(e){return this.info?this.info[e]:void 0}isRefBlock(){return"NONVARIANT"===this.type}isFiltered(){return!("."===this.filter||"PASS"===this.filter)}alleleFreq(){return this.info?this.info.AF:void 0}}class Aa{constructor(e){this.mate=e,this.chr=e.info.CHR2,this.pos=Number.parseInt(e.info.END),this.start=this.pos-1,this.end=this.pos}get info(){return this.mate.info}get names(){return this.mate.names}get referenceBases(){return this.mate.referenceBases}get alternateBases(){return this.mate.alternateBases}get quality(){return this.mate.quality}get filter(){return this.mate.filter}get calls(){return this.mate.calls}getAttributeValue(e){return this.mate.getAttributeValue(e)}getInfo(e){this.mate.getInfo(e)}isFiltered(){return this.mate.isFiltered()}alleleFreq(){return this.mate.alleleFreq()}popupData(e,t){const i=[];return i.push("SV Breakpoint"),i.push({name:"Chr",value:this.chr}),i.push({name:"Pos",value:`${F(this.pos)}`}),i.push({html:'
'}),i.push("SV"),i.push(...this.mate.popupData(e,t)),i}}class Ca{constructor({formatFields:e,sample:t,token:i}){this.info={},this.sample=t;const r=i.split(":");for(let t=0;t");for(let e of s)i.push({name:e,value:decodeURIComponent(this.info[e])});return i}}const _a=new Set(["A","C","T","G"].map((e=>e.charCodeAt(0))));function xa(e){for(let t=0;t");if(!(t>2&&n>0)){console.log("Malformed VCF header line: "+r);continue}const a=r.substring(2,t-1);i[a]||(i[a]={});const c=y(r.substring(t+1,n-1),",");for(let t of c){var s=t.split("=");s.length>1&&("ID"===s[0]?e=s[1]:o[s[0]]=s[1])}e&&(i[a][e]=o)}else if(r.startsWith("##contig")&&t){const e=r.indexOf("",e));const s=r.substring(e+4,t);i.sequenceNames.push(s)}}else if(r.startsWith("#CHROM")){const e=r.split("\t");if(e.length>8){i.sampleNameMap=new Map;for(let t=9;t9){const s=Sa(e[8].split(":"));r.calls=[];for(let t=9;t{const t=e.indexOf("E");if(t>0){if(Number.parseInt(e.substring(t+1))0||0==i.length||i.indexOf("x")>0)continue;const o=e[this.chrCol],n=s(e[this.valueCol]),a=parseInt(i)-1,c=a+1;t.push(new Ma({chr:o,start:a,end:c,value:n,line:r,columns:this.columns}))}}return t}static isGWAS(e){const t=e.split("\t");if(t.length<5)return!1;const i=[["chr","chromosome","chr_id","chrom"],["bp","pos","position","chr_pos","chromEnd"],["p","pval","p-value","p.value"]];for(let e of i)if(!t.some((t=>e.includes(t.toLowerCase()))))return!1;return!0}}class Ma{constructor({chr:e,start:t,end:i,value:r,line:s,columns:o}){this.chr=e,this.start=t,this.end=i,this.value=r,this.line=s,this.columns=o}popupData(){const e=this.line.split(/\t/);return this.columns.map((function(t,i){return{name:t,value:e[i]}}))}getAttributeValue(e){const t=this.line.split(/\t/);for(let i=0;i0?r=e:r?(s.push(r+e),r=void 0):s.push(e));for(let e of s){if(!e)return;var o=e.split("=",2);if(2===o.length){const e=o[0].trim(),i=o[1].trim();t[e]=i}}return t}function Pa(e){let t={},i=e.split(/\s+/);if(2===i.length){i[1].split(";").forEach((function(e){let i=e.split("=");"color"===i[0]?t.colorColumn=Number.parseInt(i[1])-1:"thickness"===i[0]&&(t.thicknessColumn=Number.parseInt(i[1])-1)}))}return t}function Ha(e,t){var i,r,s=e.columns;this.aed=e,this.allColumns=t,this.chr=null,this.start=null,this.end=null,this.score=1e3,this.strand=".",this.cdStart=null,this.cdEnd=null,this.name=null,this.color=null;for(let e=0;e0)for(let e=0;ee.maxv.isGreaterThan(t))));const i=[];let r;for(let t of e)r&&qa(r,t)?t.maxv.isGreaterThan(r.maxv)&&(r.maxv=t.maxv):(i.push(t),r=t);return i}function qa(e,t){const i=t.minv.block-e.maxv.block;return t.maxv.block-e.minv.block<5e6&&i<65e3}Ha.prototype.popupData=function(){for(var e=[],t=this.aed,i=0;i=28){t.getInt(),t.getInt(),t.getInt(),t.getInt(),t.getInt(),t.getInt();const e=t.getInt(),i=t.position+e;let s=0;for(;t.positiono)t.getInt(),t.getVPointer(),t.getVPointer(),t.getLong(),t.getLong();else{i[e]=[];const r=t.getInt();for(let o=0;os&&(s=o.block),i[e].push([r,o]))}}}n>0&&(this.indices[e]={binIndex:i,loffset:r})}this.lastBlockPosition=s}get sequenceNames(){return Object.keys(this.sequenceIndexMap)}chunksForRange(e,t,i){const r=this.indices[e];if(r){const e=this.reg2bins(t,i);if(0==e.length)return[];const s=[];for(let t of e)for(let e=t[0];e<=t[1];e++)if(r.binIndex[e]){const t=r.binIndex[e];for(let i of t){const t=i[0],r=i[1];s.push({minv:t,maxv:r,bin:e})}}let o=e[this.depth][0];do{if(r.binIndex[o])break;o>1+(this.getParentBin(o)<<3)?o--:o=this.getParentBin(o)}while(0!=o);return Va(s,r.loffset[o])}return[]}getParentBin(e){return 0==e?0:e-1>>3}reg2bins(e,t){(e-=1)<1&&(e=1),t>2**34&&(t=2**34),t-=1;let i=0,r=0,s=this.minShift+3*this.depth;const o=[];for(;i<=this.depth;s-=3,r+=1<<3*i,i+=1){const i=r+(e>>s),n=r+(t>>s);o.push([i,n])}return o}bin_limit(){return((1<<3*(this.depth+1))-1)/7}}class Qa{constructor(){}async parse(e,t){const i=[];let r=Number.MAX_SAFE_INTEGER,s=0;const o=new qo(new DataView(e)),n=o.getInt(),a={};if(!(21578050===n||t&&21578324===n))throw new Error(indexURL+" is not a "+(t?"tabix":"bai")+" file");{const e=o.getInt();if(t){o.getInt(),o.getInt(),o.getInt(),o.getInt(),o.getInt(),o.getInt(),o.getInt();for(let t=0;ts&&(s=n.block),e[t].push([i,n]))}}}const c=o.getInt();for(let e=0;e0&&(i[t]={binIndex:e,linearIndex:n})}this.firstBlockPosition=r,this.lastBlockPosition=s,this.indices=i,this.sequenceIndexMap=a,this.tabix=t}}get sequenceNames(){return Object.keys(this.sequenceIndexMap)}chunksForRange(e,t,i){const r=this.indices[e];if(r){const e=function(e,t){const i=[];t>=1<<29&&(t=1<<29);return--t,i.push([0,0]),i.push([1+(e>>26),1+(t>>26)]),i.push([9+(e>>23),9+(t>>23)]),i.push([73+(e>>20),73+(t>>20)]),i.push([585+(e>>17),585+(t>>17)]),i.push([4681+(e>>14),4681+(t>>14)]),i}(t,i),s=[];for(let t of e)for(let e=t[0];e<=t[1];e++)if(r.binIndex[e]){const t=r.binIndex[e];for(let e of t){const t=e[0],i=e[1];s.push({minv:t,maxv:i})}}const o=r.linearIndex.length;let n;const a=Math.min(t>>14,o-1),c=Math.min(i>>14,o-1);for(let e=a;e<=c;e++){const t=r.linearIndex[e];if(t){n=t;break}}return Va(s,n)}return[]}}class Ga{constructor(){this.tribble=!0}async parse(e){let t=0;this.chrIndex={},this.lastBlockPosition=[];const i=new qo(new DataView(e));!function(e){e.getInt(),e.getInt();const t=e.getInt();if(e.getString(),e.getLong(),e.getLong(),e.getString(),e.getInt(),t>=3){let t=e.getInt();for(;t-- >0;)e.getString(),e.getString()}}(i);let r=i.getInt();for(;r-- >0;){let e=i.getString();const r=i.getInt(),s=i.getInt(),o=i.getInt();i.getInt(),i.getInt();let n=i.getLong();const a=[];for(let e=0;et&&(t=e)}this.chrIndex[e]={chr:e,blocks:a,longestFeature:o,binWidth:r}}this.lastBlockPosition=t}get sequenceNames(){return Object.keys(this.chrIndex)}chunksForRange(e,t,i){const r=this.chrIndex[e];if(r){const e=r.blocks,s=r.longestFeature,o=r.binWidth,n=Math.max(t-s,0),a=Math.floor(n/o);if(a>=e.length)return[];{const t=Math.min(Math.floor((i-1)/o),e.length-1),r=e[a].min,s=e[t].max;if(0===s-r)return[];return[{minv:{block:r,offset:0},maxv:{block:s,offset:0}}]}}}}async function ja(e,t){let i=await Rr.loadArrayBuffer(e,ts(t)),r=new DataView(i);if(31===r.getUint8(0)&&139===r.getUint8(1)){i=tr(i).buffer,r=new DataView(i)}switch(r.getInt32(0,!0)){case 21578050:return async function(e){const t=new Qa;return await t.parse(e,!1),t}(i);case 21578324:return async function(e){const t=new Qa;return await t.parse(e,!0),t}(i);case 21582659:return async function(e){const t=new Ua;return t.parse(e),t}(i);case 1480870228:return async function(e){const t=new Ga;return t.parse(e),t}(i);case 38359875:throw Error("CSI version 2 is not supported.");default:throw Error(`Unrecognized index type: ${e}`)}}function Wa(e){return"string"==typeof e||e instanceof String?new $a(e):new Ka(e)}class $a{constructor(e){this.data=e,this.ptr=0}nextLine(){var e=this.ptr,t=this.data.indexOf("\n",e),i=this.data;if(t>0)return this.ptr=t+1,t>e&&"\r"===i.charAt(t-1)?i.substring(e,t-1):i.substring(e,t);var r=i.length;return this.ptr=r,e>=r?void 0:i.substring(e)}}class Ka{constructor(e){this.data=e,this.length=this.data.length,this.ptr=0}nextLine(){if(this.ptr>=this.data.length)return;let e=this.ptr;const t=this.data;let i="",r=!1;for(;e0)for(var a=0;a{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e);return 1+(t[17]<<8|t[16])};class Xa{constructor(e){this.config=e,this.cacheBlocks=0!=e.cacheBlocks,this.cache=void 0}async getData(e,t){const i=e.block,r=t.block,s=0===t.offset,o=await this.getInflatedBlocks(i,r,s);if(1===o.length)return o[0];let n=0;for(const e of o)n+=e.byteLength;const a=new Uint8Array(n);let c=0;for(const e of o)a.set(e,c),c+=e.byteLength;return a}async getInflatedBlocks(e,t,i){if(this.cacheBlocks){const r=this.cache;if(r&&r.startBlock<=e&&(r.endBlock>=t||i&&r.nextEndBlock===t)){const i=e-r.startBlock,s=t-r.startBlock;return ec(r.buffer,i,s)}{let s;if(!r||r.startBlock>t||r.endBlock=r.endBlock)n=r.buffer;else{const i=Math.max(0,e-r.startBlock);let s;if(t>=r.endBlock)s=r.buffer.byteLength;else{const e=Ja(r.buffer);for(let i=0;ir.endBlock){const e=await this.loadBLockData(r.endBlock,t,{skipStart:!0,skipEnd:i});o.push(e)}s=function(e){if(1===e.length)return e[0];let t=0;for(const i of e)t+=i.byteLength;const i=new Uint8Array(t);let r=0;for(const t of e)i.set(new Uint8Array(t),r),r+=t.byteLength;return i.buffer}(o)}let o=t;if(i){const e=Ja(s);t=e[e.length-1]}return this.cache={startBlock:e,endBlock:t,nextEndBlock:o,buffer:s},ec(s)}}return ec(await this.loadBLockData(e,t,{skipEnd:i}))}async loadBLockData(e,t,i){const r=this.config,s=i&&i.skipStart;let o=0;if(!(i&&i.skipEnd)){const e=ts(r,{range:{start:t,size:26}}),i=await Rr.loadArrayBuffer(r.url,e);o=Ya(i)}if(s){const t=ts(r,{range:{start:e,size:26}}),i=await Rr.loadArrayBuffer(r.url,t);e+=Ya(i)}const n=ts(r,{range:{start:e,size:t+o-e}});return Rr.loadArrayBuffer(r.url,n)}}function Ja(e){const t=e.byteLength;let i=0;const r=[0];for(;i{const t=e.indexOf("E");if(t>0){if(Number.parseInt(e.substring(t+1))0||0==i.length||i.indexOf("x")>0)continue;const r=e[this.chrColumn],o=s(e[this.pValueColumn]),n=parseInt(i)-1,a=n+1,c=e[this.snpColumn],l=e[this.phenotypeColumn],h=new rc({chr:r,start:n,end:a,pValue:o,snp:c,phenotype:l},this.columns,e);t.push(h)}}return t}static isQTL(e){const t=e.split("\t");if(t.length<5)return!1;const i=[["chr","chromosome","chr_id","chrom"],["bp","pos","position","chr_pos","chromEnd"],["p","pval","p-value","p.value"],["rsid","variant","snp"],["phenotype","gene","gene_id","molecular_trait_id"]];for(let e of i)if(!t.some((t=>e.includes(t.toLowerCase()))))return!1;return!0}}class rc{constructor({chr:e,start:t,end:i,pValue:r,snp:s,phenotype:o},n,a){this.chr=e,this.start=t,this.end=i,this.pValue=r,this.snp=s,this.phenotype=o,this.headers=n,this.tokens=a}popupData(){const e=[];for(let t=0;te.blocks)).map((e=>e.max)).reduce(((e,t)=>Math.min(e,t)),Number.MAX_SAFE_INTEGER),r=ts(this.config,{bgz:e.tabix,range:{start:0,size:i}});t=Wa(await Rr.loadString(this.config.url,r))}return this.header=await this.parser.parseHeader(t),this.header}if("service"!==this.config.sourceType){let e;if(this.indexed=!1,this.config._filecontents)e=this.config._filecontents,delete this.config._filecontents;else{const t=ts(this.config);e=await Rr.loadByteArray(this.config.url,t)}e.length<5e8&&(e=(new TextDecoder).decode(e));let t=Wa(e);return this.header=await this.parser.parseHeader(t),t=Wa(e),this.features=await this.parser.parseFeatures(t),this.sequenceNames=new Set(this.features.map((e=>e.chr))),this.header}if(this.config.seqnamesURL){const e=ts(this.config,{}),t=await Rr.loadString(this.config.seqnamesURL,e);t&&(this.sequenceNames=new Set(t.split(",").map((e=>e.trim())).filter((e=>e))))}if(this.config.headerURL){const e=ts(this.config,{}),t=Wa(await Rr.loadString(this.config.headerURL,e));return this.header=await this.parser.parseHeader(t),this.header}}getParser(e){switch(e.format){case"vcf":return new Ia(e);case"seg":return new ba("seg");case"mut":return new ba("mut");case"maf":return new ba("maf");case"gwas":return new Na(e);case"qtl":return new ic(e);case"aed":return new Da(e);default:return new aa(e)}}async loadFeaturesNoIndex(){if(this.features){const e=this.features;return delete this.features,e}{const e=ts(this.config),t=await Rr.loadByteArray(this.config.url,e);if(!this.header){const e=Wa(t);this.header=await this.parser.parseHeader(e)}const i=Wa(t),r=[];return await this._parse(r,i),r}}async loadFeaturesWithIndex(e,t,i){const r=this.config;this.parser;const s=this.index.tabix,o=s?this.index.sequenceIndexMap[e]:e;if(void 0===o)return[];const n=this.index.chunksForRange(o,t,i);if(n&&0!==n.length){const o=[];for(let a of n){let n;if(s)n=await this._blockLoader.getData(a.minv,a.maxv);else{const e=ts(r,{range:{start:a.minv.block,size:a.maxv.block-a.minv.block+1}});n=await Rr.loadString(r.url,e)}const c=Wa(a.minv.offset?n.slice(a.minv.offset):n);await this._parse(o,c,e,i,t)}return o}return[]}async loadFeaturesFromService(e,t,i){let r;r="function"==typeof this.config.url?this.config.url({chr:e,start:t,end:i}):this.config.url.replace("$CHR",e).replace("$START",t).replace("$END",i);const s=ts(this.config),o=Wa(await Rr.loadString(r,s)),n=[];return await this._parse(n,o),n}async _parse(e,t,i,r,s){let o=await this.parser.parseFeatures(t);if(o.sort((function(e,t){return e.chr===t.chr?e.start-t.start:e.chr.localeCompare(t.chr)})),void 0===i)for(let t of o)e.push(t);else{let t=!1;for(let n=0;nr){e.push(a);break}a.end>=s&&a.start<=r&&(t||(t=!0,n>0&&e.push(o[n-1])),e.push(a))}}}}async getIndex(){return this.index?this.index:this.config.indexURL?(this.index=await this.loadIndex(),this.index):void 0}async loadIndex(){return ja(this.config.indexURL,this.config)}async loadFeaturesFromDataURI(){if(this.features){const e=this.features;return delete this.features,e}{const e=nr(this.dataURI);let t=Wa(e);this.header=await this.parser.parseHeader(t),this.header instanceof String&&this.header.startsWith("##gff-version 3")&&(this.format="gff3"),t=Wa(e);const i=[];return await this._parse(i,t),i}}}const oc=b;class nc{constructor(e){this.config=e}async readFeatures(e,t,i){let r;r="function"==typeof this.config.url?this.config.url({chr:e,start:t,end:i}):this.config.url.replace("$CHR",e).replace("$START",t).replace("$END",i);let s,o=Object.assign({},this.config);void 0!==this.config.body&&("function"==typeof this.config.body?o.body=this.config.body({chr:e,start:t,end:i}):o.body=this.config.body.replace("$CHR",e).replace("$START",t).replace("$END",i));const n=await Rr.load(r,o);if(n&&(s="function"==typeof this.config.parser?this.config.parser(n):oc(n)?JSON.parse(n):n),this.config.mappings){let e=Object.keys(this.config.mappings);for(let t of s)for(let i of e)t[i]=t[this.config.mappings[i]]}return s}}const ac=function(e,t){this.config=e,this.genome=t,this.expandQueryInterval=!1};ac.prototype.readFeatures=function(e,t,i){const r=Math.max(0,Math.floor(t));let s=Math.ceil(i);if(this.genome){const t=this.genome.getChromosome(e);t&&s>t.bpLength&&(s=t.bpLength)}const o=this.config.url+"?db="+this.config.db+"&table="+this.config.tableName+"&chr="+e+"&start="+r+"&end="+s;return Rr.loadJson(o,this.config).then((function(e){return e?(e.forEach((function(e){e.hasOwnProperty("exonStarts")&&e.hasOwnProperty("exonEnds")&&e.hasOwnProperty("exonCount")&&e.hasOwnProperty("cdsStart")&&e.hasOwnProperty("cdsEnd")&&function(e){var t,i,r,s,o,n;t=e.exonCount,i=e.exonStarts.split(","),r=e.exonEnds.split(","),s=[];for(var a=0;an||e.cdsEnd=o&&e.cdsStart<=n&&(c.cdStart=e.cdsStart),e.cdsEnd>=o&&e.cdsEnd<=n&&(c.cdEnd=e.cdsEnd),s.push(c)}e.exons=s}(e)})),e):null}))};class cc{featureCaches=[];gtexChrs=new Set(["chr1","chr10","chr11","chr12","chr13","chr14","chr15","chr16","chr17","chr18","chr19","chr2","chr20","chr21","chr22","chr3","chr4","chr5","chr6","chr7","chr8","chr9","chrM","chrX","chrY"]);constructor(e){this.config=e,this.url=e.url,this.tissueId=e.tissueSiteDetailId,this.datasetId=e.datasetId||"gtex_v8"}async readFeatures(e,t,i){const r=e.startsWith("chr")?e:"MT"===e?"chrM":"chr"+e;if(!this.gtexChrs.has(r))return[];const s=Math.floor(t),o=Math.ceil(i),n=this.datasetId,a=this.url+"?chromosome="+r+"&start="+s+"&end="+o+"&tissueSiteDetailId="+this.tissueId+"&datasetId="+n,c=await Rr.loadJson(a,{withCredentials:this.config.withCredentials});return c&&c.singleTissueEqtl?c.singleTissueEqtl.map((e=>new lc(e))):[]}}class lc{constructor(e){this.chr=e.chromosome,this.start=e.pos-1,this.end=this.start+1,this.snp=e.snpId,this.phenotype=e.geneSymbol,this.pValue=e.pValue,this.json=e}popupData(){return Object.keys(this.json).map((e=>({name:e,value:this.json[e]})))}}class hc{constructor(e,t){if(this.config=e,this.genome=t,!e.format)throw Error('Format is required, and must be either "bam" or "cram"');if(this.format=e.format.toUpperCase(),"BAM"!==this.format&&"VCF"!==this.format)throw Error(`htsget format ${e.format} is not supported`)}async readHeaderData(){const e=`${dc(this.config)}?class=header&format=${this.format}`,t=await Rr.loadJson(e,ts(this.config));return await this.loadUrls(t.htsget.urls)}async readData(e,t,i){const r=`${dc(this.config)}?format=${this.format}&referenceName=${e}&start=${Math.floor(t)}&end=${Math.ceil(i)}`,s=await Rr.loadJson(r,ts(this.config));return this.loadUrls(s.htsget.urls)}async loadUrls(e){const t=[];for(let i of e)if(i.url.startsWith("data:"))t.push(Promise.resolve(uc(i.url)));else{const e={headers:i.headers||{}};t.push(Rr.loadArrayBuffer(i.url,e))}return function(e){let t=0;for(let i of e)t+=i.byteLength;let i=0;const r=new Uint8Array(t);for(let t of e){const e=new Uint8Array(t);r.set(e,i),i+=e.length}return r}(await Promise.all(t))}static async inferFormat(e){try{const t=dc(e),i=`${t}${t.includes("?")?"&":"?"}class=header`,r=await Rr.loadJson(i,ts(e));if(r.htsget){const t=r.htsget.format;if("BAM"!==t&&"VCF"!==t)throw Error(`htsget format ${t} is not supported`);e.format=t.toLowerCase(),e.sourceType="htsget",e.name||(e.name=await os(e.url))}}catch(e){}}}function dc(e){if(e.url&&e.endpoint&&e.id)return e.url+e.endpoint+e.id;if(e.endpoint&&e.id)return e.endpoint+e.id;if(e.url)return e.url.startsWith("htsget://")?e.url.replace("htsget://","https://"):e.url;throw Error("Must specify either 'url', or 'endpoint' and 'id")}function uc(e){const t=e.split(","),i=t[0].split(":")[1];let r=t[1];r=i.indexOf("base64")>=0?atob(r):decodeURI(r);const s=new Uint8Array(r.length);for(var o=0;o"start"!==e&&"end"!==e)).map((e=>t[e])).filter((e=>this.sequenceNames.has(e)));i.length>0?this.chrAliasTable.set(e,i[0]):this.chrAliasTable.set(e,e)}else this.chrAliasTable.set(e,e)}return this.chrAliasTable.get(e)}}class pc extends hc{constructor(e,t){super(e,t),this.parser=new Ia}async readHeader(){if(!this.header){let e=await this.readHeaderData();Ji(e)&&(e=er(e));const t=Wa(e);this.header=await this.parser.parseHeader(t,this.genome),this.header.sequenceNames&&this.header.sequenceNames.length>0&&(this.chromAliasManager=new fc(this.header.sequenceNames,this.genome))}return this.header}async readFeatures(e,t,i){if("all"===e)return[];if(this.config.format&&"VCF"!==this.config.format.toUpperCase())throw Error(`htsget format ${this.config.format} is not supported`);this.header||await this.readHeader();let r=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e,s=await this.readData(r,t,i);Ji(s)&&(s=er(s));const o=Wa(s);return this.parser.parseFeatures(o)}}class gc{constructor(e){this.genome=e}async nextFeature(e,t,i,r){let s=this.genome.chromosomeNames||[e],o=s.indexOf(e);if(o<0)return;const n=Math.min(1e4,r||1e4);let a=i?t:Math.max(t-n,0);for(;o=0;){e=s[o];const c=this.genome.getChromosome(e).bpLength;for(;a=0;){let s=i?a+n:Math.min(t,a+n);const o=await this.getFeatures({chr:e,start:a,end:s,visibilityWindow:r});if(o){const e=(e,t)=>e.start-t.start+e.end-t.end,r=Array.from(o);r.sort(e);let s=i?0:r.length-1;for(;s>=0&&st)return e;s++}else{if(o=0;){e=s[o];const c=this.genome.getChromosome(e).bpLength;for(;a=0;){let s=Math.min(t,a+n);const o=await this.getFeatures({chr:e,start:a,end:s,visibilityWindow:r});if(o){const e=(e,t)=>e.start-t.start+e.end-t.end,r=Array.from(o);r.sort(e);let s=i?0:r.length-1;for(;s>=0&&st)return e;s++}else{if(o=2){let e=t.getInt();for(this.windowFunctions=[];e-- >0;)this.windowFunctions.push(t.getString())}this.trackType=t.getString(),this.trackLine=t.getString();let i=t.getInt();for(this.trackNames=[];i-- >0;)this.trackNames.push(t.getString());this.genomeID=t.getString(),this.flags=t.getInt(),this.compressed=!!(1&this.flags),e=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:this.indexPos,size:this.indexSize}})),t=new qo(new DataView(e)),this.datasetIndex={};let r=t.getInt();for(;r-- >0;){const e=t.getString(),i=t.getLong(),r=t.getInt();this.datasetIndex[e]={position:i,size:r}}for(this.groupIndex={},r=t.getInt();r-- >0;){const e=t.getString(),i=t.getLong(),r=t.getInt();this.groupIndex[e]={position:i,size:r}}return this}async readDataset(e,t,i){const r=e+"_"+t+"_"+i;if(this.datasetCache[r])return this.datasetCache[r];{await this.readHeader();const s=this.version<2?"":"/"+t,o="all"===e.toLowerCase()||void 0===i?"0":i.toString();let n;n="raw"===t?"/"+e+"/raw":"/"+e+"/z"+o+s;const a=this.datasetIndex[n];if(void 0===a)return;const c=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:a.position,size:a.size}}));if(!c)return;const l=new qo(new DataView(c));let h=l.getInt();const d={};for(;h-- >0;)d[l.getString()]=l.getString();const u=l.getString(),f=l.getFloat();let p=l.getInt();const g=[];for(;p-- >0;)g.push({position:l.getLong(),size:l.getInt()});const m={name:n,attributes:d,dataType:u,tileWidth:f,tiles:g};return this.datasetCache[r]=m,m}}async readRootGroup(){const e=this.genome,t=this.groupCache["/"];if(t)return t;{const t=await this.readGroup("/"),i=t.chromosomes,r=t.maxZoom;r&&(this.maxZoom=Number(r));const s=t.totalCount;s&&(t.totalCount=Number(s));const o={};return i&&i.split(",").forEach((function(t){const i=e.getChromosomeName(t);o[i]=t})),this.chrAliasTable=o,this.groupCache["/"]=t,t}}async readGroup(e){const t=this.groupCache[e];if(t)return t;{await this.readHeader();const t=this.groupIndex[e];if(void 0===t)return;const i=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:t.position,size:t.size}}));if(!i)return;const r=new qo(new DataView(i)),s={name:e};let o=r.getInt();for(;o-- >0;){const e=r.getString(),t=r.getString();s[e]=t}return this.groupCache[e]=s,s}}async readTiles(e,t){if(e.sort((function(e,t){return e.position-t.position})),0===(e=e.filter((function(e){return e.size>0}))).length)return[];const i=[];for(let r of e){const e=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:r.position,size:r.size}}));let s;try{s=this.compressed?Zi(e).buffer:e}catch(e){console.error(e);continue}const o=new qo(new DataView(s)),n=o.getString();let a;switch(n){case"fixedStep":a=wc(o,t);break;case"variableStep":a=bc(o,t);break;case"bed":case"bedWithName":a=Fc(o,t,n);break;default:throw"Unknown tile type: "+n}i.push(a)}return i}async readTile(e,t){let i=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:e.position,size:e.size}}));if(this.compressed){i=Zi(i).buffer}const r=new qo(new DataView(i)),s=r.getString();switch(s){case"fixedStep":return wc(r,t);case"variableStep":return bc(r,t);case"bed":case"bedWithName":return Fc(r,t,s);default:throw"Unknown tile type: "+s}}}function wc(e,t){const i=e.getInt(),r=e.getInt(),s=e.getFloat(),o=[];let n=t;for(;n-- >0;){let t=i;const r=[];for(;t-- >0;)r.push(e.getFloat());o.push(r)}return{type:"fixedStep",start:r,span:s,data:o,nTracks:t,nPositions:i}}function bc(e,t){const i=e.getInt(),r=e.getFloat(),s=e.getInt(),o=[];let n=s;for(;n-- >0;)o.push(e.getInt());e.getInt();const a=[];let c=t;for(;c-- >0;){n=s;const t=[];for(;n-- >0;)t.push(e.getFloat());a.push(t)}return{type:"variableStep",tileStart:i,span:r,start:o,data:a,nTracks:t,nPositions:s}}function Fc(e,t,i){const r=e.getInt();let s=r;const o=[];for(;s-- >0;)o.push(e.getInt());s=r;const n=[];for(;s-- >0;)n.push(e.getInt());e.getInt();const a=[];let c=t;for(;c-- >0;){let t=r;const i=[];for(;t-- >0;)i.push(e.getFloat());a.push(i)}if("bedWithName"===i){s=r;const t=[];for(;s-- >0;)t.push(e.getString())}return{type:i,start:o,end:n,data:a,nTracks:t,nPositions:r}}class vc extends gc{#h={};searchable=!1;constructor(e,t){super(t),this.genome=t,this.reader=new mc(e,t),this.queryable=!0}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,windowFunction:s="mean"}){return"all"===e.toLowerCase()?this.getWGValues(s,r):this._getFeatures(e,t,i,r,s)}async _getFeatures(e,t,i,r,s){const o=new Mo(e,t,i),n=this.genome;if(!this.rootGroup&&(this.rootGroup=await this.reader.readRootGroup(),!this.normalizationFactor)){const e=this.rootGroup.totalCount;e&&(this.normalizationFactor=1e6/e)}o.bpPerPixel=r;const a=function(e,t,i){var r=i.getChromosome(e).bpLength;return Math.ceil(Math.log(Math.max(0,r/(700*t)))/_c)}(e,r,n);let c=this.reader.chrAliasTable[e],l=this.reader.maxZoom;void 0===c&&(c=e),void 0===l&&(l=-1);const h=a>l?"raw":s,d=await this.reader.readDataset(c,h,a);if(null==d)return[];const u=d.tileWidth,f=Math.floor(t/u),p=Math.floor(i/u),g=await this.reader.readTiles(d.tiles.slice(f,p+1),1),m=[];for(let s of g)switch(s.type){case"bed":yc(s,e,t,i,r,m);break;case"variableStep":Ac(s,e,t,i,r,m);break;case"fixedStep":Cc(s,e,t,i,r,m);break;default:throw"Unknown tile type: "+s.type}return m.sort((function(e,t){return e.start-t.start})),m}get supportsWholeGenome(){return!0}get windowFunctions(){return this.reader.windowFunctions}async getWGValues(e,t){const i=this.#h[e];if(i&&i.bpPerPixel>.8*t&&i.bpPerPixel<1.2*t)return i.values;{const i=[],r=this.genome;if(this.genome.wgChromosomeNames)for(let s of r.wgChromosomeNames){const o=r.getChromosome(s).bpLength;t=o/1e3;const n=await this._getFeatures(s,0,o,t,e);if(n)for(let e of n){const t=Object.assign({},e);t.chr="all",t.start=r.getGenomeCoordinate(e.chr,e.start),t.end=r.getGenomeCoordinate(e.chr,e.end),t._f=e,i.push(t)}}return this.#h[e]={values:i,bpPerPixel:t},i}}}function yc(e,t,i,r,s,o){const n=e.nPositions,a=e.start,c=e.end,l=e.data[0];for(let e=0;er)break;o.push({chr:t,start:s,end:n,value:l[e]})}}}function Ac(e,t,i,r,s,o){const n=e.nPositions,a=e.start,c=e.span,l=e.data[0];for(let e=0;er)break;o.push({chr:t,start:s,end:n,value:l[e]})}}}function Cc(e,t,i,r,s,o){const n=e.nPositions;let a=e.start;const c=e.span,l=e.data[0];for(let e=0;er)break;s>=i&&(Number.isNaN(l[e])||o.push({chr:t,start:a,end:s,value:l[e]})),a=s}}var _c=Math.log(2);class xc{static magic=610839776;littleEndian=!0;nodeCache=new Map;constructor(e,t,i,r){this.path=e,this.config=t,this.startOffset=i,this.loader=r||Rr}async init(){const e=await this.#t(this.startOffset,48);let t=e.getInt();if(t!==xc.magic&&(e.setPosition(0),this.littleEndian=!this.littleEndian,e.littleEndian=this.littleEndian,t=e.getInt(),t!==xc.magic))throw Error(`Bad magic number ${t}`);const i=e.getUInt(),r=e.getLong(),s=e.getUInt(),o=e.getUInt(),n=e.getUInt(),a=e.getUInt(),c=e.getLong(),l=e.getUInt(),h=e.getUInt(),d=this.startOffset+48;return this.header={magic:t,blockSize:i,itemCount:r,startChromIx:s,startBase:o,endChromIx:n,endBase:a,endFileOffset:c,itemsPerSlot:l,reserved:h,rootNodeOffset:d},this}async#t(e,t){const i=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:e,size:t}}));return new qo(new DataView(i),this.littleEndian)}async findLeafItemsOverlapping(e,t,i,r){const s=[],o=async n=>{const a=await this.readNode(n);for(let n of a.items)kc(n,e,t,i,r)&&(1===a.type?s.push(n):await o(n.childOffset))};return await o(this.header.rootNodeOffset),s}async readNode(e){const t=e;if(this.nodeCache.has(t))return this.nodeCache.get(t);let i=await this.#t(e,4);const r=i.getByte(),s=1===r;i.getByte();const o=i.getUShort();let n=o*(s?32:24);i=await this.#t(e+4,n);const a=[];for(let e=0;ee.startChrom||r===e.startChrom&&s>=e.startBase)&&(t!!e)),o=[];for(let e of s){const t=e.split(" ")[0];if(t.startsWith(i)&&o.push(e),t.slice(0,i.length)>i)break}if(0!==o.length){const e=new Map;for(let t of o){const[i,...r]=t.split(" ");e.set(i,r.map((e=>e.split(",")[0])))}return e}}async getIndex(e){return this.index||(this.index=await this._readIndex()),this.index}async _readIndex(e){return(await Rr.loadString(this.ixxFile)).split("\n").filter((e=>!!e)).map((e=>{const t=e.length-10,i=e.slice(0,t),r=e.slice(t);return[i,Number.parseInt(r,16)]}))}async _getBuffer(e,t){let i=0,r=65536;const s=await this.getIndex(t);for(let t=0;t{const r=await this.bpTree.readTreeNode(e);let s=null;if(1===r.type){for(const e of r.items){const t=e.key,r=e.value.id;r===i&&(s=t),this.nameToId.set(t,r),this.idToName.set(i,r)}return s}for(const e of r.items)if(s=await t.call(this,e.offset,i),null!==s)break;return s};try{return t.call(this,this.startOffset+32,e)}catch(e){throw new Error(e)}}async estimateGenomeSize(){try{const e={total:0,count:0};await this.accumulateSize(this.startOffset+32,e,1e4);return this.getItemCount()/e.count*e.total}catch(e){return console.error("Error estimating genome size",e),-1}}async accumulateSize(e,t,i){const r=await this.bpTree.readTreeNode(e);if(1===r.type)for(const e of r.items){const i=e.value;t.total+=i.size,t.count+=1}else{const e=r.items.slice().sort((()=>Math.random()-.5));for(const r of e)if(await this.accumulateSize(r.offset,t,i),t.count>i)break}return t}}class Nc{chrAliasTable=new Map;rpTreeCache=new Map;constructor(e,t){this.path=e.url,this.format=e.format||"bigwig",this.genome=t,this.config=e,this.bufferSize=512e3,this.loader=as(this.path)?new zc(nr(this.path).buffer):Rr;const i=e.trixURL||e.searchTrix;i&&(this._trix=new Sc(`${i}x`,i))}async preload(){const e=await Rr.loadArrayBuffer(this.path);this.loader=new zc(e);for(let e of this.rpTreeCache.values())e.loader=this.loader;if(this._searchTrees)for(let e of this._searchTrees)e.loader=this.loader}async readWGFeatures(e,t,i){await this.loadHeader();let r,s,o=Number.MAX_SAFE_INTEGER,n=-1;for(const t of e){const e=await this.getIdForChr(t);null!=e&&(en&&(n=e,s=t))}return this.readFeatures(r,0,s,Number.MAX_VALUE,t,i)}async readFeatures(e,t,i,r,s,o="mean"){t||(t=0),r||(r=Number.MAX_SAFE_INTEGER),await this.loadHeader();const n=await this.getIdForChr(e),a=await this.getIdForChr(i);if(void 0===n||void 0===a)return[];let c,l;if("bigwig"===this.type){const e=await this.getZoomHeaders();let t=s?function(e,t){let i;for(let r=0;r0?Zi(s):s,await l.call(this,new DataView(d.buffer),n,t,a,r,h,o)}return h.sort((function(e,t){return e.start-t.start})),h}return[]}async getIdForChr(e){if(this.chrAliasTable.has(e)&&!(e=this.chrAliasTable.get(e)))return;let t=await this.chromTree.getIdForName(e);if(void 0===t&&this.genome){const i=await this.genome.getAliasRecord(e);let r;if(i)for(let s of Object.keys(i))if("start"!==s&&"end"!==s&&(r=i[s],r!==e&&(t=await this.chromTree.getIdForName(r),void 0!==t)))break;this.chrAliasTable.set(e,r)}return t}get searchable(){return"bigbed"===this.type}async search(e){if(this.header||await this.loadHeader(),!this.header||!this.header.extraIndexCount)return;const t=await this._searchForRegions(e);if(t){const i=await this._loadFeaturesForRange(t.offset,t.length);if(i){const t=i.filter((t=>{for(let i of Object.keys(t)){const r=t[i];if(b(r)&&r.toLowerCase()===e.toLowerCase())return!0}return!1}));return t.length>0?t.reduce(((e,t)=>e.end-e.start>t.end-t.start?e:t),t[0]):void 0}}}async _searchForRegions(e){const t=await this.#d();if(t){if(this._trix){const t=e.toLowerCase(),i=await this._trix.search(t);i&&i.has(t)&&(e=i.get(t)[0])}for(let i of t){const t=await i.search(e);if(t)return t}}}async#d(){if(void 0===this._searchTrees&&this.header.extraIndexOffsets&&this.header.extraIndexOffsets.length>0){this._searchTrees=[];for(let e of this.header.extraIndexOffsets){const t=void 0,i=await Qo.loadBpTree(this.path,this.config,e,t,this.loader);this._searchTrees.push(i)}}return this._searchTrees}async getZoomHeaders(){return this.zoomLevelHeaders||await this.loadHeader(),this.zoomLevelHeaders}async loadHeader(){if(this.header)return this.header;{let e,t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:0,size:64}}));this.littleEndian=!0;const i=new qo(new DataView(t),this.littleEndian);let r=i.getUInt();if(2291137574===r)this.type="bigwig";else if(2273964779===r)this.type="bigbed";else{this.littleEndian=!1,i.littleEndian=!1,i.position=0;let e=i.getUInt();654085990===e?this.type="bigwig":3958540679===e&&(this.type="bigbed")}e={bwVersion:i.getUShort(),nZoomLevels:i.getUShort(),chromTreeOffset:i.getLong(),fullDataOffset:i.getLong(),fullIndexOffset:i.getLong(),fieldCount:i.getUShort(),definedFieldCount:i.getUShort(),autoSqlOffset:i.getLong(),totalSummaryOffset:i.getLong(),uncompressBuffSize:i.getInt(),extensionOffset:i.getLong()};const s=64;let o={start:s,size:e.totalSummaryOffset>0?e.totalSummaryOffset-s+40:Math.min(e.fullDataOffset,e.chromTreeOffset)-s};t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:o}));const n=new qo(new DataView(t),this.littleEndian),a=e.nZoomLevels;this.zoomLevelHeaders=[],this.firstZoomDataOffset=Number.MAX_SAFE_INTEGER;for(let e=1;e<=a;e++){const t=a-e,i=new Mc(t,n);this.firstZoomDataOffset=Math.min(i.dataOffset,this.firstZoomDataOffset),this.zoomLevelHeaders[t]=i}if(e.autoSqlOffset>0){n.position=e.autoSqlOffset-s;const t=n.getString();t&&(this.autoSql=function(e){let t;const i=[];let r=!1;const s=e.trim().split(/\s*[\r\n]+\s*/g);for(let e of s)if(e=e.trim(),e.length>0){if(e.startsWith("#"))continue;if(e.startsWith("table"))t=e.split(/\s+/)[1].trim();else if(e.startsWith("("))r=!0;else if(e.startsWith(")"));else if(r){const t=e.indexOf(";");if(t>0){const r=e.substr(0,t).split(/\s+/),s=e.substr(t+1).replace(/"/g,"").trim();i.push({type:r[0],name:r[1],description:s})}}}return{table:t,fields:i}}(t))}if(e.totalSummaryOffset>0&&(n.position=e.totalSummaryOffset-s,this.totalSummary=new Rc(n)),this.chromTree=new Ec(this.path,this.config,e.chromTreeOffset,this.loader),await this.chromTree.init(),"bigbed"===this.type){const t=await this.#u(e.fullDataOffset);this.featureDensity=t/await this.chromTree.estimateGenomeSize()}return this.header=e,e.extensionOffset>0&&await this.loadExtendedHeader(e.extensionOffset),this.header}}async#u(e){const t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:e,size:4}}));return new qo(new DataView(t),this.littleEndian).getInt()}async loadExtendedHeader(e){let t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:e,size:64}})),i=new qo(new DataView(t),this.littleEndian);i.getUShort();const r=i.getUShort(),s=i.getLong();if(0===r)return;let o=56*r;t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:s,size:o}})),i=new qo(new DataView(t),this.littleEndian);const n=[],a=[],c=[];for(let e=0;e0?Zi(r):r,o=Lc.call(this),n=[];return await o.call(this,new DataView(s.buffer),0,0,Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,n),n}}class Mc{constructor(e,t){this.index=e,this.reductionLevel=t.getUInt(),this.reserved=t.getInt(),this.dataOffset=t.getLong(),this.indexOffset=t.getLong()}}class Rc{constructor(e){e?(this.basesCovered=e.getLong(),this.minVal=e.getDouble(),this.maxVal=e.getDouble(),this.sumData=e.getDouble(),this.sumSquares=e.getDouble(),Bc.call(this)):(this.basesCovered=0,this.minVal=0,this.maxVal=0,this.sumData=0,this.sumSquares=0,this.mean=0,this.stddev=0)}}function Bc(){let e=this.basesCovered;if(e>0){this.mean=this.sumData/e,this.stddev=Math.sqrt(this.sumSquares/(e-1));let t=this.minVal<0?this.mean-2*this.stddev:0,i=this.maxVal>0?this.mean+2*this.stddev:0;this.defaultRange={min:t,max:i}}}async function Dc(e,t,i,r,s,o,n,a){const c=new qo(e,a),l=c.getInt(),h=c.getInt();let d=h,u=c.getInt();const f=c.getInt(),p=c.getInt(),g=c.getByte();c.getByte();let m=c.getUShort();if(l>=t&&l<=r){let e=0;for(;m-- >0;){let n;switch(g){case 1:d=c.getInt(),u=c.getInt(),n=c.getFloat();break;case 2:d=c.getInt(),n=c.getFloat(),u=d+p;break;case 3:n=c.getFloat(),d=h+e*f,u=d+p,e++}if(!(lr||l===r&&d>=s)break;if(Number.isFinite(n)){const e=await this.chromTree.getNameForId(l);o.push({chr:e,start:d,end:u,value:n})}}}}}function Lc(){const e=function(e,t,i,r){if("biginteract"===r||i&&("chromatinInteract"===i.table||"interact"===i.table))return function(e,t){return e.chr1=t[5],e.start1=Number.parseInt(t[6]),e.end1=Number.parseInt(t[7]),e.chr2=t[10],e.start2=Number.parseInt(t[11]),e.end2=Number.parseInt(t[12]),e.name=t[0],e.score=Number(t[1]),e.value=Number(t[2]),e.color="."===t[4]?void 0:"0"===t[4]?"rgb(0,0,0)":t[4],e};{const r=e-3;return function(s,o){if(r>0&&(s.name=o[0]),r>1&&(s.score=Number(o[1])),r>2&&(s.strand=o[2]),r>3&&(s.cdStart=parseInt(o[3])),r>4&&(s.cdEnd=parseInt(o[4])),r>5&&"."!==o[5]&&"0"!==o[5]&&"-1"!==o[5]){const e=ur.createColorString(o[5]);s.color=e.startsWith("rgb")?e:void 0}if(r>8){const e=parseInt(o[6]),t=o[7].split(","),i=o[8].split(","),r=[];for(let o=0;oi?r.utr=!0:(t>=s&&t<=e&&(r.cdStart=t),i>=s&&i<=e&&(r.cdEnd=i))}}(r,s.cdStart,s.cdEnd),s.exons=r}if(i)for(let r=e;r=13;){const t=a.getInt(),c=await this.chromTree.getNameForId(t),l=a.getInt(),h=a.getInt(),d=a.getString();if(!(ts||t===s&&l>=o)break;if(h>0){const t={chr:c,start:l,end:h};n.push(t);const i=d.split("\t");e(t,i)}}}}}async function Tc(e,t,i,r,s,o,n,a){const c=new qo(e,a);for(;c.remLength()>=32;){const e=c.getInt(),a=c.getInt(),l=c.getInt(),h=c.getInt(),d=c.getFloat(),u=c.getFloat(),f=c.getFloat();let p;switch(c.getFloat(),n){case"min":p=d;break;case"max":p=u;break;default:p=0===h?0:f/h}if(!(er||e===r&&a>=s)break;if(Number.isFinite(p)){const t=await this.chromTree.getNameForId(e);o.push({chr:t,start:a,end:l,value:p})}}}}class zc{constructor(e){this.data=e}loadArrayBuffer(e,t){const i=t.range;return i?this.data.slice(i.start,i.start+i.size):this.data}async dataViewForRange(e,t){const i=Math.min(this.data.byteLength-e.start,e.size);return t?new Uint8Array(this.data,e.start,i):new DataView(this.data,e.start,i)}}class Pc extends gc{queryable=!0;#h={};windowFunctions=["mean","min","max","none"];constructor(e,t){super(t),this.reader=new Nc(e,t),this.genome=t,this.format=e.format||"bigwig"}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,windowFunction:s}){await this.reader.loadHeader();const o="bigwig"===this.reader.type;let n;if("all"===e.toLowerCase()){const e=this.genome.wgChromosomeNames;n=o&&e?await this.getWGValues(e,s,r):[]}else n=await this.reader.readFeatures(e,t,e,i,r,s);return o||fa(n),n}async getHeader(){return this.reader.loadHeader()}async defaultVisibilityWindow(){return"bigwig"===this.reader.type?-1:this.reader.featureDensity?Math.floor(1e4/this.reader.featureDensity):-1}async getWGValues(e,t,i){const r=this.genome,s=this.#h[t];if(s&&s.bpPerPixel>.8*i&&s.bpPerPixel<1.2*i)return s.values;{const s=await this.reader.readWGFeatures(e,i,t);let o=[];for(let e of s){const t=e.chr,i=r.getCumulativeOffset(t);if(void 0===i)continue;const s=Object.assign({},e);s.chr="all",s.start=i+e.start,s.end=i+e.end,s._f=e,o.push(s)}return o.sort(((e,t)=>e.start-t.start)),this.#h[t]={values:o,bpPerPixel:i},o}}supportsWholeGenome(){return"bigwig"===this.reader.type}async trackType(){return this.reader.getTrackType()}get searchable(){return this.reader.searchable}async search(e){return this.reader.search(e)}}const Hc=.01;function Oc(e,t,i,r){let s=this.axisMin,o=this.axisMax;if(void 0===o&&this.dataRange&&(s=this.dataRange.min||0,o=this.dataRange.max),void 0===o)return;Co.fillRect(e,0,0,t,i,{fillStyle:"white"}),r&&Co.fillRect(e,t-4-2,0,4,i,{fillStyle:r});const n=void 0!==this.flipAxis&&this.flipAxis,a=.95*t-8-5,c=.95*t-5,l={font:"normal 10px Arial",textAlign:"right",fillStyle:"black",strokeStyle:"black"};Co.strokeLine(e,a,Hc*i,c,Hc*i,l),Co.fillText(e,d(n?s:o),a+4,Hc*i+12,l);const h=.99*i;function d(e){return Number.isInteger(e)||e%1==0?e:Math.abs(e)>=10?e.toFixed():Math.abs(e)>=1?e.toFixed(1):Math.abs(e)>=.1?e.toFixed(2):e.toExponential(1)}Co.strokeLine(e,a,h,c,h,l),Co.fillText(e,d(n?o:s),a+4,h-4,l),Co.strokeLine(e,c,Hc*i,c,h,l)}const Vc=e=>{switch(e.type){case"gradient":return new Gc(e);case"doubleGradient":case"diverging":return new jc(e);default:throw Error("Unknown color scale type: "+e)}},qc=function(e,t){return new Gc({type:"doubleGradient",min:e,max:t,minColor:"rgb(46,56,183)",maxColor:"rgb(164,0,30)"})},Uc=function(e,t,i){return new jc({type:"doubleGradient",min:0,mid:.25,max:.5,minColor:"rgb(46,56,183)",midColor:"white",maxColor:"rgb(164,0,30)"})};class Qc{constructor(e){this.thresholds=e.thresholds,this.colors=e.colors}getColor(e){for(let t of this.thresholds)if(e=this.max)return this.maxColor;const t=(e-this.min)/(this.max-this.min);return"rgb("+Math.floor(this.lowComponents[0]+t*(this.highComponents[0]-this.lowComponents[0]))+","+Math.floor(this.lowComponents[1]+t*(this.highComponents[1]-this.lowComponents[1]))+","+Math.floor(this.lowComponents[2]+t*(this.highComponents[2]-this.lowComponents[2]))+")"}toJson(){return{type:this.type,min:this.min,max:this.max,minColor:this.minColor,maxColor:this.maxColor}}clone(){return new Gc(this.toJson())}}class jc{constructor(e){this.type="diverging",this.lowGradientScale=new Gc({minColor:e.minColor||e.lowColor,maxColor:e.midColor,min:void 0!==e.min?e.min:e.low,max:e.mid}),this.highGradientScale=new Gc({minColor:e.midColor,maxColor:e.maxColor||e.highColor,min:e.mid,max:void 0!==e.max?e.max:e.high})}getColor(e){return e>6&3]+Go[Cy>>4&3]+Go[Cy>>2&3]+Go[3&Cy]);const Wo=jo.map((e=>e.toLowerCase()));class $o{littleEndian;metaIndex=new Map;chromosomeNames;constructor(e){this.url=e.twoBitURL||e.fastaURL,this.config=e,e.twoBitBptURL&&(this.bptURL=e.twoBitBptURL)}async init(){if(this.bptURL)this.index=await Qo.loadBpTree(this.bptURL,this.config,0);else{const e=await this._readIndex();this.index={search:async t=>e.has(t)?{offset:e.get(t)}:void 0}}}async readSequence(e,t,i){this.index||await this.init();const r=await this.getSequenceRecord(e);if(!r)return null;if(t<0)throw new TypeError("regionStart cannot be less than 0");(void 0===i||i>r.dnaSize)&&(i=r.dnaSize);const s=this._getOverlappingBlocks(t,i,r.nBlocks),o=this._getOverlappingBlocks(t,i,r.maskBlocks),n=Math.floor(t/4),a=r.packedPos+n,c=Math.floor(i/4)-n+1,l=await Rr.loadArrayBuffer(this.url,{range:{start:a,size:c}}),h=new Uint8Array(l);let d="";for(let e=t;ee;if(s[0]&&e>=s[0].start&&et)break;s.endr.contains(e,t,i)));if(r||(r=await this.#n(e,t,i),this.#a(r),this.#s.push(r)),r){const e=t-r.start,s=i-t;return r.features?r.features.substring(e,e+s):null}}#a(e){this.#s=this.#s.filter((t=>!e.contains(t))),this.#s.length===this.#o&&this.#s.shift(),this.browser&&this.browser.referenceFrameList.length<100&&(this.#s=this.#s.filter((e=>void 0!==this.browser.referenceFrameList.find((t=>t.overlaps(e))))))}getSequenceInterval(e,t,i){return this.#s.find((r=>r.contains(e,t,i)))}async#n(e,t,i){let r=t,s=i;if(i-t{o.features=await this.sequenceReader.readSequence(e,r,s),t(o)}));return this.#r=[o,t],t}}async init(){return this.sequenceReader.init()}get chromosomeNames(){return this.sequenceReader.chromosomeNames}getFirstChromosomeName(){return"function"==typeof this.sequenceReader.getFirstChromosomeName?this.sequenceReader.getFirstChromosomeName():void 0}#c(e){this.browser.referenceFrameList}}async function Zo(e,t){let i;return"chromsizes"===e.format?i=new Vo(e.fastaURL||e.url):"2bit"===e.format||e.twoBitURL?i=new Yo(new $o(e),t):as(e.fastaURL)||!e.indexURL?i=new Lo(e):"gbk"===e.format||e.gbkURL||(i=new Yo(new Ho(e),t)),await i.init(),i}const Xo={A:"rgb( 0, 200, 0)",C:"rgb( 0,0,200)",T:"rgb(255,0,0)",G:"rgb(209,113, 5)",N:"rgb(80,80,80)"};var Jo={color:1};Jo.parent=Jo,Jo.left=Jo,Jo.right=Jo;class en{constructor(){this.root=Jo}insert(e,t,i){var r=new an(new nn(e,t,i));for(this.treeInsert(r),r.color=2;r!==this.root&&2===r.parent.color;)if(r.parent===r.parent.parent.left){let e=r.parent.parent.right;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.right&&(r=r.parent,rn.call(this,r)),r.parent.color=1,r.parent.parent.color=2,sn.call(this,r.parent.parent))}else{let e=r.parent.parent.left;2===e.color?(r.parent.color=1,e.color=1,r.parent.parent.color=2,r=r.parent.parent):(r===r.parent.left&&(r=r.parent,sn.call(this,r)),r.parent.color=1,r.parent.parent.color=2,rn.call(this,r.parent.parent))}this.root.color=1}findOverlapping(e,t){var i=new nn(e,t,0);if(this.root===Jo)return[];var r=tn.call(this,i,this.root,[]);return r.length>1&&r.sort((function(e,t){return e.low-t.low})),r}logIntervals(){!function e(t,i){for(var r="",s=0;s=e.low&&tn.call(this,e,t.left,i),t.right!==Jo&&t.right.min<=e.high&&tn.call(this,e,t.right,i),i}function rn(e){var t=e.right;e.right=t.left,t.left!==Jo&&(t.left.parent=e),t.parent=e.parent,e.parent===Jo?this.root=t:e.parent.left===e?e.parent.left=t:e.parent.right=t,t.left=e,e.parent=t,on.call(this,e)}function sn(e){var t=e.left;e.left=t.right,t.right!==Jo&&(t.right.parent=e),t.parent=e.parent,e.parent===Jo?this.root=t:e.parent.right===e?e.parent.right=t:e.parent.left=t,t.right=e,e.parent=t,on.call(this,e)}function on(e){for(;e!==Jo;){var t=e.left.max>e.right.max?e.left.max:e.right.max,i=e.interval.high;e.max=t>i?t:i;var r=e.left.mine.low?1:this.highe.high?1:0}overlaps(e){return this.low<=e.high&&e.low<=this.high}}function an(e){this.parent=Jo,this.left=Jo,this.right=Jo,this.interval=e,this.color=2}class cn{constructor(e,t){e=e||[],this.treeMap=this.buildTreeMap(e),this.range=t,this.count=e.length}containsRange(e){return void 0===this.range||this.range.contains(e.chr,e.start,e.end)}findFeatures(e){const t=[];for(let i of Object.values(this.allFeatures))for(let r of i)e(r)&&t.push(r);return t}queryFeatures(e,t,i){const r=this.treeMap[e];if(!r)return[];const s=r.findOverlapping(t,i);if(0===s.length)return[];{const r=[],o=this.allFeatures[e];if(o){for(let e of s){const s=e.value;for(let e=s.start;ei)break;s.end>=t&&r.push(s)}}r.sort((function(e,t){return e.start-t.start}))}return r}}getAllFeatures(){return this.allFeatures}buildTreeMap(e){const t={},i=[];if(this.allFeatures={},e){for(let t of e){const e=t.chr;let r=this.allFeatures[e];r||(i.push(e),r=[],this.allFeatures[e]=r),r.push(t)}for(let e of i){const i=this.allFeatures[e];i.sort((function(e,t){return e.start===t.start?0:e.start>t.start?1:-1})),t[e]=ln(i)}}return t}}function ln(e){const t=new en,i=e.length,r=Math.max(10,Math.round(i/10));for(let s=0;s6&&"."!==e[6]&&(i.name=e[6]),e.length>7&&"."!==e[7]&&(i.score=Number(e[7])),e.length>8&&"."!==e[8]&&(i.strand1=e[8]),e.length>9&&"."!==e[9]&&(i.strand2=e[9])),t){const r=t.colorColumn;r&&rs&&t.columnNames&&t.columnNames.length===e.length&&(i.extras=e.slice(s))}return i.chr1===i.chr2&&(i.chr=i.chr1,i.start=Math.min(i.start1,i.start2),i.end=Math.max(i.end1,i.end2)),i}function un(e,t){if(!(e.length<8))return{chr:e[0],start:Number.parseInt(e[1]),end:Number.parseInt(e[2]),color:ur.createColorString(e[6]),value:Number(e[7])}}function fn(e){return e&&(e.includes("fdrDonut")||e.includes("fdr_donut"))}function pn(e,t){if(!(e.length<6))return{chr:e[0],start:Number.parseInt(e[1]),end:Number.parseInt(e[2]),chr1:e[8],start1:Number.parseInt(e[9]),end1:Number.parseInt(e[10]),chr2:e[13],start2:Number.parseInt(e[14]),end2:Number.parseInt(e[15]),name:e[3],score:Number(e[4]),value:Number(e[5]),color:"."===e[7]?void 0:"0"===e[7]?"rgb(0,0,0)":e[7]};console.log("Skipping line: "+e.join(" "))}class gn{constructor(e){this.message=e}}const mn=new Map([["%09","\t"],["%0A","\n"],["%0D","\r"],["%25","%"],["%3B",";"],["%3D","="],["%26","&"],["%2C",","]]);function wn(e){if(!e.includes("%"))return e;let t="";for(let i=0;i0&&e"),this.name&&t.push({name:"Name",value:this.name}),t.push({name:"Type",value:this.type}),t.push({name:"Source",value:this.source}),void 0!==this.score&&t.push({name:"Score",value:this.score}),t.push({name:"Phase",value:this.phase}),this.attributeString){const e=bn(this.attributeString,this.delim);for(let[i,r]of e)void 0!==r&&r.length>0&&!Mn.has(i.toLowerCase())&&t.push({name:i+":",value:r})}return t.push({name:"Location",value:`${this.chr}:${F(this.start+1)}-${F(this.end)}`}),t}getAttributeValue(e){if(this.hasOwnProperty(e))return this[e];if(this._attributeCache||(this._attributeCache=new Map),this._attributeCache.has(e))return this._attributeCache.get(e);{const t=bn(this.attributeString,this.delim);let i;for(let[r,s]of t)if(r===e){i=s;break}return this._attributeCache.set(e,i),i}}}class Bn extends Rn{constructor(e){super(e),this.exons=[],this.parts=[]}addExon(e){this.exons.push(e),this.start=Math.min(this.start,e.start),this.end=Math.max(this.end,e.end)}addPart(e){this.parts.push(e)}assembleParts(){if(0===this.parts.length)return;this.parts.sort((function(e,t){return e.start-t.start}));let e=this.parts[0].start,t=this.parts[0].end;for(let i=1;i=t&&i.start<=e)return i}addCDS(e){let t;const i=this.exons;for(let r of i)if(r.start<=e.start&&r.end>=e.end){t=r;break}t?(t.cdStart=t.cdStart?Math.min(e.start,t.cdStart):e.start,t.cdEnd=t.cdEnd?Math.max(e.end,t.cdEnd):e.end,t.readingFrame=e.readingFrame):console.error("No exon found spanning "+e.start+"-"+e.end),this.cdStart=this.cdStart?Math.min(e.start,this.cdStart):e.start,this.cdEnd=this.cdEnd?Math.max(e.end,this.cdEnd):e.end}addUTR(e){let t;const i=this.exons;for(let r=0;r=e.end){t=i[r];break}t?e.start===t.start&&e.end===t.end?t.utr=!0:(e.endt.start&&(t.cdEnd=e.start)):console.error("No exon found spanning "+cds.start+"-"+cds.end)}finish(){this.assembleParts();var e=this.cdStart,t=this.cdEnd;this.exons.sort((function(e,t){return e.start-t.start})),e&&this.exons.forEach((function(i){(i.endt)&&(i.utr=!0)}))}popupData(e){const t=super.popupData(e);for(let i of this.exons)if(!i.pseudo&&e>=i.start&&e");const r=i.popupData(e);for(let e of r)t.push(e)}for(let i of this.parts)if(e>=i.start&&e");const r=i.popupData(e);for(let e of r)t.push(e)}return t}}class Dn{static gffNameFields=new Set(["Name","transcript_id","gene_name","gene","gene_id","alias","locus","name"]);constructor(e){this.format=e.format,this.nameField=e.nameField,this.filterTypes=void 0===e.filterTypes?new Set(["chromosome"]):new Set(e.filterTypes)}combineFeatures(e,t){let i;const r=this.filterTypes;if(e=e.filter((e=>void 0===r||!r.has(e.type))),"gff3"===this.format){const t=this.combineFeaturesById(e);i=this.combineFeaturesByType(t)}else i=this.combineFeaturesByType(e);return this.numberExons(i,t),this.nameFeatures(i),i}combineFeaturesById(e){const t=new Map,i=[];for(let r of e)if(Nn(r.type)||En(r.type)||!r.id)i.push(r);else{let e=t.get(r.chr);e||(e=new Map,t.set(r.chr,e));let i=e.get(r.id);i?i.push(r):e.set(r.id,[r])}for(let e of t.values())for(let t of e.values())if(t.length>1){const e=t[0];e.exons=[];for(let i of t)e.start=Math.min(e.start,i.start),e.end=Math.max(e.end,i.end),e.exons.push({start:i.start,end:i.end});i.push(e)}else i.push(t[0]);return i}combineFeaturesByType(e){const t=e.filter((e=>"gene"===e.type||e.type.endsWith("_gene"))),i=Object.create(null);for(let e of t)i[e.id]=e;const r=Object.create(null),s=[],o=new Set,n=this.filterTypes;e=e.filter((e=>void 0===n||!n.has(e.type)));for(let t of e)if(En(t.type)){const e=t.id;if(void 0!==e){const n=new Bn(t);r[e]=n,s.push(n),o.add(t);const a=i[t.parent];a&&(n.geneObject=a,o.add(a))}}for(let t of e)if(Nn(t.type)){const e=l(t);if(e)for(let i of e){let n=r[i];if(!n&&"gtf"===this.format){const e=Object.assign({},t);e.type="transcript",n=new Bn(e),r[i]=n,s.push(n)}if(void 0!==n){if(a=t.type,_n.has(a))if(e.length>1){const e=new Rn(t);n.addExon(e)}else n.addExon(t);else n.addPart(t);o.add(t)}}}var a;s.forEach((function(e){"function"==typeof e.finish&&e.finish()}));const c=e.filter((e=>!o.has(e)));for(let e of c)s.push(e);return s;function l(e){return e.parent&&""!==e.parent.trim()?e.parent.trim().split(","):null}}numberExons(e,t){for(let i of e)if(i.exons&&(!t||i.end<=t.end&&i.start>t.start))for(let e=0;e2?parseInt(e[2]):o+1;if(isNaN(o)||isNaN(n))return new gn("Unparsable bed record.");const a=new Yn({chr:s,start:o,end:n,score:1e3});let c=3;try{if(e.length>3&&c++0&&e[3].indexOf("=")>0){const i=bn(e[3],"=");a.attributes={};for(let e of i)a.attributes[e[0]]=e[1],r&&(null!=t.nameField&&e[0]===t.nameField||!a.name&&Dn.gffNameFields.has(e[0]))&&(a.name=e[1])}a.name||r||(a.name="."===e[3]?"":e[3])}if(e.length>4&&c++5&&c++6&&c++7&&c++8&&c++11&&c++1e3)return a;const i=e[10].replace(/,$/,"").split(","),r=e[11].replace(/,$/,"").split(",");if(i.length!==r.length||t!==i.length)return a;const s=[];for(let e=0;e0&&(Qn(s,a.cdStart,a.cdEnd),a.exons=s)}if(t){let i=t.thicknessColumn,r=t.colorColumn;r&&r14&&(i.signal=Number(e[12]),i.pValue=Number(e[13]),i.qValue=Number(e[14])),i}function zn(e,t){const i=Ln(e,t,9);if(i){const t=["Coverage","% Showing Methylation","N-mod","N-canonical","N-other mod","N-delete","N-fail","N-dff","N-nocall"];for(let r=9;ri?r.utr=!0:(t>=s&&t<=e&&(r.cdStart=t),i>=s&&i<=e&&(r.cdEnd=i))}}function Gn(e,t){var i,r,s,o,n,a,c;if(!(e.length<9))return i=e[0],r=parseInt(e[1]),s=parseInt(e[2]),n=e[3],a=Number(e[4]),o=e[5].trim(),c=Number(e[6]),0===a&&(a=c),{chr:i,start:r,end:s,name:n,score:a,strand:o,signal:c,pValue:Number(e[7]),qValue:Number(e[8])}}function jn(e,t){const i=Gn(e);return e.length>9&&(i.peak=Number(e[9])),i}function Wn(e,t){if(e.length<=3)return;const i={chr:e[0],start:parseInt(e[1]),end:parseInt(e[2]),value:Number(e[3])};if(t){let r=t.colorColumn;r&&r0)for(var u=c.split(","),f=0;fd&&(d=m),l.spanning_frag_coords.push({left:g,right:m})}return l.start=h,l.end=d,l}}function ia(e,t){if(e.length<7)return null;const i={chr:e[0],start:parseInt(e[1])-1,end:parseInt(e[2]),"Strongest SNP-risk allele":e[3],"Disease/Phenotype":e[4],"P-value":e[5],"Odds ratio or beta":e[6]};return e.length>6&&(i.PUBMEDID=`${e[7]}`),i}function ra(e,t){const i=t.customFormat;if(e.length1&&(t=e)}else{this.config.decode||this.setDecoder(r.format);const e=i.split(this.delimiter||"\t");try{const i=Object.assign({columnNames:t},r);let s;if(s=this.decode(e,i)){r.firstFeature=s;break}e.length>1&&(t=e)}catch(i){e.length>1&&(t=e)}}}if(t){r.columnNames=t;for(let e=0;e0&&console.error(`Error parsing line '${o}': ${c.message}`)):c&&t.push(c)}return i===dn&&function(e){if(0==e.length)return;const t=e[0];if(void 0===t.score&&void 0!==t.name){for(let t of e)if(!ss(t.name)&&"."!==t.name)return;for(let t of e)t.score=Number(t.name),delete t.name}const i=e.filter((e=>e.chr1!==e.chr2));for(let t of i){const i=Object.assign({},t);i.dup=!0,e.push(i),t.chr=t.chr1,t.start=t.start1,t.end=t.end1,i.chr=i.chr2,i.start=i.start2,i.end=i.end2}}(t),"gtf"!==this.config.format&&"gff3"!==this.config.format&&"gff"!==this.config.format||!1===this.config.assembleGFF?t:new Dn(this.config).combineFeatures(t)}setDecoder(e){switch(e){case"broadpeak":case"regionpeak":case"peaks":this.decode=Gn,this.delimiter=this.config.delimiter||/\s+/;break;case"narrowpeak":this.decode=jn,this.delimiter=this.config.delimiter||/\s+/;break;case"bedgraph":this.decode=Wn,this.delimiter=/\s+/;break;case"wig":this.decode=$n,this.delimiter=this.config.delimiter||/\s+/;break;case"gff3":case"gff":this.decode=Jn,this.delimiter="\t";break;case"gtf":this.decode=ea,this.delimiter="\t";break;case"fusionjuncspan":this.decode=ta,this.delimiter=this.config.delimiter||/\s+/;break;case"gtexgwas":this.skipRows=1,this.decode=ia,this.delimiter="\t";break;case"refflat":this.decode=Vn,this.delimiter=this.config.delimiter||/\s+/;break;case"genepred":this.decode=Hn,this.delimiter=this.config.delimiter||/\s+/;break;case"genepredext":this.decode=On,this.delimiter=this.config.delimiter||/\s+/;break;case"ensgene":this.decode=Hn,this.header.shift=1,this.delimiter=this.config.delimiter||/\s+/;break;case"refgene":this.decode=On,this.delimiter=this.config.delimiter||/\s+/,this.header.shift=1;break;case"bed":this.decode=Ln,this.delimiter=this.config.delimiter||/\s+/;break;case"gappedpeak":this.decode=Tn,this.delimiter=this.config.delimiter||/\s+/;break;case"bedmethyl":this.decode=zn,this.delimiter=this.config.delimiter||/\s+/;break;case"bedpe":case"hiccups":this.decode=dn,this.delimiter=this.config.delimiter||"\t";break;case"bedpe-domain":this.decode=un,this.headerLine=!0,this.delimiter=this.config.delimiter||"\t";break;case"bedpe-loop":this.decode=dn,this.delimiter=this.config.delimiter||"\t",this.header={colorColumn:7};break;case"interact":this.decode=pn,this.delimiter=this.config.delimiter||/\s+/;break;case"snp":this.decode=Kn,this.delimiter="\t";break;case"rmsk":this.decode=Pn,this.delimiter="\t";break;case"gcnv":this.decode=sa,this.delimiter="\t";break;case"shoebox":this.decode=oa,this.delimiter="\t";break;default:const t=function(e){return na&&na[e]?function(e){const t=e.fields,i=["chr","start","end"];for(let r=0;r4?parseInt(t[4].split("=")[1],10):1,index:0}}function da(e){const t=e.split(/\s+/);return{format:"variableStep",chrom:t[1].split("=")[1],span:t.length>2?parseInt(t[2].split("=")[1],10):1}}function ua(e,i){const r=t({class:"igv-menu-popup-check-container"}),s=t();r.appendChild(s);const o=l("check",!0===i?"#444":"transparent");s.appendChild(o);const n=t();return n.innerText=e,r.appendChild(n),r}function fa(e,t){t=t||Number.MAX_SAFE_INTEGER;const i=[];e.sort((function(e,t){return e.start-t.start})),i.push(-1e3);for(let r of e){let e=0;const s=Math.min(i.length,t);for(e=0;e=i[e]){r.row=e,i[e]=r.end;break}r.row=e,i[e]=r.end}}async function pa(e,t,i,r){const s=new Map,o=new Map,n=e=>{const i=Object.assign({},e);if(i.chr="all",e.chr2&&e.end2){const r=s.get(e.chr1)||e.chr1,o=s.get(e.chr2)||e.chr2;i.start=t.getGenomeCoordinate(r,e.start1),i.end=t.getGenomeCoordinate(o,e.end2)}else{const r=s.get(e.chr)||e.chr;i.start=t.getGenomeCoordinate(r,e.start),i.end=t.getGenomeCoordinate(r,e.end)}return i._f=e,i.exons&&delete i.exons,i},a=new Set(t.wgChromosomeNames);if(i)for(let e of t.wgChromosomeNames){const t=await i.getAliasName(e);s.set(e,t),o.set(t,e)}const c=[];let l=0;for(let i of t.wgChromosomeNames){if(Array.isArray(e)){const i={};for(let r of e){const e=t.getChromosomeName(r.chr);i.hasOwnProperty(e)||(i[e]=[]),i[e].push(r)}e=i}const h=e[s.get(i)||i];if(h){const e=r||1e4;for(let t of h){if(t.dup)continue;const i=o.get(t.chr)||t.chr,r=t.chr2?o.get(t.chr2)||t.chr2:i;if(a.has(i)&&a.has(r))if(c.length0&&!i.startsWith("rgb(")&&!i.startsWith("rgba(")?`rgb(${i})`:i);var i;e.name||e.label?this.name=e.name||e.label:x(e.url)?this.name=e.url.name:b(e.url)&&!e.url.startsWith("data:")&&(this.name=_(e.url)),this.url=e.url,this.config.type&&(this.type=this.config.type),this.id=void 0===this.config.id?this.name:this.config.id,this.order=e.order,this.autoscaleGroup=e.autoscaleGroup,this.removable=void 0===e.removable||e.removable,this.minHeight=e.minHeight||Math.min(25,this.height),this.maxHeight=e.maxHeight||Math.max(1e3,this.height),e.onclick&&(this.onclick=e.onclick,e.onclick=void 0),e.description&&("function"==typeof e.description?this.description=e.description:this.description=()=>e.description)}async postInit(){return this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get name(){return this._name}set name(e){this._name=e,this.trackView&&this.trackView.setTrackLabelName(e)}clearCachedFeatures(){this.trackView&&this.trackView.clearCachedFeatures()}updateViews(){this.trackView&&this.trackView.updateViews()}repaintViews(){this.trackView&&this.trackView.repaintViews()}getState(){const e={},t=Object.keys(this.config).filter((e=>{return!(void 0===(t=this.config[e])||"function"==typeof t||t instanceof Promise);var t}));for(const i of t)i.startsWith("_")||(e[i]=this.config[i]);for(let t of Object.keys(e)){if(t.startsWith("_"))continue;const i=this[t];void 0===i||!es(i)&&"boolean"!=typeof i&&"metadata"!==t||(e[t]=i)}const i=Object.assign({},ma.defaults);if(this.constructor.defaults)for(let e of Object.keys(this.constructor.defaults))i[e]=this.constructor.defaults[e];for(let t of Object.keys(i))void 0!==this[t]&&i[t]!==this[t]&&(e[t]=this[t]);return!this.autoscale&&this.dataRange&&(e.min=this.dataRange.min,e.max=this.dataRange.max),this.autoscaleGroup&&(e.autoscaleGroup=this.autoscaleGroup),e}get supportsWholeGenome(){return!0===this.config.supportsWholeGenome}hasSamples(){return!1}getGenomeId(){return this.browser.genome?this.browser.genome.id:void 0}setTrackProperties(e){if(this.disposed)return;const t={};let i;for(let r of Object.keys(e))switch(r.toLowerCase()){case"usescore":t.useScore=1===e[r]||"1"===e[r]||"on"===e[r]||!0===e[r];break;case"visibility":switch(e[r]){case"2":case"3":case"pack":case"full":t.displayMode="EXPANDED";break;case"4":case"squish":t.displayMode="SQUISHED";break;case"1":case"dense":t.displayMode="COLLAPSED"}break;case"color":case"altcolor":t[r]=e[r].startsWith("rgb(")?e[r]:"rgb("+e[r]+")";break;case"featurevisiblitywindow":case"visibilitywindow":t.visibilityWindow=Number.parseInt(e[r]);break;case"maxheightpixels":i=e[r].split(":"),3===i.length&&(t.minHeight=Number.parseInt(i[2]),t.height=Number.parseInt(i[1]),t.maxHeight=Number.parseInt(i[0]));break;case"viewlimits":if(!this.config.autoscale&&!this.config.max){i=e[r].split(":");let s,o=0;1==i.length?s=Number(i[0]):2==i.length&&(o=Number(i[0]),s=Number(i[1])),Number.isNaN(s)||Number.isNaN(o)?console.warn(`Unexpected viewLimits value in track line: ${e.viewLimits}`):(t.autoscale=!1,t.dataRange={min:o,max:s},this.viewLimitMin=o,this.viewLimitMax=s)}case"name":t[r]=e[r];break;case"url":t.infoURL=e[r];break;case"type":const s=e[r];wa.has(s)?t[r]=wa.get(s):t[r]=s;break;case"graphtype":t.graphType=e[r];break;default:t[r]=e[r]}for(let e of Object.keys(t))if(!this.config.hasOwnProperty(e)||"name"===e&&this.config._derivedName){let i=t[e];if("true"===i&&(i=!0),"false"===i&&(i=!1),this[e]=i,"height"===e&&this.trackView)try{const e=Number.parseInt(i);this.trackView.setTrackHeight(e)}catch(e){console.error(e)}}}clickedFeatures(e){const t=e.viewport.cachedFeatures;if(!t||!Array.isArray(t)||0===t.length)return[];const i=e.genomicLocation,r=e.referenceFrame.bpPerPixel>.2?3*e.referenceFrame.bpPerPixel:.2;return Vr(t,i-r,i+r)}extractPopupData(e,t){const i=new Set(["row","color","chr","start","end","cdStart","cdEnd","strand","alpha"]),r=[];let s,o;for(let t in e)if(e.hasOwnProperty(t)&&!i.has(t)&&es(e[t])){let i=e[t];r.push({name:C(t),value:i}),"alleles"===t?s=e[t]:"alleleFreqs"===t&&(o=e[t])}if(s&&o){s.endsWith(",")&&(s=s.substr(0,s.length-1)),o.endsWith(",")&&(o=o.substr(0,o.length-1));let i=s.split(","),n=o.split(",");if(n.length>1){let s=[];for(let e=0;e=0;i--){let n=s[i].a;if(1===n.length){t||(t=this.getGenomeId());const i=ma.getCravatLink(e.chr,e.start+1,o,n,t);console.log(i),i&&(r.push("
"),r.push({html:i}),r.push("
"))}}}}if(e.attributes)for(let t of Object.keys(e.attributes))r.push({name:t,value:e.attributes[t]});let n=`${e.chr}:${F(e.start+1)}-${F(e.end)}`;return e.strand&&(n+=` (${e.strand})`),r.push({name:"Location",value:n}),r}description(){const e=(e,t)=>{const i=document.createElement("div");i.className="igv-track-label-popover__row";const r=document.createElement("span");r.className="igv-track-label-popover__key",r.textContent=e+":";const s=document.createElement("span");return s.className="igv-track-label-popover__value",s.textContent=t,i.appendChild(r),i.appendChild(s),i},t=document.createDocumentFragment();if(!this.url){const e=document.createElement("div");return e.className="igv-track-label-popover__row",e.textContent=this.name,t.appendChild(e),t}if(x(this.url)?t.appendChild(e("Filename",this.url.name)):t.appendChild(e("URL",this.url)),this.config){if(this.config.metadata)for(let i of Object.keys(this.config.metadata)){const r=this.config.metadata[i];t.appendChild(e(i,r))}for(let i of Object.keys(this.config)){if(i.startsWith("_"))continue;let r=i.substr(0,1);if(r!==r.toLowerCase()){const r=this.config[i];r&&es(r)&&t.appendChild(e(i,r))}}}return t}getColorForFeature(e){return"function"==typeof this.color?this.color(feature):this.color}numericDataMenuItems(){const e=[];if("heatmap"!==this.graphType){function t(e){this.trackView.track.selected?this.browser.dataRangeDialog.configure(this.trackView.browser.getSelectedTrackViews()):this.browser.dataRangeDialog.configure(this.trackView),this.browser.dataRangeDialog.present(e)}if(e.push("
"),e.push({label:"Set data range",dialog:t}),void 0!==this.logScale){function r(){this.logScale=!this.logScale,this.trackView.repaintViews()}e.push({element:ua("Log scale",this.logScale),click:r})}function i(){this.autoscaleGroup=void 0,this.autoscale=!this.autoscale,this.browser.updateViews()}e.push({element:ua("Autoscale",this.autoscale),click:i})}return e}setDataRange({min:e,max:t}){this.dataRange={min:e,max:t},this.autoscale=!1,this.autoscaleGroup=void 0,this.trackView.repaintViews()}async nextFeatureAfter(e,t,i){let r=this.trackView.viewports[0].cachedFeatures;if(r&&Array.isArray(r)&&r.length>0){if(this.browser.genome.getChromosomeName(r[0].chr)===e){const e=function(e,t,i=!0){const r=e=>(e.start+e.end)/2,s=i?(e,t)=>e.start-t.start+e.end-t.end:(e,t)=>t.start-e.start+t.end-e.end,o=Array.from(e);o.sort(s);let n=0,a=o.length;for(;n=t?n=e+1:a=e}return o[n]}(r,t,i);if(e)return e}}if("function"==typeof this.featureSource.nextFeature)return this.featureSource.nextFeature(e,t,i,this.visibilityWindow)}dispose(){this.disposed=!0;for(let e of Object.keys(this))this[e]=void 0}static getCravatLink(e,t,i,r,s){if("hg38"===s||"GRCh38"===s){return`Cravat ${i}->${r}`}}static localFileInspection(e){const t=Object.assign({},e),i={url:"file",indexURL:"indexFile"};for(const e of["url","indexURL"])t[e]&&t[e]instanceof File&&(t[i[e]]=t[e].name,delete t[e]);return t}set filter(e){this._filter=e,this.trackView.repaintViews()}getInViewFeatures(){const e=[];for(let t of this.trackView.viewports)if(t.isVisible()){const i=t.referenceFrame;i.chr;const r=i.start,s=r+i.toBP(t.getWidth());if(t.cachedFeatures){const i=Vr(t.cachedFeatures,r,s);for(let t of i)this._filter&&!this._filter(t)||e.push(t)}}return e}getFilterableAttributes(){return{}}}const wa=new Map([["wiggle_0","wig"],["bed","bed"],["bigBed","bigBed"],["bigWig","bigWig"]]);class ba{constructor(e){switch(this.type=e||"seg",this.type){case"mut":this.sampleColumn=3,this.chrColumn=0,this.startColumn=1,this.endColumn=2,this.dataColumn=4;break;case"maf":this.sampleColumn=15,this.chrColumn=4,this.startColumn=5,this.endColumn=6,this.dataColumn=8;break;default:this.sampleColumn=0,this.chrColumn=1,this.startColumn=2,this.endColumn=3}}async parseHeader(e){let t;for(;void 0!==(t=await e.nextLine());)if(!t.startsWith("#")){const e=t.split("\t");this.header={headings:e};break}return this.header}async parseFeatures(e){const t=[];let i;this.header||(this.header=await this.parseHeader(e)),"seg"===this.type&&(this.dataColumn=this.header.headings.length-1),this.header.headings.length>5&&(i=this.extractExtraColumns(this.header.headings));const r=this.header.headings[this.dataColumn];let s;for(;void 0!==(s=await e.nextLine());){const e=s.split("\t"),o="seg"===this.type?Number(e[this.dataColumn]):e[this.dataColumn];if(e.length>this.dataColumn){const s=new Fa({sample:e[this.sampleColumn],chr:e[this.chrColumn],start:parseInt(e[this.startColumn])-1,end:parseInt(e[this.endColumn]),value:o,valueColumnName:r});if(i){const t=this.extractExtraColumns(e);s.setAttributes({names:i,values:t})}t.push(s)}}return t}extractExtraColumns(e){const t=[];for(let i=0;i=0)return this.attributeValues[t]}}popupData(e,t){const i=new Set(["chr","start","end","sample","value","row","color","sampleKey","uniqueSampleKey","sampleId","chromosome","uniquePatientKey"]),r=this.chr+":"+F(this.start+1)+"-"+F(this.end),s=[{name:"Sample",value:this.sample},{name:"Location",value:r},{name:this.valueColumnName?C(this.valueColumnName):"Value",value:this.value}];if("mut"===e&&"hg38"===t){const e=this.extractCravatLink(t);e&&(s.push("
"),s.push({html:e}),s.push("
"))}if(this.attributeNames&&this.attributeNames.length>0)for(let e=0;e0)for(let r=0;r"===t||"<*>"===t||"."===t)return"NONVARIANT";{const e=t.split(",").map((function(e){return 1===i&&1===e.length?"SNP":""===e?"NONVARIANT":e.length>i&&xa(e)?"INSERTION":e.lengthe.length>0));this.alleles=[],this.start=void 0,this.end=void 0;for(let t of i)if(this.alleles.push(t),"SV"!==this.type&&xa(t)){let i=t.length,r=e.length;const s=Math.min(i,r);let o=0;for(;o0&&r>0;){const s=o+i-1,n=o+r-1;if(t.charCodeAt(s)!==e.charCodeAt(n))break;i--,r--}for(;i>0&&r>0;){const s=o,n=o;if(t.charCodeAt(s)!==e.charCodeAt(n))break;o++,i--,r--}const n=this.pos+o-1,a=n+r;this.start=void 0===this.start?n:Math.min(this.start,n),this.end=void 0===this.end?a:Math.max(this.end,a)}void 0===this.start&&(this.start=this.pos-1,this.end=this.pos),this.start===this.end&&(this.start-=.5,this.end+=.5)}}popupData(e,t){const i=`${F(this.pos)}`,r=this.start===this.end?`${F(this.start)} | ${F(this.start+1)}`:`${F(this.start+1)}-${F(this.end)}`,s=[{name:"Chr",value:this.chr},{name:"Pos",value:i},{name:"Loc",value:r},{name:"ID",value:this.names?this.names:""},{name:"Ref",value:this.referenceBases},{name:"Alt",value:this.alternateBases.replace("<","<")},{name:"Qual",value:this.quality},{name:"Filter",value:this.filter}];if(this.type&&s.push({name:"Type",value:this.type}),"SNP"===this.type){let e=this.referenceBases;if(1===e.length){let i=this.alternateBases.split(",");for(let r of i)if(1===r.length){let i=ma.getCravatLink(this.chr,this.pos,e,r,t);i&&(s.push("
"),s.push({html:i}))}}}const o=Object.keys(this.info);if(this.info&&o.length>0){s.push({html:'
'});for(let e of o)s.push({name:e,value:ka(decodeURIComponent(this.info[e]))})}return s}getInfo(e){return this.info?this.info[e]:void 0}isRefBlock(){return"NONVARIANT"===this.type}isFiltered(){return!("."===this.filter||"PASS"===this.filter)}alleleFreq(){return this.info?this.info.AF:void 0}}class Aa{constructor(e){this.mate=e,this.chr=e.info.CHR2,this.pos=Number.parseInt(e.info.END),this.start=this.pos-1,this.end=this.pos}get info(){return this.mate.info}get names(){return this.mate.names}get referenceBases(){return this.mate.referenceBases}get alternateBases(){return this.mate.alternateBases}get quality(){return this.mate.quality}get filter(){return this.mate.filter}get calls(){return this.mate.calls}getAttributeValue(e){return this.mate.getAttributeValue(e)}getInfo(e){this.mate.getInfo(e)}isFiltered(){return this.mate.isFiltered()}alleleFreq(){return this.mate.alleleFreq()}popupData(e,t){const i=[];return i.push("SV Breakpoint"),i.push({name:"Chr",value:this.chr}),i.push({name:"Pos",value:`${F(this.pos)}`}),i.push({html:'
'}),i.push("SV"),i.push(...this.mate.popupData(e,t)),i}}class Ca{constructor({formatFields:e,sample:t,token:i}){this.info={},this.sample=t;const r=i.split(":");for(let t=0;t");for(let e of s)i.push({name:e,value:decodeURIComponent(this.info[e])});return i}}const _a=new Set(["A","C","T","G"].map((e=>e.charCodeAt(0))));function xa(e){for(let t=0;t");if(!(t>2&&n>0)){console.log("Malformed VCF header line: "+r);continue}const a=r.substring(2,t-1);i[a]||(i[a]={});const c=y(r.substring(t+1,n-1),",");for(let t of c){var s=t.split("=");s.length>1&&("ID"===s[0]?e=s[1]:o[s[0]]=s[1])}e&&(i[a][e]=o)}else if(r.startsWith("##contig")&&t){const e=r.indexOf("",e));const s=r.substring(e+4,t);i.sequenceNames.push(s)}}else if(r.startsWith("#CHROM")){const e=r.split("\t");if(e.length>8){i.sampleNameMap=new Map;for(let t=9;t9){const s=Sa(e[8].split(":"));r.calls=[];for(let t=9;t{const t=e.indexOf("E");if(t>0){if(Number.parseInt(e.substring(t+1))0||0==i.length||i.indexOf("x")>0)continue;const o=e[this.chrCol],n=s(e[this.valueCol]),a=parseInt(i)-1,c=a+1;t.push(new Ma({chr:o,start:a,end:c,value:n,line:r,columns:this.columns}))}}return t}static isGWAS(e){const t=e.split("\t");if(t.length<5)return!1;const i=[["chr","chromosome","chr_id","chrom"],["bp","pos","position","chr_pos","chromEnd"],["p","pval","p-value","p.value"]];for(let e of i)if(!t.some((t=>e.includes(t.toLowerCase()))))return!1;return!0}}class Ma{constructor({chr:e,start:t,end:i,value:r,line:s,columns:o}){this.chr=e,this.start=t,this.end=i,this.value=r,this.line=s,this.columns=o}popupData(){const e=this.line.split(/\t/);return this.columns.map((function(t,i){return{name:t,value:e[i]}}))}getAttributeValue(e){const t=this.line.split(/\t/);for(let i=0;i0?r=e:r?(s.push(r+e),r=void 0):s.push(e));for(let e of s){if(!e)return;var o=e.split("=",2);if(2===o.length){const e=o[0].trim(),i=o[1].trim();t[e]=i}}return t}function Pa(e){let t={},i=e.split(/\s+/);if(2===i.length){i[1].split(";").forEach((function(e){let i=e.split("=");"color"===i[0]?t.colorColumn=Number.parseInt(i[1])-1:"thickness"===i[0]&&(t.thicknessColumn=Number.parseInt(i[1])-1)}))}return t}function Ha(e,t){var i,r,s=e.columns;this.aed=e,this.allColumns=t,this.chr=null,this.start=null,this.end=null,this.score=1e3,this.strand=".",this.cdStart=null,this.cdEnd=null,this.name=null,this.color=null;for(let e=0;e0)for(let e=0;ee.maxv.isGreaterThan(t))));const i=[];let r;for(let t of e)r&&qa(r,t)?t.maxv.isGreaterThan(r.maxv)&&(r.maxv=t.maxv):(i.push(t),r=t);return i}function qa(e,t){const i=t.minv.block-e.maxv.block;return t.maxv.block-e.minv.block<5e6&&i<65e3}Ha.prototype.popupData=function(){for(var e=[],t=this.aed,i=0;i=28){t.getInt(),t.getInt(),t.getInt(),t.getInt(),t.getInt(),t.getInt();const e=t.getInt(),i=t.position+e;let s=0;for(;t.positiono)t.getInt(),t.getVPointer(),t.getVPointer(),t.getLong(),t.getLong();else{i[e]=[];const r=t.getInt();for(let o=0;os&&(s=o.block),i[e].push([r,o]))}}}n>0&&(this.indices[e]={binIndex:i,loffset:r})}this.lastBlockPosition=s}get sequenceNames(){return Object.keys(this.sequenceIndexMap)}chunksForRange(e,t,i){const r=this.indices[e];if(r){const e=this.reg2bins(t,i);if(0==e.length)return[];const s=[];for(let t of e)for(let e=t[0];e<=t[1];e++)if(r.binIndex[e]){const t=r.binIndex[e];for(let i of t){const t=i[0],r=i[1];s.push({minv:t,maxv:r,bin:e})}}let o=e[this.depth][0];do{if(r.binIndex[o])break;o>1+(this.getParentBin(o)<<3)?o--:o=this.getParentBin(o)}while(0!=o);return Va(s,r.loffset[o])}return[]}getParentBin(e){return 0==e?0:e-1>>3}reg2bins(e,t){(e-=1)<1&&(e=1),t>2**34&&(t=2**34),t-=1;let i=0,r=0,s=this.minShift+3*this.depth;const o=[];for(;i<=this.depth;s-=3,r+=1<<3*i,i+=1){const i=r+(e>>s),n=r+(t>>s);o.push([i,n])}return o}bin_limit(){return((1<<3*(this.depth+1))-1)/7}}class Qa{constructor(){}async parse(e,t){const i=[];let r=Number.MAX_SAFE_INTEGER,s=0;const o=new qo(new DataView(e)),n=o.getInt(),a={};if(!(21578050===n||t&&21578324===n))throw new Error(indexURL+" is not a "+(t?"tabix":"bai")+" file");{const e=o.getInt();if(t){o.getInt(),o.getInt(),o.getInt(),o.getInt(),o.getInt(),o.getInt(),o.getInt();for(let t=0;ts&&(s=n.block),e[t].push([i,n]))}}}const c=o.getInt();for(let e=0;e0&&(i[t]={binIndex:e,linearIndex:n})}this.firstBlockPosition=r,this.lastBlockPosition=s,this.indices=i,this.sequenceIndexMap=a,this.tabix=t}}get sequenceNames(){return Object.keys(this.sequenceIndexMap)}chunksForRange(e,t,i){const r=this.indices[e];if(r){const e=function(e,t){const i=[];t>=1<<29&&(t=1<<29);return--t,i.push([0,0]),i.push([1+(e>>26),1+(t>>26)]),i.push([9+(e>>23),9+(t>>23)]),i.push([73+(e>>20),73+(t>>20)]),i.push([585+(e>>17),585+(t>>17)]),i.push([4681+(e>>14),4681+(t>>14)]),i}(t,i),s=[];for(let t of e)for(let e=t[0];e<=t[1];e++)if(r.binIndex[e]){const t=r.binIndex[e];for(let e of t){const t=e[0],i=e[1];s.push({minv:t,maxv:i})}}const o=r.linearIndex.length;let n;const a=Math.min(t>>14,o-1),c=Math.min(i>>14,o-1);for(let e=a;e<=c;e++){const t=r.linearIndex[e];if(t){n=t;break}}return Va(s,n)}return[]}}class Ga{constructor(){this.tribble=!0}async parse(e){let t=0;this.chrIndex={},this.lastBlockPosition=[];const i=new qo(new DataView(e));!function(e){e.getInt(),e.getInt();const t=e.getInt();if(e.getString(),e.getLong(),e.getLong(),e.getString(),e.getInt(),t>=3){let t=e.getInt();for(;t-- >0;)e.getString(),e.getString()}}(i);let r=i.getInt();for(;r-- >0;){let e=i.getString();const r=i.getInt(),s=i.getInt(),o=i.getInt();i.getInt(),i.getInt();let n=i.getLong();const a=[];for(let e=0;et&&(t=e)}this.chrIndex[e]={chr:e,blocks:a,longestFeature:o,binWidth:r}}this.lastBlockPosition=t}get sequenceNames(){return Object.keys(this.chrIndex)}chunksForRange(e,t,i){const r=this.chrIndex[e];if(r){const e=r.blocks,s=r.longestFeature,o=r.binWidth,n=Math.max(t-s,0),a=Math.floor(n/o);if(a>=e.length)return[];{const t=Math.min(Math.floor((i-1)/o),e.length-1),r=e[a].min,s=e[t].max;if(0===s-r)return[];return[{minv:{block:r,offset:0},maxv:{block:s,offset:0}}]}}}}async function ja(e,t){let i=await Rr.loadArrayBuffer(e,ts(t)),r=new DataView(i);if(31===r.getUint8(0)&&139===r.getUint8(1)){i=tr(i).buffer,r=new DataView(i)}switch(r.getInt32(0,!0)){case 21578050:return async function(e){const t=new Qa;return await t.parse(e,!1),t}(i);case 21578324:return async function(e){const t=new Qa;return await t.parse(e,!0),t}(i);case 21582659:return async function(e){const t=new Ua;return t.parse(e),t}(i);case 1480870228:return async function(e){const t=new Ga;return t.parse(e),t}(i);case 38359875:throw Error("CSI version 2 is not supported.");default:throw Error(`Unrecognized index type: ${e}`)}}function Wa(e){return"string"==typeof e||e instanceof String?new $a(e):new Ka(e)}class $a{constructor(e){this.data=e,this.ptr=0}nextLine(){var e=this.ptr,t=this.data.indexOf("\n",e),i=this.data;if(t>0)return this.ptr=t+1,t>e&&"\r"===i.charAt(t-1)?i.substring(e,t-1):i.substring(e,t);var r=i.length;return this.ptr=r,e>=r?void 0:i.substring(e)}}class Ka{constructor(e){this.data=e,this.length=this.data.length,this.ptr=0}nextLine(){if(this.ptr>=this.data.length)return;let e=this.ptr;const t=this.data;let i="",r=!1;for(;e0)for(var a=0;a{const t=ArrayBuffer.isView(e)?e:new Uint8Array(e);return 1+(t[17]<<8|t[16])};class Xa{constructor(e){this.config=e,this.cacheBlocks=0!=e.cacheBlocks,this.cache=void 0}async getData(e,t){const i=e.block,r=t.block,s=0===t.offset,o=await this.getInflatedBlocks(i,r,s);if(1===o.length)return o[0];let n=0;for(const e of o)n+=e.byteLength;const a=new Uint8Array(n);let c=0;for(const e of o)a.set(e,c),c+=e.byteLength;return a}async getInflatedBlocks(e,t,i){if(this.cacheBlocks){const r=this.cache;if(r&&r.startBlock<=e&&(r.endBlock>=t||i&&r.nextEndBlock===t)){const i=e-r.startBlock,s=t-r.startBlock;return ec(r.buffer,i,s)}{let s;if(!r||r.startBlock>t||r.endBlock=r.endBlock)n=r.buffer;else{const i=Math.max(0,e-r.startBlock);let s;if(t>=r.endBlock)s=r.buffer.byteLength;else{const e=Ja(r.buffer);for(let i=0;ir.endBlock){const e=await this.loadBLockData(r.endBlock,t,{skipStart:!0,skipEnd:i});o.push(e)}s=function(e){if(1===e.length)return e[0];let t=0;for(const i of e)t+=i.byteLength;const i=new Uint8Array(t);let r=0;for(const t of e)i.set(new Uint8Array(t),r),r+=t.byteLength;return i.buffer}(o)}let o=t;if(i){const e=Ja(s);t=e[e.length-1]}return this.cache={startBlock:e,endBlock:t,nextEndBlock:o,buffer:s},ec(s)}}return ec(await this.loadBLockData(e,t,{skipEnd:i}))}async loadBLockData(e,t,i){const r=this.config,s=i&&i.skipStart;let o=0;if(!(i&&i.skipEnd)){const e=ts(r,{range:{start:t,size:26}}),i=await Rr.loadArrayBuffer(r.url,e);o=Za(i)}if(s){const t=ts(r,{range:{start:e,size:26}}),i=await Rr.loadArrayBuffer(r.url,t);e+=Za(i)}const n=ts(r,{range:{start:e,size:t+o-e}});return Rr.loadArrayBuffer(r.url,n)}}function Ja(e){const t=e.byteLength;let i=0;const r=[0];for(;i{const t=e.indexOf("E");if(t>0){if(Number.parseInt(e.substring(t+1))0||0==i.length||i.indexOf("x")>0)continue;const r=e[this.chrColumn],o=s(e[this.pValueColumn]),n=parseInt(i)-1,a=n+1,c=e[this.snpColumn],l=e[this.phenotypeColumn],h=new rc({chr:r,start:n,end:a,pValue:o,snp:c,phenotype:l},this.columns,e);t.push(h)}}return t}static isQTL(e){const t=e.split("\t");if(t.length<5)return!1;const i=[["chr","chromosome","chr_id","chrom"],["bp","pos","position","chr_pos","chromEnd"],["p","pval","p-value","p.value"],["rsid","variant","snp"],["phenotype","gene","gene_id","molecular_trait_id"]];for(let e of i)if(!t.some((t=>e.includes(t.toLowerCase()))))return!1;return!0}}class rc{constructor({chr:e,start:t,end:i,pValue:r,snp:s,phenotype:o},n,a){this.chr=e,this.start=t,this.end=i,this.pValue=r,this.snp=s,this.phenotype=o,this.headers=n,this.tokens=a}popupData(){const e=[];for(let t=0;te.blocks)).map((e=>e.max)).reduce(((e,t)=>Math.min(e,t)),Number.MAX_SAFE_INTEGER),r=ts(this.config,{bgz:e.tabix,range:{start:0,size:i}});t=Wa(await Rr.loadString(this.config.url,r))}return this.header=await this.parser.parseHeader(t),this.header}if("service"!==this.config.sourceType){let e;if(this.indexed=!1,this.config._filecontents)e=this.config._filecontents,delete this.config._filecontents;else{const t=ts(this.config);e=await Rr.loadByteArray(this.config.url,t)}e.length<5e8&&(e=(new TextDecoder).decode(e));let t=Wa(e);return this.header=await this.parser.parseHeader(t),t=Wa(e),this.features=await this.parser.parseFeatures(t),this.sequenceNames=new Set(this.features.map((e=>e.chr))),this.header}if(this.config.seqnamesURL){const e=ts(this.config,{}),t=await Rr.loadString(this.config.seqnamesURL,e);t&&(this.sequenceNames=new Set(t.split(",").map((e=>e.trim())).filter((e=>e))))}if(this.config.headerURL){const e=ts(this.config,{}),t=Wa(await Rr.loadString(this.config.headerURL,e));return this.header=await this.parser.parseHeader(t),this.header}}getParser(e){switch(e.format){case"vcf":return new Ia(e);case"seg":return new ba("seg");case"mut":return new ba("mut");case"maf":return new ba("maf");case"gwas":return new Na(e);case"qtl":return new ic(e);case"aed":return new Da(e);default:return new aa(e)}}async loadFeaturesNoIndex(){if(this.features){const e=this.features;return delete this.features,e}{const e=ts(this.config),t=await Rr.loadByteArray(this.config.url,e);if(!this.header){const e=Wa(t);this.header=await this.parser.parseHeader(e)}const i=Wa(t),r=[];return await this._parse(r,i),r}}async loadFeaturesWithIndex(e,t,i){const r=this.config;this.parser;const s=this.index.tabix,o=s?this.index.sequenceIndexMap[e]:e;if(void 0===o)return[];const n=this.index.chunksForRange(o,t,i);if(n&&0!==n.length){const o=[];for(let a of n){let n;if(s)n=await this._blockLoader.getData(a.minv,a.maxv);else{const e=ts(r,{range:{start:a.minv.block,size:a.maxv.block-a.minv.block+1}});n=await Rr.loadString(r.url,e)}const c=Wa(a.minv.offset?n.slice(a.minv.offset):n);await this._parse(o,c,e,i,t)}return o}return[]}async loadFeaturesFromService(e,t,i){let r;r="function"==typeof this.config.url?this.config.url({chr:e,start:t,end:i}):this.config.url.replace("$CHR",e).replace("$START",t).replace("$END",i);const s=ts(this.config),o=Wa(await Rr.loadString(r,s)),n=[];return await this._parse(n,o),n}async _parse(e,t,i,r,s){let o=await this.parser.parseFeatures(t);if(o.sort((function(e,t){return e.chr===t.chr?e.start-t.start:e.chr.localeCompare(t.chr)})),void 0===i)for(let t of o)e.push(t);else{let t=!1;for(let n=0;nr){e.push(a);break}a.end>=s&&a.start<=r&&(t||(t=!0,n>0&&e.push(o[n-1])),e.push(a))}}}}async getIndex(){return this.index?this.index:this.config.indexURL?(this.index=await this.loadIndex(),this.index):void 0}async loadIndex(){return ja(this.config.indexURL,this.config)}async loadFeaturesFromDataURI(){if(this.features){const e=this.features;return delete this.features,e}{const e=nr(this.dataURI);let t=Wa(e);this.header=await this.parser.parseHeader(t),this.header instanceof String&&this.header.startsWith("##gff-version 3")&&(this.format="gff3"),t=Wa(e);const i=[];return await this._parse(i,t),i}}}const oc=b;class nc{constructor(e){this.config=e}async readFeatures(e,t,i){let r;r="function"==typeof this.config.url?this.config.url({chr:e,start:t,end:i}):this.config.url.replace("$CHR",e).replace("$START",t).replace("$END",i);let s,o=Object.assign({},this.config);void 0!==this.config.body&&("function"==typeof this.config.body?o.body=this.config.body({chr:e,start:t,end:i}):o.body=this.config.body.replace("$CHR",e).replace("$START",t).replace("$END",i));const n=await Rr.load(r,o);if(n&&(s="function"==typeof this.config.parser?this.config.parser(n):oc(n)?JSON.parse(n):n),this.config.mappings){let e=Object.keys(this.config.mappings);for(let t of s)for(let i of e)t[i]=t[this.config.mappings[i]]}return s}}const ac=function(e,t){this.config=e,this.genome=t,this.expandQueryInterval=!1};ac.prototype.readFeatures=function(e,t,i){const r=Math.max(0,Math.floor(t));let s=Math.ceil(i);if(this.genome){const t=this.genome.getChromosome(e);t&&s>t.bpLength&&(s=t.bpLength)}const o=this.config.url+"?db="+this.config.db+"&table="+this.config.tableName+"&chr="+e+"&start="+r+"&end="+s;return Rr.loadJson(o,this.config).then((function(e){return e?(e.forEach((function(e){e.hasOwnProperty("exonStarts")&&e.hasOwnProperty("exonEnds")&&e.hasOwnProperty("exonCount")&&e.hasOwnProperty("cdsStart")&&e.hasOwnProperty("cdsEnd")&&function(e){var t,i,r,s,o,n;t=e.exonCount,i=e.exonStarts.split(","),r=e.exonEnds.split(","),s=[];for(var a=0;an||e.cdsEnd=o&&e.cdsStart<=n&&(c.cdStart=e.cdsStart),e.cdsEnd>=o&&e.cdsEnd<=n&&(c.cdEnd=e.cdsEnd),s.push(c)}e.exons=s}(e)})),e):null}))};class cc{featureCaches=[];gtexChrs=new Set(["chr1","chr10","chr11","chr12","chr13","chr14","chr15","chr16","chr17","chr18","chr19","chr2","chr20","chr21","chr22","chr3","chr4","chr5","chr6","chr7","chr8","chr9","chrM","chrX","chrY"]);constructor(e){this.config=e,this.url=e.url,this.tissueId=e.tissueSiteDetailId,this.datasetId=e.datasetId||"gtex_v8"}async readFeatures(e,t,i){const r=e.startsWith("chr")?e:"MT"===e?"chrM":"chr"+e;if(!this.gtexChrs.has(r))return[];const s=Math.floor(t),o=Math.ceil(i),n=this.datasetId,a=this.url+"?chromosome="+r+"&start="+s+"&end="+o+"&tissueSiteDetailId="+this.tissueId+"&datasetId="+n,c=await Rr.loadJson(a,{withCredentials:this.config.withCredentials});return c&&c.singleTissueEqtl?c.singleTissueEqtl.map((e=>new lc(e))):[]}}class lc{constructor(e){this.chr=e.chromosome,this.start=e.pos-1,this.end=this.start+1,this.snp=e.snpId,this.phenotype=e.geneSymbol,this.pValue=e.pValue,this.json=e}popupData(){return Object.keys(this.json).map((e=>({name:e,value:this.json[e]})))}}class hc{constructor(e,t){if(this.config=e,this.genome=t,!e.format)throw Error('Format is required, and must be either "bam" or "cram"');if(this.format=e.format.toUpperCase(),"BAM"!==this.format&&"VCF"!==this.format)throw Error(`htsget format ${e.format} is not supported`)}async readHeaderData(){const e=`${dc(this.config)}?class=header&format=${this.format}`,t=await Rr.loadJson(e,ts(this.config));return await this.loadUrls(t.htsget.urls)}async readData(e,t,i){const r=`${dc(this.config)}?format=${this.format}&referenceName=${e}&start=${Math.floor(t)}&end=${Math.ceil(i)}`,s=await Rr.loadJson(r,ts(this.config));return this.loadUrls(s.htsget.urls)}async loadUrls(e){const t=[];for(let i of e)if(i.url.startsWith("data:"))t.push(Promise.resolve(uc(i.url)));else{const e={headers:i.headers||{}};t.push(Rr.loadArrayBuffer(i.url,e))}return function(e){let t=0;for(let i of e)t+=i.byteLength;let i=0;const r=new Uint8Array(t);for(let t of e){const e=new Uint8Array(t);r.set(e,i),i+=e.length}return r}(await Promise.all(t))}static async inferFormat(e){try{const t=dc(e),i=`${t}${t.includes("?")?"&":"?"}class=header`,r=await Rr.loadJson(i,ts(e));if(r.htsget){const t=r.htsget.format;if("BAM"!==t&&"VCF"!==t)throw Error(`htsget format ${t} is not supported`);e.format=t.toLowerCase(),e.sourceType="htsget",e.name||(e.name=await os(e.url))}}catch(e){}}}function dc(e){if(e.url&&e.endpoint&&e.id)return e.url+e.endpoint+e.id;if(e.endpoint&&e.id)return e.endpoint+e.id;if(e.url)return e.url.startsWith("htsget://")?e.url.replace("htsget://","https://"):e.url;throw Error("Must specify either 'url', or 'endpoint' and 'id")}function uc(e){const t=e.split(","),i=t[0].split(":")[1];let r=t[1];r=i.indexOf("base64")>=0?atob(r):decodeURI(r);const s=new Uint8Array(r.length);for(var o=0;o"start"!==e&&"end"!==e)).map((e=>t[e])).filter((e=>this.sequenceNames.has(e)));i.length>0?this.chrAliasTable.set(e,i[0]):this.chrAliasTable.set(e,e)}else this.chrAliasTable.set(e,e)}return this.chrAliasTable.get(e)}}class pc extends hc{constructor(e,t){super(e,t),this.parser=new Ia}async readHeader(){if(!this.header){let e=await this.readHeaderData();Ji(e)&&(e=er(e));const t=Wa(e);this.header=await this.parser.parseHeader(t,this.genome),this.header.sequenceNames&&this.header.sequenceNames.length>0&&(this.chromAliasManager=new fc(this.header.sequenceNames,this.genome))}return this.header}async readFeatures(e,t,i){if("all"===e)return[];if(this.config.format&&"VCF"!==this.config.format.toUpperCase())throw Error(`htsget format ${this.config.format} is not supported`);this.header||await this.readHeader();let r=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e,s=await this.readData(r,t,i);Ji(s)&&(s=er(s));const o=Wa(s);return this.parser.parseFeatures(o)}}class gc{constructor(e){this.genome=e}async nextFeature(e,t,i,r){let s=this.genome.chromosomeNames||[e],o=s.indexOf(e);if(o<0)return;const n=Math.min(1e4,r||1e4);let a=i?t:Math.max(t-n,0);for(;o=0;){e=s[o];const c=this.genome.getChromosome(e).bpLength;for(;a=0;){let s=i?a+n:Math.min(t,a+n);const o=await this.getFeatures({chr:e,start:a,end:s,visibilityWindow:r});if(o){const e=(e,t)=>e.start-t.start+e.end-t.end,r=Array.from(o);r.sort(e);let s=i?0:r.length-1;for(;s>=0&&st)return e;s++}else{if(o=0;){e=s[o];const c=this.genome.getChromosome(e).bpLength;for(;a=0;){let s=Math.min(t,a+n);const o=await this.getFeatures({chr:e,start:a,end:s,visibilityWindow:r});if(o){const e=(e,t)=>e.start-t.start+e.end-t.end,r=Array.from(o);r.sort(e);let s=i?0:r.length-1;for(;s>=0&&st)return e;s++}else{if(o=2){let e=t.getInt();for(this.windowFunctions=[];e-- >0;)this.windowFunctions.push(t.getString())}this.trackType=t.getString(),this.trackLine=t.getString();let i=t.getInt();for(this.trackNames=[];i-- >0;)this.trackNames.push(t.getString());this.genomeID=t.getString(),this.flags=t.getInt(),this.compressed=!!(1&this.flags),e=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:this.indexPos,size:this.indexSize}})),t=new qo(new DataView(e)),this.datasetIndex={};let r=t.getInt();for(;r-- >0;){const e=t.getString(),i=t.getLong(),r=t.getInt();this.datasetIndex[e]={position:i,size:r}}for(this.groupIndex={},r=t.getInt();r-- >0;){const e=t.getString(),i=t.getLong(),r=t.getInt();this.groupIndex[e]={position:i,size:r}}return this}async readDataset(e,t,i){const r=e+"_"+t+"_"+i;if(this.datasetCache[r])return this.datasetCache[r];{await this.readHeader();const s=this.version<2?"":"/"+t,o="all"===e.toLowerCase()||void 0===i?"0":i.toString();let n;n="raw"===t?"/"+e+"/raw":"/"+e+"/z"+o+s;const a=this.datasetIndex[n];if(void 0===a)return;const c=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:a.position,size:a.size}}));if(!c)return;const l=new qo(new DataView(c));let h=l.getInt();const d={};for(;h-- >0;)d[l.getString()]=l.getString();const u=l.getString(),f=l.getFloat();let p=l.getInt();const g=[];for(;p-- >0;)g.push({position:l.getLong(),size:l.getInt()});const m={name:n,attributes:d,dataType:u,tileWidth:f,tiles:g};return this.datasetCache[r]=m,m}}async readRootGroup(){const e=this.genome,t=this.groupCache["/"];if(t)return t;{const t=await this.readGroup("/"),i=t.chromosomes,r=t.maxZoom;r&&(this.maxZoom=Number(r));const s=t.totalCount;s&&(t.totalCount=Number(s));const o={};return i&&i.split(",").forEach((function(t){const i=e.getChromosomeName(t);o[i]=t})),this.chrAliasTable=o,this.groupCache["/"]=t,t}}async readGroup(e){const t=this.groupCache[e];if(t)return t;{await this.readHeader();const t=this.groupIndex[e];if(void 0===t)return;const i=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:t.position,size:t.size}}));if(!i)return;const r=new qo(new DataView(i)),s={name:e};let o=r.getInt();for(;o-- >0;){const e=r.getString(),t=r.getString();s[e]=t}return this.groupCache[e]=s,s}}async readTiles(e,t){if(e.sort((function(e,t){return e.position-t.position})),0===(e=e.filter((function(e){return e.size>0}))).length)return[];const i=[];for(let r of e){const e=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:r.position,size:r.size}}));let s;try{s=this.compressed?Yi(e).buffer:e}catch(e){console.error(e);continue}const o=new qo(new DataView(s)),n=o.getString();let a;switch(n){case"fixedStep":a=wc(o,t);break;case"variableStep":a=bc(o,t);break;case"bed":case"bedWithName":a=Fc(o,t,n);break;default:throw"Unknown tile type: "+n}i.push(a)}return i}async readTile(e,t){let i=await Rr.loadArrayBuffer(this.path,ts(this.config,{range:{start:e.position,size:e.size}}));if(this.compressed){i=Yi(i).buffer}const r=new qo(new DataView(i)),s=r.getString();switch(s){case"fixedStep":return wc(r,t);case"variableStep":return bc(r,t);case"bed":case"bedWithName":return Fc(r,t,s);default:throw"Unknown tile type: "+s}}}function wc(e,t){const i=e.getInt(),r=e.getInt(),s=e.getFloat(),o=[];let n=t;for(;n-- >0;){let t=i;const r=[];for(;t-- >0;)r.push(e.getFloat());o.push(r)}return{type:"fixedStep",start:r,span:s,data:o,nTracks:t,nPositions:i}}function bc(e,t){const i=e.getInt(),r=e.getFloat(),s=e.getInt(),o=[];let n=s;for(;n-- >0;)o.push(e.getInt());e.getInt();const a=[];let c=t;for(;c-- >0;){n=s;const t=[];for(;n-- >0;)t.push(e.getFloat());a.push(t)}return{type:"variableStep",tileStart:i,span:r,start:o,data:a,nTracks:t,nPositions:s}}function Fc(e,t,i){const r=e.getInt();let s=r;const o=[];for(;s-- >0;)o.push(e.getInt());s=r;const n=[];for(;s-- >0;)n.push(e.getInt());e.getInt();const a=[];let c=t;for(;c-- >0;){let t=r;const i=[];for(;t-- >0;)i.push(e.getFloat());a.push(i)}if("bedWithName"===i){s=r;const t=[];for(;s-- >0;)t.push(e.getString())}return{type:i,start:o,end:n,data:a,nTracks:t,nPositions:r}}class vc extends gc{#h={};searchable=!1;constructor(e,t){super(t),this.genome=t,this.reader=new mc(e,t),this.queryable=!0}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,windowFunction:s="mean"}){return"all"===e.toLowerCase()?this.getWGValues(s,r):this._getFeatures(e,t,i,r,s)}async _getFeatures(e,t,i,r,s){const o=new Mo(e,t,i),n=this.genome;if(!this.rootGroup&&(this.rootGroup=await this.reader.readRootGroup(),!this.normalizationFactor)){const e=this.rootGroup.totalCount;e&&(this.normalizationFactor=1e6/e)}o.bpPerPixel=r;const a=function(e,t,i){var r=i.getChromosome(e).bpLength;return Math.ceil(Math.log(Math.max(0,r/(700*t)))/_c)}(e,r,n);let c=this.reader.chrAliasTable[e],l=this.reader.maxZoom;void 0===c&&(c=e),void 0===l&&(l=-1);const h=a>l?"raw":s,d=await this.reader.readDataset(c,h,a);if(null==d)return[];const u=d.tileWidth,f=Math.floor(t/u),p=Math.floor(i/u),g=await this.reader.readTiles(d.tiles.slice(f,p+1),1),m=[];for(let s of g)switch(s.type){case"bed":yc(s,e,t,i,r,m);break;case"variableStep":Ac(s,e,t,i,r,m);break;case"fixedStep":Cc(s,e,t,i,r,m);break;default:throw"Unknown tile type: "+s.type}return m.sort((function(e,t){return e.start-t.start})),m}get supportsWholeGenome(){return!0}get windowFunctions(){return this.reader.windowFunctions}async getWGValues(e,t){const i=this.#h[e];if(i&&i.bpPerPixel>.8*t&&i.bpPerPixel<1.2*t)return i.values;{const i=[],r=this.genome;if(this.genome.wgChromosomeNames)for(let s of r.wgChromosomeNames){const o=r.getChromosome(s).bpLength;t=o/1e3;const n=await this._getFeatures(s,0,o,t,e);if(n)for(let e of n){const t=Object.assign({},e);t.chr="all",t.start=r.getGenomeCoordinate(e.chr,e.start),t.end=r.getGenomeCoordinate(e.chr,e.end),t._f=e,i.push(t)}}return this.#h[e]={values:i,bpPerPixel:t},i}}}function yc(e,t,i,r,s,o){const n=e.nPositions,a=e.start,c=e.end,l=e.data[0];for(let e=0;er)break;o.push({chr:t,start:s,end:n,value:l[e]})}}}function Ac(e,t,i,r,s,o){const n=e.nPositions,a=e.start,c=e.span,l=e.data[0];for(let e=0;er)break;o.push({chr:t,start:s,end:n,value:l[e]})}}}function Cc(e,t,i,r,s,o){const n=e.nPositions;let a=e.start;const c=e.span,l=e.data[0];for(let e=0;er)break;s>=i&&(Number.isNaN(l[e])||o.push({chr:t,start:a,end:s,value:l[e]})),a=s}}var _c=Math.log(2);class xc{static magic=610839776;littleEndian=!0;nodeCache=new Map;constructor(e,t,i,r){this.path=e,this.config=t,this.startOffset=i,this.loader=r||Rr}async init(){const e=await this.#t(this.startOffset,48);let t=e.getInt();if(t!==xc.magic&&(e.setPosition(0),this.littleEndian=!this.littleEndian,e.littleEndian=this.littleEndian,t=e.getInt(),t!==xc.magic))throw Error(`Bad magic number ${t}`);const i=e.getUInt(),r=e.getLong(),s=e.getUInt(),o=e.getUInt(),n=e.getUInt(),a=e.getUInt(),c=e.getLong(),l=e.getUInt(),h=e.getUInt(),d=this.startOffset+48;return this.header={magic:t,blockSize:i,itemCount:r,startChromIx:s,startBase:o,endChromIx:n,endBase:a,endFileOffset:c,itemsPerSlot:l,reserved:h,rootNodeOffset:d},this}async#t(e,t){const i=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:e,size:t}}));return new qo(new DataView(i),this.littleEndian)}async findLeafItemsOverlapping(e,t,i,r){const s=[],o=async n=>{const a=await this.readNode(n);for(let n of a.items)kc(n,e,t,i,r)&&(1===a.type?s.push(n):await o(n.childOffset))};return await o(this.header.rootNodeOffset),s}async readNode(e){const t=e;if(this.nodeCache.has(t))return this.nodeCache.get(t);let i=await this.#t(e,4);const r=i.getByte(),s=1===r;i.getByte();const o=i.getUShort();let n=o*(s?32:24);i=await this.#t(e+4,n);const a=[];for(let e=0;ee.startChrom||r===e.startChrom&&s>=e.startBase)&&(t!!e)),o=[];for(let e of s){const t=e.split(" ")[0];if(t.startsWith(i)&&o.push(e),t.slice(0,i.length)>i)break}if(0!==o.length){const e=new Map;for(let t of o){const[i,...r]=t.split(" ");e.set(i,r.map((e=>e.split(",")[0])))}return e}}async getIndex(e){return this.index||(this.index=await this._readIndex()),this.index}async _readIndex(e){return(await Rr.loadString(this.ixxFile)).split("\n").filter((e=>!!e)).map((e=>{const t=e.length-10,i=e.slice(0,t),r=e.slice(t);return[i,Number.parseInt(r,16)]}))}async _getBuffer(e,t){let i=0,r=65536;const s=await this.getIndex(t);for(let t=0;t{const r=await this.bpTree.readTreeNode(e);let s=null;if(1===r.type){for(const e of r.items){const t=e.key,r=e.value.id;r===i&&(s=t),this.nameToId.set(t,r),this.idToName.set(i,r)}return s}for(const e of r.items)if(s=await t.call(this,e.offset,i),null!==s)break;return s};try{return t.call(this,this.startOffset+32,e)}catch(e){throw new Error(e)}}async estimateGenomeSize(){try{const e={total:0,count:0};await this.accumulateSize(this.startOffset+32,e,1e4);return this.getItemCount()/e.count*e.total}catch(e){return console.error("Error estimating genome size",e),-1}}async accumulateSize(e,t,i){const r=await this.bpTree.readTreeNode(e);if(1===r.type)for(const e of r.items){const i=e.value;t.total+=i.size,t.count+=1}else{const e=r.items.slice().sort((()=>Math.random()-.5));for(const r of e)if(await this.accumulateSize(r.offset,t,i),t.count>i)break}return t}}class Nc{chrAliasTable=new Map;rpTreeCache=new Map;constructor(e,t){this.path=e.url,this.format=e.format||"bigwig",this.genome=t,this.config=e,this.bufferSize=512e3,this.loader=as(this.path)?new zc(nr(this.path).buffer):Rr;const i=e.trixURL||e.searchTrix;i&&(this._trix=new Sc(`${i}x`,i))}async preload(){const e=await Rr.loadArrayBuffer(this.path);this.loader=new zc(e);for(let e of this.rpTreeCache.values())e.loader=this.loader;if(this._searchTrees)for(let e of this._searchTrees)e.loader=this.loader}async readWGFeatures(e,t,i){await this.loadHeader();let r,s,o=Number.MAX_SAFE_INTEGER,n=-1;for(const t of e){const e=await this.getIdForChr(t);null!=e&&(en&&(n=e,s=t))}return this.readFeatures(r,0,s,Number.MAX_VALUE,t,i)}async readFeatures(e,t,i,r,s,o="mean"){t||(t=0),r||(r=Number.MAX_SAFE_INTEGER),await this.loadHeader();const n=await this.getIdForChr(e),a=await this.getIdForChr(i);if(void 0===n||void 0===a)return[];let c,l;if("bigwig"===this.type){const e=await this.getZoomHeaders();let t=s?function(e,t){let i;for(let r=0;r0?Yi(s):s,await l.call(this,new DataView(d.buffer),n,t,a,r,h,o)}return h.sort((function(e,t){return e.start-t.start})),h}return[]}async getIdForChr(e){if(this.chrAliasTable.has(e)&&!(e=this.chrAliasTable.get(e)))return;let t=await this.chromTree.getIdForName(e);if(void 0===t&&this.genome){const i=await this.genome.getAliasRecord(e);let r;if(i)for(let s of Object.keys(i))if("start"!==s&&"end"!==s&&(r=i[s],r!==e&&(t=await this.chromTree.getIdForName(r),void 0!==t)))break;this.chrAliasTable.set(e,r)}return t}get searchable(){return"bigbed"===this.type}async search(e){if(this.header||await this.loadHeader(),!this.header||!this.header.extraIndexCount)return;const t=await this._searchForRegions(e);if(t){const i=await this._loadFeaturesForRange(t.offset,t.length);if(i){const t=i.filter((t=>{for(let i of Object.keys(t)){const r=t[i];if(b(r)&&r.toLowerCase()===e.toLowerCase())return!0}return!1}));return t.length>0?t.reduce(((e,t)=>e.end-e.start>t.end-t.start?e:t),t[0]):void 0}}}async _searchForRegions(e){const t=await this.#d();if(t){if(this._trix){const t=e.toLowerCase(),i=await this._trix.search(t);i&&i.has(t)&&(e=i.get(t)[0])}for(let i of t){const t=await i.search(e);if(t)return t}}}async#d(){if(void 0===this._searchTrees&&this.header.extraIndexOffsets&&this.header.extraIndexOffsets.length>0){this._searchTrees=[];for(let e of this.header.extraIndexOffsets){const t=void 0,i=await Qo.loadBpTree(this.path,this.config,e,t,this.loader);this._searchTrees.push(i)}}return this._searchTrees}async getZoomHeaders(){return this.zoomLevelHeaders||await this.loadHeader(),this.zoomLevelHeaders}async loadHeader(){if(this.header)return this.header;{let e,t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:0,size:64}}));this.littleEndian=!0;const i=new qo(new DataView(t),this.littleEndian);let r=i.getUInt();if(2291137574===r)this.type="bigwig";else if(2273964779===r)this.type="bigbed";else{this.littleEndian=!1,i.littleEndian=!1,i.position=0;let e=i.getUInt();654085990===e?this.type="bigwig":3958540679===e&&(this.type="bigbed")}e={bwVersion:i.getUShort(),nZoomLevels:i.getUShort(),chromTreeOffset:i.getLong(),fullDataOffset:i.getLong(),fullIndexOffset:i.getLong(),fieldCount:i.getUShort(),definedFieldCount:i.getUShort(),autoSqlOffset:i.getLong(),totalSummaryOffset:i.getLong(),uncompressBuffSize:i.getInt(),extensionOffset:i.getLong()};const s=64;let o={start:s,size:e.totalSummaryOffset>0?e.totalSummaryOffset-s+40:Math.min(e.fullDataOffset,e.chromTreeOffset)-s};t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:o}));const n=new qo(new DataView(t),this.littleEndian),a=e.nZoomLevels;this.zoomLevelHeaders=[],this.firstZoomDataOffset=Number.MAX_SAFE_INTEGER;for(let e=1;e<=a;e++){const t=a-e,i=new Mc(t,n);this.firstZoomDataOffset=Math.min(i.dataOffset,this.firstZoomDataOffset),this.zoomLevelHeaders[t]=i}if(e.autoSqlOffset>0){n.position=e.autoSqlOffset-s;const t=n.getString();t&&(this.autoSql=function(e){let t;const i=[];let r=!1;const s=e.trim().split(/\s*[\r\n]+\s*/g);for(let e of s)if(e=e.trim(),e.length>0){if(e.startsWith("#"))continue;if(e.startsWith("table"))t=e.split(/\s+/)[1].trim();else if(e.startsWith("("))r=!0;else if(e.startsWith(")"));else if(r){const t=e.indexOf(";");if(t>0){const r=e.substr(0,t).split(/\s+/),s=e.substr(t+1).replace(/"/g,"").trim();i.push({type:r[0],name:r[1],description:s})}}}return{table:t,fields:i}}(t))}if(e.totalSummaryOffset>0&&(n.position=e.totalSummaryOffset-s,this.totalSummary=new Rc(n)),this.chromTree=new Ec(this.path,this.config,e.chromTreeOffset,this.loader),await this.chromTree.init(),"bigbed"===this.type){const t=await this.#u(e.fullDataOffset);this.featureDensity=t/await this.chromTree.estimateGenomeSize()}return this.header=e,e.extensionOffset>0&&await this.loadExtendedHeader(e.extensionOffset),this.header}}async#u(e){const t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:e,size:4}}));return new qo(new DataView(t),this.littleEndian).getInt()}async loadExtendedHeader(e){let t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:e,size:64}})),i=new qo(new DataView(t),this.littleEndian);i.getUShort();const r=i.getUShort(),s=i.getLong();if(0===r)return;let o=56*r;t=await this.loader.loadArrayBuffer(this.path,ts(this.config,{range:{start:s,size:o}})),i=new qo(new DataView(t),this.littleEndian);const n=[],a=[],c=[];for(let e=0;e0?Yi(r):r,o=Lc.call(this),n=[];return await o.call(this,new DataView(s.buffer),0,0,Number.MAX_SAFE_INTEGER,Number.MAX_SAFE_INTEGER,n),n}}class Mc{constructor(e,t){this.index=e,this.reductionLevel=t.getUInt(),this.reserved=t.getInt(),this.dataOffset=t.getLong(),this.indexOffset=t.getLong()}}class Rc{constructor(e){e?(this.basesCovered=e.getLong(),this.minVal=e.getDouble(),this.maxVal=e.getDouble(),this.sumData=e.getDouble(),this.sumSquares=e.getDouble(),Bc.call(this)):(this.basesCovered=0,this.minVal=0,this.maxVal=0,this.sumData=0,this.sumSquares=0,this.mean=0,this.stddev=0)}}function Bc(){let e=this.basesCovered;if(e>0){this.mean=this.sumData/e,this.stddev=Math.sqrt(this.sumSquares/(e-1));let t=this.minVal<0?this.mean-2*this.stddev:0,i=this.maxVal>0?this.mean+2*this.stddev:0;this.defaultRange={min:t,max:i}}}async function Dc(e,t,i,r,s,o,n,a){const c=new qo(e,a),l=c.getInt(),h=c.getInt();let d=h,u=c.getInt();const f=c.getInt(),p=c.getInt(),g=c.getByte();c.getByte();let m=c.getUShort();if(l>=t&&l<=r){let e=0;for(;m-- >0;){let n;switch(g){case 1:d=c.getInt(),u=c.getInt(),n=c.getFloat();break;case 2:d=c.getInt(),n=c.getFloat(),u=d+p;break;case 3:n=c.getFloat(),d=h+e*f,u=d+p,e++}if(!(lr||l===r&&d>=s)break;if(Number.isFinite(n)){const e=await this.chromTree.getNameForId(l);o.push({chr:e,start:d,end:u,value:n})}}}}}function Lc(){const e=function(e,t,i,r){if("biginteract"===r||i&&("chromatinInteract"===i.table||"interact"===i.table))return function(e,t){return e.chr1=t[5],e.start1=Number.parseInt(t[6]),e.end1=Number.parseInt(t[7]),e.chr2=t[10],e.start2=Number.parseInt(t[11]),e.end2=Number.parseInt(t[12]),e.name=t[0],e.score=Number(t[1]),e.value=Number(t[2]),e.color="."===t[4]?void 0:"0"===t[4]?"rgb(0,0,0)":t[4],e};{const r=e-3;return function(s,o){if(r>0&&(s.name=o[0]),r>1&&(s.score=Number(o[1])),r>2&&(s.strand=o[2]),r>3&&(s.cdStart=parseInt(o[3])),r>4&&(s.cdEnd=parseInt(o[4])),r>5&&"."!==o[5]&&"0"!==o[5]&&"-1"!==o[5]){const e=ur.createColorString(o[5]);s.color=e.startsWith("rgb")?e:void 0}if(r>8){const e=parseInt(o[6]),t=o[7].split(","),i=o[8].split(","),r=[];for(let o=0;oi?r.utr=!0:(t>=s&&t<=e&&(r.cdStart=t),i>=s&&i<=e&&(r.cdEnd=i))}}(r,s.cdStart,s.cdEnd),s.exons=r}if(i)for(let r=e;r=13;){const t=a.getInt(),c=await this.chromTree.getNameForId(t),l=a.getInt(),h=a.getInt(),d=a.getString();if(!(ts||t===s&&l>=o)break;if(h>0){const t={chr:c,start:l,end:h};n.push(t);const i=d.split("\t");e(t,i)}}}}}async function Tc(e,t,i,r,s,o,n,a){const c=new qo(e,a);for(;c.remLength()>=32;){const e=c.getInt(),a=c.getInt(),l=c.getInt(),h=c.getInt(),d=c.getFloat(),u=c.getFloat(),f=c.getFloat();let p;switch(c.getFloat(),n){case"min":p=d;break;case"max":p=u;break;default:p=0===h?0:f/h}if(!(er||e===r&&a>=s)break;if(Number.isFinite(p)){const t=await this.chromTree.getNameForId(e);o.push({chr:t,start:a,end:l,value:p})}}}}class zc{constructor(e){this.data=e}loadArrayBuffer(e,t){const i=t.range;return i?this.data.slice(i.start,i.start+i.size):this.data}async dataViewForRange(e,t){const i=Math.min(this.data.byteLength-e.start,e.size);return t?new Uint8Array(this.data,e.start,i):new DataView(this.data,e.start,i)}}class Pc extends gc{queryable=!0;#h={};windowFunctions=["mean","min","max","none"];constructor(e,t){super(t),this.reader=new Nc(e,t),this.genome=t,this.format=e.format||"bigwig"}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,windowFunction:s}){await this.reader.loadHeader();const o="bigwig"===this.reader.type;let n;if("all"===e.toLowerCase()){const e=this.genome.wgChromosomeNames;n=o&&e?await this.getWGValues(e,s,r):[]}else n=await this.reader.readFeatures(e,t,e,i,r,s);return o||fa(n),n}async getHeader(){return this.reader.loadHeader()}async defaultVisibilityWindow(){return"bigwig"===this.reader.type?-1:this.reader.featureDensity?Math.floor(1e4/this.reader.featureDensity):-1}async getWGValues(e,t,i){const r=this.genome,s=this.#h[t];if(s&&s.bpPerPixel>.8*i&&s.bpPerPixel<1.2*i)return s.values;{const s=await this.reader.readWGFeatures(e,i,t);let o=[];for(let e of s){const t=e.chr,i=r.getCumulativeOffset(t);if(void 0===i)continue;const s=Object.assign({},e);s.chr="all",s.start=i+e.start,s.end=i+e.end,s._f=e,o.push(s)}return o.sort(((e,t)=>e.start-t.start)),this.#h[t]={values:o,bpPerPixel:i},o}}supportsWholeGenome(){return"bigwig"===this.reader.type}async trackType(){return this.reader.getTrackType()}get searchable(){return this.reader.searchable}async search(e){return this.reader.search(e)}}const Hc=.01;function Oc(e,t,i,r){let s=this.axisMin,o=this.axisMax;if(void 0===o&&this.dataRange&&(s=this.dataRange.min||0,o=this.dataRange.max),void 0===o)return;Co.fillRect(e,0,0,t,i,{fillStyle:"white"}),r&&Co.fillRect(e,t-4-2,0,4,i,{fillStyle:r});const n=void 0!==this.flipAxis&&this.flipAxis,a=.95*t-8-5,c=.95*t-5,l={font:"normal 10px Arial",textAlign:"right",fillStyle:"black",strokeStyle:"black"};Co.strokeLine(e,a,Hc*i,c,Hc*i,l),Co.fillText(e,d(n?s:o),a+4,Hc*i+12,l);const h=.99*i;function d(e){return Number.isInteger(e)||e%1==0?e:Math.abs(e)>=10?e.toFixed():Math.abs(e)>=1?e.toFixed(1):Math.abs(e)>=.1?e.toFixed(2):e.toExponential(1)}Co.strokeLine(e,a,h,c,h,l),Co.fillText(e,d(n?o:s),a+4,h-4,l),Co.strokeLine(e,c,Hc*i,c,h,l)}const Vc=e=>{switch(e.type){case"gradient":return new Gc(e);case"doubleGradient":case"diverging":return new jc(e);default:throw Error("Unknown color scale type: "+e)}},qc=function(e,t){return new Gc({type:"doubleGradient",min:e,max:t,minColor:"rgb(46,56,183)",maxColor:"rgb(164,0,30)"})},Uc=function(e,t,i){return new jc({type:"doubleGradient",min:0,mid:.25,max:.5,minColor:"rgb(46,56,183)",midColor:"white",maxColor:"rgb(164,0,30)"})};class Qc{constructor(e){this.thresholds=e.thresholds,this.colors=e.colors}getColor(e){for(let t of this.thresholds)if(e=this.max)return this.maxColor;const t=(e-this.min)/(this.max-this.min);return"rgb("+Math.floor(this.lowComponents[0]+t*(this.highComponents[0]-this.lowComponents[0]))+","+Math.floor(this.lowComponents[1]+t*(this.highComponents[1]-this.lowComponents[1]))+","+Math.floor(this.lowComponents[2]+t*(this.highComponents[2]-this.lowComponents[2]))+")"}toJson(){return{type:this.type,min:this.min,max:this.max,minColor:this.minColor,maxColor:this.maxColor}}clone(){return new Gc(this.toJson())}}class jc{constructor(e){this.type="diverging",this.lowGradientScale=new Gc({minColor:e.minColor||e.lowColor,maxColor:e.midColor,min:void 0!==e.min?e.min:e.low,max:e.mid}),this.highGradientScale=new Gc({minColor:e.midColor,maxColor:e.maxColor||e.highColor,min:e.mid,max:void 0!==e.max?e.max:e.high})}getColor(e){return e1&&void 0!==arguments[1]?arguments[1]:1;return(t>0?e.toFixed(t).replace(/0+$/,"").replace(/\.$/,""):e.toString())||"0"}var Jc=function(){function e(t,i,r,s){$c(this,e);var o=this;if(void 0===t);else if(Array.isArray(t))this.rgba=t;else if(void 0===r){var n=t&&""+t;n&&function(t){if(t.startsWith("hsl")){var i=t.match(/([\-\d\.e]+)/g).map(Number),r=Zc(i,4),s=r[0],n=r[1],a=r[2],c=r[3];void 0===c&&(c=1),s/=360,n/=100,a/=100,o.hsla=[s,n,a,c]}else if(t.startsWith("rgb")){var l=t.match(/([\-\d\.e]+)/g).map(Number),h=Zc(l,4),d=h[0],u=h[1],f=h[2],p=h[3];void 0===p&&(p=1),o.rgba=[d,u,f,p]}else t.startsWith("#")?o.rgba=e.hexToRgb(t):o.rgba=e.nameToRgb(t)||e.hexToRgb(t)}(n.toLowerCase())}else this.rgba=[t,i,r,void 0===s?1:s]}return Kc(e,[{key:"printRGB",value:function(e){var t=(e?this.rgba:this.rgba.slice(0,3)).map((function(e,t){return Xc(e,3===t?3:0)}));return e?"rgba("+t+")":"rgb("+t+")"}},{key:"printHSL",value:function(e){var t=[360,100,100,1],i=["","%","%",""],r=(e?this.hsla:this.hsla.slice(0,3)).map((function(e,r){return Xc(e*t[r],3===r?3:1)+i[r]}));return e?"hsla("+r+")":"hsl("+r+")"}},{key:"printHex",value:function(e){var t=this.hex;return e?t:t.substring(0,7)}},{key:"rgba",get:function(){if(this._rgba)return this._rgba;if(!this._hsla)throw new Error("No color is set");return this._rgba=e.hslToRgb(this._hsla)},set:function(e){3===e.length&&(e[3]=1),this._rgba=e,this._hsla=null}},{key:"rgbString",get:function(){return this.printRGB()}},{key:"rgbaString",get:function(){return this.printRGB(!0)}},{key:"hsla",get:function(){if(this._hsla)return this._hsla;if(!this._rgba)throw new Error("No color is set");return this._hsla=e.rgbToHsl(this._rgba)},set:function(e){3===e.length&&(e[3]=1),this._hsla=e,this._rgba=null}},{key:"hslString",get:function(){return this.printHSL()}},{key:"hslaString",get:function(){return this.printHSL(!0)}},{key:"hex",get:function(){return"#"+this.rgba.map((function(e,t){return t<3?e.toString(16):Math.round(255*e).toString(16)})).map((function(e){return e.padStart(2,"0")})).join("")},set:function(t){this.rgba=e.hexToRgb(t)}}],[{key:"hexToRgb",value:function(e){var t=(e.startsWith("#")?e.slice(1):e).replace(/^(\w{3})$/,"$1F").replace(/^(\w)(\w)(\w)(\w)$/,"$1$1$2$2$3$3$4$4").replace(/^(\w{6})$/,"$1FF");if(!t.match(/^([0-9a-fA-F]{8})$/))throw new Error("Unknown hex color; "+e);var i=t.match(/^(\w\w)(\w\w)(\w\w)(\w\w)$/).slice(1).map((function(e){return parseInt(e,16)}));return i[3]=i[3]/255,i}},{key:"nameToRgb",value:function(t){var i=t.toLowerCase().replace("at","T").replace(/[aeiouyldf]/g,"").replace("ght","L").replace("rk","D").slice(-5,4),r=Yc[i];return void 0===r?r:e.hexToRgb(r.replace(/\-/g,"00").padStart(6,"f"))}},{key:"rgbToHsl",value:function(e){var t=Zc(e,4),i=t[0],r=t[1],s=t[2],o=t[3];i/=255,r/=255,s/=255;var n=Math.max(i,r,s),a=Math.min(i,r,s),c=void 0,l=void 0,h=(n+a)/2;if(n===a)c=l=0;else{var d=n-a;switch(l=h>.5?d/(2-n-a):d/(n+a),n){case i:c=(r-s)/d+(r1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e},h=s<.5?s*(1+r):s+r-s*r,d=2*s-h;n=l(d,h,i+1/3),a=l(d,h,i),c=l(d,h,i-1/3)}var u=[255*n,255*a,255*c].map(Math.round);return u[3]=o,u}}]),e}(),el=function(){function e(){$c(this,e),this._events=[]}return Kc(e,[{key:"add",value:function(e,t,i){e.addEventListener(t,i,!1),this._events.push({target:e,type:t,handler:i})}},{key:"remove",value:function(t,i,r){this._events=this._events.filter((function(s){var o=!0;return t&&t!==s.target&&(o=!1),i&&i!==s.type&&(o=!1),r&&r!==s.handler&&(o=!1),o&&e._doRemove(s.target,s.type,s.handler),!o}))}},{key:"destroy",value:function(){this._events.forEach((function(t){return e._doRemove(t.target,t.type,t.handler)})),this._events=[]}}],[{key:"_doRemove",value:function(e,t,i){e.removeEventListener(t,i,!1)}}]),e}();function tl(e,t,i){var r=!1;function s(e,t,i){return Math.max(t,Math.min(e,i))}function o(e,o,n){if(n&&(r=!0),r){e.preventDefault();var a=t.getBoundingClientRect(),c=a.width,l=a.height,h=o.clientX,d=o.clientY,u=s(h-a.left,0,c),f=s(d-a.top,0,l);i(u/c,f/l)}}function n(e,t){1===(void 0===e.buttons?e.which:e.buttons)?o(e,e,t):r=!1}function a(e,t){1===e.touches.length?o(e,e.touches[0],t):r=!1}e.add(t,"mousedown",(function(e){n(e,!0)})),e.add(t,"touchstart",(function(e){a(e,!0)})),e.add(window,"mousemove",n),e.add(t,"touchmove",a),e.add(window,"mouseup",(function(e){r=!1})),e.add(t,"touchend",(function(e){r=!1})),e.add(t,"touchcancel",(function(e){r=!1}))}var il="keydown",rl="mousedown",sl="focusin";function ol(e,t){return(t||document).querySelector(e)}function nl(e){e.preventDefault(),e.stopPropagation()}function al(e,t,i,r,s){e.add(t,il,(function(e){i.indexOf(e.key)>=0&&(s&&nl(e),r(e))}))}var cl=function(){function e(t){$c(this,e),this.settings={popup:"right",layout:"default",alpha:!0,editor:!0,editorFormat:"hex",cancelButton:!1,defaultColor:"#0cf"},this._events=new el,this.onChange=null,this.onDone=null,this.onOpen=null,this.onClose=null,this.setOptions(t)}return Kc(e,[{key:"setOptions",value:function(e){var t=this;if(e){var i=this.settings;if(e instanceof HTMLElement)i.parent=e;else{i.parent&&e.parent&&i.parent!==e.parent&&(this._events.remove(i.parent),this._popupInited=!1),function(e,t,i){for(var r in e)i&&i.indexOf(r)>=0||(t[r]=e[r])}(e,i),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var r=e.color||e.colour;r&&this._setColor(r)}var s=i.parent;if(s&&i.popup&&!this._popupInited){var o=function(e){return t.openHandler(e)};this._events.add(s,"click",o),al(this._events,s,[" ","Spacebar","Enter"],o),this._popupInited=!0}else e.parent&&!i.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===il?this._domEdit:this.domElement;setTimeout((function(){return t.focus()}),100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,i=!1;if(e)if(t===rl||t===sl){var r=(this.__containedEvent||0)+100;e.timeStamp>r&&(i=!0)}else nl(e),i=!0;else i=!0;i&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==rl&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var i=void 0;try{i=new Jc(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var r=i.hsla;r[3]=1,i.hsla=r}this.colour=this.color=i,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}(this.settings.template||'
');return this.domElement=t,this._domH=ol(".picker_hue",t),this._domSL=ol(".picker_sl",t),this._domA=ol(".picker_alpha",t),this._domEdit=ol(".picker_editor input",t),this._domSample=ol(".picker_sample",t),this._domOkay=ol(".picker_done button",t),this._domCancel=ol(".picker_cancel button",t),t.classList.add("layout_"+this.settings.layout),this.settings.alpha||t.classList.add("no_alpha"),this.settings.editor||t.classList.add("no_editor"),this.settings.cancelButton||t.classList.add("no_cancel"),this._ifPopup((function(){return t.classList.add("popup")})),this._setPosition(),this.colour?this._updateUI():this._setColor(this.settings.defaultColor),this._bindEvents(),!0}},{key:"hide",value:function(){return this._toggleDOM(!1)}},{key:"destroy",value:function(){this._events.destroy(),this.domElement&&this.settings.parent.removeChild(this.domElement)}},{key:"_bindEvents",value:function(){var e=this,t=this,i=this.domElement,r=this._events;function s(e,t,i){r.add(e,t,i)}s(i,"click",(function(e){return e.preventDefault()})),tl(r,this._domH,(function(e,i){return t._setHSLA(e)})),tl(r,this._domSL,(function(e,i){return t._setHSLA(null,e,1-i)})),this.settings.alpha&&tl(r,this._domA,(function(e,i){return t._setHSLA(null,null,null,1-i)}));var o=this._domEdit;s(o,"input",(function(e){t._setColor(this.value,{fromEditor:!0,failSilently:!0})})),s(o,"focus",(function(e){var t=this;t.selectionStart===t.selectionEnd&&t.select()})),this._ifPopup((function(){var t=function(t){return e.closeHandler(t)};s(window,rl,t),s(window,sl,t),al(r,i,["Esc","Escape"],t);var o=function(t){e.__containedEvent=t.timeStamp};s(i,rl,o),s(i,sl,o),s(e._domCancel,"click",t)}));var n=function(t){e._ifPopup((function(){return e.closeHandler(t)})),e.onDone&&e.onDone(e.colour)};s(this._domOkay,"click",n),al(r,i,["Enter"],n)}},{key:"_setPosition",value:function(){var e=this.settings.parent,t=this.domElement;e!==t.parentNode&&e.appendChild(t),this._ifPopup((function(i){"static"===getComputedStyle(e).position&&(e.style.position="relative");var r=!0===i?"popup_right":"popup_"+i;["popup_top","popup_bottom","popup_left","popup_right"].forEach((function(e){e===r?t.classList.add(e):t.classList.remove(e)})),t.classList.add(r)}))}},{key:"_setHSLA",value:function(e,t,i,r,s){s=s||{};var o=this.colour,n=o.hsla;[e,t,i,r].forEach((function(e,t){(e||0===e)&&(n[t]=e)})),o.hsla=n,this._updateUI(s),this.onChange&&!s.silent&&this.onChange(o)}},{key:"_updateUI",value:function(e){if(this.domElement){e=e||{};var t=this.colour,i=t.hsla,r="hsl("+360*i[0]+", 100%, 50%)",s=t.hslString,o=t.hslaString,n=this._domH,a=this._domSL,c=this._domA,l=ol(".picker_selector",n),h=ol(".picker_selector",a),d=ol(".picker_selector",c);b(0,l,i[0]),this._domSL.style.backgroundColor=this._domH.style.color=r,b(0,h,i[1]),F(0,h,1-i[2]),a.style.color=s,F(0,d,1-i[3]);var u=s,f=u.replace("hsl","hsla").replace(")",", 0)"),p="linear-gradient("+[u,f]+")";if(this._domA.style.background=p+", linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0 / 2em 2em,\n linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em / 2em 2em",!e.fromEditor){var g=this.settings.editorFormat,m=this.settings.alpha,w=void 0;switch(g){case"rgb":w=t.printRGB(m);break;case"hsl":w=t.printHSL(m);break;default:w=t.printHex(m)}this._domEdit.value=w}this._domSample.style.color=o}function b(e,t,i){t.style.left=100*i+"%"}function F(e,t,i){t.style.top=100*i+"%"}}},{key:"_ifPopup",value:function(e,t){this.settings.parent&&this.settings.popup?e&&e(this.settings.popup):t&&t()}},{key:"_toggleDOM",value:function(e){var t=this.domElement;if(!t)return!1;var i=e?"":"none",r=t.style.display!==i;return r&&(t.style.display=i),r}}]),e}();const ll={display:"flex",flexDirection:"row",alignItems:"center",backgroundColor:"transparent"};class hl{constructor({selected:e,label:i,onchange:r}){this.state=e,this.onchange=r,this.elem=t({style:ll});const s=t({style:{width:"14px",height:"14px",borderColor:"gray",borderWidth:"1px",borderStyle:"solid"}});if(this.svg=l("check",!0===e?"#444":"transparent"),this.svg.style.width="12px",this.svg.style.height="12px",s.appendChild(this.svg),this.elem.appendChild(s),i){const e=t({style:{marginLeft:"5px"}});e.textContent=i,this.elem.appendChild(e)}const o=e=>{e.preventDefault(),e.stopPropagation();const t=!this.state;this.selected=t,"function"==typeof this.onchange&&this.onchange(t)};this.elem.addEventListener("click",o),this.elem.addEventListener("touchend",o)}set selected(e){this.state=e;this.svg.querySelector("path").setAttributeNS(null,"fill",!0===e?"#444":"transparent")}get selected(){return this.state}onchange(e){this.onchange=e}}function dl(e,t){const i=e.getContext("2d"),r=e.width,s=(t.max-t.min)/r;for(let o=0;o{r.min=Number.parseFloat(e),dl(n,r)}});o.appendChild(a.row);const c=new pl({label:"Mid value",value:(r.mid||r.min).toString(),onchange:e=>{r.mid=Number.parseFloat(e),dl(n,r)}});o.appendChild(c.row);const l=new pl({label:"Max value",value:r.max.toString(),onchange:e=>{r.max=Number.parseFloat(e),dl(n,r)}});o.appendChild(l.row);const h=new gl({label:"Min color",value:r.minColor,onchange:e=>{r.minColor=e,dl(n,r)}});o.appendChild(h.row);const d=new gl({label:"Mid color",value:r.midColor||r.minColor,onchange:e=>{r.midColor=e,dl(n,r)}});o.appendChild(d.row);const u=new gl({label:"Max color",value:r.maxColor,onchange:e=>{r.maxColor=e,dl(n,r)}});o.appendChild(u.row);const f=new hl({selected:"diverging"===e.type,label:"Diverging Scale",onchange:e=>{e?(r.mid=r.min<0&&r.max>0?0:(r.min+r.max)/2,r.midColor="rgb(255,255,255)",r=new jc(r),c.value=r.mid,c.show(),d.value=r.midColor,d.show(),dl(n,r)):(r=new Gc(r),c.hide(),d.hide(),dl(n,r))}});f.elem.style.marginBottom="20px","diverging"!==e.type&&(c.hide(),d.hide());const p=document.createElement("div");p.appendChild(f.elem),p.appendChild(o),p.appendChild(n);const g=new w({parent:t,content:{elem:p},okHandler:()=>{i&&i(r)}});t.appendChild(g.elem),s(g.elem),dl(n,r)}}class fl{constructor({label:e,value:t,onchange:i}){this.row=document.createElement("tr");const r=document.createElement("td");this.row.appendChild(r);const s=document.createElement("div");s.innerHTML=e,r.appendChild(s)}hide(){this.row.style.display="none"}show(){this.row.style.display="table-row"}}class pl extends fl{constructor({label:e,value:t,onchange:i}){super({label:e,value:t,onchange:i});const r=document.createElement("td");this.row.appendChild(r),this.input=document.createElement("input"),t=t||"0",this.input.value=vo.sanitize(t),r.appendChild(this.input),i&&this.input.addEventListener("change",(e=>i(this.input.value)))}get value(){return this.input.value}set value(e){this.input.value=e}}class gl extends fl{constructor({label:e,value:t,onchange:i}){super({label:e,value:t,onchange:i});const r=document.createElement("td");this.row.appendChild(r);const s=document.createElement("div");r.appendChild(s),s.style.width="20px",s.style.height="20px",s.style.border="1px solid black",this.colorButton=s,t=t||"white",s.style.background=t;const o=new cl(s);o.setOptions({alpha:!1,color:t}),o.onDone=e=>{s.style.background=e.rgbString,i&&i(e.rgbString)}}set value(e){this.colorButton.style.background=e}}class ml extends ma{static defaultColor="rgb(150, 150, 150)";static defaults={height:50,flipAxis:!1,logScale:!1,windowFunction:"mean",graphType:"bar",normalize:void 0,scaleFactor:void 0,overflowColor:"rgb(255, 32, 255)",baselineColor:"lightGray",summarize:!0,visibilityWindow:void 0};constructor(e,t){super(e,t)}init(e){super.init(e),this.type="wig",this.featureType="numeric",this.resolutionAware=!0,this._paintAxis=Oc.bind(this);const t=e.format?e.format.toLowerCase():e.format;e.featureSource?(this.featureSource=e.featureSource,delete e.featureSource):this.featureSource="bigwig"===t?new Pc(e,this.browser.genome):"tdf"===t?new vc(e,this.browser.genome):El(e,this.browser.genome),void 0===e.max||!0===e.autoscale?this.autoscale=!0:this.dataRange={min:e.min||0,max:e.max},e.colorScale&&(this._colorScale=Vc(e.colorScale)),"heatmap"!==e.graphType||e.height||(this.height=20)}async postInit(){const e=await this.getHeader();this.disposed||(e&&this.setTrackProperties(e),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor)}get supportsWholeGenome(){return!this.config.indexURL&&!1!==this.config.supportsWholeGenome}get paintAxis(){return"heatmap"===this.graphType?()=>{}:this._paintAxis}get colorScale(){return this._colorScale}async getFeatures(e,t,i,r){const s=this.windowFunction,o=await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:this.visibilityWindow,windowFunction:s});if(this.normalize&&this.featureSource.normalizationFactor){const e=this.featureSource.normalizationFactor;for(let t of o)t.value*=e}if(this.scaleFactor){const e=this.scaleFactor;for(let t of o)t.value*=e}if("dynseq"===this.graphType&&o&&o.length>0)for(let e of o)try{e.sequence=await this.browser.genome.getSequence(e.chr,Math.floor(e.start),Math.floor(e.end))}catch(t){console.warn(`Failed to get sequence for feature at chr: ${e.chr}, start: ${e.start}, end: ${e.end}. Error:`,t),e.sequence=null}return!this.summarize||"mean"!==s&&"min"!==s&&"max"!==s?o:wl(o,t,r,s)}menuItemList(){const e=[];return"heatmap"===this.graphType?(e.push("
"),e.push({label:"Set color scale",click:function(){ul.open(this.colorScale,this.browser.columnContainer,(e=>{this._colorScale=e,this.trackView.repaintViews()}))}})):void 0!==this.flipAxis&&(e.push("
"),e.push({label:"Flip y-axis",click:function(){this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}})),e.push(...this.graphTypeItems()),this.featureSource.windowFunctions&&e.push(...this.wigSummarizationItems()),e.push(...this.numericDataMenuItems()),e}wigSummarizationItems(){const e=this.featureSource.windowFunctions,t=[];t.push("
"),t.push("
Windowing function
");for(const i of e){function r(){this.windowFunction=i,this.trackView.updateViews()}t.push({element:ua(i,this.windowFunction===i),click:r})}return t}graphTypeItems(){const e=["bar","line","points","heatmap","dynseq"],t=[];t.push("
"),t.push("
Graph type
");for(const i of e){function r(){this.graphType=i,this.trackView.repaintViews()}t.push({element:ua(i,this.graphType===i),click:r})}return t}async getHeader(){return"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader()),this.header}getScaleFactor(e,t,i,r){const s=!0===r?e<0?-Math.log10(Math.abs(e)+1):Math.log10(Math.abs(e)+1):e;return i/((!0===r?Math.log10(Math.abs(t)+1):t)-s)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,r=this.dataRange.min;return r=r<0?-Math.log10(Math.abs(r)+1):Math.log10(Math.abs(r)+1),i=i<0?-Math.log10(Math.abs(i)+1):Math.log10(Math.abs(i)+1),e=e<0?-Math.log10(Math.abs(e)+1):Math.log10(e+1),(this.flipAxis?e-r:i-e)*t}draw(e){const t=e.features,i=e.context,r=e.bpPerPixel,s=e.bpStart,o=e.pixelWidth,n=e.pixelHeight-1,a=s+o*r+1,c=this.getScaleFactor(this.dataRange.min,this.dataRange.max,n,this.logScale),l=e=>this.logScale?this.computeYPixelValueInLogScale(e,c):this.computeYPixelValue(e,c);if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){let o,c=-1;const h=l(0);for(let d of t){if(d.enda)break;const t=(d.start-s)/r;if(Number.isNaN(t))continue;let u=l(d.value);const f=(d.end-s)/r-t,p=e.alpha?ur.addAlpha(this.getColorForFeature(d),e.alpha):this.getColorForFeature(d);if("line"===this.graphType)void 0!==o&&Co.strokeLine(i,c,o,t,u,{fillStyle:p,strokeStyle:p}),Co.strokeLine(i,t,u,t+f,u,{fillStyle:p,strokeStyle:p});else if("points"===this.graphType){const e=this.config.pointSize||3,r=t+f/2;Co.fillCircle(i,r,u,e/2,{fillStyle:p,strokeStyle:p}),d.value>this.dataRange.max?Co.fillCircle(i,r,e/2,e/2,3,{fillStyle:this.overflowColor}):d.value0?Uc(this.dataRange.min,0,this.dataRange.max):qc(this.dataRange.min,this.dataRange.max));const e=this._colorScale.getColor(d.value);Co.fillRect(i,t,0,f,n,{fillStyle:e})}else if("dynseq"===this.graphType)this.renderDynSeq(i,d,t,f,u,h,n);else{const e=Math.min(n,u-h);Co.fillRect(i,t,h,f,e,{fillStyle:p}),d.value>this.dataRange.max?Co.fillRect(i,t,0,f,3,{fillStyle:this.overflowColor}):d.valuethis.dataRange.max?Co.fillRect(e,i,0,r,3,{fillStyle:this.overflowColor}):t.value=6&&e.bezierCurveTo(i+o[0]*n,r+o[1]*a,i+o[2]*n,r+o[3]*a,i+o[4]*n,r+o[5]*a)}e.closePath(),e.fill()}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0){const i=e.genomicLocation,r=[];t.sort((function(e,t){return Math.abs((e.start+e.end)/2-i)-Math.abs((t.start+t.end)/2-i)}));const s=t.length>10?t.slice(0,10):t;s.sort((function(e,t){return e.start-t.start}));for(let e of s)if(e){r.length>0&&r.push("
");let t=e.end-e.start===1?F(Math.floor(e.start)+1):F(Math.floor(e.start)+1)+"-"+F(Math.floor(e.end));r.push({name:"Position:",value:t}),r.push({name:"Value:     ",value:F(e.value.toFixed(4))})}return s.length..."),r}return[]}getColorForFeature(e){let t=e.value<0&&this.altColor?this.altColor:this.color||ml.defaultColor;return"function"==typeof t?t(e.value):t}getState(){const e=super.getState();return this._colorScale&&(e.colorScale=this._colorScale.toJson()),e}dispose(){this.trackView=void 0}}function wl(e,t,i,r="mean"){if(i<=1||!e||0===e.length||"none"===r)return e;const s=e[0].chr,o=i,n=[],a=e=>{const i=t+e.bin*o,a=i+o;let c;switch(r){case"mean":c=e.sumData/e.count;break;case"max":c=e.max;break;case"min":c=e.min;break;default:throw Error(`Unknown window function: ${r}`)}const l=`${r} of ${e.count} values`;n.push({chr:s,start:i,end:a,value:c,description:l})};let c;for(let i of e){let e=Math.floor((i.start-t)/o);const r=Math.floor((i.end-t)/o);if(c&&e===c.bin&&(c.add(i),e++),!c||r>c.bin){if(c&&a(c),r>e){const e=t+r*o;n.push({chr:s,start:i.start,end:e,value:i.value})}c=new bl(r,i)}}c&&a(c);const l=[];let h=n[0];for(let e of n)h.value===e.value&&e.start<=h.end?h.end=e.end:(l.push(h),h=e);return l.push(h),l}class bl{constructor(e,t){this.bin=e,this.sumData=t.value,this.count=1,this.min=t.value,this.max=t.value}add(e){this.sumData+=e.value,this.max=Math.max(e.value,this.max),this.min=Math.min(e.value,this.min),this.count++}get mean(){return this.sumData/this.count}}class Fl extends gc{constructor(e,t){super(t),this.config=e||{},this.genome=t,this.sourceType=void 0===e.sourceType?"file":e.sourceType,this.maxWGCount=e.maxWGCount||1e4,this.windowFunctions=["mean","min","max","none"];const i=new Set(["bigwig","bw","bigbed","bb","biginteract","biggenepred","bignarrowpeak","tdf"]);if(this.queryable=e.indexURL||!0===e.queryable,e.reader)this.reader=e.reader,this.queryable=!1!==e.queryable;else{if("ga4gh"===e.sourceType)throw Error("Unsupported source type 'ga4gh'");"eqtl"!==e.type&&"qtl"!==e.type||"gtex-ws"!==e.sourceType?"htsget"===e.sourceType?(this.reader=new pc(e,t),this.queryable=!0,this.supportsWholeGenome=()=>!1):"ucscservice"===e.sourceType?(this.reader=new ac(e.source),this.queryable=!0):"custom"===e.sourceType?(this.reader=new nc(e.source),this.queryable=!1!==e.source.queryable):"service"===e.sourceType?(this.reader=new sc(e,t),this.queryable=!0):(this.reader=new sc(e,t),void 0!==e.queryable?this.queryable=e.queryable:(i.has(e.format)||this.reader.indexed)&&(this.queryable=!0)):(this.reader=new cc(e),this.queryable=!0)}this.searchable=!1!==e.searchable}async defaultVisibilityWindow(){if(this.reader&&"function"==typeof this.reader.defaultVisibilityWindow)return this.reader.defaultVisibilityWindow()}async trackType(){const e=await this.getHeader();return e?e.type:void 0}async getHeader(){if(!this.header)if(this.reader&&"function"==typeof this.reader.readHeader){const e=await this.reader.readHeader();e?(this.header=e,e.format&&(this.config.format=e.format)):this.header={}}else this.header={};return this.header}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s,windowFunction:o}){const n="all"===e.toLowerCase();if(t=t||0,i=i||Number.MAX_SAFE_INTEGER,(n&&!this.wgFeatures&&this.supportsWholeGenome()||this.config.disableCache||!this.featureCache||!this.featureCache.containsRange(new Mo(e,t,i)))&&await this.loadFeatures(e,t,i,s),n){if(!this.wgFeatures)if(this.supportsWholeGenome())if("wig"===this.config.type){const e=await pa(this.featureCache.getAllFeatures(),this.genome,this.chromAliasManager,1e6);this.wgFeatures=wl(e,0,r,o)}else this.wgFeatures=await pa(this.featureCache.getAllFeatures(),this.genome,this.chromAliasManager,this.maxWGCount);else this.wgFeatures=[];return this.wgFeatures}{const r=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e;return this.featureCache.queryFeatures(r,t,i)}}async findFeatures(e){return this.featureCache?this.featureCache.findFeatures(e):[]}supportsWholeGenome(){return!this.queryable}getAllFeatures(){return this.queryable||!this.featureCache?[]:this.featureCache.getAllFeatures()}async loadFeatures(e,t,i,r){await this.getHeader();const s=this.reader;let o=t,n=i,a=e;if(!this.chromAliasManager&&this.reader&&this.reader.sequenceNames&&this.reader.sequenceNames.size>0&&(this.chromAliasManager=new fc(this.reader.sequenceNames,this.genome)),this.chromAliasManager&&(a=await this.chromAliasManager.getAliasName(e)),(!r||r<=0)&&!1!==this.config.expandQuery){const t=this.genome?this.genome.getChromosome(e):void 0;o=0,n=Math.max(t?t.bpLength:Number.MAX_SAFE_INTEGER,i)}else if(r>i-t&&!1!==this.config.expandQuery){let e=Math.min(4.1*(i-t),r);this.config.minQuerySize&&ee.chr)),this.genome):null,this.featureCache=new cn(e),(this.searchable||this.config.searchableFields)&&this.addFeaturesToDB(e,this.config)}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s}){const o=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e;return"all"===o.toLowerCase()?await pa(this.featureCache.getAllFeatures(),this.genome,this.chromAliasManager,this.maxWGCount):this.featureCache.queryFeatures(o,t,i)}getAllFeatures(){return this.featureCache.getAllFeatures()}supportsWholeGenome(){return!0}addFeaturesToDB(e,t){this.featureMap||(this.featureMap=new Map);const i=t.searchableFields||["name"];for(let t of e)for(let e of i){let i;if("function"==typeof t.getAttributeValue&&(i=t.getAttributeValue(e)),i||(i=t[e]),i){i=i.replaceAll(" ","+");const e=this.featureMap.get(i.toUpperCase());if(e&&e.end-e.start>t.end-t.start)continue;this.featureMap.set(i.toUpperCase(),t)}}}search(e){if(this.featureMap)return this.featureMap.get(e.toUpperCase())}}class yl{constructor({chr:e,locus:t,accession:i,aliases:r,features:s,sequence:o}){this.chr=e,this.locus=t,this.accession=i,this.aliases=r,this.features=s,this.sequence=o,this.bpLength=o.length}toJSON(){return{gbkURL:this.url}}getSequenceRecord(e){return{chr:this.chr,bpLength:this.bpLength}}get chromosomeNames(){return[this.chr]}getFirstChromosomeName(){return this.chr}get id(){return this.accession}get name(){return this.locus}get initialLocus(){return this.chr}get description(){return this.locus}get infoURL(){return this.url}showWholeGenomeView(){return!1}getHomeChromosomeName(){return this.chr}getChromosomeName(e){return e}getChromosomeDisplayName(e){return this.chr}getChromosome(e){if(e===this.chr)return{name:this.chr,bpLength:this.bpLength}}async loadChromosome(e){return this.getChromosome(e)}async getAliasRecord(e){}getCytobands(e){return[]}getChromosomes(){return[this.getChromosome(this.chr)]}get wgChromosomeNames(){}getGenomeCoordinate(e,t){if(e===this.chr)return t}getChromosomeCoordinate(e){return{chr:this.chr,position:e}}getCumulativeOffset(e){return 0}getGenomeLength(){return this.bpLength}async getSequence(e,t,i){return e===this.chr?this.sequence.substring(t,i):void 0}getSequenceInterval(e,t,i){return e===this.chr?new Ro(this.chr,0,this.sequence.length,this.sequence):void 0}}const Al=/\s+/,Cl=new Map;async function _l(e){let t=Cl.get(e);if(!t){t=function(e){if(!e)return null;const t=Wa(e);let i=t.nextLine();const r=i.split(/\s+/);if("LOCUS"!==r[0].toUpperCase())throw Error("Expected `LOCUS` line. Found: "+i);const s=r[1].trim();let o,n;do{if(i=t.nextLine(),i.startsWith("ACCESSION")){const e=i.split(Al);if(e.length<2)throw Error("Genbank file missing ACCESSION number.");o=e[1].trim()}else if(i.startsWith("ALIASES")){const e=i.split(Al);e.length>1&&(n=e[1].split(","))}}while(i&&!i.startsWith("FEATURES"));const a=o||s,c=function(e,t){const i=[];let r,s,o,n=0;for(;;)if(s=t.nextLine(),""!==s){if(!s||s.startsWith("ORIGIN"))break;if(s.length<6)n<10&&console("Unexpected line in genbank file (skipping): "+s),n++;else if(" "!==s.charAt(5)){let t=s.substring(5,21).trim();o={chr:e,type:t,attributes:{},getAttributeValue:function(e){return this.attributes[e]}},r=s.substring(21),"source"!==t.toLowerCase()&&i.push(o)}else{let t=s.substring(21).trim();if(t.length>0)if(47===t.charCodeAt(0)){if(47===r.charCodeAt(0)){let e=r.split("=",2);if(e.length>1){let t=e[0].length>1?e[0].substring(1):"",i=kl(e[1]);o.attributes[t]=i}}else{const t=r.includes("complement")?"-":"+";o.strand=t;let i=r.replace("join","").replace("order","").replace("complement","").replace("(","").replace(")","");if(i.includes("..")){i=i.replace("<","").replace(">","");const r=xl(i,e,t),s=r[0];o.start=s.start;const n=r[r.length-1];o.end=n.end,r.length>1&&(o.exons=r)}else o.start=parseInt(i)-1,o.end=o.start+1}r=t}else r+=t}}return i}(a,t),l=function(e){let t,i="";for(;(t=e.nextLine())&&!t.startsWith("//");){t=t.trim();const e=t.split(/\s+/);for(let t=1;t1&&(n=parseInt(r[1])),s.push({chr:t,start:o,end:n,strand:i})}return s.sort((function(e,t){return e.start-t.start})),s}function kl(e){return e.startsWith('"')&&e.endsWith('"')&&(e=e.substring(1,e.length-2)),e}class Il extends gc{constructor(e,t){super(t),this.config=e,this.searchable=!0}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s}){if(!this.featureSource){const e=await _l(this.config.url);this.featureSource=new vl({genome:this.config.genome,features:e.features,searchableFields:["gene","db_xref","locus_tag","transcript_id"]})}return this.featureSource.getFeatures({chr:e,start:t,end:i})}supportsWholeGenome(){return!1}search(e){return this.featureSource.search(e)}}const Sl=new Set(["bigwig","bw","bigbed","bb","biginteract","biggenepred","bignarrowpeak"]);function El(e,t){const i=e.format?e.format.toLowerCase():void 0;return e.features?new vl(e,t):Sl.has(i)?new Pc(e,t):"tdf"===i?new vc(e,t):"gbk"===i?new Il(e,t):new Fl(e,t)}function Nl(e){return(3-e.readingFrame)%3}function Ml(e){return e.cdStart||e.start}function Rl(e){return e.cdEnd||e.end}const Bl=.25;function Dl(e,t,i){let r=(e.start-t)/i,s=(e.end-t)/i,o=s-r;return o<3&&(o=3,r-=1.5),{px:r,px1:s,pw:o}}function Ll(e,t,i,r,s,o){try{s.save(),s.fillStyle=this.color,s.strokeStyle=this.color;const r=this.getColorForFeature(e);let n,a;s.fillStyle=r,s.strokeStyle=r,"SQUISHED"===this.displayMode&&void 0!==e.row?(n=this.featureHeight/2,a=this.margin+this.squishedRowHeight*e.row):"EXPANDED"===this.displayMode&&void 0!==e.row?(n=this.featureHeight,a=this.margin+this.expandedRowHeight*e.row):(n=this.featureHeight,a=this.margin);const c=o.pixelWidth,l=a+n/2,h=n/2,d=l-h/2,u=e.exons?e.exons.length:0,f=Dl(e,t,i),p=this.arrowSpacing,g="+"===e.strand?1:"-"===e.strand?-1:0;if(0===u){const e=Math.max(0,f.px),t=Math.min(c,f.px1),i=t-e;if(s.fillRect(e,a,i,n),0!==g){s.fillStyle="white",s.strokeStyle="white";for(let i=e+p/2;ic)break;if(f.utr)s.fillRect(w,d,F,h);else{if(f.cdStart&&(m=Math.round((f.cdStart-t)/i),s.fillRect(w,d,m-w,h),F-=m-w,w=m),f.cdEnd&&(m=Math.round((f.cdEnd-t)/i),s.fillRect(m,d,b-m,h),F-=b-m,b=m),F=Math.max(F,1),s.fillRect(w,a,F,n),void 0!==f.readingFrame&&o.bpPerPixel0&&void 0!==e.exons[u-1].readingFrame?e.exons[u-1]:void 0,r=up+5&&0!==g&&o.bpPerPixel>Bl){s.fillStyle="white",s.strokeStyle="white";for(let e=w+p/2;e{const f=Math.round((i-o)/n),p=Math.round((r-o)/n)-f;let g;if(void 0===s){if(l.hasSequence(i,r)){const e=l.getSequence(i,r);if(e&&3===e.length){const i="+"===t?e:So(e.split("").reverse().join(""));g=Jl[i]}}}else g=s;e.fillStyle="M"===s||"M"===g&&0===u?"#83f902":"STOP"===g?"#ff2101":h[d],e.fillRect(f,a,p,c),g&&(e.save(),((t,i,r,s,o)=>{"STOP"===o&&(o="*");const n=e.measureText(o).width;Co.fillText(e,o,r+(i-n)/2,s-4,{fillStyle:"#ffffff"})})(0,p,f,a+c,g),e.restore());const m=r-i;return m>0&&m<3?{start:i,end:r}:void 0},u=Nl(r);let f,p,g,m,w,b=Ml(r),F=Rl(r),v=1;if("+"===t){for(u>0&&(b+=u),v=1,w=0,f=b;f0||g){const e=u>0?Pl.call(this,t,u,b-u,b,g,i,r,s,l):Pl.call(this,t,void 0,void 0,void 0,g,i,r,s,l);if(e){const{left:i,rite:r}=e;i&&d(t,b-u,b,i.aminoAcidLetter,0,void 0),r&&d(t,g.start,g.end,r.aminoAcidLetter,m,void 0)}}}else{for(u>0&&(F-=u),v=1,w=0,w=0,p=F;p>b;w++,p-=3)m=v%2,f=Math.max(b,p-3),g=d(t,f,p,void 0,v%2,w),++v;if(u>0||g){const e=u>0?Pl.call(this,t,u,F,F+u,g,i,r,s,l):Pl.call(this,t,void 0,void 0,void 0,g,i,r,s,l);if(e){const{left:i,rite:r}=e;r&&d(t,F,F+u,r.aminoAcidLetter,0,void 0),i&&d(t,g.start,g.end,i.aminoAcidLetter,m,void 0)}}}e.restore()}function zl(e,t,i,r,s,o,n){try{e.save();let o=t[this.config.labelField?this.config.labelField:"name"];if(void 0===o&&t.gene&&(o=t.gene.name),void 0===o&&(o=t.id||t.ID),!o||"."===o)return;let a=n.pixelXOffset||0;const c=Math.max(i,-a);let l,h=(c+Math.min(r,-a+n.viewportWidth))/2;"COLLAPSED"===this.displayMode&&"SLANT"===this.labelDisplayMode&&(l={rotate:{angle:45}});const d=function(e,t){return t?e+20:e+25}(s,l);let u=this.getColorForFeature(t),f=this.browser.qtlSelections.hasPhenotype(t.name);const p={textAlign:"SLANT"===this.labelDisplayMode?void 0:"center",fillStyle:u,strokeStyle:u},g=e.measureText(o),m=h-g.width/2,w=h+g.width/2,b=n.rowLastLabelX[t.row]||-Number.MAX_SAFE_INTEGER;(n.labelAllFeatures||m>b||f)&&(n.rowLastLabelX[t.row]=w,e.clearRect(h-g.width/2-1,d-g.actualBoundingBoxAscent-1,g.width+2,g.actualBoundingBoxAscent+g.actualBoundingBoxDescent+2),Co.fillText(e,o,h,d,p,l))}finally{e.restore()}}function Pl(e,t,i,r,s,o,n,a,c){let l,h,d="",u="",f="";const p={left:void 0,rite:void 0};if("+"===e){if(t){if(u=c.getSequence(i,r),!u)return;if([l,h]=[Rl(o)-(3-t),Rl(o)],d=c.getSequence(l,h),!d)return;f=d+u,p.left={triplet:f,aminoAcidLetter:Jl[f]}}if(s){if(d=c.getSequence(s.start,s.end),!d)return;const e=Nl(a),t=Ml(a);if(u=c.getSequence(t,t+e),!u)return;f=d+u,p.rite={triplet:f,aminoAcidLetter:Jl[f]}}}else{if(t){if(d=c.getSequence(i,r),void 0===d)return;if([l,h]=[Ml(a),Ml(a)+(3-t)],u=c.getSequence(l,h),void 0===u)return;f=d+u,f=So(f.split("").reverse().join("")),p.rite={triplet:f,aminoAcidLetter:Jl[f]}}if(s){if(u=c.getSequence(s.start,s.end),void 0===u)return;const e=Nl(o),t=Rl(o);if(d=c.getSequence(t-e,t),void 0===d)return;f=d+u,f=So(f.split("").reverse().join("")),p.left={triplet:f,aminoAcidLetter:Jl[f]}}}return p}const Hl=new Set(["nonsense","missense","stop-loss","frameshift","cds-indel"]),Ol=new Set(["coding-synon"]),Vl=new Set(["splice-3","splice-5"]),ql=new Set(["untranslated-5","untranslated-3"]);function Ul(e,t,i,r,s){var o,n,a,c,l,h,d=Dl(e,t,i),u=this.margin,f=this.snpColors.length;switch(o="squished"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight,this.colorBy){case"function":c=e.func,h=c.split(","),l=h.map((function(e){return Hl.has(e)||Vl.has(e)?f-1:Ol.has(e)?f-2:ql.has(e)?f-3:0})),n=l.reduce((function(e,t){return Math.max(e,t)}));break;case"class":n="deletion"===(a=e.class)?f-1:"mnp"===a?f-2:"microsatellite"===a||"named"===a?f-3:0}s.fillStyle=this.snpColors[n],s.fillRect(d.px,u,d.pw,o)}function Ql(e,t,i,r,s){const o="EXPANDED"===this.displayMode?this.expandedRowHeight:this.squishedRowHeight;let n=this.margin;"COLLAPSED"!==this.displayMode&&void 0!==e.row&&(n+=e.row*o);const a=n+.5*o,c=a-.5*o,l=a+.5*o,h=Math.round((e.junction_left-t)/i),d=Math.round((e.junction_right-t)/i);s.beginPath(),s.moveTo(h,a),s.bezierCurveTo(h,c,d,c,d,a),s.lineWidth=1+Math.log(e.num_junction_reads)/Math.log(2),s.strokeStyle="blue",s.stroke();const u=e.spanning_frag_coords;for(let e=0;et&&(t=i.row);return this.margin+(t+1)*("SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight)}}draw(e){const{features:t,context:i,bpPerPixel:r,bpStart:s,bpEnd:o,pixelWidth:n,pixelHeight:a,referenceFrame:c}=e;if(r0?s:0,o>t?t:o)}if(this.isMergedTrack||Co.fillRect(i,0,e.pixelTop,n,a,{fillStyle:"rgb(255, 255, 255)"}),t){const c=[];e.rowLastX=[],e.rowLastLabelX=[];for(let i of t)if((!this._filter||this._filter(i))&&i.start>s&&i.end!isNaN(e)))));let h=[];const d=[];for(let n of t){if(this._filter&&!this._filter(n))continue;if(n.endo)break;"COLLAPSED"===this.displayMode&&this.browser.qtlSelections.hasPhenotype(n.name)&&d.push(n);const t="COLLAPSED"===this.displayMode?0:n.row;e.drawLabel=e.labelAllFeatures||l>10;const c=Math.ceil((n.end-s)/r),u=h[t];if(!u||c>u){this.render.call(this,n,s,r,a,i,e);const o=Math.floor((n.start-s)/r);u&&o-u<=0&&(i.globalAlpha=.5,Co.strokeLine(i,o,0,o,a,{strokeStyle:"rgb(255, 255, 255)"}),i.globalAlpha=1),h[t]=c}}for(let t of d)e.drawLabel=!0,this.render.call(this,t,s,r,a,i,e)}else console.log("No feature list")}clickedFeatures(e){const t=e.y-this.margin,i=super.clickedFeatures(e);let r;switch(this.displayMode){case"SQUISHED":r=Math.floor(t/this.squishedRowHeight);break;case"EXPANDED":r=Math.floor(t/this.expandedRowHeight);break;default:r=void 0}return i.filter((function(e){return void 0===r||void 0===e.row||r===e.row}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,r=[];for(let e of t){const t=e._f||e,s="function"==typeof t.popupData?t.popupData(i):this.extractPopupData(t);if(s){r.length>0&&r.push("

");const o=this.infoURL||this.config.infoURL;for(let t of s)if(r.push(t),o&&t.name&&"name"===t.name.toLowerCase()&&t.value&&b(t.value)&&!t.value.startsWith("<")){const i=o.replace("$$",e.name);t.value=`${t.value}`}const n="gff"===this.config.format||"gff3"===this.config.format||"gtf"===this.config.format;if(t.exons&&t.exons.length>1)for(let e=0;e=s.start&&i<=s.end){const i=n?s.number:"-"===t.strand?t.exons.length-e:e+1;i&&(r.push("
"),r.push({name:"Exon Number",value:i}));break}}}}return r}menuItemList(){const e=[];if(this.render===Ul){e.push("
");for(const i of["function","class"]){function r(){this.colorBy=i,this.trackView.repaintViews()}e.push({element:ua(`Color by ${i}`,i===this.colorBy),click:r})}}e.push("
");const t={COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"};for(const s of["COLLAPSED","SQUISHED","EXPANDED"]){function o(){this.displayMode=s,this.config.displayMode=s,this.trackView.checkContentHeight(),this.trackView.repaintViews()}e.push({element:ua(t[s],s===this.displayMode),click:o})}return e}contextMenuItemList(e){const t=this.clickedFeatures(e);if(void 0===t||0===t.length)return;t.length>1&&t.sort(((e,t)=>t.end-t.start-(e.end-e.start)));const i=t[0];if(i.end-i.start<=1e6){const e=[{label:"View feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=Eo(e)):e="Unknown sequence",this.browser.alert.present(e)}}];return ds()&&void 0!==navigator.clipboard&&e.push({label:"Copy feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=Eo(e)):e="Unknown sequence";try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),e.push("
"),e}}description(){if(Ul===this.render){let e=""+this.name+"
";return e+="Color By Function:
",e+='Red: Coding-Non-Synonymous, Splice Site
',e+='Green: Coding-Synonymous
',e+='Blue: Untranslated
',e+='Black: Intron, Locus, Unknown

',e+="Color By Class:
",e+='Red: Deletion
',e+='Green: MNP
',e+='Blue: Microsatellite, Named
',e+='Black: Indel, Insertion, SNP',e+="",e}return super.description()}getColorForFeature(e){const t=e._f||e;let i;if(e.name&&this.browser.qtlSelections.hasPhenotype(e.name))i=this.browser.qtlSelections.colorForGene(e.name);else if(this.altColor&&"-"===t.strand)i="function"==typeof this.altColor?this.altColor(t):this.altColor;else if(this.color)i="function"==typeof this.color?this.color(t):this.color;else if(this.colorBy){const e=t.getAttributeValue?t.getAttributeValue(this.colorBy):t[this.colorBy];i=this.colorTable.getColor(e)}else t.color&&(i=t.color);if(i||(i=Gl.defaultColor),t.alpha&&1!==t.alpha)i=ur.addAlpha(i,t.alpha);else if(this.useScore&&t.score&&!Number.isNaN(t.score)){const e=function(e,t,i){const r=(t-e)/9,s=Math.floor((i-e)/r);return Math.min(1,.2+.8*s/9)}(this.config.min?this.config.min:this.viewLimitMin?this.viewLimitMin:0,this.config.max?this.config.max:this.viewLimitMax?this.viewLimitMax:1e3,t.score);t.alpha=e,i=ur.addAlpha(i,e)}return i}dispose(){this.trackView=void 0}}class jl{constructor(e){if(this.config=e,this.browser=e.browser,this.columnFormat=e.columnFormat,this.tableRowSelectionList=[],this.tableDOM=t({class:"igv-roi-table"}),e.width){let[t]=e.width.split("px");t=parseInt(t,10),this.tableDOM.style.width=`${Math.min(t,1600)}px`}e.parent.appendChild(this.tableDOM),this.headerDOM=e,this.tableColumnTitles=this.tableDOM,this.tableRowContainer=this.tableDOM,this.footerDOM=e.gotoButtonHandler}set headerDOM({browser:e,parent:i,headerTitle:r,dismissHandler:s}){const o=t();this.tableDOM.appendChild(o);const n=t();o.appendChild(n),n.innerHTML=r;const a=t();o.appendChild(a),a.appendChild(l("times")),this.boundDismissHandler=function(e){e.stopPropagation(),s()}.bind(this),a.addEventListener("click",this.boundDismissHandler);const{y:c}=e.root.getBoundingClientRect(),{y:h}=i.getBoundingClientRect(),d=-(h-c);p(this.tableDOM,o,{minX:0,minY:d}),this.tableDOM.style.display="none",this._headerDOM=o}set tableColumnTitles(e){const i=t({class:"igv-roi-table-column-titles"});e.appendChild(i);for(const{label:e,width:r}of this.columnFormat){const s=t();i.appendChild(s),s.style.width=r,s.innerText=e}this._tableColumnTitlesDOM=i}get tableColumnTitles(){return this._tableColumnTitlesDOM}set tableRowContainer(e){const i=t({class:"igv-roi-table-row-container"});e.appendChild(i),this._tableRowContainerDOM=i}get tableRowContainer(){return this._tableRowContainerDOM}set footerDOM(e){const i=t();this.tableDOM.appendChild(i);const r=t({class:"igv-roi-table-button"});i.appendChild(r),r.id="igv-roi-table-view-button",r.textContent="Go To",r.style.pointerEvents="none",this._footerDOM=i,this.gotoButton=r,this.boundGotoButtonHandler=e.bind(this),this.gotoButton.addEventListener("click",this.boundGotoButtonHandler)}tableRowDOMHelper(e){e.addEventListener("mousedown",(t=>{t.stopPropagation(),e.classList.toggle("igv-roi-table-row-selected"),e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover"),this.setTableRowSelectionState(e.classList.contains("igv-roi-table-row-selected"))})),e.addEventListener("mouseover",(t=>{e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover")})),e.addEventListener("mouseout",(t=>{e.classList.remove("igv-roi-table-row-hover")}))}clearTable(){const e=this.tableRowContainer.querySelectorAll(".igv-roi-table-row");for(let t of e)t.remove()}setTableRowSelectionState(e){e?this.tableRowSelectionList.push(1):this.tableRowSelectionList.pop(),this.gotoButton.style.pointerEvents=this.tableRowSelectionList.length>0?"auto":"none"}present(){this.tableDOM.style.left="0px";const{y:e}=this.browser.root.getBoundingClientRect(),{y:t}=this.config.parent.getBoundingClientRect();this.tableDOM.style.top=e-t+"px",this.tableDOM.style.display="flex"}dismiss(){this.tableDOM.style.display="none"}isVisible(){return"none"!==this.tableDOM.style.display}dispose(){this.tableDOM.innerHTML="",this.tableDOM.remove();for(const e of Object.keys(this))this[e]=void 0;document.removeEventListener("click",this.boundDismissHandler)}}class Wl extends jl{constructor(e){super(Object.assign({width:"1024px"},e)),this.descriptionDOM=e}set descriptionDOM(e){if(e.description){let i;i=t({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(i,this.tableColumnTitles),i.style.height="auto",i.innerHTML="BLAT result for query sequence:",i=t({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(i,this.tableColumnTitles),i.style.height="auto",i.style.maxHeight="128px",i.innerHTML=e.description,i=t({class:"igv-roi-table-goto-explainer"}),this.tableDOM.insertBefore(i,this.tableColumnTitles),i.innerHTML="Select one or more rows and click Go To to view the regions"}}tableRowDOM(e){const i=t({class:"igv-roi-table-row"}),r=e.map((e=>isFinite(e)?F(e):e));for(let e=0;ee.remove())),e.length>0)for(let t of e){const e=this.tableRowDOM(t);this.tableRowContainer.appendChild(e)}}static getColumnFormatConfiguration(){return[{label:"chr",width:"7%"},{label:"start",width:"12%"},{label:"end",width:"12%"},{label:"strand",width:"5%"},{label:"score",width:"5%"},{label:"match",width:"5%"},{label:"mis-match",width:"7%"},{label:"rep. match",width:"7%"},{label:"N's",width:"3%"},{label:"Q gap count",width:"9%"},{label:"Q gap bases",width:"9%"},{label:"T gap count",width:"9%"},{label:"T gap bases",width:"9%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(const e of t){const t=[];e.querySelectorAll("div").forEach((e=>t.push(e.innerText)));const[r,s,o]=t;i.push(`${r}:${s}-${o}`)}for(const e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),this.browser.search(i.join(" "))}}async function $l({url:e,userSeq:t,db:i}){if(e=e||"https://igv.org/services/blatUCSC.php",!i)throw Error("Blat database is not defined");const r=await async function(e="",t,i){const r=new URLSearchParams;r.append("userSeq",t),r.append("db",i);const s=await fetch(e,{method:"post",body:r});return s.json()}(e,t,i);r.fields;return r.blat.map(qn)}const Kl=25e3;class Zl extends Gl{constructor(e,t){super(e,t),this.name||(this.name="Blat Results"),this.sequence=e.sequence,this.table=void 0,e.features&&(this._features=e.features,this.featureSource=new vl({features:e.features},this.browser.genome),delete e.features)}async postInit(){if(!this.featureSource){const e=this.browser.genome.ucscID,t=this.browser.config.blatServerURL,i=await $l({url:t,userSeq:this.sequence,db:e});this._features=i,this.featureSource=new vl({features:i},this.browser.genome)}this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor}openTableView(){if(void 0===this.table){const e=this._features.map((e=>[this.browser.genome.getChromosomeDisplayName(e.chr),e.start+1,e.end,e.strand,e.score,e.matches,e.misMatches,e.repMatches,e.nCount,e.qNumInsert,e.qBaseInsert,e.tNumInsert,e.tBaseInsert])),t={browser:this.browser,parent:this.browser.columnContainer,headerTitle:this.config.title,description:this.sequence,dismissHandler:()=>{this.table.dismiss(),this.table.dispose(),this.table=void 0},columnFormat:Wl.getColumnFormatConfiguration(),gotoButtonHandler:Wl.gotoButtonHandler};this.table=new Wl(t),this.table.renderTable(e)}this.table.present()}menuItemList(){const e=super.menuItemList();return e.push("
"),e.push({label:"Open table view",click:function(){this.openTableView()}}),e}dispose(){super.dispose(),this.table&&this.table.popover.parentElement.removeChild(this.table.popover)}}async function Yl({sequence:e,browser:t,name:i,title:r}){if(e.length>Kl)t.alert.present(`Sequence size exceeds maximum allowed length (${e.length} > 25000)`);else try{const s=t.genome.ucscID,o=t.config.blatServerURL||"https://igv.org/services/blatUCSC.php",n={type:"blat",name:i||"blat results",title:r||"blat results",sequence:e,altColor:"rgb(176, 176, 236)",color:"rgb(236, 176, 176)",searchable:!1,features:await $l({url:o,userSeq:e,db:s})};(await t.loadTrackList([n]))[0].openTableView()}catch(e){t.alert.present(`Error performing blat search: ${e}`)}}const Xl=Number.MIN_SAFE_INTEGER,Jl={TTT:"F",TTC:"F",TTA:"L",TTG:"L",CTT:"L",CTC:"L",CTA:"L",CTG:"L",ATT:"I",ATC:"I",ATA:"I",ATG:"M",GTT:"V",GTC:"V",GTA:"V",GTG:"V",TCT:"S",TCC:"S",TCA:"S",TCG:"S",CCT:"P",CCC:"P",CCA:"P",CCG:"P",ACT:"T",ACC:"T",ACA:"T",ACG:"T",GCT:"A",GCC:"A",GCA:"A",GCG:"A",TAT:"Y",TAC:"Y",TAA:"STOP",TAG:"STOP",CAT:"H",CAC:"H",CAA:"Q",CAG:"Q",AAT:"N",AAC:"N",AAA:"K",AAG:"K",GAT:"D",GAC:"D",GAA:"E",GAG:"E",TGT:"C",TGC:"C",TGA:"STOP",TGG:"W",CGT:"R",CGC:"R",CGA:"R",CGG:"R",AGT:"S",AGC:"S",AGA:"R",AGG:"R",GGT:"G",GGC:"G",GGA:"G",GGG:"G"},eh={},th=["A","G","C","T","Y","R","W","S","K","M","D","V","H","B","N","X"],ih=["T","C","G","A","R","Y","W","S","M","K","H","B","D","V","N","X"];for(let xy=0;xy{this.reversed=!this.reversed,this.trackView.repaintViews()}},{name:this.frameTranslate?"Close Translation":"Three-frame Translate",click:()=>{if(this.frameTranslate=!this.frameTranslate,this.frameTranslate){for(let e of this.trackView.viewports)e.setContentHeight(rh);this.trackView.setTrackHeight(rh)}else{for(let e of this.trackView.viewports)e.setContentHeight(25);this.trackView.setTrackHeight(25)}this.trackView.repaintViews()}}]}contextMenuItemList(e){const t=e.viewport;if(t.referenceFrame.bpPerPixel<=1){const e=t.getWidth()*t.referenceFrame.bpPerPixel,i=t.referenceFrame.chr,r=Math.floor(t.referenceFrame.start),s=Math.ceil(r+e),o=[{label:this.reversed?"View visible sequence (reversed)...":"View visible sequence...",click:async()=>{let e=await this.browser.genome.getSequence(i,r,s);e?this.reversed&&(e=Eo(e)):e="Unknown sequence",this.browser.alert.present(e)}}];return ds()&&o.push({label:"Copy visible sequence",click:async()=>{let e=await this.browser.genome.getSequence(i,r,s);e?this.reversed&&(e=Eo(e)):e="Unknown sequence";try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),o.push({label:"BLAT visible sequence",click:async()=>{let e=await this.browser.genome.getSequence(i,r,s);if(e){this.reversed&&(e=Eo(e));const t=`blat: ${i}:${r+1}-${s}`,o=`blat: ${i}:${r+1}-${s}`;Yl({sequence:e,browser:this.browser,name:t,title:o})}}}),o.push("
"),o}}translateSequence(e){const t=[[],[],[]];for(let i of[0,1,2]){let r=i;for(;e.length-r>=3;){let s=e.slice(r,r+3);this.reversed&&(s=s.split("").reverse().join(""));const o=Jl[s.toUpperCase()]||"";t[i].push({codons:s,aminoA:o}),r+=3}}return t}async getSequenceSource(){return this.config.fastaURL?(this.fasta||(this.fasta=new oh(this.config,this.browser.genome),await this.fasta.init()),this.fasta):this.browser.genome}async getFeatures(e,t,i,r){if(t=Math.floor(t),i=Math.floor(i),r&&r>10)return null;{const r=await this.getSequenceSource();return{bpStart:t,sequence:await r.getSequence(e,t,i)}}}draw(e){const t=e.context;if(e.features){let i=e.features.sequence;if(!i)return;this.reversed&&(i=i.split("").map((function(e){return eh[e]})).join(""));const r=e.features.bpStart,s=1+e.bpStart+e.pixelWidth*e.bpPerPixel;for(let o=Math.floor(e.bpStart);o<=s;o++){const s=Math.floor(o-r);if(s>=0&&s.1)Co.fillRect(t,r,5,n,10,{fillStyle:c});else{const i=r+.5*(n-t.measureText(a).width);"y"===e.axis?(t.save(),Co.labelTransformWithContext(t,i),Co.strokeText(t,a,i,15,{strokeStyle:c}),t.restore()):Co.strokeText(t,a,i,15,{strokeStyle:c})}}}if(this.frameTranslate){let s=25;const o=this.translateSequence(i);for(let i=0;ie.pixelWidth)break;let f=c.aminoA;c.aminoA.indexOf("STOP")>-1?(a="rgb(255, 0, 0)",f="STOP"):"M"===c.aminoA&&(a="rgb(0, 153, 0)",f="START"),Co.fillRect(t,h,s,d-h,25,{fillStyle:a}),e.bpPerPixel<=.1&&Co.strokeText(t,f,u-t.measureText(f).width/2,s+15)}s+=30}}}}get supportsWholeGenome(){return!1}computePixelHeight(e){return this.height=this.frameTranslate?rh:25,this.height}fillColor(e){return this.color?this.color:"dna"===this.sequenceType?this.browser.nucleotideColors[e]||"gray":"rgb(0, 0, 150)"}getState(){const e={type:"sequence"};return this.order!==Xl&&(e.order=this.order),this.reversed&&(e.revealed=!0),e}}class oh{constructor(e,t){this.config=e,this.genome=t}async init(){this.fasta=await Yo(this.config),this.chrNameMap=new Map;for(let e of this.fasta.chromosomeNames)this.chrNameMap.set(this.genome.getChromosomeName(e),e)}async getSequence(e,t,i){const r=this.chrNameMap.has(e)?this.chrNameMap.get(e):e;return this.fasta.getSequence(r,t,i)}}class nh{constructor(e,t,i,r){this.guid=n(),this.trackView=e,this.referenceFrame=i,this.browser=e.browser,this.viewportElement=document.createElement("div"),this.viewportElement.className="igv-viewport",t.appendChild(this.viewportElement),e.track.height&&this.setHeight(e.track.height);const s=e.track.type||"untyped";this.viewportElement.setAttribute("data-track-type",s),e.track instanceof sh&&(this.alert=new Ao(this.viewportElement)),this.contentTop=0,this.contentHeight=this.viewportElement.clientHeight,this.setWidth(r),this.initializationHelper()}initializationHelper(){}showMessage(e){this.messageDiv||(this.messageDiv=document.createElement("div"),this.messageDiv.className="igv-viewport-message",this.viewportElement.appendChild(this.messageDiv)),this.messageDiv.textContent=e,this.messageDiv.style.display="inline-block"}hideMessage(){this.messageDiv&&(this.messageDiv.style.display="none")}setTrackLabel(e){}startSpinner(){}stopSpinner(){}checkZoomIn(){return!0}shift(){}setTop(e){this.contentTop=e}async loadFeatures(){}clearCache(){}repaint(){}draw(e,t,i){console.log("Viewport - draw(drawConfiguration, features, roiFeatures)")}checkContentHeight(e){const t=this.trackView.track;if(e=e||this.cachedFeatures,"FILL"===t.displayMode)this.setContentHeight(this.viewportElement.clientHeight);else if("function"==typeof t.computePixelHeight&&e&&e.length>0){const i=t.computePixelHeight(e,this.referenceFrame.bpPerPixel);i!==this.contentHeight&&this.setContentHeight(i)}}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}isLoading(){return!1}saveSVG(){}isVisible(){return this.viewportElement.clientWidth>0}setWidth(e){this.viewportElement.style.width=`${e}px`}getWidth(){return this.viewportElement.clientWidth}setHeight(e){this.viewportElement.style.height=`${e}px`}getContentTop(){return this.contentTop}containsPosition(e,t){console.log("Viewport - containsPosition(chr, position)")}addMouseHandlers(){}dispose(){this.viewportElement.remove();for(const e in this)this.hasOwnProperty(e)&&(this[e]=void 0)}} + */var $c=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Kc=function(){function e(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:1;return(t>0?e.toFixed(t).replace(/0+$/,"").replace(/\.$/,""):e.toString())||"0"}var Jc=function(){function e(t,i,r,s){$c(this,e);var o=this;if(void 0===t);else if(Array.isArray(t))this.rgba=t;else if(void 0===r){var n=t&&""+t;n&&function(t){if(t.startsWith("hsl")){var i=t.match(/([\-\d\.e]+)/g).map(Number),r=Yc(i,4),s=r[0],n=r[1],a=r[2],c=r[3];void 0===c&&(c=1),s/=360,n/=100,a/=100,o.hsla=[s,n,a,c]}else if(t.startsWith("rgb")){var l=t.match(/([\-\d\.e]+)/g).map(Number),h=Yc(l,4),d=h[0],u=h[1],f=h[2],p=h[3];void 0===p&&(p=1),o.rgba=[d,u,f,p]}else t.startsWith("#")?o.rgba=e.hexToRgb(t):o.rgba=e.nameToRgb(t)||e.hexToRgb(t)}(n.toLowerCase())}else this.rgba=[t,i,r,void 0===s?1:s]}return Kc(e,[{key:"printRGB",value:function(e){var t=(e?this.rgba:this.rgba.slice(0,3)).map((function(e,t){return Xc(e,3===t?3:0)}));return e?"rgba("+t+")":"rgb("+t+")"}},{key:"printHSL",value:function(e){var t=[360,100,100,1],i=["","%","%",""],r=(e?this.hsla:this.hsla.slice(0,3)).map((function(e,r){return Xc(e*t[r],3===r?3:1)+i[r]}));return e?"hsla("+r+")":"hsl("+r+")"}},{key:"printHex",value:function(e){var t=this.hex;return e?t:t.substring(0,7)}},{key:"rgba",get:function(){if(this._rgba)return this._rgba;if(!this._hsla)throw new Error("No color is set");return this._rgba=e.hslToRgb(this._hsla)},set:function(e){3===e.length&&(e[3]=1),this._rgba=e,this._hsla=null}},{key:"rgbString",get:function(){return this.printRGB()}},{key:"rgbaString",get:function(){return this.printRGB(!0)}},{key:"hsla",get:function(){if(this._hsla)return this._hsla;if(!this._rgba)throw new Error("No color is set");return this._hsla=e.rgbToHsl(this._rgba)},set:function(e){3===e.length&&(e[3]=1),this._hsla=e,this._rgba=null}},{key:"hslString",get:function(){return this.printHSL()}},{key:"hslaString",get:function(){return this.printHSL(!0)}},{key:"hex",get:function(){return"#"+this.rgba.map((function(e,t){return t<3?e.toString(16):Math.round(255*e).toString(16)})).map((function(e){return e.padStart(2,"0")})).join("")},set:function(t){this.rgba=e.hexToRgb(t)}}],[{key:"hexToRgb",value:function(e){var t=(e.startsWith("#")?e.slice(1):e).replace(/^(\w{3})$/,"$1F").replace(/^(\w)(\w)(\w)(\w)$/,"$1$1$2$2$3$3$4$4").replace(/^(\w{6})$/,"$1FF");if(!t.match(/^([0-9a-fA-F]{8})$/))throw new Error("Unknown hex color; "+e);var i=t.match(/^(\w\w)(\w\w)(\w\w)(\w\w)$/).slice(1).map((function(e){return parseInt(e,16)}));return i[3]=i[3]/255,i}},{key:"nameToRgb",value:function(t){var i=t.toLowerCase().replace("at","T").replace(/[aeiouyldf]/g,"").replace("ght","L").replace("rk","D").slice(-5,4),r=Zc[i];return void 0===r?r:e.hexToRgb(r.replace(/\-/g,"00").padStart(6,"f"))}},{key:"rgbToHsl",value:function(e){var t=Yc(e,4),i=t[0],r=t[1],s=t[2],o=t[3];i/=255,r/=255,s/=255;var n=Math.max(i,r,s),a=Math.min(i,r,s),c=void 0,l=void 0,h=(n+a)/2;if(n===a)c=l=0;else{var d=n-a;switch(l=h>.5?d/(2-n-a):d/(n+a),n){case i:c=(r-s)/d+(r1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e},h=s<.5?s*(1+r):s+r-s*r,d=2*s-h;n=l(d,h,i+1/3),a=l(d,h,i),c=l(d,h,i-1/3)}var u=[255*n,255*a,255*c].map(Math.round);return u[3]=o,u}}]),e}(),el=function(){function e(){$c(this,e),this._events=[]}return Kc(e,[{key:"add",value:function(e,t,i){e.addEventListener(t,i,!1),this._events.push({target:e,type:t,handler:i})}},{key:"remove",value:function(t,i,r){this._events=this._events.filter((function(s){var o=!0;return t&&t!==s.target&&(o=!1),i&&i!==s.type&&(o=!1),r&&r!==s.handler&&(o=!1),o&&e._doRemove(s.target,s.type,s.handler),!o}))}},{key:"destroy",value:function(){this._events.forEach((function(t){return e._doRemove(t.target,t.type,t.handler)})),this._events=[]}}],[{key:"_doRemove",value:function(e,t,i){e.removeEventListener(t,i,!1)}}]),e}();function tl(e,t,i){var r=!1;function s(e,t,i){return Math.max(t,Math.min(e,i))}function o(e,o,n){if(n&&(r=!0),r){e.preventDefault();var a=t.getBoundingClientRect(),c=a.width,l=a.height,h=o.clientX,d=o.clientY,u=s(h-a.left,0,c),f=s(d-a.top,0,l);i(u/c,f/l)}}function n(e,t){1===(void 0===e.buttons?e.which:e.buttons)?o(e,e,t):r=!1}function a(e,t){1===e.touches.length?o(e,e.touches[0],t):r=!1}e.add(t,"mousedown",(function(e){n(e,!0)})),e.add(t,"touchstart",(function(e){a(e,!0)})),e.add(window,"mousemove",n),e.add(t,"touchmove",a),e.add(window,"mouseup",(function(e){r=!1})),e.add(t,"touchend",(function(e){r=!1})),e.add(t,"touchcancel",(function(e){r=!1}))}var il="keydown",rl="mousedown",sl="focusin";function ol(e,t){return(t||document).querySelector(e)}function nl(e){e.preventDefault(),e.stopPropagation()}function al(e,t,i,r,s){e.add(t,il,(function(e){i.indexOf(e.key)>=0&&(s&&nl(e),r(e))}))}var cl=function(){function e(t){$c(this,e),this.settings={popup:"right",layout:"default",alpha:!0,editor:!0,editorFormat:"hex",cancelButton:!1,defaultColor:"#0cf"},this._events=new el,this.onChange=null,this.onDone=null,this.onOpen=null,this.onClose=null,this.setOptions(t)}return Kc(e,[{key:"setOptions",value:function(e){var t=this;if(e){var i=this.settings;if(e instanceof HTMLElement)i.parent=e;else{i.parent&&e.parent&&i.parent!==e.parent&&(this._events.remove(i.parent),this._popupInited=!1),function(e,t,i){for(var r in e)i&&i.indexOf(r)>=0||(t[r]=e[r])}(e,i),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var r=e.color||e.colour;r&&this._setColor(r)}var s=i.parent;if(s&&i.popup&&!this._popupInited){var o=function(e){return t.openHandler(e)};this._events.add(s,"click",o),al(this._events,s,[" ","Spacebar","Enter"],o),this._popupInited=!0}else e.parent&&!i.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===il?this._domEdit:this.domElement;setTimeout((function(){return t.focus()}),100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,i=!1;if(e)if(t===rl||t===sl){var r=(this.__containedEvent||0)+100;e.timeStamp>r&&(i=!0)}else nl(e),i=!0;else i=!0;i&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==rl&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var i=void 0;try{i=new Jc(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var r=i.hsla;r[3]=1,i.hsla=r}this.colour=this.color=i,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}(this.settings.template||'
');return this.domElement=t,this._domH=ol(".picker_hue",t),this._domSL=ol(".picker_sl",t),this._domA=ol(".picker_alpha",t),this._domEdit=ol(".picker_editor input",t),this._domSample=ol(".picker_sample",t),this._domOkay=ol(".picker_done button",t),this._domCancel=ol(".picker_cancel button",t),t.classList.add("layout_"+this.settings.layout),this.settings.alpha||t.classList.add("no_alpha"),this.settings.editor||t.classList.add("no_editor"),this.settings.cancelButton||t.classList.add("no_cancel"),this._ifPopup((function(){return t.classList.add("popup")})),this._setPosition(),this.colour?this._updateUI():this._setColor(this.settings.defaultColor),this._bindEvents(),!0}},{key:"hide",value:function(){return this._toggleDOM(!1)}},{key:"destroy",value:function(){this._events.destroy(),this.domElement&&this.settings.parent.removeChild(this.domElement)}},{key:"_bindEvents",value:function(){var e=this,t=this,i=this.domElement,r=this._events;function s(e,t,i){r.add(e,t,i)}s(i,"click",(function(e){return e.preventDefault()})),tl(r,this._domH,(function(e,i){return t._setHSLA(e)})),tl(r,this._domSL,(function(e,i){return t._setHSLA(null,e,1-i)})),this.settings.alpha&&tl(r,this._domA,(function(e,i){return t._setHSLA(null,null,null,1-i)}));var o=this._domEdit;s(o,"input",(function(e){t._setColor(this.value,{fromEditor:!0,failSilently:!0})})),s(o,"focus",(function(e){var t=this;t.selectionStart===t.selectionEnd&&t.select()})),this._ifPopup((function(){var t=function(t){return e.closeHandler(t)};s(window,rl,t),s(window,sl,t),al(r,i,["Esc","Escape"],t);var o=function(t){e.__containedEvent=t.timeStamp};s(i,rl,o),s(i,sl,o),s(e._domCancel,"click",t)}));var n=function(t){e._ifPopup((function(){return e.closeHandler(t)})),e.onDone&&e.onDone(e.colour)};s(this._domOkay,"click",n),al(r,i,["Enter"],n)}},{key:"_setPosition",value:function(){var e=this.settings.parent,t=this.domElement;e!==t.parentNode&&e.appendChild(t),this._ifPopup((function(i){"static"===getComputedStyle(e).position&&(e.style.position="relative");var r=!0===i?"popup_right":"popup_"+i;["popup_top","popup_bottom","popup_left","popup_right"].forEach((function(e){e===r?t.classList.add(e):t.classList.remove(e)})),t.classList.add(r)}))}},{key:"_setHSLA",value:function(e,t,i,r,s){s=s||{};var o=this.colour,n=o.hsla;[e,t,i,r].forEach((function(e,t){(e||0===e)&&(n[t]=e)})),o.hsla=n,this._updateUI(s),this.onChange&&!s.silent&&this.onChange(o)}},{key:"_updateUI",value:function(e){if(this.domElement){e=e||{};var t=this.colour,i=t.hsla,r="hsl("+360*i[0]+", 100%, 50%)",s=t.hslString,o=t.hslaString,n=this._domH,a=this._domSL,c=this._domA,l=ol(".picker_selector",n),h=ol(".picker_selector",a),d=ol(".picker_selector",c);b(0,l,i[0]),this._domSL.style.backgroundColor=this._domH.style.color=r,b(0,h,i[1]),F(0,h,1-i[2]),a.style.color=s,F(0,d,1-i[3]);var u=s,f=u.replace("hsl","hsla").replace(")",", 0)"),p="linear-gradient("+[u,f]+")";if(this._domA.style.background=p+", linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0 / 2em 2em,\n linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em / 2em 2em",!e.fromEditor){var g=this.settings.editorFormat,m=this.settings.alpha,w=void 0;switch(g){case"rgb":w=t.printRGB(m);break;case"hsl":w=t.printHSL(m);break;default:w=t.printHex(m)}this._domEdit.value=w}this._domSample.style.color=o}function b(e,t,i){t.style.left=100*i+"%"}function F(e,t,i){t.style.top=100*i+"%"}}},{key:"_ifPopup",value:function(e,t){this.settings.parent&&this.settings.popup?e&&e(this.settings.popup):t&&t()}},{key:"_toggleDOM",value:function(e){var t=this.domElement;if(!t)return!1;var i=e?"":"none",r=t.style.display!==i;return r&&(t.style.display=i),r}}]),e}();const ll={display:"flex",flexDirection:"row",alignItems:"center",backgroundColor:"transparent"};class hl{constructor({selected:e,label:i,onchange:r}){this.state=e,this.onchange=r,this.elem=t({style:ll});const s=t({style:{width:"14px",height:"14px",borderColor:"gray",borderWidth:"1px",borderStyle:"solid"}});if(this.svg=l("check",!0===e?"#444":"transparent"),this.svg.style.width="12px",this.svg.style.height="12px",s.appendChild(this.svg),this.elem.appendChild(s),i){const e=t({style:{marginLeft:"5px"}});e.textContent=i,this.elem.appendChild(e)}const o=e=>{e.preventDefault(),e.stopPropagation();const t=!this.state;this.selected=t,"function"==typeof this.onchange&&this.onchange(t)};this.elem.addEventListener("click",o),this.elem.addEventListener("touchend",o)}set selected(e){this.state=e;this.svg.querySelector("path").setAttributeNS(null,"fill",!0===e?"#444":"transparent")}get selected(){return this.state}onchange(e){this.onchange=e}}function dl(e,t){const i=e.getContext("2d"),r=e.width,s=(t.max-t.min)/r;for(let o=0;o{r.min=Number.parseFloat(e),dl(n,r)}});o.appendChild(a.row);const c=new pl({label:"Mid value",value:(r.mid||r.min).toString(),onchange:e=>{r.mid=Number.parseFloat(e),dl(n,r)}});o.appendChild(c.row);const l=new pl({label:"Max value",value:r.max.toString(),onchange:e=>{r.max=Number.parseFloat(e),dl(n,r)}});o.appendChild(l.row);const h=new gl({label:"Min color",value:r.minColor,onchange:e=>{r.minColor=e,dl(n,r)}});o.appendChild(h.row);const d=new gl({label:"Mid color",value:r.midColor||r.minColor,onchange:e=>{r.midColor=e,dl(n,r)}});o.appendChild(d.row);const u=new gl({label:"Max color",value:r.maxColor,onchange:e=>{r.maxColor=e,dl(n,r)}});o.appendChild(u.row);const f=new hl({selected:"diverging"===e.type,label:"Diverging Scale",onchange:e=>{e?(r.mid=r.min<0&&r.max>0?0:(r.min+r.max)/2,r.midColor="rgb(255,255,255)",r=new jc(r),c.value=r.mid,c.show(),d.value=r.midColor,d.show(),dl(n,r)):(r=new Gc(r),c.hide(),d.hide(),dl(n,r))}});f.elem.style.marginBottom="20px","diverging"!==e.type&&(c.hide(),d.hide());const p=document.createElement("div");p.appendChild(f.elem),p.appendChild(o),p.appendChild(n);const g=new w({parent:t,content:{elem:p},okHandler:()=>{i&&i(r)}});t.appendChild(g.elem),s(g.elem),dl(n,r)}}class fl{constructor({label:e,value:t,onchange:i}){this.row=document.createElement("tr");const r=document.createElement("td");this.row.appendChild(r);const s=document.createElement("div");s.innerHTML=e,r.appendChild(s)}hide(){this.row.style.display="none"}show(){this.row.style.display="table-row"}}class pl extends fl{constructor({label:e,value:t,onchange:i}){super({label:e,value:t,onchange:i});const r=document.createElement("td");this.row.appendChild(r),this.input=document.createElement("input"),t=t||"0",this.input.value=vo.sanitize(t),r.appendChild(this.input),i&&this.input.addEventListener("change",(e=>i(this.input.value)))}get value(){return this.input.value}set value(e){this.input.value=e}}class gl extends fl{constructor({label:e,value:t,onchange:i}){super({label:e,value:t,onchange:i});const r=document.createElement("td");this.row.appendChild(r);const s=document.createElement("div");r.appendChild(s),s.style.width="20px",s.style.height="20px",s.style.border="1px solid black",this.colorButton=s,t=t||"white",s.style.background=t;const o=new cl(s);o.setOptions({alpha:!1,color:t}),o.onDone=e=>{s.style.background=e.rgbString,i&&i(e.rgbString)}}set value(e){this.colorButton.style.background=e}}class ml extends ma{static defaultColor="rgb(150, 150, 150)";static defaults={height:50,flipAxis:!1,logScale:!1,windowFunction:"mean",graphType:"bar",normalize:void 0,scaleFactor:void 0,overflowColor:"rgb(255, 32, 255)",baselineColor:"lightGray",summarize:!0,visibilityWindow:void 0};constructor(e,t){super(e,t)}init(e){super.init(e),this.type="wig",this.featureType="numeric",this.resolutionAware=!0,this._paintAxis=Oc.bind(this);const t=e.format?e.format.toLowerCase():e.format;e.featureSource?(this.featureSource=e.featureSource,delete e.featureSource):this.featureSource="bigwig"===t?new Pc(e,this.browser.genome):"tdf"===t?new vc(e,this.browser.genome):El(e,this.browser.genome),void 0===e.max||!0===e.autoscale?this.autoscale=!0:this.dataRange={min:e.min||0,max:e.max},e.colorScale&&(this._colorScale=Vc(e.colorScale)),"heatmap"!==e.graphType||e.height||(this.height=20)}async postInit(){const e=await this.getHeader();this.disposed||(e&&this.setTrackProperties(e),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor)}get supportsWholeGenome(){return!this.config.indexURL&&!1!==this.config.supportsWholeGenome}get paintAxis(){return"heatmap"===this.graphType?()=>{}:this._paintAxis}get colorScale(){return this._colorScale}async getFeatures(e,t,i,r){const s=this.windowFunction,o=await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:this.visibilityWindow,windowFunction:s});if(this.normalize&&this.featureSource.normalizationFactor){const e=this.featureSource.normalizationFactor;for(let t of o)t.value*=e}if(this.scaleFactor){const e=this.scaleFactor;for(let t of o)t.value*=e}if("dynseq"===this.graphType&&o&&o.length>0)for(let e of o)try{e.sequence=await this.browser.genome.getSequence(e.chr,Math.floor(e.start),Math.floor(e.end))}catch(t){console.warn(`Failed to get sequence for feature at chr: ${e.chr}, start: ${e.start}, end: ${e.end}. Error:`,t),e.sequence=null}return!this.summarize||"mean"!==s&&"min"!==s&&"max"!==s?o:wl(o,t,r,s)}menuItemList(){const e=[];return"heatmap"===this.graphType?(e.push("
"),e.push({label:"Set color scale",click:function(){ul.open(this.colorScale,this.browser.columnContainer,(e=>{this._colorScale=e,this.trackView.repaintViews()}))}})):void 0!==this.flipAxis&&(e.push("
"),e.push({label:"Flip y-axis",click:function(){this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}})),e.push(...this.graphTypeItems()),this.featureSource.windowFunctions&&e.push(...this.wigSummarizationItems()),e.push(...this.numericDataMenuItems()),e}wigSummarizationItems(){const e=this.featureSource.windowFunctions,t=[];t.push("
"),t.push("
Windowing function
");for(const i of e){function r(){this.windowFunction=i,this.trackView.updateViews()}t.push({element:ua(i,this.windowFunction===i),click:r})}return t}graphTypeItems(){const e=["bar","line","points","heatmap","dynseq"],t=[];t.push("
"),t.push("
Graph type
");for(const i of e){function r(){this.graphType=i,this.trackView.repaintViews()}t.push({element:ua(i,this.graphType===i),click:r})}return t}async getHeader(){return"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader()),this.header}getScaleFactor(e,t,i,r){const s=!0===r?e<0?-Math.log10(Math.abs(e)+1):Math.log10(Math.abs(e)+1):e;return i/((!0===r?Math.log10(Math.abs(t)+1):t)-s)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,r=this.dataRange.min;return r=r<0?-Math.log10(Math.abs(r)+1):Math.log10(Math.abs(r)+1),i=i<0?-Math.log10(Math.abs(i)+1):Math.log10(Math.abs(i)+1),e=e<0?-Math.log10(Math.abs(e)+1):Math.log10(e+1),(this.flipAxis?e-r:i-e)*t}draw(e){const t=e.features,i=e.context,r=e.bpPerPixel,s=e.bpStart,o=e.pixelWidth,n=e.pixelHeight-1,a=s+o*r+1,c=this.getScaleFactor(this.dataRange.min,this.dataRange.max,n,this.logScale),l=e=>this.logScale?this.computeYPixelValueInLogScale(e,c):this.computeYPixelValue(e,c);if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){let o,c=-1;const h=l(0);for(let d of t){if(d.enda)break;const t=(d.start-s)/r;if(Number.isNaN(t))continue;let u=l(d.value);const f=(d.end-s)/r-t,p=e.alpha?ur.addAlpha(this.getColorForFeature(d),e.alpha):this.getColorForFeature(d);if("line"===this.graphType)void 0!==o&&Co.strokeLine(i,c,o,t,u,{fillStyle:p,strokeStyle:p}),Co.strokeLine(i,t,u,t+f,u,{fillStyle:p,strokeStyle:p});else if("points"===this.graphType){const e=this.config.pointSize||3,r=t+f/2;Co.fillCircle(i,r,u,e/2,{fillStyle:p,strokeStyle:p}),d.value>this.dataRange.max?Co.fillCircle(i,r,e/2,e/2,3,{fillStyle:this.overflowColor}):d.value0?Uc(this.dataRange.min,0,this.dataRange.max):qc(this.dataRange.min,this.dataRange.max));const e=this._colorScale.getColor(d.value);Co.fillRect(i,t,0,f,n,{fillStyle:e})}else if("dynseq"===this.graphType)this.renderDynSeq(i,d,t,f,u,h,n);else{const e=Math.min(n,u-h);Co.fillRect(i,t,h,f,e,{fillStyle:p}),d.value>this.dataRange.max?Co.fillRect(i,t,0,f,3,{fillStyle:this.overflowColor}):d.valuethis.dataRange.max?Co.fillRect(e,i,0,r,3,{fillStyle:this.overflowColor}):t.value=6&&e.bezierCurveTo(i+o[0]*n,r+o[1]*a,i+o[2]*n,r+o[3]*a,i+o[4]*n,r+o[5]*a)}e.closePath(),e.fill()}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0){const i=e.genomicLocation,r=[];t.sort((function(e,t){return Math.abs((e.start+e.end)/2-i)-Math.abs((t.start+t.end)/2-i)}));const s=t.length>10?t.slice(0,10):t;s.sort((function(e,t){return e.start-t.start}));for(let e of s)if(e){r.length>0&&r.push("
");let t=e.end-e.start===1?F(Math.floor(e.start)+1):F(Math.floor(e.start)+1)+"-"+F(Math.floor(e.end));r.push({name:"Position:",value:t}),r.push({name:"Value:     ",value:F(e.value.toFixed(4))})}return s.length..."),r}return[]}getColorForFeature(e){let t=e.value<0&&this.altColor?this.altColor:this.color||ml.defaultColor;return"function"==typeof t?t(e.value):t}getState(){const e=super.getState();return this._colorScale&&(e.colorScale=this._colorScale.toJson()),e}dispose(){this.trackView=void 0}}function wl(e,t,i,r="mean"){if(i<=1||!e||0===e.length||"none"===r)return e;const s=e[0].chr,o=i,n=[],a=e=>{const i=t+e.bin*o,a=i+o;let c;switch(r){case"mean":c=e.sumData/e.count;break;case"max":c=e.max;break;case"min":c=e.min;break;default:throw Error(`Unknown window function: ${r}`)}const l=`${r} of ${e.count} values`;n.push({chr:s,start:i,end:a,value:c,description:l})};let c;for(let i of e){let e=Math.floor((i.start-t)/o);const r=Math.floor((i.end-t)/o);if(c&&e===c.bin&&(c.add(i),e++),!c||r>c.bin){if(c&&a(c),r>e){const e=t+r*o;n.push({chr:s,start:i.start,end:e,value:i.value})}c=new bl(r,i)}}c&&a(c);const l=[];let h=n[0];for(let e of n)h.value===e.value&&e.start<=h.end?h.end=e.end:(l.push(h),h=e);return l.push(h),l}class bl{constructor(e,t){this.bin=e,this.sumData=t.value,this.count=1,this.min=t.value,this.max=t.value}add(e){this.sumData+=e.value,this.max=Math.max(e.value,this.max),this.min=Math.min(e.value,this.min),this.count++}get mean(){return this.sumData/this.count}}class Fl extends gc{constructor(e,t){super(t),this.config=e||{},this.genome=t,this.sourceType=void 0===e.sourceType?"file":e.sourceType,this.maxWGCount=e.maxWGCount||1e4,this.windowFunctions=["mean","min","max","none"];const i=new Set(["bigwig","bw","bigbed","bb","biginteract","biggenepred","bignarrowpeak","tdf"]);if(this.queryable=e.indexURL||!0===e.queryable,e.reader)this.reader=e.reader,this.queryable=!1!==e.queryable;else{if("ga4gh"===e.sourceType)throw Error("Unsupported source type 'ga4gh'");"eqtl"!==e.type&&"qtl"!==e.type||"gtex-ws"!==e.sourceType?"htsget"===e.sourceType?(this.reader=new pc(e,t),this.queryable=!0,this.supportsWholeGenome=()=>!1):"ucscservice"===e.sourceType?(this.reader=new ac(e.source),this.queryable=!0):"custom"===e.sourceType?(this.reader=new nc(e.source),this.queryable=!1!==e.source.queryable):"service"===e.sourceType?(this.reader=new sc(e,t),this.queryable=!0):(this.reader=new sc(e,t),void 0!==e.queryable?this.queryable=e.queryable:(i.has(e.format)||this.reader.indexed)&&(this.queryable=!0)):(this.reader=new cc(e),this.queryable=!0)}this.searchable=!1!==e.searchable}async defaultVisibilityWindow(){if(this.reader&&"function"==typeof this.reader.defaultVisibilityWindow)return this.reader.defaultVisibilityWindow()}async trackType(){const e=await this.getHeader();return e?e.type:void 0}async getHeader(){if(!this.header)if(this.reader&&"function"==typeof this.reader.readHeader){const e=await this.reader.readHeader();e?(this.header=e,e.format&&(this.config.format=e.format)):this.header={}}else this.header={};return this.header}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s,windowFunction:o}){const n="all"===e.toLowerCase();if(t=t||0,i=i||Number.MAX_SAFE_INTEGER,(n&&!this.wgFeatures&&this.supportsWholeGenome()||this.config.disableCache||!this.featureCache||!this.featureCache.containsRange(new Mo(e,t,i)))&&await this.loadFeatures(e,t,i,s),n){if(!this.wgFeatures)if(this.supportsWholeGenome())if("wig"===this.config.type){const e=await pa(this.featureCache.getAllFeatures(),this.genome,this.chromAliasManager,1e6);this.wgFeatures=wl(e,0,r,o)}else this.wgFeatures=await pa(this.featureCache.getAllFeatures(),this.genome,this.chromAliasManager,this.maxWGCount);else this.wgFeatures=[];return this.wgFeatures}{const r=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e;return this.featureCache.queryFeatures(r,t,i)}}async findFeatures(e){return this.featureCache?this.featureCache.findFeatures(e):[]}supportsWholeGenome(){return!this.queryable}getAllFeatures(){return this.queryable||!this.featureCache?[]:this.featureCache.getAllFeatures()}async loadFeatures(e,t,i,r){await this.getHeader();const s=this.reader;let o=t,n=i,a=e;if(!this.chromAliasManager&&this.reader&&this.reader.sequenceNames&&this.reader.sequenceNames.size>0&&(this.chromAliasManager=new fc(this.reader.sequenceNames,this.genome)),this.chromAliasManager&&(a=await this.chromAliasManager.getAliasName(e)),(!r||r<=0)&&!1!==this.config.expandQuery){const t=this.genome?this.genome.getChromosome(e):void 0;o=0,n=Math.max(t?t.bpLength:Number.MAX_SAFE_INTEGER,i)}else if(r>i-t&&!1!==this.config.expandQuery){let e=Math.min(4.1*(i-t),r);this.config.minQuerySize&&ee.chr)),this.genome):null,this.featureCache=new cn(e),(this.searchable||this.config.searchableFields)&&this.addFeaturesToDB(e,this.config)}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s}){const o=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e;return"all"===o.toLowerCase()?await pa(this.featureCache.getAllFeatures(),this.genome,this.chromAliasManager,this.maxWGCount):this.featureCache.queryFeatures(o,t,i)}getAllFeatures(){return this.featureCache.getAllFeatures()}supportsWholeGenome(){return!0}addFeaturesToDB(e,t){this.featureMap||(this.featureMap=new Map);const i=t.searchableFields||["name"];for(let t of e)for(let e of i){let i;if("function"==typeof t.getAttributeValue&&(i=t.getAttributeValue(e)),i||(i=t[e]),i){i=i.replaceAll(" ","+");const e=this.featureMap.get(i.toUpperCase());if(e&&e.end-e.start>t.end-t.start)continue;this.featureMap.set(i.toUpperCase(),t)}}}search(e){if(this.featureMap)return this.featureMap.get(e.toUpperCase())}}class yl{constructor({chr:e,locus:t,accession:i,aliases:r,features:s,sequence:o}){this.chr=e,this.locus=t,this.accession=i,this.aliases=r,this.features=s,this.sequence=o,this.bpLength=o.length}toJSON(){return{gbkURL:this.url}}getSequenceRecord(e){return{chr:this.chr,bpLength:this.bpLength}}get chromosomeNames(){return[this.chr]}getFirstChromosomeName(){return this.chr}get id(){return this.accession}get name(){return this.locus}get initialLocus(){return this.chr}get description(){return this.locus}get infoURL(){return this.url}showWholeGenomeView(){return!1}getHomeChromosomeName(){return this.chr}getChromosomeName(e){return e}getChromosomeDisplayName(e){return this.chr}getChromosome(e){if(e===this.chr)return{name:this.chr,bpLength:this.bpLength}}async loadChromosome(e){return this.getChromosome(e)}async getAliasRecord(e){}getCytobands(e){return[]}getChromosomes(){return[this.getChromosome(this.chr)]}get wgChromosomeNames(){}getGenomeCoordinate(e,t){if(e===this.chr)return t}getChromosomeCoordinate(e){return{chr:this.chr,position:e}}getCumulativeOffset(e){return 0}getGenomeLength(){return this.bpLength}async getSequence(e,t,i){return e===this.chr?this.sequence.substring(t,i):void 0}getSequenceInterval(e,t,i){return e===this.chr?new Ro(this.chr,0,this.sequence.length,this.sequence):void 0}}const Al=/\s+/,Cl=new Map;async function _l(e){let t=Cl.get(e);if(!t){t=function(e){if(!e)return null;const t=Wa(e);let i=t.nextLine();const r=i.split(/\s+/);if("LOCUS"!==r[0].toUpperCase())throw Error("Expected `LOCUS` line. Found: "+i);const s=r[1].trim();let o,n;do{if(i=t.nextLine(),i.startsWith("ACCESSION")){const e=i.split(Al);if(e.length<2)throw Error("Genbank file missing ACCESSION number.");o=e[1].trim()}else if(i.startsWith("ALIASES")){const e=i.split(Al);e.length>1&&(n=e[1].split(","))}}while(i&&!i.startsWith("FEATURES"));const a=o||s,c=function(e,t){const i=[];let r,s,o,n=0;for(;;)if(s=t.nextLine(),""!==s){if(!s||s.startsWith("ORIGIN"))break;if(s.length<6)n<10&&console("Unexpected line in genbank file (skipping): "+s),n++;else if(" "!==s.charAt(5)){let t=s.substring(5,21).trim();o={chr:e,type:t,attributes:{},getAttributeValue:function(e){return this.attributes[e]}},r=s.substring(21),"source"!==t.toLowerCase()&&i.push(o)}else{let t=s.substring(21).trim();if(t.length>0)if(47===t.charCodeAt(0)){if(47===r.charCodeAt(0)){let e=r.split("=",2);if(e.length>1){let t=e[0].length>1?e[0].substring(1):"",i=kl(e[1]);o.attributes[t]=i}}else{const t=r.includes("complement")?"-":"+";o.strand=t;let i=r.replace("join","").replace("order","").replace("complement","").replace("(","").replace(")","");if(i.includes("..")){i=i.replace("<","").replace(">","");const r=xl(i,e,t),s=r[0];o.start=s.start;const n=r[r.length-1];o.end=n.end,r.length>1&&(o.exons=r)}else o.start=parseInt(i)-1,o.end=o.start+1}r=t}else r+=t}}return i}(a,t),l=function(e){let t,i="";for(;(t=e.nextLine())&&!t.startsWith("//");){t=t.trim();const e=t.split(/\s+/);for(let t=1;t1&&(n=parseInt(r[1])),s.push({chr:t,start:o,end:n,strand:i})}return s.sort((function(e,t){return e.start-t.start})),s}function kl(e){return e.startsWith('"')&&e.endsWith('"')&&(e=e.substring(1,e.length-2)),e}class Il extends gc{constructor(e,t){super(t),this.config=e,this.searchable=!0}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s}){if(!this.featureSource){const e=await _l(this.config.url);this.featureSource=new vl({genome:this.config.genome,features:e.features,searchableFields:["gene","db_xref","locus_tag","transcript_id"]})}return this.featureSource.getFeatures({chr:e,start:t,end:i})}supportsWholeGenome(){return!1}search(e){return this.featureSource.search(e)}}const Sl=new Set(["bigwig","bw","bigbed","bb","biginteract","biggenepred","bignarrowpeak"]);function El(e,t){const i=e.format?e.format.toLowerCase():void 0;return e.features?new vl(e,t):Sl.has(i)?new Pc(e,t):"tdf"===i?new vc(e,t):"gbk"===i?new Il(e,t):new Fl(e,t)}function Nl(e){return(3-e.readingFrame)%3}function Ml(e){return e.cdStart||e.start}function Rl(e){return e.cdEnd||e.end}const Bl=.25;function Dl(e,t,i){let r=(e.start-t)/i,s=(e.end-t)/i,o=s-r;return o<3&&(o=3,r-=1.5),{px:r,px1:s,pw:o}}function Ll(e,t,i,r,s,o){try{s.save(),s.fillStyle=this.color,s.strokeStyle=this.color;const r=this.getColorForFeature(e);let n,a;s.fillStyle=r,s.strokeStyle=r,"SQUISHED"===this.displayMode&&void 0!==e.row?(n=this.featureHeight/2,a=this.margin+this.squishedRowHeight*e.row):"EXPANDED"===this.displayMode&&void 0!==e.row?(n=this.featureHeight,a=this.margin+this.expandedRowHeight*e.row):(n=this.featureHeight,a=this.margin);const c=o.pixelWidth,l=a+n/2,h=n/2,d=l-h/2,u=e.exons?e.exons.length:0,f=Dl(e,t,i),p=this.arrowSpacing,g="+"===e.strand?1:"-"===e.strand?-1:0;if(0===u){const e=Math.max(0,f.px),t=Math.min(c,f.px1),i=t-e;if(s.fillRect(e,a,i,n),0!==g){s.fillStyle="white",s.strokeStyle="white";for(let i=e+p/2;ic)break;if(f.utr)s.fillRect(w,d,F,h);else{if(f.cdStart&&(m=Math.round((f.cdStart-t)/i),s.fillRect(w,d,m-w,h),F-=m-w,w=m),f.cdEnd&&(m=Math.round((f.cdEnd-t)/i),s.fillRect(m,d,b-m,h),F-=b-m,b=m),F=Math.max(F,1),s.fillRect(w,a,F,n),void 0!==f.readingFrame&&o.bpPerPixel0&&void 0!==e.exons[u-1].readingFrame?e.exons[u-1]:void 0,r=up+5&&0!==g&&o.bpPerPixel>Bl){s.fillStyle="white",s.strokeStyle="white";for(let e=w+p/2;e{const f=Math.round((i-o)/n),p=Math.round((r-o)/n)-f;let g;if(void 0===s){if(l.hasSequence(i,r)){const e=l.getSequence(i,r);if(e&&3===e.length){const i="+"===t?e:So(e.split("").reverse().join(""));g=Jl[i]}}}else g=s;e.fillStyle="M"===s||"M"===g&&0===u?"#83f902":"STOP"===g?"#ff2101":h[d],e.fillRect(f,a,p,c),g&&(e.save(),((t,i,r,s,o)=>{"STOP"===o&&(o="*");const n=e.measureText(o).width;Co.fillText(e,o,r+(i-n)/2,s-4,{fillStyle:"#ffffff"})})(0,p,f,a+c,g),e.restore());const m=r-i;return m>0&&m<3?{start:i,end:r}:void 0},u=Nl(r);let f,p,g,m,w,b=Ml(r),F=Rl(r),v=1;if("+"===t){for(u>0&&(b+=u),v=1,w=0,f=b;f0||g){const e=u>0?Pl.call(this,t,u,b-u,b,g,i,r,s,l):Pl.call(this,t,void 0,void 0,void 0,g,i,r,s,l);if(e){const{left:i,rite:r}=e;i&&d(t,b-u,b,i.aminoAcidLetter,0,void 0),r&&d(t,g.start,g.end,r.aminoAcidLetter,m,void 0)}}}else{for(u>0&&(F-=u),v=1,w=0,w=0,p=F;p>b;w++,p-=3)m=v%2,f=Math.max(b,p-3),g=d(t,f,p,void 0,v%2,w),++v;if(u>0||g){const e=u>0?Pl.call(this,t,u,F,F+u,g,i,r,s,l):Pl.call(this,t,void 0,void 0,void 0,g,i,r,s,l);if(e){const{left:i,rite:r}=e;r&&d(t,F,F+u,r.aminoAcidLetter,0,void 0),i&&d(t,g.start,g.end,i.aminoAcidLetter,m,void 0)}}}e.restore()}function zl(e,t,i,r,s,o,n){try{e.save();let o=t[this.config.labelField?this.config.labelField:"name"];if(void 0===o&&t.gene&&(o=t.gene.name),void 0===o&&(o=t.id||t.ID),!o||"."===o)return;let a=n.pixelXOffset||0;const c=Math.max(i,-a);let l,h=(c+Math.min(r,-a+n.viewportWidth))/2;"COLLAPSED"===this.displayMode&&"SLANT"===this.labelDisplayMode&&(l={rotate:{angle:45}});const d=function(e,t){return t?e+20:e+25}(s,l);let u=this.getColorForFeature(t),f=this.browser.qtlSelections.hasPhenotype(t.name);const p={textAlign:"SLANT"===this.labelDisplayMode?void 0:"center",fillStyle:u,strokeStyle:u},g=e.measureText(o),m=h-g.width/2,w=h+g.width/2,b=n.rowLastLabelX[t.row]||-Number.MAX_SAFE_INTEGER;(n.labelAllFeatures||m>b||f)&&(n.rowLastLabelX[t.row]=w,e.clearRect(h-g.width/2-1,d-g.actualBoundingBoxAscent-1,g.width+2,g.actualBoundingBoxAscent+g.actualBoundingBoxDescent+2),Co.fillText(e,o,h,d,p,l))}finally{e.restore()}}function Pl(e,t,i,r,s,o,n,a,c){let l,h,d="",u="",f="";const p={left:void 0,rite:void 0};if("+"===e){if(t){if(u=c.getSequence(i,r),!u)return;if([l,h]=[Rl(o)-(3-t),Rl(o)],d=c.getSequence(l,h),!d)return;f=d+u,p.left={triplet:f,aminoAcidLetter:Jl[f]}}if(s){if(d=c.getSequence(s.start,s.end),!d)return;const e=Nl(a),t=Ml(a);if(u=c.getSequence(t,t+e),!u)return;f=d+u,p.rite={triplet:f,aminoAcidLetter:Jl[f]}}}else{if(t){if(d=c.getSequence(i,r),void 0===d)return;if([l,h]=[Ml(a),Ml(a)+(3-t)],u=c.getSequence(l,h),void 0===u)return;f=d+u,f=So(f.split("").reverse().join("")),p.rite={triplet:f,aminoAcidLetter:Jl[f]}}if(s){if(u=c.getSequence(s.start,s.end),void 0===u)return;const e=Nl(o),t=Rl(o);if(d=c.getSequence(t-e,t),void 0===d)return;f=d+u,f=So(f.split("").reverse().join("")),p.left={triplet:f,aminoAcidLetter:Jl[f]}}}return p}const Hl=new Set(["nonsense","missense","stop-loss","frameshift","cds-indel"]),Ol=new Set(["coding-synon"]),Vl=new Set(["splice-3","splice-5"]),ql=new Set(["untranslated-5","untranslated-3"]);function Ul(e,t,i,r,s){var o,n,a,c,l,h,d=Dl(e,t,i),u=this.margin,f=this.snpColors.length;switch(o="squished"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight,this.colorBy){case"function":c=e.func,h=c.split(","),l=h.map((function(e){return Hl.has(e)||Vl.has(e)?f-1:Ol.has(e)?f-2:ql.has(e)?f-3:0})),n=l.reduce((function(e,t){return Math.max(e,t)}));break;case"class":n="deletion"===(a=e.class)?f-1:"mnp"===a?f-2:"microsatellite"===a||"named"===a?f-3:0}s.fillStyle=this.snpColors[n],s.fillRect(d.px,u,d.pw,o)}function Ql(e,t,i,r,s){const o="EXPANDED"===this.displayMode?this.expandedRowHeight:this.squishedRowHeight;let n=this.margin;"COLLAPSED"!==this.displayMode&&void 0!==e.row&&(n+=e.row*o);const a=n+.5*o,c=a-.5*o,l=a+.5*o,h=Math.round((e.junction_left-t)/i),d=Math.round((e.junction_right-t)/i);s.beginPath(),s.moveTo(h,a),s.bezierCurveTo(h,c,d,c,d,a),s.lineWidth=1+Math.log(e.num_junction_reads)/Math.log(2),s.strokeStyle="blue",s.stroke();const u=e.spanning_frag_coords;for(let e=0;et&&(t=i.row);return this.margin+(t+1)*("SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight)}}draw(e){const{features:t,context:i,bpPerPixel:r,bpStart:s,bpEnd:o,pixelWidth:n,pixelHeight:a,referenceFrame:c}=e;if(r0?s:0,o>t?t:o)}if(this.isMergedTrack||Co.fillRect(i,0,e.pixelTop,n,a,{fillStyle:"rgb(255, 255, 255)"}),t){const c=[];e.rowLastX=[],e.rowLastLabelX=[];for(let i of t)if((!this._filter||this._filter(i))&&i.start>s&&i.end!isNaN(e)))));let h=[];const d=[];for(let n of t){if(this._filter&&!this._filter(n))continue;if(n.endo)break;"COLLAPSED"===this.displayMode&&this.browser.qtlSelections.hasPhenotype(n.name)&&d.push(n);const t="COLLAPSED"===this.displayMode?0:n.row;e.drawLabel=e.labelAllFeatures||l>10;const c=Math.ceil((n.end-s)/r),u=h[t];if(!u||c>u){this.render.call(this,n,s,r,a,i,e);const o=Math.floor((n.start-s)/r);u&&o-u<=0&&(i.globalAlpha=.5,Co.strokeLine(i,o,0,o,a,{strokeStyle:"rgb(255, 255, 255)"}),i.globalAlpha=1),h[t]=c}}for(let t of d)e.drawLabel=!0,this.render.call(this,t,s,r,a,i,e)}else console.log("No feature list")}clickedFeatures(e){const t=e.y-this.margin,i=super.clickedFeatures(e);let r;switch(this.displayMode){case"SQUISHED":r=Math.floor(t/this.squishedRowHeight);break;case"EXPANDED":r=Math.floor(t/this.expandedRowHeight);break;default:r=void 0}return i.filter((function(e){return void 0===r||void 0===e.row||r===e.row}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,r=[];for(let e of t){const t=e._f||e,s="function"==typeof t.popupData?t.popupData(i):this.extractPopupData(t);if(s){r.length>0&&r.push("

");const o=this.infoURL||this.config.infoURL;for(let t of s)if(r.push(t),o&&t.name&&"name"===t.name.toLowerCase()&&t.value&&b(t.value)&&!t.value.startsWith("<")){const i=o.replace("$$",e.name);t.value=`${t.value}`}const n="gff"===this.config.format||"gff3"===this.config.format||"gtf"===this.config.format;if(t.exons&&t.exons.length>1)for(let e=0;e=s.start&&i<=s.end){const i=n?s.number:"-"===t.strand?t.exons.length-e:e+1;i&&(r.push("
"),r.push({name:"Exon Number",value:i}));break}}}}return r}menuItemList(){const e=[];if(this.render===Ul){e.push("
");for(const i of["function","class"]){function r(){this.colorBy=i,this.trackView.repaintViews()}e.push({element:ua(`Color by ${i}`,i===this.colorBy),click:r})}}e.push("
");const t={COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"};for(const s of["COLLAPSED","SQUISHED","EXPANDED"]){function o(){this.displayMode=s,this.config.displayMode=s,this.trackView.checkContentHeight(),this.trackView.repaintViews()}e.push({element:ua(t[s],s===this.displayMode),click:o})}return e}contextMenuItemList(e){const t=this.clickedFeatures(e);if(void 0===t||0===t.length)return;t.length>1&&t.sort(((e,t)=>t.end-t.start-(e.end-e.start)));const i=t[0];if(i.end-i.start<=1e6){const e=[{label:"View feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=Eo(e)):e="Unknown sequence",this.browser.alert.present(e)}}];return ds()&&void 0!==navigator.clipboard&&e.push({label:"Copy feature sequence",click:async()=>{let e=await this.browser.genome.getSequence(i.chr,i.start,i.end);e?"-"===i.strand&&(e=Eo(e)):e="Unknown sequence";try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),e.push("
"),e}}description(){if(Ul===this.render){let e=""+this.name+"
";return e+="Color By Function:
",e+='Red: Coding-Non-Synonymous, Splice Site
',e+='Green: Coding-Synonymous
',e+='Blue: Untranslated
',e+='Black: Intron, Locus, Unknown

',e+="Color By Class:
",e+='Red: Deletion
',e+='Green: MNP
',e+='Blue: Microsatellite, Named
',e+='Black: Indel, Insertion, SNP',e+="",e}return super.description()}getColorForFeature(e){const t=e._f||e;let i;if(e.name&&this.browser.qtlSelections.hasPhenotype(e.name))i=this.browser.qtlSelections.colorForGene(e.name);else if(this.altColor&&"-"===t.strand)i="function"==typeof this.altColor?this.altColor(t):this.altColor;else if(this.color)i="function"==typeof this.color?this.color(t):this.color;else if(this.colorBy){const e=t.getAttributeValue?t.getAttributeValue(this.colorBy):t[this.colorBy];i=this.colorTable.getColor(e)}else t.color&&(i=t.color);if(i||(i=Gl.defaultColor),t.alpha&&1!==t.alpha)i=ur.addAlpha(i,t.alpha);else if(this.useScore&&t.score&&!Number.isNaN(t.score)){const e=function(e,t,i){const r=(t-e)/9,s=Math.floor((i-e)/r);return Math.min(1,.2+.8*s/9)}(this.config.min?this.config.min:this.viewLimitMin?this.viewLimitMin:0,this.config.max?this.config.max:this.viewLimitMax?this.viewLimitMax:1e3,t.score);t.alpha=e,i=ur.addAlpha(i,e)}return i}dispose(){this.trackView=void 0}}class jl{constructor(e){if(this.config=e,this.browser=e.browser,this.columnFormat=e.columnFormat,this.tableRowSelectionList=[],this.tableDOM=t({class:"igv-roi-table"}),e.width){let[t]=e.width.split("px");t=parseInt(t,10),this.tableDOM.style.width=`${Math.min(t,1600)}px`}e.parent.appendChild(this.tableDOM),this.headerDOM=e,this.tableColumnTitles=this.tableDOM,this.tableRowContainer=this.tableDOM,this.footerDOM=e.gotoButtonHandler}set headerDOM({browser:e,parent:i,headerTitle:r,dismissHandler:s}){const o=t();this.tableDOM.appendChild(o);const n=t();o.appendChild(n),n.innerHTML=r;const a=t();o.appendChild(a),a.appendChild(l("times")),this.boundDismissHandler=function(e){e.stopPropagation(),s()}.bind(this),a.addEventListener("click",this.boundDismissHandler);const{y:c}=e.root.getBoundingClientRect(),{y:h}=i.getBoundingClientRect(),d=-(h-c);p(this.tableDOM,o,{minX:0,minY:d}),this.tableDOM.style.display="none",this._headerDOM=o}set tableColumnTitles(e){const i=t({class:"igv-roi-table-column-titles"});e.appendChild(i);for(const{label:e,width:r}of this.columnFormat){const s=t();i.appendChild(s),s.style.width=r,s.innerText=e}this._tableColumnTitlesDOM=i}get tableColumnTitles(){return this._tableColumnTitlesDOM}set tableRowContainer(e){const i=t({class:"igv-roi-table-row-container"});e.appendChild(i),this._tableRowContainerDOM=i}get tableRowContainer(){return this._tableRowContainerDOM}set footerDOM(e){const i=t();this.tableDOM.appendChild(i);const r=t({class:"igv-roi-table-button"});i.appendChild(r),r.id="igv-roi-table-view-button",r.textContent="Go To",r.style.pointerEvents="none",this._footerDOM=i,this.gotoButton=r,this.boundGotoButtonHandler=e.bind(this),this.gotoButton.addEventListener("click",this.boundGotoButtonHandler)}tableRowDOMHelper(e){e.addEventListener("mousedown",(t=>{t.stopPropagation(),e.classList.toggle("igv-roi-table-row-selected"),e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover"),this.setTableRowSelectionState(e.classList.contains("igv-roi-table-row-selected"))})),e.addEventListener("mouseover",(t=>{e.classList.contains("igv-roi-table-row-selected")?e.classList.remove("igv-roi-table-row-hover"):e.classList.add("igv-roi-table-row-hover")})),e.addEventListener("mouseout",(t=>{e.classList.remove("igv-roi-table-row-hover")}))}clearTable(){const e=this.tableRowContainer.querySelectorAll(".igv-roi-table-row");for(let t of e)t.remove()}setTableRowSelectionState(e){e?this.tableRowSelectionList.push(1):this.tableRowSelectionList.pop(),this.gotoButton.style.pointerEvents=this.tableRowSelectionList.length>0?"auto":"none"}present(){this.tableDOM.style.left="0px";const{y:e}=this.browser.root.getBoundingClientRect(),{y:t}=this.config.parent.getBoundingClientRect();this.tableDOM.style.top=e-t+"px",this.tableDOM.style.display="flex"}dismiss(){this.tableDOM.style.display="none"}isVisible(){return"none"!==this.tableDOM.style.display}dispose(){this.tableDOM.innerHTML="",this.tableDOM.remove();for(const e of Object.keys(this))this[e]=void 0;document.removeEventListener("click",this.boundDismissHandler)}}class Wl extends jl{constructor(e){super(Object.assign({width:"1024px"},e)),this.descriptionDOM=e}set descriptionDOM(e){if(e.description){let i;i=t({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(i,this.tableColumnTitles),i.style.height="auto",i.innerHTML="BLAT result for query sequence:",i=t({class:"igv-roi-table-description"}),this.tableDOM.insertBefore(i,this.tableColumnTitles),i.style.height="auto",i.style.maxHeight="128px",i.innerHTML=e.description,i=t({class:"igv-roi-table-goto-explainer"}),this.tableDOM.insertBefore(i,this.tableColumnTitles),i.innerHTML="Select one or more rows and click Go To to view the regions"}}tableRowDOM(e){const i=t({class:"igv-roi-table-row"}),r=e.map((e=>isFinite(e)?F(e):e));for(let e=0;ee.remove())),e.length>0)for(let t of e){const e=this.tableRowDOM(t);this.tableRowContainer.appendChild(e)}}static getColumnFormatConfiguration(){return[{label:"chr",width:"7%"},{label:"start",width:"12%"},{label:"end",width:"12%"},{label:"strand",width:"5%"},{label:"score",width:"5%"},{label:"match",width:"5%"},{label:"mis-match",width:"7%"},{label:"rep. match",width:"7%"},{label:"N's",width:"3%"},{label:"Q gap count",width:"9%"},{label:"Q gap bases",width:"9%"},{label:"T gap count",width:"9%"},{label:"T gap bases",width:"9%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(const e of t){const t=[];e.querySelectorAll("div").forEach((e=>t.push(e.innerText)));const[r,s,o]=t;i.push(`${r}:${s}-${o}`)}for(const e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),this.browser.search(i.join(" "))}}async function $l({url:e,userSeq:t,db:i}){if(e=e||"https://igv.org/services/blatUCSC.php",!i)throw Error("Blat database is not defined");const r=await async function(e="",t,i){const r=new URLSearchParams;r.append("userSeq",t),r.append("db",i);const s=await fetch(e,{method:"post",body:r});return s.json()}(e,t,i);r.fields;return r.blat.map(qn)}const Kl=25e3;class Yl extends Gl{constructor(e,t){super(e,t),this.name||(this.name="Blat Results"),this.sequence=e.sequence,this.table=void 0,e.features&&(this._features=e.features,this.featureSource=new vl({features:e.features},this.browser.genome),delete e.features)}async postInit(){if(!this.featureSource){const e=this.browser.genome.ucscID,t=this.browser.config.blatServerURL,i=await $l({url:t,userSeq:this.sequence,db:e});this._features=i,this.featureSource=new vl({features:i},this.browser.genome)}this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor}openTableView(){if(void 0===this.table){const e=this._features.map((e=>[this.browser.genome.getChromosomeDisplayName(e.chr),e.start+1,e.end,e.strand,e.score,e.matches,e.misMatches,e.repMatches,e.nCount,e.qNumInsert,e.qBaseInsert,e.tNumInsert,e.tBaseInsert])),t={browser:this.browser,parent:this.browser.columnContainer,headerTitle:this.config.title,description:this.sequence,dismissHandler:()=>{this.table.dismiss(),this.table.dispose(),this.table=void 0},columnFormat:Wl.getColumnFormatConfiguration(),gotoButtonHandler:Wl.gotoButtonHandler};this.table=new Wl(t),this.table.renderTable(e)}this.table.present()}menuItemList(){const e=super.menuItemList();return e.push("
"),e.push({label:"Open table view",click:function(){this.openTableView()}}),e}dispose(){super.dispose(),this.table&&this.table.popover.parentElement.removeChild(this.table.popover)}}async function Zl({sequence:e,browser:t,name:i,title:r}){if(e.length>Kl)t.alert.present(`Sequence size exceeds maximum allowed length (${e.length} > 25000)`);else try{const s=t.genome.ucscID,o=t.config.blatServerURL||"https://igv.org/services/blatUCSC.php",n={type:"blat",name:i||"blat results",title:r||"blat results",sequence:e,altColor:"rgb(176, 176, 236)",color:"rgb(236, 176, 176)",searchable:!1,features:await $l({url:o,userSeq:e,db:s})};(await t.loadTrackList([n]))[0].openTableView()}catch(e){t.alert.present(`Error performing blat search: ${e}`)}}const Xl=Number.MIN_SAFE_INTEGER,Jl={TTT:"F",TTC:"F",TTA:"L",TTG:"L",CTT:"L",CTC:"L",CTA:"L",CTG:"L",ATT:"I",ATC:"I",ATA:"I",ATG:"M",GTT:"V",GTC:"V",GTA:"V",GTG:"V",TCT:"S",TCC:"S",TCA:"S",TCG:"S",CCT:"P",CCC:"P",CCA:"P",CCG:"P",ACT:"T",ACC:"T",ACA:"T",ACG:"T",GCT:"A",GCC:"A",GCA:"A",GCG:"A",TAT:"Y",TAC:"Y",TAA:"STOP",TAG:"STOP",CAT:"H",CAC:"H",CAA:"Q",CAG:"Q",AAT:"N",AAC:"N",AAA:"K",AAG:"K",GAT:"D",GAC:"D",GAA:"E",GAG:"E",TGT:"C",TGC:"C",TGA:"STOP",TGG:"W",CGT:"R",CGC:"R",CGA:"R",CGG:"R",AGT:"S",AGC:"S",AGA:"R",AGG:"R",GGT:"G",GGC:"G",GGA:"G",GGG:"G"},eh={},th=["A","G","C","T","Y","R","W","S","K","M","D","V","H","B","N","X"],ih=["T","C","G","A","R","Y","W","S","M","K","H","B","D","V","N","X"];for(let ky=0;ky{this.reversed=!this.reversed,this.trackView.repaintViews()}},{name:this.frameTranslate?"Close Translation":"Three-frame Translate",click:()=>{if(this.frameTranslate=!this.frameTranslate,this.frameTranslate){for(let e of this.trackView.viewports)e.setContentHeight(rh);this.trackView.setTrackHeight(rh)}else{for(let e of this.trackView.viewports)e.setContentHeight(25);this.trackView.setTrackHeight(25)}this.trackView.repaintViews()}}]}contextMenuItemList(e){const t=e.viewport;if(t.referenceFrame.bpPerPixel<=1){const e=t.getWidth()*t.referenceFrame.bpPerPixel,i=t.referenceFrame.chr,r=Math.floor(t.referenceFrame.start),s=Math.ceil(r+e),o=[{label:this.reversed?"View visible sequence (reversed)...":"View visible sequence...",click:async()=>{let e=await this.browser.genome.getSequence(i,r,s);e?this.reversed&&(e=Eo(e)):e="Unknown sequence",this.browser.alert.present(e)}}];return ds()&&o.push({label:"Copy visible sequence",click:async()=>{let e=await this.browser.genome.getSequence(i,r,s);e?this.reversed&&(e=Eo(e)):e="Unknown sequence";try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),o.push({label:"BLAT visible sequence",click:async()=>{let e=await this.browser.genome.getSequence(i,r,s);if(e){this.reversed&&(e=Eo(e));const t=`blat: ${i}:${r+1}-${s}`,o=`blat: ${i}:${r+1}-${s}`;Zl({sequence:e,browser:this.browser,name:t,title:o})}}}),o.push("
"),o}}translateSequence(e){const t=[[],[],[]];for(let i of[0,1,2]){let r=i;for(;e.length-r>=3;){let s=e.slice(r,r+3);this.reversed&&(s=s.split("").reverse().join(""));const o=Jl[s.toUpperCase()]||"";t[i].push({codons:s,aminoA:o}),r+=3}}return t}async getSequenceSource(){return this.config.fastaURL?(this.fasta||(this.fasta=new oh(this.config,this.browser.genome),await this.fasta.init()),this.fasta):this.browser.genome}async getFeatures(e,t,i,r){if(t=Math.floor(t),i=Math.floor(i),r&&r>10)return null;{const r=await this.getSequenceSource();return{bpStart:t,sequence:await r.getSequence(e,t,i)}}}draw(e){const t=e.context;if(e.features){let i=e.features.sequence;if(!i)return;this.reversed&&(i=i.split("").map((function(e){return eh[e]})).join(""));const r=e.features.bpStart,s=1+e.bpStart+e.pixelWidth*e.bpPerPixel;for(let o=Math.floor(e.bpStart);o<=s;o++){const s=Math.floor(o-r);if(s>=0&&s.1)Co.fillRect(t,r,5,n,10,{fillStyle:c});else{const i=r+.5*(n-t.measureText(a).width);"y"===e.axis?(t.save(),Co.labelTransformWithContext(t,i),Co.strokeText(t,a,i,15,{strokeStyle:c}),t.restore()):Co.strokeText(t,a,i,15,{strokeStyle:c})}}}if(this.frameTranslate){let s=25;const o=this.translateSequence(i);for(let i=0;ie.pixelWidth)break;let f=c.aminoA;c.aminoA.indexOf("STOP")>-1?(a="rgb(255, 0, 0)",f="STOP"):"M"===c.aminoA&&(a="rgb(0, 153, 0)",f="START"),Co.fillRect(t,h,s,d-h,25,{fillStyle:a}),e.bpPerPixel<=.1&&Co.strokeText(t,f,u-t.measureText(f).width/2,s+15)}s+=30}}}}get supportsWholeGenome(){return!1}computePixelHeight(e){return this.height=this.frameTranslate?rh:25,this.height}fillColor(e){return this.color?this.color:"dna"===this.sequenceType?this.browser.nucleotideColors[e]||"gray":"rgb(0, 0, 150)"}getState(){const e={type:"sequence"};return this.order!==Xl&&(e.order=this.order),this.reversed&&(e.revealed=!0),e}}class oh{constructor(e,t){this.config=e,this.genome=t}async init(){this.fasta=await Zo(this.config),this.chrNameMap=new Map;for(let e of this.fasta.chromosomeNames)this.chrNameMap.set(this.genome.getChromosomeName(e),e)}async getSequence(e,t,i){const r=this.chrNameMap.has(e)?this.chrNameMap.get(e):e;return this.fasta.getSequence(r,t,i)}}class nh{constructor(e,t,i,r){this.guid=n(),this.trackView=e,this.referenceFrame=i,this.browser=e.browser,this.viewportElement=document.createElement("div"),this.viewportElement.className="igv-viewport",t.appendChild(this.viewportElement),e.track.height&&this.setHeight(e.track.height);const s=e.track.type||"untyped";this.viewportElement.setAttribute("data-track-type",s),e.track instanceof sh&&(this.alert=new Ao(this.viewportElement)),this.contentTop=0,this.contentHeight=this.viewportElement.clientHeight,this.setWidth(r),this.initializationHelper()}initializationHelper(){}showMessage(e){this.messageDiv||(this.messageDiv=document.createElement("div"),this.messageDiv.className="igv-viewport-message",this.viewportElement.appendChild(this.messageDiv)),this.messageDiv.textContent=e,this.messageDiv.style.display="inline-block"}hideMessage(){this.messageDiv&&(this.messageDiv.style.display="none")}setTrackLabel(e){}startSpinner(){}stopSpinner(){}checkZoomIn(){return!0}shift(){}setTop(e){this.contentTop=e}async loadFeatures(){}clearCache(){}repaint(){}draw(e,t,i){console.log("Viewport - draw(drawConfiguration, features, roiFeatures)")}checkContentHeight(e){const t=this.trackView.track;if(e=e||this.cachedFeatures,"FILL"===t.displayMode)this.setContentHeight(this.viewportElement.clientHeight);else if("function"==typeof t.computePixelHeight&&e&&e.length>0){const i=t.computePixelHeight(e,this.referenceFrame.bpPerPixel);i!==this.contentHeight&&this.setContentHeight(i)}}getContentHeight(){return this.contentHeight}setContentHeight(e){this.contentHeight=e}isLoading(){return!1}saveSVG(){}isVisible(){return this.viewportElement.clientWidth>0}setWidth(e){this.viewportElement.style.width=`${e}px`}getWidth(){return this.viewportElement.clientWidth}setHeight(e){this.viewportElement.style.height=`${e}px`}getContentTop(){return this.contentTop}containsPosition(e,t){console.log("Viewport - containsPosition(chr, position)")}addMouseHandlers(){}dispose(){this.viewportElement.remove();for(const e in this)this.hasOwnProperty(e)&&(this[e]=void 0)}} /*!! * Canvas 2 Svg v1.0.19 * A low level canvas to SVG converter. Uses a mock canvas context to build an SVG document. * * Licensed under the MIT license: * http://www.opensource.org/licenses/mit-license.php * * Author: * Kerry Liu * * Copyright (c) 2014 Gliffy Inc. - */function ah(e,t){var i,r=Object.keys(t);for(i=0;i0){"path"===this.__currentElement.nodeName&&(this.__currentElementsToStyle||(this.__currentElementsToStyle={element:t,children:[]}),this.__currentElementsToStyle.children.push(this.__currentElement),this.__applyCurrentDefaultPath());var i=this.__createElement("g");t.appendChild(i),this.__currentElement=i}var r=this.__currentElement.getAttribute("transform");r?r+=" ":r="",r+=e,this.__currentElement.setAttribute("transform",r)}addTrackGroupWithTranslationAndClipRect(e,t,i,r,s,o){const n=e+"_clip_rect";let a=this.__createElement("clipPath",{id:n});this.__defs.appendChild(a),a.appendChild(this.__createElement("rect",{x:"0",y:o.toString(),width:r.toString(),height:s.toString()}));let c=this.__createElement("g");this.__rootGroup.appendChild(c),c.setAttribute("transform",ah("translate({x},{y})",{x:t,y:i})),c.setAttribute("id",e+"_group"),c.setAttribute("clip-path",ah("url(#{id})",{id:n})),this.__currentElement=c}scale(e,t){void 0===t&&(t=e),this.__addTransform(ah("scale({x},{y})",{x:e,y:t}))}rotate(e){var t=180*e/Math.PI;this.__addTransform(ah("rotate({angle},{cx},{cy})",{angle:t,cx:0,cy:0}))}translate(e,t){this.__addTransform(ah("translate({x},{y})",{x:e,y:t}))}transform(e,t,i,r,s,o){this.__addTransform(ah("matrix({a},{b},{c},{d},{e},{f})",{a:e,b:t,c:i,d:r,e:s,f:o}))}beginPath(){var e;this.__currentDefaultPath="",this.__currentPosition={},e=this.__createElement("path",{},!0),this.__closestGroupOrSvg().appendChild(e),this.__currentElement=e}__applyCurrentDefaultPath(){var e=this.__currentElement;"path"===e.nodeName?e.setAttribute("d",this.__currentDefaultPath):console.error("Attempted to apply path command to node",e.nodeName)}__addPathCommand(e){this.__currentDefaultPath+=" ",this.__currentDefaultPath+=e}moveTo(e,t){"path"!==this.__currentElement.nodeName&&this.beginPath(),this.__currentPosition={x:e,y:t},this.__addPathCommand(ah("M {x} {y}",{x:e,y:t}))}closePath(){this.__currentDefaultPath&&this.__addPathCommand("Z")}lineTo(e,t){this.__currentPosition={x:e,y:t},this.__currentDefaultPath&&this.__currentDefaultPath.indexOf("M")>-1?this.__addPathCommand(ah("L {x} {y}",{x:e,y:t})):this.__addPathCommand(ah("M {x} {y}",{x:e,y:t}))}bezierCurveTo(e,t,i,r,s,o){this.__currentPosition={x:s,y:o},this.__addPathCommand(ah("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",{cp1x:e,cp1y:t,cp2x:i,cp2y:r,x:s,y:o}))}quadraticCurveTo(e,t,i,r){this.__currentPosition={x:i,y:r},this.__addPathCommand(ah("Q {cpx} {cpy} {x} {y}",{cpx:e,cpy:t,x:i,y:r}))}arcTo(e,t,i,r,s){var o=this.__currentPosition&&this.__currentPosition.x,n=this.__currentPosition&&this.__currentPosition.y;if(void 0!==o&&void 0!==n){if(s<0)throw new Error("IndexSizeError: The radius provided ("+s+") is negative.");if(o===e&&n===t||e===i&&t===r||0===s)this.lineTo(e,t);else{var a=hh([o-e,n-t]),c=hh([i-e,r-t]);if(a[0]*c[1]!==a[1]*c[0]){var l=a[0]*c[0]+a[1]*c[1],h=Math.acos(Math.abs(l)),d=hh([a[0]+c[0],a[1]+c[1]]),u=s/Math.sin(h/2),f=e+u*d[0],p=t+u*d[1],g=[-a[1],a[0]],m=[c[1],-c[0]],w=function(e){var t=e[0];return e[1]>=0?Math.acos(t):-Math.acos(t)},b=w(g),F=w(m);this.lineTo(f+g[0]*s,p+g[1]*s),this.arc(f,p,s,b,F)}else this.lineTo(e,t)}}}stroke(){"path"===this.__currentElement.nodeName&&this.__currentElement.setAttribute("paint-order","fill stroke markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("stroke")}fill(){"path"===this.__currentElement.nodeName&&this.__currentElement.setAttribute("paint-order","stroke fill markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("fill")}rect(e,t,i,r){"path"!==this.__currentElement.nodeName&&this.beginPath(),this.moveTo(e,t),this.lineTo(e+i,t),this.lineTo(e+i,t+r),this.lineTo(e,t+r),this.lineTo(e,t),this.closePath()}fillRect(e,t,i,r){r<0&&(t+=r,r=-r),i<0&&(e+=i,i=-i);var s,o,n,a={x:e,y:t,width:i,height:r};(!this.viewbox||(s=this.viewbox,o=a,s.xo.x&&s.yo.y))&&(n=this.__createElement("rect",a,!0),this.__closestGroupOrSvg().appendChild(n),this.__currentElement=n,this.__applyStyleToCurrentElement("fill"))}strokeRect(e,t,i,r){var s;s=this.__createElement("rect",{x:e,y:t,width:i,height:r},!0),this.__closestGroupOrSvg().appendChild(s),this.__currentElement=s,this.__applyStyleToCurrentElement("stroke")}strokeEllipse(e,t,i,r,s,o,n,a){this.__ellipse(e,t,i,r,s,o,n,a,"stroke")}fillEllipse(e,t,i,r,s,o,n,a){this.__ellipse(e,t,i,r,s,o,n,a,"fill")}__ellipse(e,t,i,r,s,o,n,a,c){const l={cx:e,cy:t,rx:i,ry:r},h=this.__createElement("ellipse",l,!0);this.__closestGroupOrSvg().appendChild(h),this.__currentElement=h,this.__applyStyleToCurrentElement(c)}__clearCanvas(){for(var e=this.__closestGroupOrSvg().getAttribute("transform"),t=this.__root.childNodes[1],i=t.childNodes,r=i.length-1;r>=0;r--)i[r]&&t.removeChild(i[r]);this.__currentElement=t,this.__groupStack=[],e&&this.__addTransform(e)}clearRect(e,t,i,r){if(0!==e||0!==t||i!==this.width||r!==this.height){var s,o=this.__closestGroupOrSvg();s=this.__createElement("rect",{x:e,y:t,width:i,height:r,fill:"#FFFFFF"},!0),o.appendChild(s)}else this.__clearCanvas()}createLinearGradient(e,t,i,r){var s=this.__createElement("linearGradient",{id:ch(this.__ids),x1:e+"px",x2:i+"px",y1:t+"px",y2:r+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(s),new fh(s,this)}createRadialGradient(e,t,i,r,s,o){var n=this.__createElement("radialGradient",{id:ch(this.__ids),cx:r+"px",cy:s+"px",r:o+"px",fx:e+"px",fy:t+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(n),new fh(n,this)}__parseFont(){var e=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i.exec(this.font),t={style:e[1]||"normal",size:e[4]||"10px",family:e[6]||"sans-serif",weight:e[3]||"normal",decoration:e[2]||"normal",href:null};return"underline"===this.__fontUnderline&&(t.decoration="underline"),this.__fontHref&&(t.href=this.__fontHref),t}__wrapTextLink(e,t){if(e.href){var i=this.__createElement("a");return i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",e.href),i.appendChild(t),i}return t}__applyText(e,t,i,r){var s,o,n=this.__parseFont(),a=this.__closestGroupOrSvg(),c=this.__createElement("text",{"font-family":n.family,"font-size":n.size,"font-style":n.style,"font-weight":n.weight,"text-decoration":n.decoration,x:t,y:i,"text-anchor":(s=this.textAlign,o={left:"start",right:"end",center:"middle",start:"start",end:"end"},o[s]||o.start),"dominant-baseline":lh(this.textBaseline)},!0);c.appendChild(this.__document.createTextNode(e)),this.__currentElement=c,this.__applyStyleToCurrentElement(r),a.appendChild(this.__wrapTextLink(n,c))}fillText(e,t,i){this.__applyText(e,t,i,"fill")}strokeText(e,t,i){this.__applyText(e,t,i,"stroke")}measureText(e){return this.__ctx.font=this.font,this.__ctx.measureText(e)}arc(e,t,i,r,s,o){if(r!==s){(r%=2*Math.PI)===(s%=2*Math.PI)&&(s=(s+2*Math.PI-.001*(o?-1:1))%(2*Math.PI));var n=e+i*Math.cos(s),a=t+i*Math.sin(s),c=e+i*Math.cos(r),l=t+i*Math.sin(r),h=o?0:1,d=0,u=s-r;u<0&&(u+=2*Math.PI),d=o?u>Math.PI?0:1:u>Math.PI?1:0,this.lineTo(c,l),this.__addPathCommand(ah("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",{rx:i,ry:i,xAxisRotation:0,largeArcFlag:d,sweepFlag:h,endX:n,endY:a})),this.__currentPosition={x:n,y:a}}}clip(){var e=this.__closestGroupOrSvg(),t=this.__createElement("clipPath"),i=ch(this.__ids),r=this.__createElement("g");this.__applyCurrentDefaultPath(),e.removeChild(this.__currentElement),t.setAttribute("id",i),t.appendChild(this.__currentElement),this.__defs.appendChild(t),e.setAttribute("clip-path",ah("url(#{id})",{id:i})),e.appendChild(r),this.__currentElement=r}drawImage(){var e,t,i,r,s,o,n,a,c,l,h,d,u,f=Array.prototype.slice.call(arguments),p=f[0],g=0,m=0;if(3===f.length)e=f[1],t=f[2],i=s=p.width,r=o=p.height;else if(5===f.length)e=f[1],t=f[2],i=f[3],r=f[4],s=p.width,o=p.height;else{if(9!==f.length)throw new Error("Invalid number of arguments passed to drawImage: "+arguments.length);g=f[1],m=f[2],s=f[3],o=f[4],e=f[5],t=f[6],i=f[7],r=f[8]}n=this.__closestGroupOrSvg(),this.__currentElement;var w="translate("+e+", "+t+")";if(p instanceof gh){if((a=p.getSvg().cloneNode(!0)).childNodes&&a.childNodes.length>1){for(c=a.childNodes[0];c.childNodes.length;)u=c.childNodes[0].getAttribute("id"),this.__ids[u]=u,this.__defs.appendChild(c.childNodes[0]);if(l=a.childNodes[1]){var b,F=l.getAttribute("transform");b=F?F+" "+w:w,l.setAttribute("transform",b),n.appendChild(l)}}}else"CANVAS"!==p.nodeName&&"IMG"!==p.nodeName||((h=this.__createElement("image")).setAttribute("width",i),h.setAttribute("height",r),h.setAttribute("preserveAspectRatio","none"),(g||m||s!==p.width||o!==p.height)&&((d=this.__document.createElement("canvas")).width=i,d.height=r,d.getContext("2d").drawImage(p,g,m,s,o,0,0,i,r),p=d),h.setAttribute("transform",w),h.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","CANVAS"===p.nodeName?p.toDataURL():p.getAttribute("src")),n.appendChild(h))}createPattern(e,t){let i,r=this.__document.__createElement("pattern"),s=ch(this.__ids);return r.setAttribute("id",s),r.setAttribute("width",e.width),r.setAttribute("height",e.height),"CANVAS"===e.nodeName||"IMG"===e.nodeName?(i=this.__createElement("image"),i.setAttribute("width",e.width),i.setAttribute("height",e.height),i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","CANVAS"===e.nodeName?e.toDataURL():e.getAttribute("src")),r.appendChild(i),this.__defs.appendChild(r)):e instanceof gh&&(r.appendChild(e.__root.childNodes[1]),this.__defs.appendChild(r)),new ph(r,this)}setLineDash(e){e&&e.length>0?this.lineDash=e.join(","):this.lineDash=null}drawFocusRing(){}createImageData(){}getImageData(){}putImageData(){}globalCompositeOperation(){}setTransform(){}}function mh(e){if(e.startsWith("GCF")||e.startsWith("GCA")&&e.length>=13){return"https://hgdownload.soe.ucsc.edu/hubs/"+e.substring(0,3)+"/"+e.substring(4,7)+"/"+e.substring(7,10)+"/"+e.substring(10,13)+"/"+e+"/hub.txt"}}const wh=new Set(["visibility","priority","group"]),bh=new Set(["track","type","shortLabel","longLabel","bigDataUrl","parent","superTrack","priority","view","compositeContainer","compositeTrack"]);class Fh{properties=new Map;constructor(e,t){this.type=e,this.name=t}setProperty(e,t){this.properties.set(e,t)}getProperty(e){return this.properties.has("noInherit")?this.properties.get(e):this.parent&&wh.has(e)&&this.parent.hasProperty(e)?this.parent.getProperty(e):this.properties.has(e)?this.properties.get(e):this.parent&&!bh.has(e)?this.parent.getProperty(e):void 0}hasProperty(e){return null!==this.getProperty(e)&&void 0!==this.getProperty(e)}hasOwnProperty(e){return this.properties.has(e)}getOwnProperty(e){return this.properties.get(e)}removeProperty(e){this.properties.delete(e)}get format(){const e=this.getProperty("type");if(e)return function(e){const t=e.indexOf(" ");return t>0?e.substring(0,t):e}(e)}get displayMode(){let e=this.getProperty("visibility");if(!e)return"COLLAPSED";switch(e=e.toLowerCase(),e){case"dense":default:return"COLLAPSED";case"pack":return"EXPANDED";case"squish":return"SQUISHED"}}}class vh{constructor(e,t,i,r){this.name=e,this.priority=i,this.label=t,this.defaultOpen=r,this.tracks=[],this.children=[]}isEmpty(){return 0===this.tracks.length&&(!this.children||0===this.children.length||this.children.every((e=>e.isEmpty())))}map(e){this.tracks.forEach(e),this.children.forEach((t=>t.map(e)))}findTracks(e){const t=[];return this._find(t,e),t}_find(e,t){this.tracks.forEach((i=>{t(i)&&e.push(i)})),this.children.forEach((i=>i._find(e,t)))}countTracks(){return this.tracks.length+this.children.reduce(((e,t)=>e+t.countTracks()),0)}countSelectedTracks(){return this.tracks.filter((e=>e.visible)).length+this.children.reduce(((e,t)=>e+t.countSelectedTracks()),0)}trim(){this.children=this.children.filter((e=>!e.isEmpty())),this.children.forEach((e=>e.trim()))}setTrackVisibility(e){this.tracks.forEach((t=>{t.visible=e.has(t.url)})),this.children.forEach((t=>t.setTrackVisibility(e)))}}const yh=new Set(["bigbed","bigwig","biggenepred","vcftabix","refgene","bam","sampleinfo","vcf.list","ucscsnp","bed","tdf","gff","gff3","gtf","vcf","vcfphasedtrio","bigdbsnp","rmask","genepred","wig","bedgraph","interact","broadpeak","narrowpeak","gappedpeak","gistic","seg","mut, bigrmsk"]),Ah=new Set(["cytoBandIdeo","assembly","gap","gapOverlap","allGaps","cpgIslandExtUnmasked","windowMasker"]);class Ch{constructor(e,t){this.groupStanzas=t,this.trackStanzas=e}getSupportedTrackCount(){let e=0;for(const t of this.trackStanzas)!Ah.has(t.name)&&t.hasProperty("bigDataUrl")&&t.format&&yh.has(t.format.toLowerCase())&&e++;return e}getGroupedTrackConfigurations(){if(!this.groupTrackConfigs){this.groupTrackConfigs=[];const e=new Map,t=new vh("","",0,!0);this.groupTrackConfigs.push(t);const i=this.groupStanzas&&this.groupStanzas.length>0;if(i)for(const t of this.groupStanzas){const i=t.getProperty("name"),r="0"===t.getProperty("defaultIsClosed"),s=t.hasProperty("priority")?xh(t.getProperty("priority")):Number.MAX_SAFE_INTEGER-1,o=new vh(i,t.getProperty("label"),s,r);e.set(i,o),this.groupTrackConfigs.push(o)}for(let r of this.trackStanzas){const s=r.hasOwnProperty("superTrack")&&!r.hasOwnProperty("bigDataUrl")||r.hasOwnProperty("compositeTrack")||r.hasOwnProperty("view")||r.hasOwnProperty("container")&&r.getOwnProperty("container").equals("multiWig");let o;if(r.hasOwnProperty("parent")&&(o=e.get(r.getOwnProperty("parent"))),!o&&i&&r.hasProperty("group")){const t=r.getProperty("group");if(e.has(t))o=e.get(t);else{const i=new vh(t,t,1e3,!0);e.set(t,i),this.groupTrackConfigs.push(i),o=i}}if(s){const t=r.getProperty("track"),i=r.hasProperty("priority")?xh(r.getProperty("priority")):Number.MAX_SAFE_INTEGER-1,s="0"===r.getProperty("defaultIsClosed"),n=r.getOwnProperty("longLabel"),a=n&&n.length<50?n:r.getOwnProperty("shortLabel"),c=new vh(t,a,i,s);if(e.has(t))throw new Error(`Duplicate track container: ${t}`);e.set(t,c),o?o.children.push(c):this.groupTrackConfigs.push(c)}else if(!Ah.has(r.name)&&r.hasProperty("bigDataUrl")&&r.format&&yh.has(r.format.toLowerCase())){const e=this.#f(r);o?o.tracks.push(e):t.tracks.push(e)}}}return this.groupTrackConfigs.forEach((e=>e.trim())),this.groupTrackConfigs=this.groupTrackConfigs.filter((e=>!e.isEmpty())),this.groupTrackConfigs.sort(((e,t)=>e.priority-t.priority)),this.groupTrackConfigs}#p(e){return this.trackStanzas.filter((t=>yh.has(t.format)&&t.hasProperty("bigDataUrl")&&(!e||e(t)))).map((e=>this.#f(e)))}#f(e){const t=e.format,i={id:e.getProperty("track"),name:e.getProperty("shortLabel"),format:t,url:e.getProperty("bigDataUrl"),displayMode:e.displayMode};if("vcfTabix"===t&&(i.indexURL=i.url+".tbi"),e.hasProperty("longLabel")&&e.hasProperty("html")?(i.description&&(i.description+="
"),i.description=`${e.getProperty("longLabel")}`):e.hasProperty("longLabel")&&(i.description=e.getProperty("longLabel")),e.hasProperty("autoScale")&&(i.autoscale="on"===e.getProperty("autoScale").toLowerCase()),e.hasProperty("maxHeightPixels")){const t=e.getProperty("maxHeightPixels").split(":");i.maxHeight=Number.parseInt(t[0]),i.height=Number.parseInt(t[1]),i.minHeight=Number.parseInt(t[2])}if(e.hasProperty("color")){const t=e.getProperty("color");i.color=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("altColor")){const t=e.getProperty("altColor");i.altColor=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("viewLimits")){const t=e.getProperty("viewLimits").split(":");let r,s;t.length>1&&(r=Number.parseInt(t[0]),s=Number.parseInt(t[1])),Number.isNaN(s)||Number.isNaN(r)?console.warn(`Unexpected viewLimits value in track line: ${properties.viewLimits}`):(i.min=r,i.max=s)}if(e.hasProperty("itemRgb"),"hide"===e.getProperty("visibility")&&(i.visible=!1),e.hasProperty("url")&&(i.infoURL=e.getProperty("url")),e.hasProperty("searchIndex")&&(i.searchIndex=e.getProperty("searchIndex")),e.hasProperty("searchTrix")&&(i.trixURL=e.getProperty("searchTrix")),e.hasProperty("html")&&(i.html=e.getProperty("html")),e.hasProperty("group")&&(i._group=e.getProperty("group"),this.groupPriorityMap&&this.groupPriorityMap.has(i._group))){const e=this.groupPriorityMap.get(i._group)+1;i.order=e,this.groupPriorityMap.set(i._group,e)}if(e.hasProperty("metadata")&&(i.attributes=function(e){const t=new Map;let i=-1;for(;e&&e.length>0;)try{if(e.length===i)break;i=e.length;let r,s=e.indexOf("=");if(-1===s||s===e.length-1)break;const o=C(A(e.substring(0,s)));let n;if('"'===e.charAt(s+1)?(s++,r=e.indexOf('" ',s+1),n=r>0?e.substring(s+1,r):e.substring(s+1),r++):(r=e.indexOf(" ",s+1),-1===r&&(r=e.length),n=e.substring(s+1,r)),n=A(n),n.endsWith('"')&&(n=n.substring(0,n.length-1)),n.startsWith("<")&&n.endsWith(">")&&(n=_h(n)),t.set(o,n),r===e.length)break;e=r>0?e.substring(r+1).trim():""}catch(e){}return t}(e.getProperty("metadata"))),e.hasProperty("maxWindowToDraw")){let t=parseInt(e.getProperty("maxWindowToDraw"),10);t>Number.MAX_SAFE_INTEGER&&(t=Number.MAX_SAFE_INTEGER),i.visibilityWindow=t}if(e.hasProperty("maxWindowCoverage")){let t=parseInt(e.getProperty("maxWindowCoverage"),10);t>Number.MAX_SAFE_INTEGER&&(t=Number.MAX_SAFE_INTEGER),i.visibilityWindow=t}return i}}function _h(e){const t=e.indexOf(">"),i=e.indexOf("<",t);return t>0&&i>t?e.substring(t+1,i):e}function xh(e){try{const t=e.trim().split(".");let i=100*parseInt(t[0],10);return t.length>1&&(i+=10*parseInt(t[1],10)),t.length>2&&(i+=parseInt(t[2],10)),i}catch(t){return console.error(`Error parsing priority string: ${e}`,t),Number.MAX_SAFE_INTEGER}}const kh=new Map([["hg38","GCF_000001405.40"],["hg38_1kg","GCF_000001405.40"],["mm39","GCF_000001635.27"],["mm10","GCF_000001635.26"],["bosTau9","GCF_002263795.1"],["canFam4","GCF_011100685.1"],["canFam6","GCF_000002285.5"],["ce11","GCF_000002985.6"],["dm6","GCF_000001215.4"],["galGal6","GCF_000002315.6"],["gorGor6","GCF_008122165.1"],["macFas5","GCA_000364345.1"],["panTro6","GCA_002880755.3"],["rn6","GCF_000001895.5"],["rn7","GCF_015227675.2"],["sacCer3","GCF_000146045.2"],["sacCer2","GCF_000146045.2"],["susScr11","GCF_000003025.6"],["taeGut1","GCF_000002275.3"],["tetNig2","GCF_000002275.3"],["xenTro10","GCF_000002035.6"],["xenTro9","GCF_000002035.6"],["tair10","GCF_000001735.4"]]);class Ih{static supportedTypes=new Set(["bigBed","bigWig","bigGenePred","vcfTabix"]);static filterTracks=new Set(["cytoBandIdeo","assembly","gap","gapOverlap","allGaps","cpgIslandExtUnmasked","windowMasker"]);constructor(e,t,i,r,s){if(this.url=e,this.hubStanza=t,this.genomeStanzas=i,this.trackStanzas=r,this.groupStanzas=s,this.cytobandStanza=null,this.trackHubMap=new Map,r){const e=i[0].getProperty("genome");this.trackHubMap.set(e,new Ch(r,s)),this.cytobandStanza=this.trackStanzas.find((e=>"cytoBandIdeo"===e.name&&e.hasProperty("bigDataUrl")))||null}}getName(){return this.hubStanza.getProperty("hub")}getShortLabel(){return this.hubStanza.getProperty("shortLabel")}getLongLabel(){return this.hubStanza.getProperty("longLabel")}getDescriptionUrl(){return this.hubStanza.getProperty("descriptionUrl")}getGenomeConfig(e){const t=e?this.genomeStanzas.find((t=>t.getProperty("genome")===e)):this.genomeStanzas[0];if(!t)throw new Error(`Genome not found in hub: ${e}`);return this.#g(t)}#g(e){const t=e.getProperty("genome"),i=this.hubStanza.getProperty("shortLabel")||e.getProperty("scientificName")||e.getProperty("organism")||e.getProperty("description"),r={id:t,name:i+(i?` (${t})`:` ${t}`),twoBitURL:e.getProperty("twoBitPath"),nameSet:"ucsc",hubs:[this.url]};if(e.hasProperty("chromSizes")?r.chromSizesURL=e.getProperty("chromSizes"):(r.wholeGenomeView=!1,r.showChromosomeWidget=!1),e.hasProperty("defaultPos")){const t=e.getProperty("defaultPos");r.locus=t}e.hasProperty("blat")&&(r.blat=e.getProperty("blat")),e.hasProperty("chromAliasBb")&&(r.chromAliasBbURL=e.getProperty("chromAliasBb")),e.hasProperty("chromAlias")&&(r.aliasURL=e.getProperty("chromAlias")),e.hasProperty("twoBitBptURL")&&(r.twoBitBptURL=e.getProperty("twoBitBptURL")),e.hasProperty("twoBitBptUrl")&&(r.twoBitBptURL=e.getProperty("twoBitBptUrl")),this.cytobandStanza&&(r.cytobandBbURL=this.cytobandStanza.getProperty("bigDataUrl")),this.hubStanza.hasProperty("longLabel")?r.description=this.hubStanza.getProperty("longLabel").replace("/","\n"):(r.description=r.id,e.hasProperty("description")&&(r.description+=`\n${e.getProperty("description")}`),e.hasProperty("organism")&&(r.description+=`\n${e.getProperty("organism")}`),e.hasProperty("scientificName")&&(r.description+=`\n${e.getProperty("scientificName")}`),e.hasProperty("htmlPath")&&(r.infoURL=e.getProperty("htmlPath")));return r.tracks=this.#p((e=>!Ih.filterTracks.has(e.name)&&"hide"!==e.getProperty("visibility"))),r}async getGroupedTrackConfigurations(e){let t=await this.#m(e);return!t&&kh.has(e)&&(t=await this.#m(kh.get(e))),t||console.log(`Warning: no trackDB found for genomeId ${e}.`),t?t.getGroupedTrackConfigurations():[]}async#m(e){let t=this.trackHubMap.get(e);if(!t)for(let i of this.genomeStanzas)if(e===i.getProperty("genome")){try{const r=i.getProperty("trackDb"),s=await Mh(r);t=new Ch(s,this.groupStanzas),this.trackHubMap.set(e,t)}catch(e){console.error(`Error loading trackDb file: ${i.getProperty("trackDb")}`,e)}break}return t}#p(e){return this.trackStanzas.filter((t=>Ih.supportedTypes.has(t.format)&&t.hasProperty("bigDataUrl")&&(!e||e(t)))).map((e=>this.#f(e)))}#f(e){const t=e.format,i={id:e.getProperty("track"),name:e.getProperty("shortLabel"),format:t,url:e.getProperty("bigDataUrl"),displayMode:e.displayMode};if("vcfTabix"===t&&(i.indexURL=i.url+".tbi"),e.hasProperty("longLabel")&&e.hasProperty("html")?(i.description&&(i.description+="
"),i.description=`${e.getProperty("longLabel")}`):e.hasProperty("longLabel")&&(i.description=e.getProperty("longLabel")),e.hasProperty("autoScale")&&(i.autoscale="on"===e.getProperty("autoScale").toLowerCase()),e.hasProperty("maxHeightPixels")){const t=e.getProperty("maxHeightPixels").split(":");i.maxHeight=Number.parseInt(t[0]),i.height=Number.parseInt(t[1]),i.minHeight=Number.parseInt(t[2])}if(e.hasProperty("color")){const t=e.getProperty("color");i.color=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("altColor")){const t=e.getProperty("altColor");i.altColor=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("viewLimits")){const t=e.getProperty("viewLimits").split(":");let r,s;t.length>1&&(r=Number.parseInt(t[0]),s=Number.parseInt(t[1])),Number.isNaN(s)||Number.isNaN(r)?console.warn(`Unexpected viewLimits value in track line: ${e.getProperty("viewLimits")}`):(i.min=r,i.max=s)}if(e.hasProperty("itemRgb"),"hide"===e.getProperty("visibility")&&(i.visible=!1),e.hasProperty("url")&&(i.infoURL=e.getProperty("url")),e.hasProperty("searchIndex")&&(i.searchIndex=e.getProperty("searchIndex")),e.hasProperty("searchTrix")&&(i.trixURL=e.getProperty("searchTrix")),e.hasProperty("group")&&(i._group=e.getProperty("group"),this.groupPriorityMap&&this.groupPriorityMap.has(i._group))){const e=this.groupPriorityMap.get(i._group)+1;i.order=e,this.groupPriorityMap.set(i._group,e)}const r=e.hasProperty("defaultLabelFields")?e.getProperty("defaultLabelFields"):e.getProperty("labelFields");return r&&(i.labelField=r.split(",")[0]),i}}const Sh=new Set(["descriptionUrl","desriptionUrl","twoBitPath","blat","chromAliasBb","twoBitBptURL","twoBitBptUrl","htmlPath","bigDataUrl","genomesFile","trackDb","groups","include","html","searchTrix","groups","chromSizes"]),Eh=new Map;async function Nh(e){if(Eh.has(e))return Eh.get(e);const t=await Mh(e);if(t.length<1)throw new Error("Empty hub file");const i=t[0];if("hub"!==i.type)throw new Error("First stanza must be a hub stanza");let r,s;if("on"===i.getProperty("useOneFile")){if("genome"!==t[1].type)throw new Error("Unexpected hub file -- expected 'genome' stanza but found "+t[1].type);const e=t[1];if(r=[e],s=t.slice(2),e.hasOwnProperty("chromSizes")){const t=e.getProperty("chromSizes");try{await Rr.getContentLength(t)>1e5&&e.removeProperty("chromSizes")}catch(e){console.error(`Error getting content length for chromSizes ${t}`,e)}}}else{if(!i.hasProperty("genomesFile"))throw new Error("hub.txt must specify 'genomesFile'");r=await Mh(i.getProperty("genomesFile"))}const o=new Set;r.forEach((e=>{const t=e.getProperty("groups");t&&o.add(t)}));const n=[],a=Array.from(o).map((async e=>await Mh(e)));(await Promise.all(a)).forEach((e=>n.push(...e)));const c=new Ih(e,i,r,s,n);return Eh.set(e,c),c}async function Mh(e){const t=e.lastIndexOf("/"),i=e.substring(0,t+1),r=function(e){let t;if(e.startsWith("https://")||e.startsWith("http://"))try{const i=new URL(e);t=`${i.protocol}//${i.host}`}catch(e){throw console.error("Error parsing base URL host",e),e}else t="";return t}(e),s=(await Rr.loadString(e,{})).split(/\n|\r\n|\r/g),o=[];let n,a=!0;for(let e=0;e=s.length));)t=t.substring(0,t.length-1)+s[e].trim();if(t.startsWith("include")){const e=Bh(t.substring(8).trim(),r,i),s=await Mh(e);for(let e of s)o.push(e)}const c=t.indexOf(" "),l=t.substring(0,c).trim();let h=t.substring(c+1).trim();if("type"===l){const e=h.split(/\s+/);if(h=e[0],"bigWig"===h&&3===e.length){const t=e[1],i=e[2];n&&(n.setProperty("min",t),n.setProperty("max",i))}}else if(!["shortLabel","longLabel","metadata","label"].includes(l)){const e=h.split(/\s+/);h=e[0]}(Sh.has(l)||h.endsWith("URL")||h.endsWith("Url"))&&(h=Bh(h,r,i)),a&&(n=new Fh(l,h),o.push(n),a=!1),n.setProperty(l,h)}}return function(e){const t=new Map;for(let i of e)t.set(i.name,i);for(let i of e)if(i.properties.has("parent")){const e=Rh(i.properties.get("parent"));i.parent=t.get(e)}return e}(o)}function Rh(e){const t=e.indexOf(" ");return t>0?e.substring(0,t):e}function Bh(e,t,i){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("gs://")||e.startsWith("s3://")?e:e.startsWith("/")?t+e:i+e}const Dh={initializeGenomes:async function(e){if(!Dh.KNOWN_GENOMES){let t={};const i=(e,t)=>(e.forEach((function(e){t[e.id]=e})),t);if(!1!==e.loadDefaultGenomes)try{i(await Rr.loadJson("https://igv.org/genomes/genomes3.json",{timeout:2e3}),t)}catch(e){try{console.error("Error initializing default genomes:",e);i(await Rr.loadJson("https://raw.githubusercontent.com/igvteam/igv-data/refs/heads/main/genomes/web/genomes.json",{timeout:1e4}),t)}catch(t){console.error("Error initializing backup genomes:",e)}}const r=e.genomeList||e.genomes;if(r)if("string"==typeof r){i(await Rr.loadJson(r,{}),t)}else i(r,t);Dh.KNOWN_GENOMES=t}},isWholeGenomeView:function(e){return"all"===e.toLowerCase()},expandReference:async function(e,t){if(b(t)&&t.startsWith("{"))try{t=JSON.parse(t)}catch(e){}let i;if(b(t)?i=t:t.genome?i=t.genome:void 0===t.id||t.fastaURL||t.twobitURL||(i=t.id),i){let t=Dh.KNOWN_GENOMES[i];if(!t){if((i.startsWith("GCA_")||i.startsWith("GCF_"))&&i.length>=13)try{const e=mh(i);t=(await Nh(e)).getGenomeConfig(i)}catch(e){console.error(e)}t||e.present(new Error(`Unknown genome id: ${i}`),void 0)}return t}return t}};let Lh,Th,zh=0,Ph=[];class Hh extends nh{constructor(e,t,i,r){super(e,t,i,r)}initializationHelper(){this.spinnerElement=document.createElement("div"),this.spinnerElement.className="igv-loading-spinner-container",this.viewportElement.appendChild(this.spinnerElement),this.spinnerElement.appendChild(document.createElement("div")),this.overlayElement=document.createElement("div"),this.overlayElement.style.position="absolute",this.overlayElement.style.width="100%",this.overlayElement.style.height="100%",this.viewportElement.appendChild(this.overlayElement);const e=this.trackView.track;"sequence"!==e.type&&(this.zoomInNoticeElement=Hh.createZoomInNotice(this.viewportElement)),"sequence"!==e.id&&(this.trackLabelElement=document.createElement("div"),this.trackLabelElement.className="igv-track-label",this.viewportElement.appendChild(this.trackLabelElement),this.setTrackLabel(e.name||""),!1===this.browser.doShowTrackLabels&&(this.trackLabelElement.style.display="none"),this.trackView.track.height&&this.setHeight(this.trackView.track.height)),this.doRenderBucketLabels=new Set(["seg","mut"]).has(this.trackView.track.type),this.stopSpinner(),this.addMouseHandlers()}didPresentZoomInNotice(){const e=!(void 0===this.zoomInNoticeElement);return!1===e?e:"flex"===this.zoomInNoticeElement.style.display}setContentHeight(e){super.setContentHeight(e),this.featureCache&&(this.featureCache.redraw=!0)}setTrackLabel(e){this.trackLabelElement.innerHTML="",this.trackLabelElement.innerHTML=e;const t=this.trackLabelElement.textContent;this.trackLabelElement.setAttribute("title",t)}startSpinner(){this.spinnerElement&&(this.spinnerElement.style.display="flex")}stopSpinner(){this.spinnerElement&&(this.spinnerElement.style.display="none")}checkZoomIn(){if(this.trackView.track&&"sequence"===this.trackView.track.type&&this.referenceFrame.bpPerPixel>10)return this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.canvas=void 0,!1;if(!this.viewIsReady())return!1;if((()=>{if("all"===this.referenceFrame.chr.toLowerCase())return!this.trackView.track.supportsWholeGenome;{const e=this.trackView.track.visibilityWindow;return void 0!==e&&e>0&&this.referenceFrame.bpPerPixel*this.viewportElement.clientWidth>e}})()){if(this.canvas&&this.canvas.parentNode&&(this.canvas.parentNode.removeChild(this.canvas),this.canvas=void 0),this.trackView.track.autoHeight){const e=this.trackView.minHeight||0;this.setContentHeight(e)}return this.zoomInNoticeElement&&(this.zoomInNoticeElement.style.display="flex"),!1}return this.zoomInNoticeElement&&(this.zoomInNoticeElement.style.display="none"),!0}shift(){const e=this.referenceFrame;this.canvas&&this.canvas._data&&this.canvas._data.referenceFrame.chr===this.referenceFrame.chr&&this.canvas._data.bpPerPixel===e.bpPerPixel&&(this.canvas._data.pixelShift=Math.round((this.canvas._data.bpStart-e.start)/e.bpPerPixel),this.canvas.style.left=this.canvas._data.pixelShift+"px")}genomicRange(){return{start:this.referenceFrame.start,end:this.referenceFrame.start+this.referenceFrame.bpPerPixel*this.viewportElement.clientWidth}}setTop(e){if(super.setTop(e),this.overlayElement.style.top=`-${e}px`,this.canvas){const t=this.viewportElement.clientHeight,i=this.canvas._data.pixelTop-e,r=i+this.canvas._data.pixelHeight;(i>0||r0)for(let r of a.roiSets){const s=await r.getFeatures(t,o,n,e.bpPerPixel);i.push({track:r,features:s})}const r=a&&a.resolutionAware,s=this.windowFunction;return this.featureCache=new Oh(t,o,n,e.bpPerPixel,c,i,r,s),this.loading=!1,this.hideMessage(),this.stopSpinner(),this.browser.fireEvent("featuresloaded",[this]),this.featureCache}}catch(e){this.trackView&&!0!==this.trackView.disposed&&(this.showMessage("Error loading track data"),this.browser.alert.present(e),console.error(e))}finally{this.loading=!1,this.stopSpinner()}}get track(){return this.trackView.track}get windowFunction(){return this.track?this.track.windowFunction:void 0}repaintDimensions(){const e=Dh.isWholeGenomeView(this.referenceFrame.chr),t=e?this.viewportElement.clientWidth:3*this.viewportElement.clientWidth,i=this.referenceFrame.bpPerPixel;return{bpStart:this.referenceFrame.start-(e?0:this.viewportElement.clientWidth*i),bpEnd:e?Number.MAX_SAFE_INTEGER:this.referenceFrame.start+2*this.viewportElement.clientWidth*i+1,pixelWidth:t}}repaint(){if(void 0===this.featureCache)return;const{features:e,roiFeatures:t}=this.featureCache,{bpStart:i,bpEnd:r,pixelWidth:s}=this.repaintDimensions(),o=this.viewportElement.clientHeight,n=this.getContentHeight(),a=t?Math.max(n,o):n,c=Math.min(a,3*o);if(0===s||0===c)return void(this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas));const l=Math.max(0,this.contentTop-Math.floor(c/3)),h=this.referenceFrame.bpPerPixel,d=Math.round((i-this.referenceFrame.start)/h),u=l-(this.contentTop||0),f=document.createElement("canvas");f.style.position="relative",f.style.display="block",f.style.width=s+"px",f.style.height=c+"px",f.style.left=d+"px",f.style.top=u+"px";const p="FILL"===this.trackView.track.displayMode||!1!==this.trackView.track.supportHiDPI?window.devicePixelRatio:1;f.width=p*s,f.height=p*c;const g=f.getContext("2d");g.scale(p,p),g.translate(0,-l);const m={context:g,contentTop:this.contentTop,pixelXOffset:d,pixelWidth:s,pixelHeight:c,pixelTop:l,bpStart:i,bpEnd:r,bpPerPixel:h,pixelShift:d,windowFunction:this.windowFunction,referenceFrame:this.referenceFrame,selection:this.selection,viewport:this,viewportWidth:this.viewportElement.clientWidth};this.draw(m,e,t),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),f._data=m,this.canvas=f,this.viewportElement.appendChild(f)}refresh(){if(!this.canvas||!this.featureCache)return;const e=this.canvas._data;e.context.clearRect(0,0,this.canvas.width,this.canvas.height);const{features:t,roiFeatures:i}=this.featureCache;this.draw(e,t,i)}draw(e,t,i){if(t&&(e.features=t,this.trackView.track.draw(e)),i&&i.length>0)for(let t of i)e.features=t.features,t.track.draw(e)}containsPosition(e,t){return this.referenceFrame.chr===e&&t>=this.referenceFrame.start&&t<=this.referenceFrame.calculateEnd(this.getWidth())}isLoading(){return this.loading}savePNG(){if(!this.canvas)return;const e=this.viewportElement.clientWidth*window.devicePixelRatio,t=this.viewportElement.clientHeight*window.devicePixelRatio,i=-this.canvas.offsetLeft*window.devicePixelRatio,r=this.canvas._data,s=r?r.pixelTop:0,o=(this.contentTop-s)*window.devicePixelRatio,n=this.canvas.getContext("2d").getImageData(i,o,e,t),a=document.createElement("canvas"),c=a.getContext("2d");a.width=n.width,a.height=n.height,c.putImageData(n,0,0);k((this.trackLabelElement&&this.trackLabelElement.textContent?this.trackLabelElement.textContent:"image")+".png",a.toDataURL("image/png"))}saveSVG(){let{width:e,height:t}=this.browser.columnContainer.getBoundingClientRect();const i=new gh({width:e,height:8e3,backdropColor:"white",multiLocusGap:0,viewbox:{x:0,y:0,width:e,height:8e3}}),r={deltaX:32,deltaY:32};this.renderSVGContext(i,r,!1),i.setHeight(t);const s=(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,""),o=this.browser.referenceFrameList.indexOf(this.referenceFrame),a=i.getSerializedSvg(!0),c=URL.createObjectURL(new Blob([a],{type:"application/octet-stream"}));k(`${`${s}_referenceFrame_${o}_guid_${n()}`}.svg`,c)}renderSVGContext(e,{deltaX:t,deltaY:i},r=!0){if(!1===this.didPresentZoomInNotice()){const{width:r,height:s}=this.viewportElement.getBoundingClientRect(),o=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_referenceFrame_${this.browser.referenceFrameList.indexOf(this.referenceFrame)}_guid_${n()}`,a=t,c=i-this.contentTop,l=this.contentTop;e.saveWithTranslationAndClipRect(o,a,c,r,s,l);const{start:h,bpPerPixel:d}=this.referenceFrame,u=Math.round((h-this.referenceFrame.start)/d),f={context:e,contentTop:this.contentTop,pixelXOffset:u,pixelWidth:r,pixelHeight:s,pixelTop:l,bpStart:h,bpEnd:h+r*d,bpPerPixel:d,pixelShift:u,referenceFrame:this.referenceFrame,selection:this.selection,viewport:this,viewportWidth:this.viewportElement.clientWidth},p=this.featureCache?this.featureCache.features:void 0,g=this.featureCache?this.featureCache.roiFeatures:void 0;this.draw(f,p,g),e.restore()}if(r&&this.trackLabelElement&&this.browser.doShowTrackLabels){const{x:r,y:s,width:o,height:n}=this.viewportElement.getBoundingClientRect(),{x:a,y:c,width:l,height:h}=this.trackLabelElement.getBoundingClientRect(),d=a-r,u=c-s,f=l,p=h;this.renderTrackLabelSVG(e,t+d,i+u,f,p)}}renderTrackLabelSVG(e,t,i,r,s){const o=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_track_label_guid_${n()}`,a=this.trackLabelElement.textContent,{width:c}=e.measureText(a),l=.25*(r-c),h=.7*(s-12);this.renderElementSVG(e,o,t,i,r,s,a,l,h)}renderElementSVG(e,t,i,r,s,o,n,a,c){e.saveWithTranslationAndClipRect(t,i,r,s,o,0),e.fillStyle="white",e.fillRect(0,0,s,o),e.font="12px Arial",e.fillStyle="rgb(68, 68, 68)",e.fillText(n,a,o-c),e.strokeStyle="rgb(68, 68, 68)",e.strokeRect(0,0,s,o),e.restore()}get cachedFeatures(){return this.featureCache?this.featureCache.features:[]}clearCache(){this.featureCache=void 0,this.canvas&&(this.canvas._data=void 0)}async getFeatures(e,t,i,r,s){if(this.featureCache&&this.featureCache.containsRange(t,i,r,s,this.windowFunction))return this.featureCache.features;if("function"==typeof e.getFeatures){const o=await e.getFeatures(t,i,r,s,this);return this.checkContentHeight(o),o}}needsRepaint(){if(!this.canvas)return!0;const e=this.canvas._data;return!e||this.referenceFrame.starte.bpEnd||this.referenceFrame.chr!==e.referenceFrame.chr||this.referenceFrame.bpPerPixel!==e.bpPerPixel||this.windowFunction!==e.windowFunction}needsReload(){if(!this.featureCache)return!0;const{chr:e,bpPerPixel:t}=this.referenceFrame,{bpStart:i,bpEnd:r}=this.repaintDimensions();return!this.featureCache.containsRange(e,i,r,t,this.windowFunction)}static createZoomInNotice(e){const t=document.createElement("div");t.className="igv-zoom-in-notice-container",e.appendChild(t);const i=document.createElement("div");return t.appendChild(i),i.textContent="Zoom in to see features",t.style.display="none",t}viewIsReady(){return this.browser&&this.browser.referenceFrameList&&this.referenceFrame}addMouseHandlers(){this.addViewportContextMenuHandler(this.viewportElement);const e=e=>{this.enableClick=!0,this.browser.mouseDownOnViewport(e,this),o(e)};this.viewportElement.addEventListener("mousedown",e),this.viewportElement.addEventListener("touchstart",e);const t=e=>{this.browser.dragObject||this.browser.isScrolling?(this.browser.cancelTrackPan(),this.enableClick=!1):(this.browser.cancelTrackPan(),this.browser.endTrackDrag())};if(this.viewportElement.addEventListener("mouseup",t),this.viewportElement.addEventListener("touchend",t),"function"==typeof this.trackView.track.hoverText){let e=0;this.viewportElement.addEventListener("mousemove",(t=>{const i=Date.now();if(0===t.buttons&&i-e>100){e=i;const r=this.createClickState(t);if(r){const e=this.trackView.track.hoverText(r);e?this.viewportElement.setAttribute("title",e):this.viewportElement.removeAttribute("title")}}}))}this.addViewportClickHandler(this.viewportElement),this.trackView.track.name&&"sequence"!==this.trackView.track.config.type&&this.addTrackLabelClickHandler(this.trackLabelElement)}addViewportContextMenuHandler(e){e.addEventListener("contextmenu",(e=>{if(this.browser.dragObject)return!1;const t=this.createClickState(e);if(void 0===t)return!1;e.preventDefault(),e.stopPropagation();let i=[];if("function"==typeof this.trackView.track.contextMenuItemList){const e=this.trackView.track.contextMenuItemList(t);e&&(i=e)}i.length>0&&i.push({label:document.createElement("hr")}),i.push({label:"Save Image (PNG)",click:()=>this.savePNG()}),i.push({label:"Save Image (SVG)",click:()=>this.saveSVG()}),this.browser.menuPopup.presentTrackContextMenu(e,i)}))}addViewportClickHandler(e){e.addEventListener("click",(e=>{if(this.enableClick&&this.canvas){if(3===e.which||e.ctrlKey)return;if(this.browser.dragObject||this.browser.isScrolling)return;e.preventDefault();const t=a(e,this.viewportElement).x,i=a(e,this.canvas).x,r=this.referenceFrame;Math.floor(r.start+r.toBP(i));const s=Date.now();if(s-zhe));t[this.browser.referenceFrameList.indexOf(this.referenceFrame)]=e,s=t.join(" ")}this.browser.search(s)}else e.shiftKey?this.browser.zoomWithScaleFactor(2,i,this.referenceFrame):this.browser.zoomWithScaleFactor(.5,i,this.referenceFrame)}else"function"==typeof this.trackView.track.popupData&&(Lh=setTimeout((()=>{const t=this.getPopupContent(e);if(t)if(!1===e.shiftKey){if(Th&&Th.dispose(),Ph.length>0){for(const e of Ph)e.dispose();Ph.length=0}Th=new us(this.viewportElement.parentElement,!0,void 0,(()=>{Th.dispose()})),Th.presentContentWithEvent(e,t)}else{let i=new us(this.viewportElement.parentElement,!0,void 0,(()=>{const e=Ph.indexOf(i);Ph.splice(e,1),i.dispose()}));Ph.push(i),i.presentContentWithEvent(e,t)}window.clearTimeout(Lh),Lh=void 0}),this.browser.constants.doubleClickDelay));zh=s}}))}addTrackLabelClickHandler(e){e.addEventListener("click",(e=>{e.stopPropagation(),this.removeTrackLabelPopover();const{track:t}=this.trackView;let i;if("function"==typeof t.description)i=t.description();else if(t.description){const e=document.createElement("div");e.className="igv-track-label-popover__row",e.textContent=t.description,i=e}i&&this.showTrackLabelPopover(e,i,t.name||"")}))}showTrackLabelPopover(e,t,i){const r=document.createElement("div");r.className="igv-track-label-popover";const s=document.createElement("div");s.className="igv-track-label-popover__header";const o=document.createElement("div");o.className="igv-track-label-popover__title",o.textContent=i;const n=document.createElement("div");n.className="igv-track-label-popover__close",n.setAttribute("tabindex","0"),n.setAttribute("aria-label","Close"),n.appendChild(l("times")),n.addEventListener("click",(()=>this.removeTrackLabelPopover())),s.appendChild(o),s.appendChild(n);const a=document.createElement("div");a.className="igv-track-label-popover__body",a.appendChild(t),r.appendChild(s),r.appendChild(a);const c=this.trackLabelElement.getBoundingClientRect(),h=this.browser.columnContainer.getBoundingClientRect(),d=c.left-h.left,u=c.bottom-h.top+5;r.style.left=`${d}px`,r.style.top=`${u}px`,r.style.position="absolute",this._trackLabelPopover=r,this.browser.columnContainer.appendChild(r),p(r,s,{minX:0,minY:0})}removeTrackLabelPopover(){this._trackLabelPopover&&(this._trackLabelPopover.remove(),this._trackLabelPopover=null,this._trackLabelPopoverListener&&(document.removeEventListener("mousedown",this._trackLabelPopoverListener),this._trackLabelPopoverListener=null))}createClickState(e){if(!this.canvas)return;const t=this.referenceFrame,i=a(e,this.viewportElement),r=a(e,this.canvas),s=t.start+t.toBP(i.x);return{event:e,viewport:this,referenceFrame:t,genomicLocation:s,y:i.y+this.contentTop,canvasX:r.x,canvasY:r.y}}getPopupContent(e){const t=this.createClickState(e);if(void 0===t)return;let i=this.trackView.track;const r=i.popupData(t),s=this.browser.fireEvent("trackclick",[i,r,t.genomicLocation]);let o;return void 0===s||!0===s?r&&r.length>0&&(o=r.map((e=>{if(e.name){const t=`${e.name}   ${e.value}`;return`
${t}
`}return"
"===e?e:e.html?e.html:`
${e}
`})).join("")):"string"==typeof s&&(o=s),o}dispose(){this.popover&&this.popover.dispose(),super.dispose()}}class Oh{constructor(e,t,i,r,s,o,n,a){this.chr=e,this.bpStart=t,this.bpEnd=i,this.bpPerPixel=r,this.features=s,this.roiFeatures=o,this.multiresolution=n,this.windowFunction=a}containsRange(e,t,i,r,s){if(s&&s!==this.windowFunction)return!1;const o=this.multiresolution?this.bpPerPixel/r:1;return t>=this.bpStart&&i<=this.bpEnd&&e===this.chr&&o>.5&&o<2}overlapsRange(e,t,i){return this.chr===e&&i>=this.bpStart&&t<=this.bpEnd}}const Vh=1/16,qh=function(e,t){const{r:i,g:r,b:s}=Qr[e];return`rgba(${i},${r},${s},${t})`}("nickel",Vh),Uh=qh;class Qh{constructor(e,t){if(this.url=e.url,e.name&&(this.name=e.name),this.isUserDefined=e.isUserDefined,e.featureSource)this.featureSource=e.featureSource;else if(e.features)this.featureSource=new jh(e.features,t);else{if(!e.format)throw Error("ROI configuration must define either features or file format");this.featureSource=El(e,t)}if(e.color&&!e.color.startsWith("rgba")&&(e.color=ur.addAlpha(e.color,Vh)),!0===this.isUserDefined)this.color=e.color||Uh,this.headerColor="rgba(155,185,129)";else{this.color=e.color||qh,this.headerColor="rgb(190,190,190)";const[t,i,r,s]=function(e){if(e.startsWith("rgba(")){const[t,i]=e.split("("),[r]=i.split(")");return r.split(",").map(((e,t)=>t<3?parseInt(e):parseFloat(e)))}}(this.color);this.headerColor=`rgba(${t},${i},${r},1)`}delete e.isVisible}async getFeatures(e,t,i){return this.featureSource.getFeatures({chr:e,start:t,end:i})}async getAllFeatures(){return"function"==typeof this.featureSource.getAllFeatures?await this.featureSource.getAllFeatures():{}}addFeature(e){this.featureSource.addFeature(e)}removeFeature(e){this.featureSource.removeFeature(e)}toJSON(){if(this.url)return{name:this.name,color:this.color,url:this.url,isUserDefined:this.isUserDefined,isVisible:this.isVisible};{const e=this.featureSource.getAllFeatures(),t=[];for(let i of Object.keys(e))for(let r of e[i])t.push(r);return{name:this.name,color:this.color,features:t,isUserDefined:this.isUserDefined,isVisible:this.isVisible}}}dispose(){for(let e of Object.keys(this))this[e]=void 0}}function Gh(e,t,i,r){let s=Math.round((e-i)/r);let o=Math.round((t-i)/r)-s;return o<3&&(o=3,s-=1),{x:s,width:o}}class jh{constructor(e,t){this.featureMap={},this.genome=t;for(let i of e){const e=t?t.getChromosomeName(i.chr):i.chr;let r=this.featureMap[e];r||(r=[],this.featureMap[e]=r),r.push(i)}for(let e of Object.keys(this.featureMap))this.featureMap[e].sort(((e,t)=>e.start-t.start))}async getFeatures({chr:e,start:t,end:i}){if("all"===e.toLowerCase())return await pa(this.featureMap,this.genome);{const r=this.featureMap[e];return r?r.filter((e=>e.end>t&&e.starte.start-t.start))}removeFeature({chr:e,start:t,end:i}){if(this.featureMap[e]){const r=`${e}-${t}-${i}`;this.featureMap[e]=this.featureMap[e].filter((e=>r!==`${e.chr}-${e.start}-${e.end}`)),0===this.featureMap[e].length&&delete this.featureMap[e]}}}class Wh{constructor(e,i,r,s){this.rulerViewport=e,this.rulerSweeper=t({class:"igv-ruler-sweeper"}),i.appendChild(this.rulerSweeper),this.browser=r,this.referenceFrame=s,this.isMouseHandlers=void 0,this.addBrowserObserver()}addBrowserObserver(){this.boundObserverHandler=(()=>{this.referenceFrame&&(Dh.isWholeGenomeView(this.referenceFrame.chr)?this.removeMouseHandlers():this.addMouseHandlers())}).bind(this),this.browser.on("locuschange",this.boundObserverHandler)}removeBrowserObserver(){this.browser.off("locuschange",this.boundObserverHandler)}addMouseHandlers(){if(!0===this.isMouseHandlers)return;let e,t,i,r,s,o;this.boundContentMouseDownHandler=function(o){e=!0,t=!0;const{x:n}=a(o,this.rulerViewport.contentDiv);r=i=n,s=1,this.rulerSweeper.style.display="block",this.rulerSweeper.style.backgroundColor=!0===o.shiftKey?Uh:"rgba(68, 134, 247, 0.25)",this.rulerSweeper.style.left=`${r}px`,this.rulerSweeper.style.width=`${s}px`}.bind(this),this.rulerViewport.contentDiv.addEventListener("mousedown",this.boundContentMouseDownHandler),this.boundDocumentMouseMoveHandler=function(n){let c;if(e&&t){const{x:e}=a(n,this.rulerViewport.contentDiv);c=Math.max(Math.min(e,this.rulerViewport.contentDiv.clientWidth),0),o=c-i,s=Math.abs(o),this.rulerSweeper.style.width=`${s}px`,o<0&&(r=i+o,this.rulerSweeper.style.left=`${r}px`)}}.bind(this),document.addEventListener("mousemove",this.boundDocumentMouseMoveHandler),this.boundDocumentMouseUpHandler=function(i){let o;if(!0===e&&!0===t&&(e=t=void 0,this.rulerSweeper.style.display="none",s>1)){o={start:Math.floor(this.referenceFrame.calculateEnd(r)),end:Math.floor(this.referenceFrame.calculateEnd(r+s))};!0===i.shiftKey?this.browser.roiManager.updateUserDefinedROISet(Object.assign({chr:this.referenceFrame.chr},o)):(rs(this.browser.genome.getChromosome(this.referenceFrame.chr).bpLength,o,this.browser.minimumBases()),function(e,t,i){e.start=Math.round(t.start),e.end=Math.round(t.end),e.bpPerPixel=(e.end-e.start)/i}(this.referenceFrame,o,this.rulerViewport.contentDiv.clientWidth),this.browser.updateViews(this.referenceFrame))}}.bind(this),document.addEventListener("mouseup",this.boundDocumentMouseUpHandler),this.isMouseHandlers=!0}removeMouseHandlers(){this.rulerViewport.contentDiv.removeEventListener("mousedown",this.boundContentMouseDownHandler),document.removeEventListener("mousemove",this.boundDocumentMouseMoveHandler),document.removeEventListener("mouseup",this.boundDocumentMouseUpHandler),this.isMouseHandlers=!1}dispose(){this.removeBrowserObserver(),this.removeMouseHandlers(),this.rulerSweeper.remove()}}function $h(e){if(Kh[e])return Kh[e];if(Kh["chr"+e]){const t=Kh["chr"+e];return Kh[e]=t,t}{const t=ur.randomRGB(0,255);return Kh[e]=t,t}}const Kh={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0)",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};let Zh,Yh;class Xh extends Hh{constructor(e,t,i,r){super(e,t,i,r)}get contentDiv(){return this.viewportElement}initializationHelper(){this.multiLocusCloseButton=document.createElement("div"),this.multiLocusCloseButton.className="igv-multi-locus-close-button",this.viewportElement.appendChild(this.multiLocusCloseButton);const e=l("times-circle");this.multiLocusCloseButton.appendChild(e),this.multiLocusCloseButton.addEventListener("click",(()=>{this.browser.removeMultiLocusPanel(this.referenceFrame)})),this.rulerLabel=document.createElement("div"),this.rulerLabel.className="igv-multi-locus-ruler-label",this.viewportElement.appendChild(this.rulerLabel);const t=document.createElement("div");this.rulerLabel.appendChild(t),this.rulerLabel.addEventListener("click",(async e=>{e.stopPropagation(),await this.browser.gotoMultilocusPanel(this.referenceFrame)})),this.tooltip=document.createElement("div"),this.tooltip.className="igv-ruler-tooltip",this.tooltip.style.height=`${this.viewportElement.clientHeight}px`,this.viewportElement.appendChild(this.tooltip),this.tooltipContent=document.createElement("div"),this.tooltip.appendChild(this.tooltipContent),this.rulerSweeper=new Wh(this,this.viewportElement.parentElement,this.browser,this.referenceFrame),this.attachMouseHandlers(Dh.isWholeGenomeView(this.referenceFrame.chr)),this.tooltip.style.display="none",this.dismissLocusLabel()}presentLocusLabel(e){this.multiLocusCloseButton.style.display="block",this.rulerLabel.style.display="block",this.rulerLabel.style.backgroundColor=$h(this.referenceFrame.chr);const t=this.rulerLabel.querySelector("div"),{width:i}=this.rulerLabel.getBoundingClientRect();t.innerHTML=`${this.referenceFrame.getMultiLocusLabel(e)}`;const{width:r}=t.getBoundingClientRect();r/i>.5&&(t.innerHTML=`${this.referenceFrame.getMultiLocusLabelBPLengthOnly(e)}`)}dismissLocusLabel(){this.rulerLabel.style.display="none",this.multiLocusCloseButton.style.display="none"}attachMouseHandlers(e){!0===e?(this.viewportElement.addEventListener("click",(e=>{const{x:t}=a(e,this.viewportElement),i=Math.round(this.referenceFrame.start+this.referenceFrame.toBP(t));let r;const{chr:s}=this.browser.genome.getChromosomeCoordinate(i);if(1===this.browser.referenceFrameList.length)r=s;else{const e=this.browser.referenceFrameList.indexOf(this.referenceFrame),t=this.browser.referenceFrameList.map((({locusSearchString:e})=>e));t[e]=s,r=t.join(" ")}this.browser.search(r)})),this.viewportElement.style.cursor="pointer"):this.viewportElement.style.cursor="default"}mouseMove(e){if(this.browser.doShowCursorGuide){void 0===Yh?(Yh=this,this.tooltip.style.display="block"):Yh.guid!==this.guid?(Yh.tooltip&&(Yh.tooltip.style.display="none"),this.tooltip.style.display="block",Yh=this):this.tooltip.style.display="block";if(this.browser.isMultiLocusWholeGenomeView()||Dh.isWholeGenomeView(this.referenceFrame.chr))return void(this.tooltip.style.display="none");const{x:t}=a(e,this.viewportElement),{start:i,end:r,bpPerPixel:s}=this.referenceFrame,o=Math.round(.5+i+Math.max(0,t)*s);this.tooltipContent.textContent=F(o);const n=this.tooltipContent.getBoundingClientRect(),c=this.viewportElement.getBoundingClientRect(),l=cr(t,0,c.width-n.width);return this.tooltip.style.left=`${l}px`,clearTimeout(Zh),Zh=setTimeout((()=>{this.tooltip&&(this.tooltip.style.display="none")}),1e4),{start:i,bp:o,end:r}}}startSpinner(){}stopSpinner(){}dispose(){this.rulerSweeper.dispose(),super.dispose()}}let Jh;class ed extends Hh{featureCache=new td;constructor(e,t,i,r){super(e,t,i,r)}initializationHelper(){this.canvas=document.createElement("canvas"),this.canvas.className="igv-ideogram-canvas",this.viewportElement.appendChild(this.canvas),this.ideogram_ctx=this.canvas.getContext("2d"),this.tooltip=document.createElement("div"),this.tooltip.className="igv-cytoband-tooltip",this.tooltip.style.height=`${this.viewportElement.clientHeight}px`,this.viewportElement.appendChild(this.tooltip),this.tooltipContent=document.createElement("div"),this.tooltip.appendChild(this.tooltipContent),this.tooltip.style.display="none",this.addMouseHandlers()}async getFeatures(e,t,i,r){return this.featureCache.containsRange(e)?this.featureCache.get(e):this.loadFeatures()}async loadFeatures(){const e=this.referenceFrame.chr,t=await this.referenceFrame.genome.getCytobands(e);return this.featureCache.set(e,t),t}repaint(){if(void 0===this.featureCache)return;const{width:e,height:t}=this.viewportElement.getBoundingClientRect();Co.configureHighDPICanvas(this.ideogram_ctx,e,t);const i=this.referenceFrame.chr,r=this.featureCache.get(i),s={context:this.ideogram_ctx,pixelWidth:e,pixelHeight:t,referenceFrame:this.referenceFrame,features:r};this.trackView.track.draw(s)}addMouseHandlers(){this.addViewportClickHandler(this.viewportElement),this.trackView.track.showCytobandNames&&(this.viewportElement.addEventListener("mousemove",this.mouseMove.bind(this)),this.viewportElement.addEventListener("mouseleave",this.mouseLeave.bind(this)))}mouseMove(e){const{x:t}=a(e,this.viewportElement),i=this.featureCache.get(this.referenceFrame.chr);if(i){const{width:e}=this.viewportElement.getBoundingClientRect(),r=e/i[i.length-1].end;let s=!1;for(let o=0;o=a&&t<=c){this.tooltipContent.textContent=n.name;const{width:t}=this.tooltipContent.getBoundingClientRect();const i=cr((a+c)/2-t/2,0,e-t);this.tooltip.style.left=`${i}px`,clearTimeout(Jh),Jh=setTimeout((()=>{this.tooltip&&(this.tooltip.style.display="none")}),1e4),this.tooltip.style.display="block",s=!0;break}}if(s)return}this.tooltip.style.display="none"}mouseLeave(e){this.tooltip.style.display="none"}addViewportClickHandler(e){this.boundClickHandler=function(e){const{xNormalized:t,width:i}=a(e,this.ideogram_ctx.canvas),{bpLength:r}=this.browser.genome.getChromosome(this.referenceFrame.chr),s=this.referenceFrame.bpPerPixel*i/r;let o=t;o-s/2<0&&(o=s/2);o+s/2>1&&(o=1-s/2);const n=Math.round((o-s/2)*r),c=Math.round((o+s/2)*r);this.referenceFrame.start=n,this.referenceFrame.end=c,this.referenceFrame.bpPerPixel=(c-n)/i,this.browser.updateViews(this.referenceFrame,this.browser.trackViews,!0)}.bind(this),e.addEventListener("click",this.boundClickHandler)}setWidth(e){this.viewportElement.style.width=e+"px"}renderSVGContext(e,{deltaX:t,deltaY:i},r=!0){const{width:s,height:o}=this.viewportElement.getBoundingClientRect(),a=`ideogram_referenceFrame_${this.browser.referenceFrameList.indexOf(this.referenceFrame)}_guid_${n()}`,c=t,l=this.contentTop+i,h=-this.contentTop;e.saveWithTranslationAndClipRect(a,c,l,s,o,h),this.trackView.track.draw({context:e,pixelWidth:s,pixelHeight:o,referenceFrame:this.referenceFrame,features:this.featureCache.get(this.referenceFrame.chr)}),e.restore()}startSpinner(){}stopSpinner(){}}class td{features=new Map;containsRange(e){return this.features.has(e)}set(e,t){this.features.set(e,t)}get(e){return this.features.get(e)}}function id(e,t,i,r){if("ruler"===e.track.type)return new Xh(e,t,i,r);if("ideogram"===e.track.id)return new ed(e,t,i,r);{const s=new Hh(e,t,i,r);return i.viewport=s,s}}const rd=["rgb(255, 0, 0)","rgb(0, 255, 0)","rgb(0, 0, 255)","rgb(255, 0, 255)","rgb(0, 255, 255)","rgb(128, 0, 128)","rgb(255, 165, 0)","rgb(255, 105, 180)","rgb(255, 127, 80)","rgb(220, 20, 60)","rgb(255, 99, 71)","rgb(173, 216, 230)","rgb(144, 238, 144)","rgb(224, 255, 255)","rgb(250, 250, 210)","rgb(152, 251, 152)","rgb(70, 130, 180)","rgb(102, 205, 170)"].map((e=>{const[t,i,r]=e.split(","),[s,o]=t.split("("),[n,a]=r.split(")");return[o,i,n]}));class sd{static emptySpaceReplacement="|";static colorForNA=Gr("magnesium");static sampleInfoFileHeaders=["#sampleTable","#sampleMapping","#colors"];constructor(e){e.tracks.some((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfoControl.setButtonVisibility(!0),this.initialize()}initialize(){this.sampleInfoFiles=[],this.attributeNames=[],this.sampleDictionary={},this.sampleMappingDictionary={},this.colorDictionary={},this.attributeRangeLUT={},this.initialized=!1}get attributeCount(){return this.attributeNames?this.attributeNames.length:0}isInitialized(){return this.initialized}hasAttributes(){return this.attributeCount>0}getAttributes(e){const t=this.sampleMappingDictionary[e]||e;return this.sampleDictionary[t]}getAttributeValue(e,t){const i=this.getAttributes(e);return i?i[t]:void 0}async loadSampleInfo(e){if(e.url)await this.loadSampleInfoFile(e.url);else{const t={...e};for(const[e,i]of Object.entries(t))t[e]=sd.toNumericalRepresentation(i);const[i]=Object.values(t),r=Object.keys(i);this.loadSampleInfoHelper(r,t)}this.initialized=!0}loadSampleInfoHelper(e,t){const i=function(e,t){const i={};for(const r of Object.values(t))for(const t of e){let e=r[t];void 0===i[t]&&(i[t]=[]),i[t].push(e)}const r=e=>"number"==typeof e,s=e=>"string"==typeof e;for(const e of Object.keys(i)){const t=i[e],o=new Set(t),n=Array.from(o);if(!0===n.some(s)&&!0===n.some(r)?i[e]=n.filter((e=>!s(e))):i[e]=n,!i[e].some(s)){const t=i[e].slice();i[e]=[Math.min(...t),Math.max(...t)]}}return i}(e,t);od(this.attributeRangeLUT,i);const r=new Set(this.attributeNames);for(const t of e)r.has(t)||this.attributeNames.push(t);od(this.sampleDictionary,t)}async loadSampleInfoFile(e){const t=await Rr.loadString(e);this.#w(t),this.sampleInfoFiles.push(e)}discard(){this.initialize()}getAttributeColor(e,t){let i;if("-"===t)i=Gr("snow");else if("string"==typeof t&&this.colorDictionary[t])i=this.colorDictionary[t]();else if(this.colorDictionary[e])i=this.colorDictionary[e](t);else if("string"==typeof t)i="NA"===t?sd.colorForNA:sd.stringToRGBString(t);else{const[r,s]=this.attributeRangeLUT[e],o=.2,n=Math.max((t-r)/(s-r),o),[a,c,l]=rd[Object.keys(this.attributeRangeLUT).indexOf(e)];i=`rgba(${a},${c},${l},${n})`}return i}sortSampleKeysByAttribute(e,t,i){const r=e.filter((e=>{const i=this.getAttributes(e);if(void 0===i)return!1;return"number"==typeof i[t]})),s=e.filter((e=>{const i=this.getAttributes(e);if(void 0===i)return!1;return"string"==typeof i[t]})),o=(e,r)=>{const s=this.getAttributes(e)[t],o=this.getAttributes(r)[t];return"string"==typeof s&&"string"==typeof o?i*s.localeCompare(o):"number"==typeof s&&"number"==typeof o?i*(s-o):void 0};return r.sort(o),s.sort(o),-1===i?[...r,...s]:[...s,...r]}#w(e){const t=function(e){const t={},i=e.split(/\r?\n|\r/).map((e=>e.trim())).filter((e=>""!==e));let r;sd.sampleInfoFileHeaders.includes(i[0])||(r="#sampleTable",t[r]=[]);for(const e of i)sd.sampleInfoFileHeaders.includes(e)?(r=e,t[r]=[]):r&&!1===e.startsWith("#")&&t[r].push(e);return t}(e);for(const[e,i]of Object.entries(t))switch(e){case"#sampleTable":this.#b(i);break;case"#sampleMapping":this.#F(i);break;case"#colors":this.#v(i)}}#b(e){const t=e.shift().split("\t").filter((e=>e.length>0));t.shift();const i=t.map((e=>e.split(" ").join(sd.emptySpaceReplacement))),r=e.filter((e=>e.length>0));let s;for(const e of r){const t=e.split("\t"),r=t.shift();void 0===s&&(s={}),s[r]={};for(let e=0;e{let r;switch(t){case 0:r=e.split(" ").join(sd.emptySpaceReplacement);break;case 1:r=e.includes(":")?e.split(":").map((e=>parseFloat(e))):e;break;case 2:case 3:r=`rgb(${e})`}return r},i=e.map((e=>e.split("\t").map(t))),r=i.filter((e=>3===e.length&&!e.includes("*"))).filter((([e,t,i])=>!Array.isArray(t))),s={};for(const e of r){const[t,i,r]=e;void 0===s[t]&&(s[t]={}),s[t][i.toUpperCase()]=r}for(const[e,t]of Object.entries(s)){const i=Object.assign({},t);this.colorDictionary[e]=e=>{const t=e.toUpperCase();return i[t]||Gr("snow")}}const o=i.filter((e=>Array.isArray(e[1])));for(const e of o){const[t,i]=e[1],r=e[0];if(3===e.length){const[s,o,n]=Xr(e[2]);this.colorDictionary[r]=e=>{e=cr(e,t,i);return Zr(s,o,n,(e-t)/(i-t))}}else if(4===e.length){const[t,i]=e[1],[r,s,o,n]=e;this.colorDictionary[r]=e=>{e=cr(e,t,i);return Jr(o,n,(e-t)/(i-t))}}}const n=i.filter((e=>3===e.length&&e.includes("*")));for(const e of n)if("*"===e[1]){const[t,i,r]=e;this.colorDictionary[t]=e=>{if("NA"===e)return sd.colorForNA;{const[i,s]=this.attributeRangeLUT[t],o=(e-i)/(s-i),[n,a,c]=Xr(r);return Zr(n,a,c,o)}}}else if("*"===e[0]){const[t,i,r]=e;this.colorDictionary[i]=()=>r}}static toNumericalRepresentation(e){const t=Object.assign({},e);for(const[e,i]of Object.entries(t))"string"!=typeof i||isNaN(i)||(t[e]=Number(i));return t}static stringToRGBString(e){let t=0;for(let i=0;i>8*e&255;i.push(r)}return`rgb(${i.join(", ")})`}export(){const e={},t=Object.fromEntries(Object.entries(this.sampleMappingDictionary).map((([e,t])=>[t,e])));for(const i of Object.keys(this.sampleDictionary)){const r=t[i]||i,s=this.getAttributes(i);s&&(e[r]=s)}console.log(JSON.stringify(e,null,2))}}function od(e,t){for(const[i,r]of Object.entries(t))i in e&&e[i]===r||(e[i]=r)}const nd=16,ad=F;class cd{constructor(e){this.browser=e,this.height=40,this.name="",this.disableButtons=!0,this.ignoreTrackMenu=!0,this.order=.01*Number.MIN_SAFE_INTEGER,this.removable=!1,this.type="ruler",this.id="ruler"}async getFeatures(e,t,i){return[]}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,bpPerPixel:s,bpStart:o}){Dh.isWholeGenomeView(t.chr)?this.drawWholeGenome({context:e,pixelWidth:i,pixelHeight:r,bpPerPixel:s}):this.doDraw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,bpStart:o})}drawWholeGenome({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:r}){e.save(),Co.fillRect(e,0,0,t,i,{fillStyle:"white"});for(let t of this.browser.genome.wgChromosomeNames){let s=this.browser.genome.getCumulativeOffset(t),o=this.browser.genome.getChromosome(t).bpLength,n=Math.round(s/r),a=Math.round(o/r);this.renderChromosomeRect(e,n,0,a,i,t)}e.restore()}doDraw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,bpStart:s}){e.clearRect(0,0,i,r);const o=function(e,t){if(e<10)return new ld(1,"bp",1);const i=Math.floor(Math.log10(e));let r="bp",s=1;i>9?(r="gb",s=1e9):i>6?(r="mb",s=1e6):i>3&&(r="kb",s=1e3);const o=Math.pow(10,i-1),n=e/o,a=75,c=Math.pow(10,i-1),l=Math.pow(10,i)/2;return new ld(n0&&u+c<=d&&(Co.fillText(e,i,r,this.height-8),d=0),l>0&&Co.strokeLine(e,l,this.height-6,l,this.height-2),h=Math.floor((1+n)*o.majorTick);let f=l+(Math.round(t.toPixels(h-1-s+.5))-l)/2;f>0&&Co.strokeLine(e,f,this.height-6,f,this.height-2),++n,d+=a}while(le.measureText(n).width&&Co.fillText(e,n,t+r/2,i+s/2,{fillStyle:ur.greyScale(68)})}get supportsWholeGenome(){return!0}dispose(){}}class ld{constructor(e,t,i){this.majorTick=e,this.minorTick=e/10,this.majorUnit=t,this.unitMultiplier=i}description(e){console.log((e||"")+" tick "+ad(this.majorTick)+" label width "+ad(this.labelWidthBP)+" multiplier "+this.unitMultiplier)}}const hd=16;function dd(e,t){const i=new Set(e.attributeNames),r=t[0];if(void 0===e.getAttributes(r))return!1;{const t=Object.keys(e.getAttributes(r));for(const e of t)if(!1===i.has(e))return!1}return!0}function ud(e,t,i,r,s,o,n){if(!n||0===n.size)return;const a=t+r;e.save(),e.fillStyle="black";let c=s+8;c>t&&Co.dashedLine(e,0,c,i,c);for(const r of n.values()){if(c+=r.count*o+hd,c>a)break;c>t&&Co.dashedLine(e,0,c,i,c)}e.restore()}class fd{constructor(e,i,r){this.guid=n(),this.trackView=e,this.isIdeogram="ideogram"===e.track.type,this.browser=e.browser,this.viewport=t({class:"igv-viewport"}),i.appendChild(this.viewport),this.viewport.style.height=`${e.track.height}px`,this.isIdeogram&&(this.viewport.style.zIndex=16,this.viewport.style.overflow="visible"),this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.ctx.font="10px verdana",this.contentTop=0,this.hitList=void 0,this.setWidth(r),this.addMouseHandlers()}resizeCanvas(){const e=window.devicePixelRatio,t=this.browser.getSampleInfoViewportWidth();let i;if(this.browser.trackViews.length>1&&this.isIdeogram){const[e,t]=[this.browser.ideogramTrackView.track,this.browser.rulerTrackView.track];i=e.height+t.height}else i=this.viewport.clientHeight;if(this.canvas.width!==t*e||this.canvas.height!==i*e){const r=this.canvas;r.width=t*e,r.height=i*e,r.style.width=`${t}px`,r.style.height=`${i}px`,this.ctx=this.canvas.getContext("2d"),this.ctx.scale(e,e),this.isIdeogram&&Co.fillRect(this.ctx,0,0,this.ctx.canvas.width,this.ctx.canvas.height,{fillStyle:Gr("snow")})}}setTop(e){"function"==typeof this.trackView.track.getSamples&&(this.contentTop=e,this.repaint())}setWidth(e){this.viewport.innerWidth=e,this.resizeCanvas()}setHeight(e){const t=this.browser.getSampleInfoViewportWidth();this.viewport.style.width=`${t}px`,this.viewport.style.height=`${e}px`;const i=window.devicePixelRatio;this.canvas.width=t*i,this.canvas.height=e*i,this.canvas.style.width=`${t}px`,this.canvas.style.height=`${e}px`,this.ctx=this.canvas.getContext("2d"),this.ctx.scale(i,i),this.isIdeogram&&Co.fillRect(this.ctx,0,0,this.ctx.canvas.width,this.ctx.canvas.height,{fillStyle:Gr("snow")})}repaint(){if(this.resizeCanvas(),this.isIdeogram&&(this.browser.rulerTrackView&&this.browser.rulerTrackView.setTrackHeight(!0===this.browser.sampleInfoControl.showSampleInfo?this.calculateSampleInfoColumnHeight():40,!0),this.renderSampleInfoColumns(this.ctx)),"function"==typeof this.trackView.track.getSamples){const e=this.trackView.track.getSamples();e.names&&e.names.length>0&&this.draw({context:this.ctx,samples:e})}}calculateSampleInfoColumnHeight(){const e=this.browser.sampleInfo.attributeNames.map((e=>this.ctx.measureText(e).width));return 4+Math.min(Math.max(...e),128)}draw({context:e,samples:t}){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillStyle=Gr("snow"),e.fillRect(0,0,e.canvas.width,e.canvas.height);const i=this.viewport.getBoundingClientRect().height,r=this.viewport.getBoundingClientRect().width;if(t&&t.names.length>0){const s=this.browser.sampleInfo.attributeNames;let o=1;const n=t.height;o=n-2*o<=1?0:1;let a=t.yOffset-this.contentTop,c=0;this.hitList={};for(const r of t.names){const l=this.browser.sampleInfo.getAttributes(r);if(l){let r=a+o;if(t.groupIndeces&&t.groups.size>0&&(r+=(t.groupIndeces[c]+1)*hd),r>i)break;if(r+n>0){const t=n-2*o,i=Object.entries(l);for(const o of i){const[i,n]=o,a=8+s.indexOf(i)*nd;e.fillStyle=this.browser.sampleInfo.getAttributeColor(i,n),e.fillRect(a,r,15,t);const c=`${Math.floor(a)}#${Math.floor(r)}#16#${Math.ceil(t)}`;this.hitList[c]=`${i}#${n}`}}}a+=n,c++}ud(e,0,r,i,t.yOffset-this.contentTop,t.height,t.groups)}}renderSampleInfoColumns(e){const t=(e,t,i,r,s,o)=>{e.save(),e.font="10px verdana",e.translate(i+s/2,r+o),e.rotate(-Math.PI/2),e.textAlign="left",e.fillStyle=Gr("lead"),e.fillText(t,2,2),e.restore()},i=this.browser.sampleInfo.attributeNames;this.hitList={};for(let r=0;r{const{marginTop:r}=window.getComputedStyle(i),{x:s,y:o}=a(e,this.browser.columnContainer.querySelector(".igv-sample-info-column"));return{x:Math.floor(s),y:Math.floor(o-parseInt(r,10))}},r=this.browser.columnContainer.querySelector(".igv-sample-info-column"),{x:s,y:o}=i(r,this.viewport);r.setAttribute("title","");for(const[e,i]of t){const[t,n,a,c]=e.split("#").map((e=>parseInt(e,10)));if(!(st+a||on+c)){r.setAttribute("title",`${i}`);break}}}else{const{x:i,y:r}=a(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,s]of t){const[t,o,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+n||ro+a)){const[e,t]=s.split("#");this.viewport.setAttribute("title",`${e.split(sd.emptySpaceReplacement).join(" ")}: ${"-"===t?"":t}`);break}}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}addMouseClickHandler(){this.boundMouseClickHandler=function(e){if(this.hitList){const t=Object.entries(this.hitList);if(this.isIdeogram){const i=(t,i)=>{const{marginTop:r}=window.getComputedStyle(i),{x:s,y:o}=a(e,this.browser.columnContainer.querySelector(".igv-sample-info-column"));return{x:Math.floor(s),y:Math.floor(o-parseInt(r,10))}},r=this.browser.columnContainer.querySelector(".igv-sample-info-column"),{x:s,y:o}=i(r,this.viewport);for(const[e,i]of t){const[t,r,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(st+n||or+a)){const e=this.browser.findTracks((e=>"function"==typeof e.sortByAttribute));for(const t of e)t.sortByAttribute(i);break}}}else{const{x:i,y:r}=a(e,this.viewport);for(const[e,s]of t){const[t,o,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+n||ro+a)){s.split("#");break}}}}}.bind(this),this.viewport.addEventListener("click",this.boundMouseClickHandler)}removeMouseHandlers(){this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler),this.viewport.removeEventListener("click",this.boundMouseClickHandler)}dispose(){this.removeMouseHandlers(),this.viewport.remove()}show(){this.viewport.style.display="block"}hide(){this.viewport.style.display="none"}}class pd{constructor(e,i,r,s){this.guid=n(),this.trackView=e,this.browser=e.browser,this.viewport=t({class:"igv-viewport"}),i.appendChild(this.viewport),e.track.height&&(this.viewport.style.height=`${e.track.height}px`),this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.contentTop=0,this.hitList=void 0,this.setWidth(s),this.addMouseHandlers()}checkCanvas(){let e=0;!0===this.browser.showSampleNames&&(e=void 0===this.browser.sampleNameViewportWidth?0:this.browser.sampleNameViewportWidth),this.ctx.canvas.width=e*window.devicePixelRatio,this.ctx.canvas.style.width=`${e}px`,this.ctx.canvas.height=this.viewport.clientHeight*window.devicePixelRatio,this.ctx.canvas.style.height=`${this.viewport.clientHeight}px`,this.ctx.scale(window.devicePixelRatio,window.devicePixelRatio)}setTop(e){if("function"==typeof this.trackView.track.getSamples){this.contentTop=e;const t=this.trackView.track.getSamples();this.repaint(t)}}setWidth(e){this.viewport.innerWidth=e,this.checkCanvas()}async repaint(e){if(e.names.length>0&&!0===this.browser.showSampleNames&&(this.checkCanvas(),this.draw({context:this.ctx,samples:e}),void 0===this.browser.sampleNameViewportWidth)){const t=e.names.map((e=>this.ctx.measureText(e).width));this.browser.sampleNameViewportWidth=Math.min(200,4+Math.ceil(Math.max(...t))),this.browser.layoutChange()}}draw({context:e,samples:t}){if(Co.fillRect(e,0,0,e.canvas.width,t.height,{fillStyle:Gr("snow")}),t&&t.names.length>0){const i=this.viewport.getBoundingClientRect().height,r=t.height,s=r-2<=1?0:1;let o=t.yOffset-this.contentTop,n=0;this.hitList={};for(const a of t.names){const c=0;let l=o+s;if(t.groupIndeces&&t.groups.size>0&&(l+=(t.groupIndeces[n]+1)*hd),l+r>0){const t=r-2*s;gd(e,a,c+2,l,e.canvas.width,t)}if(o+=r,n++,o>i)break}ud(e,0,e.canvas.width,e.canvas.height,t.yOffset-this.contentTop,t.height,t.groups)}}renderSVGContext(e,{deltaX:t,deltaY:i}){if("function"==typeof this.trackView.track.getSamples){const r=this.trackView.track.getSamples(),s=0,{width:o,height:a}=this.viewport.getBoundingClientRect(),c=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_sample_names_guid_${n()}`;e.saveWithTranslationAndClipRect(c,t,i+s,o,a,-s),this.draw({context:e,samples:r}),e.restore()}}addMouseHandlers(){this.boundClickHandler=function(e){e.preventDefault();const t={label:"Name Panel Width",value:this.browser.sampleNameViewportWidth,callback:e=>{this.browser.sampleNameViewportWidth=parseInt(e),this.browser.layoutChange()}};this.browser.inputDialog.present(t,e)}.bind(this),this.viewport.addEventListener("contextmenu",this.boundClickHandler),this.boundMouseMoveHandler=function(e){if(this.hitList){const t=Object.entries(this.hitList),{x:i,y:r}=a(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,s]of t){const[t,o,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+n||ro+a)){this.viewport.setAttribute("title",`${s}`);break}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}removeMouseHandlers(){this.viewport.removeEventListener("contextmenu",this.boundClickHandler),this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler)}dispose(){this.removeMouseHandlers(),this.viewport.remove()}}function gd(e,t,i,r,s,o){const n=Math.min(o,10);e.font=`${n}px sans-serif`,e.textAlign="start",e.fillStyle=Gr("lead");const a=i,c=e.measureText(t),l=r+o/2+(c.actualBoundingBoxAscent+c.actualBoundingBoxDescent)/2;e.fillText(t,a,l)}class md{constructor(e){this.popover=t({class:"igv-menu-popup"}),e.appendChild(this.popover),this.parent=e;const i=t({class:"igv-menu-popup-header"});this.popover.appendChild(i),u(i,(()=>this.popover.style.display="none")),this.popoverContent=t(),this.popover.appendChild(this.popoverContent),p(this.popover,i),i.addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault()})),this.popover.style.display="none"}presentMenuList(e,t,i){if(wd(this.parent),t.length>0){this.popoverContent.innerHTML="";const r=this.parseMenuList(e,t);for(let e of r)e.init&&e.init(),0===r.indexOf(e)&&e.element.classList.remove("igv-track-menu-border-top"),e.element.classList.contains("igv-track-menu-border-top")||e.element.classList.contains("igv-menu-popup-check-container")||"div"===e.element.tagName.toLowerCase()&&e.element.classList.add("igv-menu-popup-shim"),this.popoverContent.appendChild(e.element);this.popover.style.display="flex";const{width:s}=this.popover.getBoundingClientRect();"left"===i.gearColumnPosition?this.popover.style.right=`${s}px`:this.popover.style.left=-s+"px",this.popover.style.top="0px"}}parseMenuList(e,t){return t.map(((t,i)=>{let r;if(t.name)r=document.createElement("div"),r.textContent=t.name;else if(t.element)r=t.element;else if("string"==typeof t.label)r=document.createElement("div"),r.innerHTML=t.label;else if("string"==typeof t)if(t.startsWith("<")){const e=document.createElement("div");e.innerHTML=t,r=e.firstChild}else r=document.createElement("div"),r.textContent=t;if(0===i&&r.classList.add("igv-track-menu-border-top"),t.click||t.dialog){const i=i=>{if(i.preventDefault(),i.stopPropagation(),t.click)if(e.track.selected){const r=e.browser.getSelectedTrackViews();if(!0===t.doAllMultiSelectedTracks)t.click.call(e.track,i);else if("removeTrack"===t.menuItemType){const s=()=>{e.browser.overlayTrackButton.setVisibility(!1);for(const{track:e}of r)t.click.call(e,i)},o={html:`Are you sure you want to delete ${r.length} tracks?`,callback:s};e.browser.menuUtils.dialog.present(o,i)}else for(const{track:e}of r)t.click.call(e,i)}else t.click.call(e.track,i);else t.dialog&&t.dialog.call(e.track,i);this.popover.style.display="none"};void 0===r&&console.log("element is undefined"),r.addEventListener("click",i),r.addEventListener("touchend",(e=>i(e))),r.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}return{element:r,init:t.init||void 0}}))}presentTrackContextMenu(e,i){this.popoverContent.innerHTML="";const s=function(e,i){return e.map((e=>{let s;if("string"==typeof e&&"
"===e)s=document.createElement("hr");else if("string"==typeof e)s=t({class:"context-menu"}),s.innerHTML=e;else if("Node"==typeof e)s=e;else if("function"==typeof e.init&&e.init(),"checkbox"===e.type?s=ua("Show all bases",e.value):(s=t({class:"context-menu"}),"string"==typeof e.label&&(s.innerHTML=e.label)),e.click&&"color"!==e.type){function o(t){e.click(),r(i),t.preventDefault(),t.stopPropagation()}s.addEventListener("click",o),s.addEventListener("touchend",o),s.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}return{el:s,init:e.init}}))}(i,this.popover);for(let{el:e}of s)this.popoverContent.appendChild(e);!function(e,t){t.style.display="flex";const{x:i,y:r}=a(e,t.parentNode),{width:s}=t.getBoundingClientRect(),o=i+s,{width:n}=t.parentNode.getBoundingClientRect();t.style.left=`${o>n?i-(o-n):i}px`,t.style.top=`${r}px`}(e,this.popover)}hide(){this.popover.style.display="none"}dispose(){this.popoverContent.innerHTML="",this.popover.innerHTML="",Object.keys(this).forEach((function(e){this[e]=void 0}))}}const wd=e=>{const t=e.querySelectorAll(".igv-menu-popup");for(const e of t)e.style.display="none"};class bd{constructor(e,i,r,s,o,n,a){this.browser=i,this.button=t({class:"igv-navbar-text-button"}),e.appendChild(this.button),Array.isArray(r)?(this.textContent=r[0],this.title=r[1]):this.textContent=this.title=r,this.buttonLabel=s,this.imageDictionary={image:`url("data:image/svg+xml,${encodeURIComponent(o)}")`,imageHover:`url("data:image/svg+xml,${encodeURIComponent(n)}")`},this.responsiveKey="text",this.configureButton(this.textContent,this.title),this.setState(a),i.on("navbar-resize",(e=>{this.navbarResizeHandler(e)}))}navbarResizeHandler(e){const t="igv-navbar-icon-button"===e?"image":"text";t!==this.responsiveKey&&(this.responsiveKey=t,this.configureButton(this.textContent,this.title),this.setState(void 0))}configureButton(e,t){this.groupElement=void 0,this.button.title=t,this.button.innerHTML="",this.button.style.backgroundImage="none",this.button.classList.remove("igv-navbar-icon-button"),this.button.classList.remove("igv-navbar-text-button"),"text"===this.responsiveKey?this.configureTextButton(e):this.configureIconButton()}configureTextButton(e){this.button.classList.add("igv-navbar-text-button");const t=document.createElement("div");t.innerHTML=this.buttonLabel;const i=t.firstChild;this.button.appendChild(i),this.groupElement=i.querySelector("#igv-navbar-button-group");i.querySelector("#igv-navbar-button-label").textContent=e}configureIconButton(){this.button.classList.add("igv-navbar-icon-button")}setState(e){void 0!==e&&(this.doHover=e),"text"===this.responsiveKey?this.setTextButtonState(this.doHover):this.setIconButtonState(this.doHover)}setTextButtonState(e){this.groupElement.classList.remove(...this.groupElement.classList);const t=!0===e?"igv-navbar-text-button-svg-hover":"igv-navbar-text-button-svg-inactive";this.groupElement.classList.add(t)}setIconButtonState(e){this.button.style.backgroundImage=!0===e?this.imageDictionary.imageHover:this.imageDictionary.image}show(){this.button.style.display=""}hide(){this.button.style.display="none"}setVisibility(e){!0===e?this.show():this.hide()}}const Fd='\n \n \n \n \n \n \n \n \n';class vd extends ma{static defaults={autoscale:void 0,alpha:.5,height:50};constructor(e,t,i){super(e,t),this.type="merged",this.paintAxis=Oc,this.graphType=e.graphType,this.tracks=i||[]}async postInit(){if(this.config.tracks){for(let e of this.config.tracks){const t=await this.browser.createTrack(e);t?this.tracks.push(t):console.warn("Could not create track "+e),"function"==typeof t.postInit&&await t.postInit()}this.config.tracks.every((e=>void 0!==e.autoscale||void 0!==e.max))||(this.config.autoscale=void 0===this.config.max)}for(let e of this.tracks)e.isMergedTrack=!0;if(this.config.autoscale?this.autoscale=this.config.autoscale:void 0!==this.config.max&&this.setDataRange({min:this.config.min||0,max:this.config.max}),void 0!==this.config.flipAxis)for(let e of this.tracks)e.flipAxis=this.config.flipAxis;if(void 0!==this.config.logScale)for(let e of this.tracks)e.logScale=this.config.logScale;this.resolutionAware=this.tracks.some((e=>e.resolutionAware))}set flipAxis(e){this.config.flipAxis=e;for(let t of Ad(this.tracks))t.flipAxis=e}get flipAxis(){return Ad(this.tracks).every((e=>e.flipAxis))}set logScale(e){this.config.logScale=e;for(let t of Ad(this.tracks))t.logScale=e}get logScale(){return Ad(this.tracks).every((e=>e.logScale))}get height(){return this._height}set height(e){if(this.config.height=e,this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}set autoscale(e){if(this._autoscale=e,!1===e&&this.tracks)for(let e of this.tracks)e.autoscale=!1}get autoscale(){return this._autoscale}set autoscaleGroup(e){if(this.tracks)for(let t of this.tracks)t.autoscaleGroup=e}get autoscaleGroup(){if(this.tracks&&this.tracks.length>0){const e=this.tracks[0].autoscaleGroup;return this.tracks.some((t=>e!==t.autoscaleGroup))?void 0:e}}setDataRange({min:e,max:t}){this.autoscale=!1;for(const i of Ad(this.tracks))i.dataRange={min:e,max:t},i.autoscale=!1,i.autoscaleGroup=!1}set dataRange({min:e,max:t}){for(const i of Ad(this.tracks))i.dataRange={min:e,max:t}}get dataRange(){if(this.tracks){const e=Ad(this.tracks);if(e.length>0){const t=e[0].dataRange;if(e.every((e=>e.dataRange&&e.dataRange.min===t.min&&e.dataRange.max===t.max)))return t}}}menuItemList(){const e=[];return Ad(this.tracks).length>0&&(void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:function(){this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e.push(...this.numericDataMenuItems())),e.push("
"),e.push(this.overlayTrackAlphaAdjustmentMenuItem()),e.push(this.trackSeparationMenuItem()),e}async getFeatures(e,t,i,r){const s=this.tracks.map((s=>s.getFeatures(e,t,i,r))),o=await Promise.all(s);if(o.every((e=>0===e.length)))return new yd([],[]);{const e=this.tracks.map((e=>e.name));return new yd(o,e)}}draw(e){const t=e.features;for(let i=0,r=this.tracks.length;i0&&i.push("
"),i.push(`
${t[s].trackName}
`),t[s].features.length>0){r=!1;const o=this.tracks[s].popupData(e,t[s].features);i.push(...o)}else i.push("Missing or 0 value(s)");return!0===r?[]:i}}clickedFeatures(e){const t=e.viewport.cachedFeatures;if(!t||!t.featureArrays||!Array.isArray(t.featureArrays)||0===t.featureArrays.length)return[];const i=e.genomicLocation,r=[],s=e.referenceFrame.bpPerPixel>.2?3*e.referenceFrame.bpPerPixel:.2,o=i-s,n=i+s;for(let e=0;ee.supportsWholeGenome))}getState(){const e=super.getState(),t=[];for(let e of this.tracks)t.push(e.getState());return e.tracks=t,e}updateScales(e){let t;if(this.autoscale){t=!0;let i=[];for(let t of e){if(t.featureCache&&t.featureCache.features){const e=t.referenceFrame,r=e.start,s=r+e.toBP(t.getWidth()),o=t.featureCache.features;this.autoscale&&(i.push({value:o.getMax(r,s)}),i.push({value:o.getMin(r,s)}))}const e=is(i);for(const t of Ad(this.tracks))t.dataRange=e}}else{let i=-1;for(let r of this.tracks)if(++i,r.autoscale){t=!0;let s=[];for(let t of e)if(t.featureCache&&t.featureCache.features){const e=t.referenceFrame,r=e.start,o=r+e.toBP(t.getWidth()),n=t.featureCache.features.featureArrays[i];if(n)for(let e of n)if(!(e.endo)break;s.push(e)}}r.dataRange=is(s)}}return t}overlayTrackAlphaAdjustmentMenuItem(){const e=t();return e.innerText="Set transparency",{element:e,dialog:function(e){const t={label:"Transparency",value:this.alpha,min:0,max:1,scaleFactor:1e3,callback:e=>{this.alpha=Math.max(.001,e),this.repaintViews()}};this.browser.sliderDialog.present(t,e)}}}trackSeparationMenuItem(){let e=document.createElement("div");return e.textContent="Separate tracks",{element:e,click:async function(e){const t=this.autoscale,i=this.name,r=this.tracks,s=this.browser,o=this.order;s.removeTrack(this);for(let e of r)e.order=o,t&&(e.autoscaleGroup=i),e.isMergedTrack=!1,s.addTrack(e);await s.updateViews(),s.reorderTracks()}}}}class yd{constructor(e,t){this.featureArrays=e,this.trackNames=t}getMax(e,t){let i=-Number.MAX_VALUE;for(let r of this.featureArrays)if(Array.isArray(r))for(let s of r)if(!(void 0===s.value||Number.isNaN(s.value)||s.endt)break;i=Math.max(i,s.value)}return i!==-Number.MAX_VALUE?i:100}getMin(e,t){let i=0;for(let r of this.featureArrays)if(Array.isArray(r))for(let s of r)if(void 0!==s.value&&!Number.isNaN(s.value)){if(s.endt)break;i=Math.min(i,s.value)}return i}}const Ad=e=>e?e.filter((e=>void 0!==e.dataRange||void 0!==e.autoscale||void 0!==e.autoscaleGroup)):[];class Cd extends bd{constructor(e,t){super(e,t,"Overlay Tracks",Fd,'\n Overlay Tracks\n \n \n \n \n \n \n \n \n \n \n \n \n \n','\n Overlay Tracks Hover\n \n \n \n \n \n \n \n \n \n \n \n \n \n',!1),this.button.addEventListener("mouseenter",(()=>this.setState(!0))),this.button.addEventListener("mouseleave",(()=>this.setState(!1)));this.boundMouseClickHandler=(()=>{this.setVisibility(!1),_d.call(this)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(!0)}}async function _d(e){if(!0===xd(this.browser)){const e=this.browser.getSelectedTrackViews().map((({track:e})=>e));for(const t of e)t.selected=!1;const t=[];for(let i of e)"merged"===i.type?t.push(...i.tracks):t.push(i);const i={name:"Overlay",type:"merged",autoscale:!1,alpha:.5,height:Math.max(...e.map((({height:e})=>e))),order:Math.min(...e.map((({order:e})=>e)))},r=new vd(i,this.browser,t);for(const t of e){const e=this.browser.trackViews.indexOf(t.trackView);this.browser.trackViews.splice(e,1),t.trackView.dispose()}this.browser.addTrack(r),await r.trackView.updateViews(),this.browser.reorderTracks()}}function xd(e){const t=e.getSelectedTrackViews();if(t&&t.length>1){const e=new Set(["wig","merged"]);return t.filter((({track:t})=>e.has(t.type))).length>1}return!1}const kd=new Set(["sequence","ruler","ideogram"]),Id=new Set(["ruler","sequence","ideogram"]);class Sd{constructor(e,t,i){this.namespace=`trackview-${n()}`,this.browser=e,this.track=i,i.trackView=this,this.addDOMToColumnContainer(e,t,e.referenceFrameList)}startSpinner(){this.viewports&&this.viewports.length>0&&this.viewports[0].startSpinner()}stopSpinner(){this.viewports&&this.viewports.length>0&&this.viewports[0].stopSpinner()}addDOMToColumnContainer(e,t,i){this.axis=this.createAxis(e,this.track),this.createViewports(e,t,i),this.sampleInfoViewport=new fd(this,e.columnContainer.querySelector(".igv-sample-info-column"),e.getSampleInfoViewportWidth()),this.sampleNameViewport=new pd(this,e.columnContainer.querySelector(".igv-sample-name-column"),void 0,e.getSampleNameViewportWidth()),this.createTrackScrollbar(e),this.createTrackDragHandle(e),this.createTrackGearPopup(e)}createViewports(e,t,i){this.viewports=[];const r=e.calculateViewportWidth(i.length),s=t.querySelectorAll(".igv-column");for(let e=0;e0?this.viewports[this.viewports.length-1]:void 0}createAxis(e,i){const r=e.columnContainer.querySelector(".igv-axis-column");if(!r)return;const s=t();if(this.axis=s,r.appendChild(s),s.dataset.tracktype=i.type,s.style.height=`${i.height}px`,"function"==typeof i.paintAxis){const{width:e,height:t}=s.getBoundingClientRect();this.axisCanvas=document.createElement("canvas"),this.axisCanvas.style.width=`${e}px`,this.axisCanvas.style.height=`${t}px`,s.appendChild(this.axisCanvas)}if(!1===Md.has(this.track.type)){this.trackSelectionContainer=t(),s.appendChild(this.trackSelectionContainer);const e='',i=document.createRange().createContextualFragment(e).firstChild;this.trackSelectionContainer.appendChild(i),i.checked=this.track.selected||!1,i.addEventListener("change",(e=>{e.preventDefault(),e.stopPropagation(),this.track.selected=e.target.checked,this.setDragHandleSelectionState(e.target.checked),this.browser.overlayTrackButton.setVisibility(xd(this.browser))})),this.enableTrackSelection(!1)}return s}resizeAxisCanvas(e,t){this.axis.style.width=`${e}px`,this.axis.style.height=`${t}px`,"function"==typeof this.track.paintAxis&&(this.axisCanvas.style.width=`${e}px`,this.axisCanvas.style.height=`${t}px`)}renderSVGContext(e,{deltaX:t,deltaY:i}){!function(e,t,i,r,s){if("function"==typeof t.paintAxis){const{y:o,width:a,height:c}=i.getBoundingClientRect(),l=`${(t.name||t.id).replace(/\W/g,"")}_axis_guid_${n()}`;e.saveWithTranslationAndClipRect(l,r,o+s,a,c,0),t.paintAxis(e,a,c),e.restore()}}(e,this.track,this.axisCanvas,t,i);const{width:r}=this.axis.getBoundingClientRect(),{y:s}=this.viewports[0].viewportElement.getBoundingClientRect();let o={deltaX:r+t,deltaY:s+i};for(let t of this.viewports){t.renderSVGContext(e,o);const{width:i}=t.viewportElement.getBoundingClientRect();o.deltaX+=i}if(!0===this.browser.sampleInfo.isInitialized()&&!0===this.browser.sampleInfoControl.showSampleInfo){this.sampleInfoViewport.renderSVGContext(e,o);const{width:t}=this.sampleInfoViewport.viewport.getBoundingClientRect();o.deltaX+=t}!0===this.browser.showSampleNames&&this.sampleNameViewport.renderSVGContext(e,o)}presentColorPicker(e,t){if(!1===Id.has(this.track.type)){let i,r;i="color"===e?this.track._initialColor||this.track.constructor.defaultColor:this.track._initialAltColor||this.track.constructor.defaultColor;const s=this.browser.getSelectedTrackViews();r=s.length>0&&new Set(s).has(this)?{color:e=>{for(const t of s)t.track.color=e,t.repaintViews()},altColor:e=>{for(const t of s)t.track.altColor=e,t.repaintViews()}}:{color:e=>{this.track.color=qr(e),this.repaintViews()},altColor:e=>{this.track.altColor=qr(e),this.repaintViews()}};const o="color"===e?this.track.color||this.track.constructor.defaultColor:this.track.altColor||this.track.constructor.defaultColor;this.browser.genericColorPicker.configure(i,r[e],o),this.browser.genericColorPicker.present(t)}}setTrackHeight(e,t){t||(this.track.minHeight&&(e=Math.max(this.track.minHeight,e)),this.track.maxHeight&&(e=Math.min(this.track.maxHeight,e))),this.track.height=e,this.resizeAxisCanvas(this.axis.clientWidth,this.track.height),"function"==typeof this.track.paintAxis&&this.paintAxis();for(let t of this.viewports)t.setHeight(e);if(this.sampleInfoViewport.setHeight(e),this.sampleNameViewport.viewport.style.height=`${e}px`,"function"!=typeof this.track.computePixelHeight)for(let t of this.viewports)t.setContentHeight(e);this.repaintViews(),this.updateScrollbar(),this.dragHandle.style.height=`${e}px`,this.gearContainer.style.height=`${e}px`}updateScrollbar(){const e=this.viewports[0].viewportElement.clientHeight;if(this.outerScroll.style.height=`${e}px`,!1===kd.has(this.track.type)){const t=this.maxViewportContentHeight(),i=Math.round(e/t*e);t>e?(this.innerScroll.style.display="block",this.innerScroll.style.height=`${i}px`):this.innerScroll.style.display="none"}}setTop(e){for(let t of this.viewports)t.setTop(e);this.sampleInfoViewport.setTop(e),this.sampleNameViewport.setTop(e)}moveScroller(e){const t=this.innerScroll.offsetTop+e,i=Math.min(Math.max(0,t),this.outerScroll.clientHeight-this.innerScroll.clientHeight);this.innerScroll.style.top=`${i}px`;const r=this.maxViewportContentHeight(),s=Math.round(i*(r/this.viewports[0].viewportElement.clientHeight));this.setTop(s)}scrollByPixels(e){const t=this.viewports[0].getContentTop(),i=this.maxViewportContentHeight(),r=i-this.viewports[0].viewportElement.clientHeight,s=Math.min(Math.max(0,t+e),r);if(this.setTop(s),this.innerScroll){const e=this.viewports[0].viewportElement.clientHeight,t=Math.round(s*(e/i));this.innerScroll.style.top=`${t}px`}}repaintViews(){for(let e of this.viewports)e.isVisible()&&e.repaint();"function"==typeof this.track.paintAxis&&this.paintAxis(),this.repaintSampleInfo(),this.repaintSamples()}repaintSampleInfo(){this.sampleInfoViewport.repaint()}repaintSamples(){if("function"==typeof this.track.getSamples){const e=this.track.getSamples();e.names&&e.names.length>0&&this.sampleNameViewport.repaint(e)}}setTrackLabelName(e){this.viewports.forEach((t=>t.setTrackLabel(e)))}resize(e){for(let t of this.viewports)t.setWidth(e)}async updateViews(){if(!this.browser||!this.browser.referenceFrameList)return;const e=this.viewports.filter((e=>e.isVisible()));if(e.forEach((e=>e.shift())),this.browser.dragObject)return;const t=e.filter((e=>e.needsRepaint())).filter((e=>e.checkZoomIn())),i=e.filter((e=>e.checkZoomIn())).filter((e=>e.needsReload()));for(let e of i)await e.loadFeatures();if(this.disposed)return;if(this.track&&"function"==typeof this.track.variantRowCount&&i.length>0){let e=0;for(let t of this.viewports)t.featureCache&&t.featureCache.features&&(e=Math.max(e,t.featureCache.features.reduce(((e,t)=>Math.max(e,t.row||0)),0)));if(this.track.nVariantRows!==e+1){this.track.variantRowCount(e+1);for(let e of this.viewports)e.checkContentHeight()}}let r;if("merged"===this.track.type)r=this.track.updateScales(e);else if(this.track.autoscale){let t=[];for(let i of e){const e=i.referenceFrame,r=e.start,s=r+e.toBP(i.getWidth());if(i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const e=i.featureCache.features.getMax(r,s);if(t.push({value:e}),"function"==typeof i.featureCache.features.getMin){const e=i.featureCache.features.getMin(r,s);t.push({value:e})}}else{const e=Vr(i.featureCache.features,r,s);for(let i of e)t.push(i)}}"function"==typeof this.track.doAutoscale?this.track.dataRange=this.track.doAutoscale(t):this.track.dataRange=is(t)}const s=this.track.autoscale||this.track.autoscaleGroup||"ruler"===this.track.type||r||this.track.groupBy;for(let i of e)t.includes(i)?i.repaint():s&&i.refresh();this.adjustTrackHeight(),this.repaintSampleInfo(),this.repaintSamples(),this.updateRulerViewportLabels()}clearCachedFeatures(){for(let e of this.viewports)e.clearCache()}updateRulerViewportLabels(){const e=this.browser.calculateViewportWidth(this.viewports.length);for(let t of this.viewports)"ruler"===this.track.type&&(this.viewports.length>1?t.presentLocusLabel(e):t.dismissLocusLabel())}async getInViewFeatures(){if(!this.browser||!this.browser.referenceFrameList)return[];let e=[];const t=this.viewports.filter((e=>e.isVisible()));for(let i of t){const t=i.referenceFrame,{chr:r,start:s,bpPerPixel:o}=i.referenceFrame,n=s+t.toBP(i.getWidth());if((!i.featureCache||!i.featureCache.containsRange(r,s,n,o))&&await i.loadFeatures(),i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const t=i.featureCache.features.getMax(s,n);e.push({value:t})}else{const t="function"==typeof i.featureCache.queryFeatures?i.featureCache.queryFeatures(r,s,n):Vr(i.featureCache.features,s,n);e=e.concat(t)}}return e}checkContentHeight(){for(let e of this.viewports)e.checkContentHeight();this.adjustTrackHeight()}adjustTrackHeight(){var e=this.maxViewportContentHeight();if(this.track.autoHeight?this.setTrackHeight(e,!1):this.track.paintAxis&&this.paintAxis(),!1===kd.has(this.track.type)){const t=this.viewports[0].getContentTop(),i=this.viewports[0].viewportElement.clientHeight,r=Math.min(0,i-e);te!==this&&void 0!==e.trackGearPopup)))t.trackGearPopup.popover.style.display="none";this.trackGearPopup.presentMenuList(this,e.menuUtils.trackMenuItemList(this),e.config)}else this.trackGearPopup.popover.style.display="none"}!1===e.config.showGearColumn&&(i.style.color="white"),this.gear.appendChild(i),this.trackGearPopup=new md(this.gear),this.boundTrackGearClickHandler=r.bind(this),this.gear.addEventListener("click",this.boundTrackGearClickHandler)}}addTrackScrollMouseHandlers(e){this.boundTrackScrollMouseDownHandler=function(t){t.stopPropagation();const{y:i}=o(t);this.innerScroll.dataset.yDown=i.toString(),this.boundColumnContainerMouseMoveHandler=function(e){e.stopPropagation();const{y:t}=o(e);this.moveScroller(t-parseInt(this.innerScroll.dataset.yDown)),this.innerScroll.dataset.yDown=t.toString()}.bind(this),e.columnContainer.addEventListener("mousemove",this.boundColumnContainerMouseMoveHandler)}.bind(this),this.innerScroll.addEventListener("mousedown",this.boundTrackScrollMouseDownHandler),this.boundColumnContainerMouseUpHandler=function(t){e.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler)}.bind(this),e.columnContainer.addEventListener("mouseup",this.boundColumnContainerMouseUpHandler),e.columnContainer.addEventListener("mouseleave",this.boundColumnContainerMouseUpHandler)}removeTrackScrollMouseHandlers(){!1===kd.has(this.track.type)&&(this.innerScroll.removeEventListener("mousedown",this.boundTrackScrollMouseDownHandler),this.browser.columnContainer.removeEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.browser.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.browser.columnContainer.removeEventListener("mouseleave",this.boundColumnContainerMouseMoveHandler))}addTrackDragMouseHandlers(e){if("sequence"===this.track.type||!1===Md.has(this.track.type)){let t;function i(i){i.preventDefault(),t=i.target,!1!==this.track.selected&&"sequence"!==this.track.type||(t.classList.remove("igv-track-drag-handle-color"),t.classList.add("igv-track-drag-handle-hover-color")),e.startTrackDrag(this)}function r(i){e.endTrackDrag(),t&&i.target!==t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(t.classList.remove("igv-track-drag-handle-hover-color"),t.classList.add("igv-track-drag-handle-color"))),t=void 0}function s(i){i.preventDefault(),void 0===t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(i.target.classList.remove("igv-track-drag-handle-color"),i.target.classList.add("igv-track-drag-handle-hover-color"))),e.updateTrackDrag(this)}function o(e){e.preventDefault(),void 0===t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(e.target.classList.remove("igv-track-drag-handle-hover-color"),e.target.classList.add("igv-track-drag-handle-color")))}this.boundTrackDragMouseDownHandler=i.bind(this),this.dragHandle.addEventListener("mousedown",this.boundTrackDragMouseDownHandler),this.boundDocumentTrackDragMouseUpHandler=r.bind(this),document.addEventListener("mouseup",this.boundDocumentTrackDragMouseUpHandler),this.boundTrackDragMouseEnterHandler=s.bind(this),this.dragHandle.addEventListener("mouseenter",this.boundTrackDragMouseEnterHandler),this.dragHandle.addEventListener("mouseout",(e=>{e.preventDefault(),void 0===t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(e.target.classList.remove("igv-track-drag-handle-hover-color"),e.target.classList.add("igv-track-drag-handle-color")))})),this.boundTrackDragMouseOutHandler=o.bind(this),this.dragHandle.addEventListener("mouseout",this.boundTrackDragMouseOutHandler)}}removeTrackDragMouseHandlers(){"ideogram"===this.track.type||"ruler"===this.track.type||(this.dragHandle.removeEventListener("mousedown",this.boundTrackDragMouseDownHandler),document.removeEventListener("mouseup",this.boundDocumentTrackDragMouseUpHandler),this.dragHandle.removeEventListener("mouseup",this.boundTrackDragMouseEnterHandler),this.dragHandle.removeEventListener("mouseout",this.boundTrackDragMouseOutHandler))}removeTrackGearMouseHandlers(){!0===this.track.ignoreTrackMenu||this.gear.removeEventListener("click",this.boundTrackGearClickHandler)}removeDOMFromColumnContainer(){this.axis.remove(),this.removeViewportsFromColumnContainer(),this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove()}removeViewportsFromColumnContainer(){for(let e of this.viewports)e.viewportElement.remove()}dispose(){this.axis.remove();for(let e of this.viewports)e.dispose();this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove(),"function"==typeof this.track.dispose&&this.track.dispose();for(let e of Object.keys(this))this[e]=void 0;this.alert&&this.alert.container.remove(),this.disposed=!0}paintAxis(){if("function"==typeof this.track.paintAxis){const{width:e,height:t}=this.axisCanvas.getBoundingClientRect(),i=window.devicePixelRatio||1;this.axisCanvas.height=i*t,this.axisCanvas.width=i*e;const r=this.axisCanvas.getContext("2d");if(r.scale(i,i),this.track.autoscaleGroup){if(void 0===Rd[this.track.autoscaleGroup]){const e=jr.Dark2,t=Math.floor(Math.random()*jr.Dark2.length);Rd[this.track.autoscaleGroup]=e[t]}const i=ur.addAlpha(Rd[this.track.autoscaleGroup],.75);this.track.paintAxis(r,e,t,i)}else this.track.paintAxis(r,e,t,void 0)}}maxViewportContentHeight(){return Math.max(...this.viewports.map((e=>e.getContentHeight())))}enableTrackSelection(e){const t=this.trackSelectionContainer;if(t&&!Md.has(this.track.type))if(!1!==e)t.style.display="grid";else{this.track.selected=!1;t.querySelector("[name=track-select]").checked=this.track.selected,this.dragHandle&&this.setDragHandleSelectionState(!1),t.style.display="none"}}setDragHandleSelectionState(e){const t=this.dragHandle;e?(t.classList.remove("igv-track-drag-handle-color"),t.classList.remove("igv-track-drag-handle-hover-color"),t.classList.add("igv-track-drag-handle-selected-color")):(t.classList.remove("igv-track-drag-handle-hover-color"),t.classList.remove("igv-track-drag-handle-selected-color"),t.classList.add("igv-track-drag-handle-color"))}}const Ed=new Set(["bedtype","alignment","annotation","variant","wig","interact","shoebox"]),Nd=new Set(["alignment","annotation","variant","eqtl","qtl","snp","shoebox","wig"]),Md=new Set(["sequence","ruler","ideogram"]),Rd={};class Bd{constructor(e){this.browser=e,this.initialize()}initialize(){const e=new c;e.add("...");const t={parent:this.browser.root,content:e};this.dialog=new w(t),this.browser.root.appendChild(this.dialog.elem),r(this.dialog.elem)}trackMenuItemList(e){const t=[];return"sequence"!==e.track.config.type&&t.push(function(){const e=document.createElement("div");function t(e){const t=()=>{if(void 0!==this.browser.inputDialog.value){const e=parseInt(this.browser.inputDialog.value,10);if(e>0){const t=[];this.trackView.track.selected?t.push(...this.trackView.browser.getSelectedTrackViews().map((({track:e})=>e))):t.push(this);for(const i of t)i.trackView.autoHeight=!1,void 0!==i.minHeight&&i.minHeight>e&&(i.minHeight=e),void 0!==i.maxHeight&&i.maxHeight1&&new Set(t).has(e)}(e)?t.push(...this.multiSelectMenuItems(e)):("sequence"!==e.track.config.type&&t.push(function(){const e=document.createElement("div");function t(e){const t=()=>{let e=this.browser.inputDialog.value;e=""===e||void 0===e?"untitled":e.trim(),this.name=e},i={label:"Track Name",value:zd(this)||"unnamed",callback:t};this.browser.inputDialog.present(i,e)}return e.textContent="Set track name",{element:e,click:t}}()),t.push(...this.defaultMenuItems(e))),!1!==e.track.removable&&(t.push("
"),t.push(function(e){const t=e.track.selected?"Remove tracks":"Remove track",i=document.createElement("div");function r(e){this.trackView.browser._removeTrack(this)}return i.textContent=t,{element:i,click:r,menuItemType:"removeTrack"}}(e))),t}defaultMenuItems(e){const t=[];return Pd(e.track)&&(t.push("
"),t.push(Dd(e,"Set track color","color")),t.push(Ld(e,"Unset track color")),"wig"!==e.track.config.type&&"annotation"!==e.track.config.type||(t.push(Dd(e,"Set alt color","altColor")),t.push(Td(e,"Unset alt color")))),e.track.menuItemList&&t.push(...e.track.menuItemList()),function(e){const t=e.track;return t&&t.config&&void 0!==t.config.visibilityWindow||t&&Nd.has(t.type)}(e)&&(t.push("
"),t.push(function(e){const t=document.createElement("div");function i(t){const i=()=>{let e=this.browser.inputDialog.value;e=""===e||void 0===e?-1:e.trim(),this.visibilityWindow=Number.parseInt(e),this.config.visibilityWindow=Number.parseInt(e),this.trackView.updateViews()},r={label:"wig"===e?"Visibility window (bp). Enter 0 for whole chromosome, -1 for whole genome.":"Visibility window (bp). Enter 0 for whole chromosome.",value:this.visibilityWindow,callback:i};this.browser.inputDialog.present(r,t)}return t.textContent="Set visibility window",{element:t,click:i}}(e.track.type))),t}multiSelectMenuItems(e){const t=[],i=e.browser.getSelectedTrackViews();var r;return!0===(r=i.map((({track:e})=>e.type)),1===[...new Set(r)].length)?(t.push(...this.defaultMenuItems(e)),"wig"===e.track.type&&(t.push("
"),t.push(function(){const e=document.createElement("div");function t(e){const t=jr.Dark2,i=Math.floor(Math.random()*t.length),r=`auto-scale-group-${n()}`;Rd[r]=t[i];const s=this.browser.getSelectedTrackViews();for(const{track:e}of s)e.autoscaleGroup=r;this.browser.updateViews()}return e.textContent="Group autoscale",{element:e,doAllMultiSelectedTracks:!0,click:t}}()))):Pd(e.track)&&(t.push("
"),t.push(Dd(e,"Set track color","color")),t.push(Ld(e,"Unset track color")),"wig"!==e.track.config.type&&"annotation"!==e.track.config.type||(t.push(Dd(e,"Set alt color","altColor")),t.push(Td(e,"Unset alt color")))),t}}function Dd(e,t,i){const r=document.createElement("div");r.textContent=t;return{element:r,click:t=>{e.presentColorPicker(i,t)}}}function Ld(e,t){const i=document.createElement("div");return i.textContent=t,{element:i,click:()=>{e.track.color=e.track._initialColor||e.track.constructor.defaultColor,e.repaintViews()}}}function Td(e,t){const i=document.createElement("div");return i.textContent=t,{element:i,click:()=>{e.track.altColor=e.track._initialAltColor||e.track.constructor.defaultColor,e.repaintViews()}}}function zd(e){return e.name}function Pd(e){return void 0===e.type||Ed.has(e.type)&&"heatmap"!==e.graphType}class Hd{constructor(e,t){this.browser=e,this.container=document.createElement("div"),this.container.className="igv-generic-dialog-container",t.appendChild(this.container);const i=document.createElement("div");i.className="igv-generic-dialog-header",this.container.appendChild(i),u(i,(()=>{this.minimumInput.value="",this.maximumInput.value="",this.hide()})),this.minimum=document.createElement("div"),this.minimum.className="igv-generic-dialog-label-input",this.container.appendChild(this.minimum);const r=document.createElement("div");r.textContent="Minimum",this.minimum.appendChild(r),this.minimumInput=document.createElement("input"),this.minimum.appendChild(this.minimumInput),this.maximum=document.createElement("div"),this.maximum.className="igv-generic-dialog-label-input",this.container.appendChild(this.maximum);const s=document.createElement("div");s.textContent="Maximum",this.maximum.appendChild(s),this.maximumInput=document.createElement("input"),this.maximum.appendChild(this.maximumInput);const o=document.createElement("div");o.className="igv-generic-dialog-ok-cancel",this.container.appendChild(o),this.okButton=document.createElement("div"),this.okButton.textContent="OK",o.appendChild(this.okButton),this.cancelButton=document.createElement("div"),this.cancelButton.textContent="Cancel",o.appendChild(this.cancelButton),this.cancelButton.addEventListener("click",(()=>{this.minimumInput.value="",this.maximumInput.value="",this.hide()})),p(this.container,i),this.container.style.display="none"}configure(e){let t;if(Array.isArray(e)){t={min:Number.MAX_SAFE_INTEGER,max:-Number.MAX_SAFE_INTEGER};for(const i of e)i.track.dataRange&&(t.min=Math.min(i.track.dataRange.min,t.min),t.max=Math.max(i.track.dataRange.max,t.max))}else t=e.track.dataRange;t&&(this.minimumInput.value=t.min,this.maximumInput.value=t.max),this.minimumInput.onkeyup=null,this.minimumInput.onkeyup=t=>{13===t.keyCode&&this.processResults(e),t.stopImmediatePropagation()},this.maximumInput.onkeyup=null,this.maximumInput.onkeyup=t=>{13===t.keyCode&&(t.stopImmediatePropagation(),this.processResults(e))},this.okButton.onclick=null,this.okButton.onclick=()=>{this.processResults(e)}}processResults(e){const t=this.minimumInput.value.trim(),i=this.maximumInput.value.trim();if(""!==t&&""!==i){const r=Number(t),s=Number(i);if(isNaN(r)||isNaN(s))this.browser.alert.present(new Error("Must input numeric values"),void 0);else{const t=Array.isArray(e)?e:[e];for(const e of t)e.track.setDataRange({min:r,max:s})}this.minimumInput.value="",this.maximumInput.value=""}this.hide()}hide(){this.container.style.top="20%",this.container.style.left="75%",this.container.style.display="none"}present(e){const{top:t}=e.currentTarget.parentElement.getBoundingClientRect();this.container.style.top=`${t}px`,this.container.style.display="flex"}}class Od{constructor(e){this.parent=e,this.container=t({class:"igv-ui-generic-dialog-container"}),e.appendChild(this.container);const i=t({class:"igv-ui-generic-dialog-header"});this.container.appendChild(i),this.label=t({class:"igv-ui-generic-dialog-one-liner"}),this.container.appendChild(this.label),this.label.textContent="Unlabeled",this.input_container=t({class:"igv-ui-generic-dialog-input"}),this.container.appendChild(this.input_container),this._input=document.createElement("input"),Od.FORM_EMBED_MODE&&Od.captureKeyInput(this._input),this.input_container.appendChild(this._input);const s=t({class:"igv-ui-generic-dialog-ok-cancel"});this.container.appendChild(s),this.ok=t(),s.appendChild(this.ok),this.ok.textContent="OK",this.cancel=t(),s.appendChild(this.cancel),this.cancel.textContent="Cancel",r(this.container),this._input.addEventListener("keyup",(e=>{"Enter"===e.code&&("function"==typeof this.callback&&(this.callback(this._input.value),this.callback=void 0),this._input.value=void 0,r(this.container)),e.stopImmediatePropagation()})),this.ok.addEventListener("click",(()=>{"function"==typeof this.callback&&(this.callback(this._input.value),this.callback=void 0),this._input.value=void 0,r(this.container)}));const o=()=>{this._input.value="",r(this.container)};this.cancel.addEventListener("click",o),u(i,o),p(this.container,i)}get value(){return vo.sanitize(this._input.value)}present(e,t){this.label.textContent=e.label,this._input.value=e.value,this.callback=e.callback||e.click,this.container.style.display="";const i=t.clientX,r=t.clientY,s=this.container.offsetWidth,o=this.container.offsetHeight,n=window.innerWidth,a=window.innerHeight;let c=i,l=r;c+s>n&&(c=n-s-10),l+o>a&&(l=a-o-10),c=Math.max(10,c),l=Math.max(10,l),this.container.style.left=`${c}px`,this.container.style.top=`${l}px`}static captureKeyInput(e){e.addEventListener("mousedown",(t=>{e.focus()})),e.addEventListener("keydown",(t=>{t.preventDefault(),t.stopPropagation();const i=e.selectionStart,r=e.selectionEnd;if(1===t.key.length){const s=e.value;e.value=s.slice(0,i)+t.key+s.slice(r),e.selectionStart=e.selectionEnd=i+1}else"Backspace"===t.key?i===r&&i>0?(e.value=e.value.slice(0,i-1)+e.value.slice(i),e.selectionStart=e.selectionEnd=i-1):i{"function"==typeof a&&a(e),this.hide()})),p(this.container,l),this.hide()}show(){this.container.style.display="flex"}hide(){this.container.style.display="none"}dispose(){this.container.parent&&this.container.parent.removeChild(this.container)}}class qd extends Vd{static maxRecentColors=10;constructor({parent:e,width:i}){super({parent:e,width:i,border:"1px solid gray"}),this.container.classList.add("igv-ui-colorpicker-container"),this.colorSwatchContainer=t(),this.container.appendChild(this.colorSwatchContainer),this.moreColorsContainer=t(),this.container.appendChild(this.moreColorsContainer),this.recentColorsSwatches=t(),this.container.appendChild(this.recentColorsSwatches),this.recentColors=[],this.moreColorsPresentationColor=void 0}configure(e,i,r){this.moreColorsPresentationColor=r,this.colorSwatchContainer.innerHTML="",this.recentColorsSwatches.innerHTML="";const s=Object.values(Ur);for(const e of s){const r=t({class:"igv-ui-color-swatch"});this.colorSwatchContainer.appendChild(r),this.decorateSwatch(r,e,i)}if(this.recentColors.length>0)for(const e of this.recentColors){const r=t({class:"igv-ui-color-swatch"});this.recentColorsSwatches.appendChild(r),this.decorateSwatch(r,e,i)}this.decorateMoreColorsButton(this.moreColorsContainer,i)}decorateSwatch(e,t,i){e.style.backgroundColor=t,e.addEventListener("click",(e=>{e.stopPropagation(),i(t),this.moreColorsPresentationColor=t})),e.addEventListener("touchend",(e=>{e.stopPropagation(),i(t),this.moreColorsPresentationColor=t}))}decorateMoreColorsButton(e,t){e.innerText="More Colors ...",e.addEventListener("click",(i=>{i.stopPropagation(),this.createAndPresentMoreColorsPicker(e,(e=>t(e)))}))}updateRecentColorsSwatches(e){this.recentColorsSwatches.innerHTML="";for(const i of this.recentColors){const r=t({class:"igv-ui-color-swatch"});this.recentColorsSwatches.appendChild(r),this.decorateSwatch(r,i,e)}}createAndPresentMoreColorsPicker(e,t){let i;e.innerHTML="",e.innerText="More Colors ...";const r=document.createElement("div");r.style.position="absolute",e.appendChild(r);const{width:s,height:o}=e.getBoundingClientRect();r.style.right="0px",r.style.top="0px",r.style.width=`${s}px`,r.style.height=`${o}px`,r.addEventListener("click",(e=>{e.stopPropagation()})),i=new cl;const n={parent:r,popup:"top",editor:!1,editorFormat:"rgb",alpha:!1,color:this.moreColorsPresentationColor};i.setOptions(n),i.setColor(this.moreColorsPresentationColor,!0),i.onOpen=()=>{console.log("picker - onOpen")},i.onChange=t=>e.style.backgroundColor=t.rgba,i.onDone=e=>{const s=e.hex.substring(0,7);this.recentColors.unshift(s);const o=this.recentColors.slice(0);this.recentColors=[...new Set(o)].slice(0,qd.maxRecentColors),t(s),this.updateRecentColorsSwatches(t),this.moreColorsPresentationColor=s,i.destroy(),r.remove()},i.show()}present(e){const{top:t}=e.currentTarget.parentElement.getBoundingClientRect();this.container.style.top=`${t}px`,this.show()}}class Ud{constructor(e){this.dialog=new Ao(e)}present(e,t){this.dialog.present(e,t)}}function Qd(e){if(e)switch(e.toLowerCase()){case"bw":case"bigwig":case"wig":case"bedgraph":case"tdf":return"wig";case"vcf":return"variant";case"seg":return"seg";case"mut":case"maf":return"mut";case"bam":case"cram":return"alignment";case"hiccups":case"bedpe":case"bedpe-loop":case"biginteract":return"interact";case"bp":return"arc";case"gwas":return"gwas";case"bed":case"bigbed":case"bb":case"biggenepred":case"bignarrowpeak":return"bedtype";case"fasta":return"sequence";case"pytor":return"cnvpytor";case"qtl":return"qtl";default:return"annotation"}}function Gd(e){e.featureType&&(e.type=e.type||e.featureType,e.featureType=void 0),"junctions"===e.type?e.type="junction":"bed"===e.type?(e.type="annotation",e.format=e.format||"bed"):"annotations"===e.type?e.type="annotation":"alignments"===e.type?e.type="alignment":"bam"===e.type?(e.type="alignment",e.format="bam"):"vcf"===e.type?(e.type="variant",e.format="vcf"):"t2d"===e.type?e.type="gwas":"FusionJuncSpan"!==e.type||e.format?"aed"===e.type&&(e.type="annotation",e.format=e.format||"aed"):e.format="fusionjuncspan"}var jd=Object.freeze({__proto__:null,inferTrackType:Qd,translateDeprecatedTypes:Gd});const Wd={threshold:2e3,r:0,g:0,b:255};class $d{constructor(e){e=e||Wd,this.threshold=e.threshold,this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[],this.nbins=2e3,this.binsize=this.threshold/this.nbins}setThreshold(e){this.threshold=e,this.cache=[],this.binsize=this.threshold/this.nbins}getThreshold(){return this.threshold}setColorComponents(e){this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[]}getColorComponents(){return{r:this.r,g:this.g,b:this.b}}equals(e){return JSON.stringify(this)===JSON.stringify(e)}getColor(e){const t=Math.floor(Math.min(this.threshold,e)/this.binsize);if(void 0===this.cache[t]){const i=(cr(e,0,this.threshold)-0)/(this.threshold-0);this.cache[t]=`rgba(${this.r},${this.g},${this.b}, ${i})`}return this.cache[t]}stringify(){return this.threshold+","+this.r+","+this.g+","+this.b}static parse(e){var t,i;return e.startsWith("R:")?(t=e.substring(2).split(":"),(i=new RatioColorScale(Number.parseFloat(t[0]))).positiveScale=r(t[1]),i.negativeScale=r(t[2]),i):r(e);function r(e){var t,i;return t={threshold:(i=e.split(","))[0],r:i[1],g:i[2],b:i[3]},new $d(t)}}}const Kd="None";class Zd extends ma{static defaults={type:"seg",groupBy:Kd,isLog:void 0,displayMode:"EXPANDED",height:300,maxHeight:500,squishedRowHeight:2,expandedRowHeight:13};constructor(e,t){super(e,t),this.groups=new Map}init(e){if(super.init(e),"maf"===this.type&&(this.type="mut"),this.sortDirections=new Map,this.sampleKeys=[],this.groups=new Map,this.sampleHeight=this.squishedRowHeight,e.samples){for(let t of e.samples)this.sampleKeys.push(t);this.explicitSamples=!0}e.color?this.color=e.color:e.colorTable?this.colorTable=new $r(e.colorTable):"mut"===this.type?this.colorTable=new $r(Jd):(this.posColorScale=new Gc(e.posColorScale||Yd),this.negColorScale=new Gc(e.negColorScale||Xd));const t=Object.assign({},this.config);t.maxWGCount=t.maxWGCount||Number.MAX_SAFE_INTEGER,this.featureSource=El(t,this.browser.genome),this.initialSort=e.sort}async postInit(){"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader(),this.disposed)||(this.header&&this.setTrackProperties(this.header),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this.didTrackDragEnd=void 0,this.browser.on("trackdragend",(()=>this.didTrackDragEnd=!0)))}menuItemList(){const e=[];if(!0===dd(this.browser.sampleInfo,this.sampleKeys)){e.push("
"),e.push("Sort by attribute:");for(const r of this.browser.sampleInfo.attributeNames){if(this.sampleKeys.some((e=>{const t=this.browser.sampleInfo.getAttributes(e);return t&&t[r]}))){const s=document.createElement("div");function o(){this.sortByAttribute(r)}s.innerHTML=`  ${r.split(sd.emptySpaceReplacement).join(" ")}`,e.push({element:s,click:o})}}}e.push("
"),e.push("Group by attribute:");for(const n of[Kd,...this.browser.sampleInfo.attributeNames]){let a=!1;a=Kd===n?Kd===this.groupBy:n===this.groupBy;const c=ua(n,a);e.push({element:c,click:function(){this.groupByAttribute(n)}})}const t={SQUISHED:"Squish",EXPANDED:"Expand",FILL:"Fill"};e.push("
"),e.push("DisplayMode:");const i="seg"===this.type?["SQUISHED","EXPANDED","FILL"]:["SQUISHED","EXPANDED"];for(let l of i)e.push({element:ua(t[l],l===this.displayMode),click:function(){this.displayMode=l,this.config.displayMode=l,this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.createGroupLabels()}});return e}hasSamples(){return!0}getSamples(){const e=Kd!==this.groupBy?this.sampleKeys.map((e=>this.getGroupIndex(e))):void 0;return{names:this.sampleKeys,height:this.sampleHeight,yOffset:0,groups:this.groups,groupIndeces:e,groupMarginHeight:hd}}filter(e){const t=this._trackFilterObjects||[];if(0===t.length)return!0;for(const i of t){const t=(i.scores||{})[e];if("seg"===this.type){if(">"===i.op){if(!(t>i.value))return!1}else if("<"===i.op&&!(t0){const t=this._trackFilterObjects.map((e=>{const{scores:t,...i}=e;return i}));e.filters=t}return e}async getFeatures(e,t,i){const r=await this.featureSource.getFeatures({chr:e,start:t,end:i});if(this.updateSampleKeys(r),this.initialSort){const s=this.initialSort;if(void 0===s.option||"VALUE"===s.option.toUpperCase()){const o=s.chr===e&&s.start>=t&&s.end<=i?r:void 0;this.sortByValue(s,o)}else if("ATTRIBUTE"===s.option.toUpperCase()&&s.attribute){const e="DESC"===s.direction?1:-1;this.sortByAttribute(s.attribute,e)}this.initialSort=void 0}return r}draw({context:e,pixelTop:t,pixelWidth:i,pixelHeight:r,features:s,bpPerPixel:o,bpStart:n}){if(Co.fillRect(e,0,t,i,r,{fillStyle:"rgb(255, 255, 255)"}),s&&s.length>0){if(this.checkForLog(s),"shoebox"===this.type&&!this.sbColorScale){const e=this.featureSource.hicFile.percentile95||2e3;this.sbColorScale=new $d({threshold:e,r:0,g:0,b:255})}const a={};let c;switch(this.sampleKeys.forEach((function(e,t){a[e]=t})),this.displayMode){case"FILL":this.sampleHeight=(r-(this.groups.size+1)*hd)/this.sampleKeys.length,c=0;break;case"SQUISHED":this.sampleHeight=this.squishedRowHeight,c=0;break;default:this.sampleHeight=this.expandedRowHeight,c=1}const l=this.sampleHeight;for(let e of s)e.pixelRect=void 0;const h=t+r,d=n+i*o+1,u=o;this.sampleYStart=void 0;for(let i of s){if(i.endd)continue;const r=i.sampleKey||i.sample;i.row=a[r];let s=i.row*l;this.groups.size>1&&(s+=(this.getGroupIndex(r)+1)*hd),void 0===this.sampleYStart&&(this.sampleYStart=s);if(s+lh)continue;const o=Math.max(i.start,n);let f=Math.round((o-n)/u);const p=Math.min(i.end,d),g=Math.round((p-n)/u);let m,w,b=Math.max(1,g-f);if(this.color?m="function"==typeof this.color?this.color(i):this.color:this.colorTable&&(m=this.colorTable.getColor(i.value.toLowerCase())),"mut"===this.type)w=l-2*c,b<3&&(b=3,f-=1);else{let e=i.value;this.isLog||(e=lr(e/2)),m=e<-.1?this.negColorScale.getColor(e):e>.1?this.posColorScale.getColor(e):"white";let t=l;if(l<.25){const i=.1+2*Math.abs(e);t=Math.min(1,i*l)}w=t-2*c}i.pixelRect={x:f,y:s,w:b,h:w},e.fillStyle=m,e.fillRect(f,s,b,w)}Kd!==this.groupBy&&ud(e,t,i,r,0,this.sampleHeight,this.groups)}}getGroupIndex(e){const t=this.browser.sampleInfo.getAttributeValue(e,this.groupBy)||"";return this.groups.has(t)?this.groups.get(t).index:this.groups.size}checkForLog(e){if(void 0===this.isLog){this.isLog=!1;for(let t of e)if(t.value<0)return void(this.isLog=!0)}}computePixelHeight(e){if(!e)return 0;const t="SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight;return this.sampleKeys.length*t+(this.groups.size>1?(this.groups.size+1)*hd:0)}async sortByValue(e,t){const i=e.chr,r=void 0!==e.position?e.position-1:e.start,s=void 0===e.end?r+1:e.end,o=await this.computeRegionScores({chr:i,start:r,end:s},t),n="ASC"===e.direction?1:-1;this.sampleKeys.sort((function(e,t){let i=o[e],r=o[t];return i||(i=n*Number.MAX_VALUE),r||(r=n*Number.MAX_VALUE),i===r?0:i>r?n:-1*n})),Kd!==this.groupBy&&(this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,this.groupBy,1)),this.config.sort=e,this.trackView.repaintViews()}async computeRegionScores(e,t){const i=e.chr;let r,s;if(e.position?(r=e.position-1,s=r+1):(r=e.start,s=e.end),t||(t=await this.featureSource.getFeatures({chr:i,start:r,end:s})),!t)return;this.updateSampleKeys(t);const o={},n=s-r+1;for(let e of t){if(e.ends)break;const t=e.sampleKey||e.sample;if("mut"===this.type)o[t]=(o[t]||0)+1;else{const i=Math.max(r,e.start),a=(Math.min(s,e.end)-i)/n;o[t]=(o[t]||0)+a*e.value}}return o}sortByAttribute(e,t){t=t||this.sortDirections.get(e)||1,this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,e,t),Kd!==this.groupBy&&(this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,this.groupBy,1)),this.config.sort={option:"ATTRIBUTE",attribute:e,direction:1===t?"ASC":"DESC"},this.sortDirections.set(e,-1*t),this.trackView.repaintViews()}groupByAttribute(e){if(this.groupBy=e,this.groups.clear(),Kd!==e){this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,e,1);const t=this.sampleKeys;for(let i of t){const t=this.browser.sampleInfo.getAttributeValue(i,e)||"";t&&(this.groups.has(t)?this.groups.get(t).count+=1:this.groups.set(t,{index:this.groups.size,count:1}))}}this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.createGroupLabels()}createGroupLabels(){const e=this.trackView.getLastViewport();if(e.overlayElement.innerHTML="",0===this.groups.size)return;let t;switch(this.displayMode){case"EXPANDED":t=this.expandedRowHeight;break;case"SQUISHED":t=this.squishedRowHeight;break;default:t=(e.viewportElement.getBoundingClientRect().height-(this.groups.size-1)*hd)/this.sampleKeys.length}let i=hd;for(const r of this.groups.keys()){const s=document.createElement("div");s.className="igv-attribute-group-label",e.overlayElement.appendChild(s),s.innerText=r,s.style.top=`${i}px`,i+=this.groups.get(r).count*t+hd}}clickedFeatures(e){const t=super.clickedFeatures(e),i=e.y;return t.filter((function(e){const t=e.pixelRect;return t&&i>=t.y&&i<=t.y+t.h}))}hoverText(e){const t=this.clickedFeatures(e);if(t&&t.length>0)return`${t[0].sample}: ${t[0].value}`}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){i.length>0&&(i.push("
"),i.push("
"));const t=e._f||e,r="function"==typeof t.popupData?t.popupData(this.type,this.browser.genome.id):this.extractPopupData(t);Array.prototype.push.apply(i,r)}return i}contextMenuItemList(e){const{genomicLocation:t,referenceFrame:i,viewport:r,event:s}=e,o=e=>{const t=r.cachedFeatures;this.sortByValue(e,t)},n=i.toBP(2.5),a=["DESC","ASC"].map((e=>{const r="DESC"===e?"descending":"ascending";return{label:"seg"===this.type||"shoebox"===this.type?`Sort by value (${r})`:`Sort by count (${r})`,click:()=>{const r={option:"VALUE",direction:e,chr:i.chr,start:Math.floor(t-n),end:Math.floor(t+n)};o(r)}}}));return a.push("
"),a}get supportsWholeGenome(){return(!1===this.config.indexed||!this.config.indexURL)&&!1!==this.config.supportsWholeGenome}updateSampleKeys(e){if(this.explicitSamples)return;let t=!1;const i=new Set(this.sampleKeys);for(let r of e){const e=r.sampleKey||r.sample;if(!i.has(e)){const r=this.sampleKeys;r.push(e),this.sampleKeys=r,i.add(e),t=!0}}t&&Kd!==this.groupBy&&this.groupByAttribute(this.groupBy)}}const Yd={low:.1,high:1.5,lowColor:"rgb(255,255,255)",highColor:"rgb(255,0,0)"},Xd={low:-1.5,high:-.1,lowColor:"rgb(0,0,255)",highColor:"rgb(255,255,255)"},Jd={indel:"rgb(0,200,0)","targeted region":"rgb(236,155,43)",truncating:"rgb(\t150,0,0)","non-coding transcript":"rgb(0,0,150)",synonymous:"rgb(109,165,95)",silent:"rgb(109,135,80)",missense_mutation:"rgb(72,130,187)",missense:"rgb(72,130,187)","splice site":"rgb(143,83,155)",splice_region:"rgb(143,83,155)",nonsense:"rgb(216, 57,81)",nonsense_mutation:"rgb(216, 57,81)",frame_shift_del:"rgb(226,135,65)",frame_shift_ins:"rgb(226,135,65)",in_frame_del:"rgb(247,235,94)",in_frame_ins:"rgb(247,235,94)","*other*":"rgb(159,91,50)"};class eu{constructor(e){this.paired=!0,this.firstAlignment=e,this.chr=e.chr,this.readName=e.readName,e.startt.start?this.connectingEnd=e.start:this.connectingStart=e.start+e.lengthOnRef,this.start=Math.min(t.start,e.start),this.end=Math.max(t.start+t.lengthOnRef,e.start+e.lengthOnRef),this.lengthOnRef=this.end-this.start,this.scStart=Math.min(t.scStart,e.scStart);const i=Math.max(t.scStart+t.scLengthOnRef,e.scStart+e.scLengthOnRef);this.scLengthOnRef=i-this.scStart}containsLocation(e,t){const i=t?this.scStart:this.start,r=t?this.scLengthOnRef:this.lengthOnRef;return e>=i&&e<=i+r}alignmentContaining(e,t){return this.firstAlignment.containsLocation(e,t)?this.firstAlignment:this.secondAlignment&&this.secondAlignment.containsLocation(e,t)?this.secondAlignment:void 0}popupData(e,t,i){let r=this.firstAlignment.popupData(e,t,i);return this.secondAlignment&&(r.push("-------------------------------"),r=r.concat(this.secondAlignment.popupData(e,t,i))),r}isPaired(){return!0}isMateMapped(){return!0}isProperPair(){return this.firstAlignment.isProperPair()}get fragmentLength(){return Math.abs(this.firstAlignment.fragmentLength)}get firstOfPairStrand(){return this.firstAlignment.firstOfPairStrand}get pairOrientation(){return this.firstAlignment.pairOrientation}hasTag(e){return this.firstAlignment.hasTag(e)||this.secondAlignment&&this.secondAlignment.hasTag(e)}getGroupValue({option:e,tag:t}){switch(e){case"strand":return this.isNegativeStrand()?"-":"+";case"FIRST_IN_PAIR_STRAND":return this.isPaired()?this.isFirstOfPair()?this.isNegativeStrand()?"-":"+":this.isSecondOfPair()?this.isNegativeStrand()?"+":"-":void 0:void 0;case"START":return this.start;case"INSERT_SIZE":return this.fragmentLength;case"MATE_CHR":return this.mate?this.mate.chr:void 0;case"MQ":return this.mq;case"ALIGNED_READ_LENGTH":return this.lengthOnRef;case"TAG":return this.tags()[t];case"PHASE":return this.tags().HP;case"READ_ORDER":return this.isPaired()&&this.isFirstOfPair()?"FIRST":this.isPaired()&&this.isSecondOfPair()?"SECOND":"";default:return}}}class tu{static instances=new Map;static getKey(e,t,i){const r=""+e+t+i;return tu.instances.has(r)||tu.instances.set(r,new tu(e,t,i)),tu.instances.get(r)}constructor(e,t,i){this.base=e,this.strand=t,this.modification=i,this.canonicalBase="+"===this.strand?this.base:Io(this.base)}getCanonicalBase(){}toString(){return""+this.base+this.strand+this.modification}static compare(e,t){const i=e.modification,r=t.modification;return i===r?e.strand.charAt(0)-t.strand.charAt(0):iu.has(i)&iu.has(r)?iu.get(i)-iu.get(r):iu.has(i)?1:iu.has(r)?-1:i>r?1:-1}}const iu=new Map(["NONE_C","NONE_T","NONE_G","NONE_A","m","h","f","c","C","g","e","b","T","U","a","A","o","G","n","N"].map(((e,t)=>[e,t])));class ru{constructor(e,t,i,r){this.base=e,this.modification=i,this.strand=t,this.likelihoods=r,this.canonicalBase="+"==this.strand?this.base:Io(this.base),this.key=tu.getKey(e,t,i)}containsPosition(e){return this.likelihoods.has(e)}is5mC(){return this.modification.equals("m")&&("C"===this.base&&"+"===this.strand||"G"===this.base&&"-"===this.strand)}fullName(){return su.get(this.modification)||this.modification}}const su=new Map;su.set("m","5mC"),su.set("h","5hmC"),su.set("f","5fC"),su.set("c","5caC"),su.set("g","5hmU"),su.set("e","5fU"),su.set("b","5caU"),su.set("a","6mA"),su.set("o","8xoG"),su.set("n","Xao"),su.set("C","Unknown C"),su.set("T","Unknown T"),su.set("A","Unknown A"),su.set("G","Unknown G"),su.set("N","Unknown");const ou=new Map([["m","5mC"],["h","5hmC"],["f","5fC"],["c","5caC"],["g","5hmU"],["e","5fU"],["b","5caU"],["a","6mA"],["o","8xoG"],["n","Xao"],["C","Unknown C"],["T","Unknown T"],["A","Unknown A"],["G","Unknown G"],["N","Unknown"]]),nu=new Set;function au(e){return ou.has(e)?ou.get(e):"Uknown"}function cu(e){if(!e)return!1;const t=e.length;if(0==t)return!1;for(let i=0;i"9")return!1}return!0}function lu(e){return e<0?e+256:e}class hu{allModifications=new Set;simplexModifications=new Set;maxLikelihoods=new Map;nomodLikelihoods=new Map;lastThreshold;incrementCounts(e){if(!e.blocks)return;const t=e.getBaseModificationSets();if(t)for(let i of e.blocks)if("S"!==i.type)for(let e=0;en&&(o=e.canonicalBase,n=c,r=t)}}if(0!=o){const t=i.start+e,s=tu.getKey(o,"+","NONE_"+o);this.allModifications.add(s);const c=(e,t,i,r)=>{let s=r.get(i);s||(s=new Map,r.set(i,s));let o=s.get(e);o||(o=[],s.set(e,o)),o.push(t)};c(t,n,r,this.maxLikelihoods),a>n?c(t,a,s,this.nomodLikelihoods):c(t,n,r,this.nomodLikelihoods)}}}getCount(e,t,i,r){this.lastThreshold=i;const s=255*i,o=r?this.nomodLikelihoods.get(t):this.maxLikelihoods.get(t);if(!o)return 0;const n=o.get(e);if(n){let e=0;for(let t of n){lu(t)>=s&&e++}return e}return 0}getLikelihoodSum(e,t,i,r){this.lastThreshold=i;const s=255*i,o=(r?this.nomodLikelihoods.get(t):this.maxLikelihoods.get(t)).get(e);if(o){let e=0;for(let t of o){const i=lu(t);i>=s&&(e+=i)}return e}return 0}popupData(e,t){const i=[];i.push("Modifications with likelihood > "+100*this.lastThreshold+"%");for(let r of this.maxLikelihoods.keys()){if(this.maxLikelihoods.get(r).has(e)){let s="basemod2"===t;const o=this.getCount(e,r,this.lastThreshold,s);if(o>0){const t=this.getLikelihoodSum(e,r,this.lastThreshold,s)/o*.3921568,n=au(r.modification);i.push(n+" ("+r.base+r.strand+"): "+o+" @ average likelihood "+Math.round(t)+"%")}}}return i}computeSimplex(){const e=new Set(Array.from(this.allModifications).filter((e=>"-"===e.strand)).map((e=>e.modification)));for(let t of this.allModifications)"+"!==t.strand||e.has(t.modification)||(this.simplexModifications.add(t.modification),this.simplexModifications.add("NONE_"+t.getCanonicalBase()))}}class du{constructor(){this.alignments=[],this.score=void 0}findAlignment(e,t=!1){const i=(e,i)=>i>=e.start&&i=o.start&&e0?h-=e:0===h&&(h=1)}return h}(o,s,e);case"strand":return o.strand?1:-1;case"START":return o.start;case"TAG":return o.tags()[i];case"READ_NAME":return o.readName;case"INSERT_SIZE":return-Math.abs(o.fragmentLength);case"GAP_SIZE":return-o.gapSizeAt(e);case"MATE_CHR":return o.mate?o.mate.chr:Number.MAX_VALUE;case"MQ":return void 0===o.mq?Number.MAX_VALUE:-o.mq;case"ALIGNED_READ_LENGTH":return-o.lengthOnRef;default:return Number.MAX_VALUE}}}var uu={fr:{F1R2:"LR",F2R1:"LR",F1F2:"LL",F2F1:"LL",R1R2:"RR",R2R1:"RR",R1F2:"RL",R2F1:"RL"},rf:{R1F2:"LR",R2F1:"LR",R1R2:"LL",R2R1:"LL",F1F2:"RR",F2F1:"RR",F1R2:"RL",F2R1:"RL"},ff:{F2F1:"LR",R1R2:"LR",F2R1:"LL",R1F2:"LL",R2F1:"RR",F1R2:"RR",R2R1:"RL",F1F2:"RL"}};class fu{#y=[];baseModificationKeys=new Set;constructor(e,t,i,{samplingWindowSize:r,samplingDepth:s,alleleFreqThreshold:o,colorBy:n}){this.alleleFreqThreshold=void 0===o?.2:o,this.samplingWindowSize=r||100,this.samplingDepth=s||1e3,this.chr=e,this.start=Math.floor(t),this.end=Math.ceil(i),this.length=i-t,this.coverageMap=new gu(e,t,i,this.alleleFreqThreshold),this.downsampledIntervals=[],n&&n.startsWith("basemod")&&(this.baseModCounts=new hu),this.alignments=[],this.pairsCache=new Map,this.downsampledReads=new Set,this.currentBucket=new pu(this.start,this.start+this.samplingWindowSize,this),this.hasPairs=!1}pack({viewAsPairs:e,showSoftClips:t,expectedPairOrientation:i,groupBy:r,displayMode:s}){let o=this.allAlignments();o=e?function(e){const t=new Map,i=e.map((e=>{if(Fu(e)){let i=t.get(e.readName);return i?(i.setSecondAlignment(e),t.delete(e.readName),i):(i=new eu(e),t.set(e.readName,i),i)}return e}));return i}(o):function(e){return e.flatMap((e=>e instanceof eu?[e.firstAlignment,e.secondAlignment].filter(Boolean):[e]))}(o),this.packAlignmentRows(o,t,i,r,s),this.alignments&&delete this.alignments}packAlignmentRows(e,t,i,r,s){this.#y=[];const o=(e,i)=>{e.sort((function(e,i){return t?e.scStart-i.scStart:e.start-i.start}));const r=new bu(i);let s,o=0,n=0;const a=new Set,c=()=>{s=new du,r.push(s),o=0,n=0,a.clear()};for(c();e.length>0;)if(n>=0&&n(t?e.scStart:e.start)>o),n)}else e=e.filter((e=>!a.has(e))),c();return r},n=(e,t)=>{e.sort((function(e,t){return e.start-t.start}));const i=new bu(t),{start:r,end:s}=this.viewport.genomicRange();for(let t of e)if(t.ends)this.#y.push(t);else{const e=new du;e.alignments.push(t),i.push(e)}return i};if(!e||0===e.length)return new Map;{const t=new Map;if(r)for(let s of e){const e=yu(s,r,i)||"";t.has(e)||t.set(e,[]),t.get(e).push(s)}else t.set("",e);const a=new Map,c=Array.from(t.keys()).sort(function(e){switch(e){case"pairOrientation":return function(){const e=["LL","RR","RL","LR",""];return(t,i)=>e.indexOf(t)-e.indexOf(i)}();case"strand":case"firstOfPairStrand":return _u;default:return e&&e.startsWith("base:")?Cu:xu}}(r));for(let e of c){const i=t.get(e),r="FULL"===s?n(i,e):o(i,e);a.set(e,r)}this.packedGroups=a}}push(e){this.hasPairs=this.hasPairs||e.isPaired(),this.coverageMap.incCounts(e);const t=e.getBaseModificationSets();if(t)for(let e of t)this.baseModificationKeys.add(e.key);this.baseModCounts&&this.baseModCounts.incrementCounts(e),this.downsampledReads.has(e.readName)?this.currentBucket.downsampledCount++:(e.start>=this.currentBucket.end&&(this.finishBucket(),this.currentBucket=new pu(e.start,e.start+this.samplingWindowSize,this)),this.currentBucket.addAlignment(e))}finish(){void 0!==this.currentBucket&&this.finishBucket(),this.hasAlignments=this.alignments.length>0,this.alignments.sort((function(e,t){return e.start-t.start})),this.baseModCounts&&this.baseModCounts.computeSimplex(),delete this.currentBucket,delete this.pairsCache,delete this.downsampledReads}contains(e,t,i){return this.chr===e&&this.start<=t&&this.end>=i}hasDownsampledIntervals(){return this.downsampledIntervals&&this.downsampledIntervals.length>0}finishBucket(){this.alignments=this.alignments.concat(this.currentBucket.alignments),this.currentBucket.downsampledCount>0&&this.downsampledIntervals.push(new wu(this.currentBucket.start,this.currentBucket.end,this.currentBucket.downsampledCount))}allAlignments(){if(this.alignments)return this.alignments;if(this.packedGroups){const e=Array.from(this.packedGroups.values()).flatMap((e=>e.rows.flatMap((e=>e.alignments))));if(this.#y&&this.#y.length>0)for(let t of this.#y)e.push(t);return e}return[]}getMax(e,t){return this.coverageMap.getMax(e,t)}sortRows(e){if(this.packedGroups)for(let t of this.packedGroups.values())t.sortRows(e,this)}}class pu{constructor(e,t,{samplingDepth:i,downsampledReads:r,pairsCache:s}){this.start=e,this.end=t,this.alignments=[],this.downsampledCount=0,this.samplingDepth=i,this.downsampledReads=r,this.pairsCache=s,this.hasPairs=!1}addAlignment(e){this.hasPairs=this.hasPairs||e.isPaired();const t=this.hasPairs?Math.ceil(this.samplingDepth/2):this.samplingDepth;if(Fu(e)){const t=this.pairsCache.get(e.readName);if(t)return t.setSecondAlignment(e),void this.pairsCache.delete(e.readName)}if(this.alignments.lengtht)break;const o=this.coverage[s];r>=e&&o&&(i=Math.max(i,o.total))}return i}incCounts(e){var t=this;if(void 0===e.blocks?i(e):e.blocks.forEach((function(e){i(e)})),e.gaps)for(let i of e.gaps)if("D"===i.type){const e=i.start-t.bpStart;for(let r=e;r=this.coverage.length)return 0;const r=this.coverage[i];switch(t){case"A":case"a":return r.posA;case"C":case"c":return r.posC;case"T":case"t":return r.posT;case"G":case"g":return r.posG;case"N":case"n":return r.posN;default:return 0}}getNegCount(e,t){const i=e-this.bpStart;if(i<0||i>=this.coverage.length)return 0;const r=this.coverage[i];switch(t){case"A":case"a":return r.negA;case"C":case"c":return r.negC;case"T":case"t":return r.negT;case"G":case"g":return r.negG;case"N":case"n":return r.negN;default:return 0}}getCount(e,t){return this.getPosCount(e,t)+this.getNegCount(e,t)}getTotalCount(e){const t=e-this.bpStart;return t>=0&&t=t}}class wu{constructor(e,t,i){this.start=e,this.end=t,this.counts=i}popupData(e){return[{name:"start",value:Math.floor(this.start+1)},{name:"end",value:this.end},{name:"# downsampled:",value:this.counts}]}}class bu{pixelTop=0;pixelBottom=0;rows=[];constructor(e){this.name=this.name}push(e){this.rows.push(e)}get length(){return this.rows.length}sortRows(e,t){const i=[],r=[];for(let t of this.rows){void 0!==t.findAlignment(e.position,e.sortAsPairs)?i.push(t):r.push(t)}i.sort(((i,r)=>{const s=e.direction,o=i.getSortValue(e,t),n=r.getSortValue(e,t);if(void 0===n&&void 0!==n)return 1;if(void 0!==o&&void 0===n)return-1;const a=o>n?1:o>1);t(e[i])?s=i:r=i}return s}function yu(e,t,i){let r,s,o;if(t.startsWith("tag:"))r=t.substring(4),t="tag";else if(t.startsWith("base:")){const e=t.split(":");3===e.length&&(t="base",s=e[1],o=Number.parseInt(e[2].replaceAll(",",""))-1)}switch(t){case"strand":return e.strand?"+":"-";case"firstOfPairStrand":const t=e.firstOfPairStrand;return void 0===t?"":t?"+":"-";case"mateChr":return e.mate&&e.isMateMapped()?e.mate.chr:"";case"pairOrientation":return uu[i][e.pairOrientation]||"";case"chimeric":return e.tags().SA?"chimeric":"";case"supplementary":return e.isSupplementary?"supplementary":"";case"readOrder":return e.isPaired()&&e.isFirstOfPair()?"first":e.isPaired()&&e.isSecondOfPair()?"second":"";case"phase":return e.tags().HP||"";case"tag":return e.tags()[r]||"";case"base":if(e.chr===s&&e.start<=o&&e.end>o){const t=e.readBaseAt(o);return t||"GAP"}return"";default:return}}const Au=new Map([["A",1],["T",2],["C",3],["G",4],["N",5],["GAP",5],["",7]]);function Cu(e,t){return Au.has(e)&&Au.has(t)?Au.get(e)-Au.get(t):e.localeCompare(t,void 0,{sensitivity:"base"})}function _u(e,t){return e===t?0:e&&t?-e.localeCompare(t):e?1:-1}function xu(e,t){if(e||t){if(e){if(t){if(e===t)return 0;if(ss(e)&&(ss(t),1))return Number.parseFloat(e)-Number.parseFloat(t);{let i=e.toString(),r=t.toString();return i.localeCompare(r,void 0,{sensitivity:"base"})}}return-1}return 1}return 0}class ku{constructor(e){const t=e.split(",");this.chr=t[0],this.start=parseInt(t[1]),this.strand=t[2].charAt(0),this.mapQ=parseInt(t[4]),this.numMismatches=parseInt(t[5]),this.lenOnRef=function(e){let t=0,i="";for(let r=0;r47&&s<58)i+=e.charAt(r);else{switch(s){case 78:case 68:case 77:case 61:case 88:t+=parseInt(i.toString())}i=""}}return t}(t[3])}printString(){return this.chr+":"+F(this.start)+"-"+F(this.start+this.lenOnRef)+" ("+this.strand+") = "+F(this.lenOnRef)+"bp @MAPQ: "+this.mapQ+" NM: "+this.numMismatches}}function Iu(e){return e.split(";").filter((e=>e.length>0)).map((e=>new ku(e)))}const Su={c:1,C:1,s:2,S:2,i:4,I:4,f:4};class Eu{constructor(){this.hidden=!1}isMapped(){return!(4&this.flags)}isPaired(){return!!(1&this.flags)}isProperPair(){return!!(2&this.flags)}isFirstOfPair(){return!!(64&this.flags)}isSecondOfPair(){return!!(128&this.flags)}isSecondary(){return!!(256&this.flags)}isSupplementary(){return!!(2048&this.flags)}isFailsVendorQualityCheck(){return!!(512&this.flags)}isDuplicate(){return!!(1024&this.flags)}isMateMapped(){return!(8&this.flags)}isNegativeStrand(){return!!(16&this.flags)}isMateNegativeStrand(){return!!(32&this.flags)}hasTag(e){const t=this.tagDict||function(e){let t=0;const i=e.length,r={};for(;t=i&&e<=i+r}popupData(e,t,i){const r=[];if(e=Math.floor(e),this.insertions){const t=this.seq;for(let i of this.insertions){var s=i.start;if(e===s||e===s-1)return r.push({name:"Insertion",value:t.substr(i.seqOffset,i.len)}),r.push({name:"Location",value:s}),r}}r.push({name:"Read Name",value:this.readName}),r.push("
"),r.push({name:"Alignment Start",value:F(1+this.start),borderTop:!0}),r.push({name:"Read Strand",value:!0===this.strand?"(+)":"(-)",borderTop:!0});let o=this.cigar;if(o&&o.length>50){const e=25;o=`${o.substring(0,e-2)} ... ${o.substring(o.length-e+2)}`}r.push({name:"Cigar",value:o}),r.push({name:"Mapping Quality",value:this.mq}),r.push({name:"Secondary",value:c(this.isSecondary())}),r.push({name:"Supplementary",value:c(this.isSupplementary())}),r.push({name:"Duplicate",value:c(this.isDuplicate())}),r.push({name:"Failed QC",value:c(this.isFailsVendorQualityCheck())}),this.isPaired()&&(r.push("
"),r.push({name:"First in Pair",value:!this.isSecondOfPair(),borderTop:!0}),r.push({name:"Mate is Mapped",value:c(this.isMateMapped())}),this.pairOrientation&&r.push({name:"Pair Orientation",value:this.pairOrientation}),this.isMateMapped()&&(r.push({name:"Mate Chromosome",value:this.mate.chr}),r.push({name:"Mate Start",value:this.mate.position+1}),r.push({name:"Mate Strand",value:!0===this.mate.strand?"(+)":"(-)"}),r.push({name:"Insert Size",value:this.fragmentLength})));const n=this.tags();if(n.hasOwnProperty("SA")){r.push("
"),r.push({name:"Supplementary Alignments",value:""});const e=Iu(n.SA);if(e){r.push("
    ");for(let t of e)r.push(`
  • ${t.printString()}
  • `);r.push("
")}}r.push("
");for(let e in n)i?.has(e)?r.push({name:e,value:n[e]}):i?t.add(e):t.has(e)||r.push({name:e,value:n[e]});t&&t.size>0&&r.push({name:"Hidden Tags",value:Array.from(t).join(", ")}),r.push("
"),r.push({name:"Genomic Location: ",value:F(1+e)}),r.push({name:"Read Base:",value:this.readBaseAt(e)}),r.push({name:"Base Quality:",value:this.readBaseQualityAt(e)});const a=this.getBaseModificationSets();if(a){const t=this.positionToReadIndex(e);if(void 0!==t){let e=!1;for(let i of a)if(i.containsPosition(t)){e||(r.push("
"),r.push("Base modifications:"),e=!0);const s=Math.round(100/255*lu(i.likelihoods.get(t)));r.push(`${i.fullName()} @ likelihood = ${s}%`)}}}return r;function c(e){return e?"Yes":"No"}}readBaseAt(e){const t=Mu(this.blocks,e);if(t){if("*"===this.seq)return"*";{const i=t.seqIndexAt(e);return this.seq[i]}}}readBaseQualityAt(e){const t=Mu(this.blocks,e);if(t){if("*"===this.qual)return 30;{const i=t.seqIndexAt(e);return i>=0&&this.qual&&i=t.start&&e1)if(cu(e))h.push(e);else for(let t=0;t=r.start&&t>1)+r;a+4=t)return!1;if("B"!==String.fromCharCode(e[a+2])||"I"!==String.fromCharCode(e[a+3]))return!1;var l=ju(e,a+4),h=a+8;if(h+4*l>t)return!1;var d="",u=0;o.length=0,a=h;for(var f=0;f>4,m=Vu[15&p];"M"!==m&&"EQ"!==m&&"X"!==m&&"D"!==m&&"N"!==m&&"="!==m||(u+=g),d=d+g+m,o.push({len:g,ltr:m})}return s.cigar=d,s.lengthOnRef=u,!0},decodeBamRecords:function(e,t,i,r,s,o,n,a){for(;te.length)return;if(p<0){t=u;continue}if(void 0!==s&&(p>s||p===s&&g>n))return!0;if(void 0!==s&&p>8,b=255&m,F=ju(e,t+16),v=(4294901760&F)>>16,y=65535&F,A=ju(e,t+20),C=ju(e,t+24),_=ju(e,t+28),x=ju(e,t+32);let k=[];for(let i=0;i>4,h=Vu[15&c];"M"!==h&&"EQ"!==h&&"X"!==h&&"D"!==h&&"N"!==h&&"="!==h||(I+=l),S=S+l+h,E+=4,M={len:l,ltr:h},N.push(M)}if(f.chr=r[p],f.start=g,f.flags=v,f.strand=!(16&v),f.readName=k,f.cigar=S,f.lengthOnRef=I,f.fragmentLength=x,f.mq=w,Qu.bam_tag2cigar(e,u,E,A,f,N),f.end=f.start+f.lengthOnRef,f.end>1;for(let t=0;t>4]),R.push(Ou[15&d])}R=R.slice(0,A).join(""),E+=B;const D=[];for(let t=0;t=0&&(f.mate={chr:r[C],position:_,strand:!(32&v)}),f.seq=R,f.qual=D;const L=new Uint8Array(e.buffer.slice(E,u));f.tagDict=Ku(L),this.setPairOrientation(f),(void 0===a||a.pass(f))&&(Gu(f,N),i.push(f)),t=u}},decodeSamRecords:function(e,t,i,r,s,o){var n,a,c,l,h,d,u,f,p,g;for(l=(n=v(e)).length,a=0;as)break;if(f=0,(g=Wu(p.cigar)).forEach((function(e){var t=e.len,i=e.ltr;"M"!==i&&"EQ"!==i&&"X"!==i&&"D"!==i&&"N"!==i&&"="!==i||(f+=t)})),p.lengthOnRef=f,!(p.start+fUu&&(console.log("Warning: attempt to set sampling depth > maximum value of "+Uu),e.samplingDepth=Uu)},setPairOrientation:function(e){if(e.isMapped()&&e.mate&&e.isMateMapped()&&e.mate.chr===e.chr){var t=e.strand?"F":"R",i=e.mate,r=i.strand?"F":"R",s=" ",o=" ";e.isFirstOfPair()?(s="1",o="2"):e.isSecondOfPair()&&(s="2",o="1");var n=[],a=e.fragmentLength,c=e.end-e.start;if(0===a)a=(e.start0?(n[0]=t,n[1]=s,n[2]=r,n[3]=o):(n[2]=t,n[3]=s,n[0]=r,n[1]=o),e.pairOrientation=n.join("")}}};function Gu(e,t){const i=[];let r,s,o=0,n=e.start;e.scStart=e.start,e.scLengthOnRef=e.lengthOnRef;for(let a of t){let t;switch(a.ltr){case"H":case"P":break;case"S":t=n,e.scLengthOnRef+=a.len,0===i.length&&(e.scStart-=a.len,t-=a.len),i.push(new zu({start:t,seqOffset:o,len:a.len,type:"S"})),o+=a.len;break;case"N":case"D":void 0===s&&(s=[]),s.push({start:n,len:a.len,type:a.ltr}),n+=a.len;break;case"I":void 0===r&&(r=[]),r.push(new zu({start:n,len:a.len,seqOffset:o,type:"I"})),o+=a.len;break;case"M":case"EQ":case"=":case"X":i.push(new zu({start:n,seqOffset:o,len:a.len,type:"M"})),o+=a.len,n+=a.len;break;default:console.log("Error processing cigar element: "+a.len+a.ltr)}}e.blocks=i,e.insertions=r,e.gaps=s}function ju(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function Wu(e){var t,i,r,s,o,n,a,c,l;for(t=[],i=[],o=null,s=e.length,r=0;r=48&&l<=57?i.push(n):(a=n,c=Number.parseInt(i.join("")),i=[],null!==o&&o.ltr===a?o.len+=c:(o={len:c,ltr:a},t.push(o)));return t}function $u(e){var t={};return e.forEach((function(e){var i=e.split(":");t[i[0]]=i[2]})),t}function Ku(e){let t=0;const i=e.length,r={},s=new DataView(e.buffer);for(;t=0?atob(r):decodeURI(r);const s=new Uint8Array(r.length);for(var o=0;o"start"!==e&&"end"!==e)).map((e=>i[e])).filter((e=>t.has(e)));e.length>0&&(r=e[0])}return this.chrAliasTable.set(e,r),r}return e}}class Yu{chrAliasTable=new Map;constructor(e,t){this.config=e,this.genome=t,this.bamPath=e.url,this.baiPath=e.indexURL,Qu.setReaderDefaults(this,e),this._blockLoader=new Xa(e)}async readAlignments(e,t,i){const r=await this.#_(e),s=new fu(e,t,i,this.config);if(void 0===r)return s;{const e=(await this.getIndex()).chunksForRange(r,t,i);if(!e||0===e.length)return s;for(let o of e){const e=await this._blockLoader.getData(o.minv,o.maxv);if(Qu.decodeBamRecords(e,o.minv.offset,s,this.header.chrNames,r,t,i,this.filter))break}return s.finish(),s}}async#_(e){if(await this.getHeader(),this.chrAliasTable.has(e)&&void 0===(e=this.chrAliasTable.get(e)))return;let t=this.header.chrToIndex[e];if(void 0===t){const i=await this.genome.getAliasRecord(e);let r;if(i){const e=Object.keys(i).filter((e=>"start"!==e&&"end"!==e)).map((e=>i[e])).filter((e=>void 0!==this.header.chrToIndex[e]));e.length>0&&(r=e[0],t=this.header.chrToIndex[e[0]])}this.chrAliasTable.set(e,r)}return t}async getHeader(){if(!this.header){const e=this.genome,t=await this.getIndex();let i;if(t.firstBlockPosition){const e=ts(this.config,{range:{start:t.firstBlockPosition,size:26}}),r=ir(await Rr.loadArrayBuffer(this.bamPath,e));i=t.firstBlockPosition+r}else i=64e3;const r=ts(this.config,{range:{start:0,size:i}});this.header=await Qu.readHeader(this.bamPath,r,e)}return this.header}async getIndex(){return this.index||(this.index=await ja(this.baiPath,this.config)),this.index}async getChrIndex(){if(this.chrToIndex)return this.chrToIndex;{const e=await this.getHeader();return this.chrToIndex=e.chrToIndex,this.indexToChr=e.chrNames,this.chrNames=new Set(e.chrNames),this.chrToIndex}}}class Xu{constructor(e,t){this.config=e,this.genome=t;const i={};e.sources.sequences.forEach((function(r){const s=t?t.getChromosomeName(r):r;i[s]=function(e,t,i){const r={url:e.sources.url.replace("$CHR",i)};e.sources.indexURL&&(r.indexURL=e.sources.indexURL.replace("$CHR",i));const s=Object.assign(e,r);return new Yu(s,t)}(e,t,r)})),this.bamReaders=i,Qu.setReaderDefaults(this,e)}async readAlignments(e,t,i){if(this.bamReaders.hasOwnProperty(e)){let r=this.bamReaders[e];return await r.readAlignments(e,t,i)}return new fu(e,t,i,this.config)}}const Ju=function(e,t){this.config=e,this.genome=t,Qu.setReaderDefaults(this,e)};function ef(){const e=this,t=this.genome;if(this.header)return Promise.resolve(this.header);{const i=this.config.url+"?file="+this.config.alignmentFile+"&options=-b,-H",r=ts(this.config);return Qu.readHeader(i,r,t).then((function(t){return e.header=t,t}))}}Ju.prototype.readAlignments=function(e,t,i){var r=this;return ef.call(r).then((function(s){var o,n;return o=s.chrAliasTable.hasOwnProperty(e)?s.chrAliasTable[e]:e,n=r.config.url+"?reference="+r.config.referenceFile+"&file="+r.config.alignmentFile+"®ion="+o+":"+t+"-"+i,Rr.loadString(n,ts(r.config)).then((function(n){var a;return s.chrToIndex[o],a=new fu(e,t,i,r.config),Qu.decodeSamRecords(n,a,o,t,i,r.filter),a}))}))};class tf extends hc{chrNames=new Set;constructor(e,t){super(e,t),Qu.setReaderDefaults(this,e)}async readAlignments(e,t,i){if("all"===e)return[];if(!this.header){const e=tr((await this.readHeaderData()).buffer);this.header=Qu.decodeBamHeader(e,this.genome);for(let e of this.header.chrNames)this.chrNames.add(e);this.chromAliasManager=this.genome?new fc(this.header.chrNames,this.genome):null}let r=e;if(this.chrNames.size>0&&!this.chrNames.has(e)&&this.chromAliasManager&&(r=await this.chromAliasManager.getAliasName(e)),!this.chrNames.has(r))return console.warn("Chromosome "+e+" not found in BAM header"),new fu(e,t,i,this.config);const s=tr((await this.readData(r,t,i)).buffer);this.header=Qu.decodeBamHeader(s,this.genome);const o=this.header.chrToIndex[e],n=new fu(e,t,i,this.config);return Qu.decodeBamRecords(s,this.header.size,n,this.header.chrNames,o,t,i,this.filter),n.finish(),n}} -/*! For license information please see cram-bundle.js.LICENSE.txt */var rf,sf,of=(rf={24:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toHex=function(e){let t="";for(let i=0,s=e.length;i>>4&15]}${i[15&e]}`},78:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(24),s=[0,1,3,7,15,31,63,127,255];t.default=class{constructor(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1}_ensureByte(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)}read(e){let t=0;for(;e>0;){this._ensureByte();const i=8-this.bitOffset;if(e>=i)t<<=i,t|=s[i]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=i;else{t<<=e;const r=i-e;t|=(this.curByte&s[e]<>r,this.bitOffset+=e,e=0}}return t}seek(e){const t=e%8,i=(e-t)/8;this.bitOffset=t,this.stream.seek(i),this.hasByte=!1}pi(){const e=new Uint8Array(6);for(let t=0;t{const r=i(1308).A;e.exports=r,e.exports.default=r},500:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=i(6272),o=i(6761),n=r(i(588)),a=r(i(9685)),c=r(i(7480)),l=i(7580),h=i(2549);function d(e,t,i,r){const o=!!(r.mate||void 0!==r.mateRecordNumber&&r.mateRecordNumber!==t);i.readName||(i.readName=String(i.uniqueId),r.readName=i.readName),i.mate={sequenceId:r.sequenceId,alignmentStart:r.alignmentStart,uniqueId:r.uniqueId},r.readName&&(i.mate.readName=r.readName),r.mate||void 0!==r.mateRecordNumber||(r.mate={sequenceId:i.sequenceId,alignmentStart:i.alignmentStart,uniqueId:i.uniqueId},i.readName&&(r.mate.readName=i.readName)),i.flags|=n.default.BAM_FPAIRED,r.flags&n.default.BAM_FUNMAP&&(i.flags|=n.default.BAM_FMUNMAP),i.flags&n.default.BAM_FUNMAP&&(r.flags|=n.default.BAM_FMUNMAP),r.flags&n.default.BAM_FREVERSE&&(i.flags|=n.default.BAM_FMREVERSE),i.flags&n.default.BAM_FREVERSE&&(r.flags|=n.default.BAM_FMREVERSE),void 0===i.templateLength&&(o?function(e,t,i){const r=function t(i){const r=[i];if(void 0!==i.mateRecordNumber&&i.mateRecordNumber>=0){const o=e[i.mateRecordNumber];if(!o)throw new s.CramMalformedError("intra-slice mate record not found, this file seems malformed");r.push(...t(o))}return r}(i),o=r.map((e=>e.alignmentStart)),n=r.map((e=>e.alignmentStart+e.readLength-1)),a=Math.max(...n)-Math.min(...o)+1;a>=0&&r.forEach((e=>{if(void 0!==e.templateLength)throw new s.CramMalformedError("mate pair group has some members that have template lengths already, this file seems malformed");e.templateLength=a}))}(e,0,i):function(e,t){const i=Math.min(e.alignmentStart,t.alignmentStart),r=Math.max(e.alignmentStart+e.readLength-1,t.alignmentStart+t.readLength-1)-i+1;e.templateLength=r,t.templateLength=r}(i,r)),i.mateRecordNumber=void 0}class u{constructor(e,t,i){this.container=e,this.containerPosition=t,this.sliceSize=i,this.file=e.file}async getHeader(){const{majorVersion:e}=await this.file.getDefinition(),t=(0,l.getSectionParsers)(e),i=await this.container.getHeader(),r=await this.file.readBlock(i._endPosition+this.containerPosition);if("MAPPED_SLICE_HEADER"===r.contentType){const e=(0,h.parseItem)(r.content,t.cramMappedSliceHeader.parser,0,i._endPosition);return{...r,parsedContent:e}}if("UNMAPPED_SLICE_HEADER"===r.contentType){const e=(0,h.parseItem)(r.content,t.cramUnmappedSliceHeader.parser,0,i._endPosition);return{...r,parsedContent:e}}throw new s.CramMalformedError(`error reading slice header block, invalid content type ${r.contentType}`)}async getBlocks(){const e=await this.getHeader();let t=e._endPosition;const i=new Array(e.parsedContent.numBlocks);for(let e=0;e{"EXTERNAL_DATA"===e.contentType&&(t[e.contentId]=e)})),t}async getBlockByContentId(e){return(await this._getBlocksContentIdIndex())[e]}async getReferenceRegion(){const e=new TextDecoder("utf8"),t=(await this.getHeader()).parsedContent;if(!(0,l.isMappedSliceHeader)(t))throw new Error("slice header not mapped");if(t.refSeqId<0)return;const i=await this.container.getCompressionScheme();if(void 0===i)throw new Error("compression scheme undefined");if(t.refBaseBlockId>=0){const i=await this.getBlockByContentId(t.refBaseBlockId);if(!i)throw new s.CramMalformedError("embedded reference specified, but reference block does not exist");return{seq:e.decode(i.data),start:t.refSeqStart,end:t.refSeqStart+t.refSeqSpan-1,span:t.refSeqSpan}}if(i.referenceRequired||this.file.fetchReferenceSequenceCallback){if(!this.file.fetchReferenceSequenceCallback)throw new Error("reference sequence not embedded, and seqFetch callback not provided, cannot fetch reference sequence");const e=await this.file.fetchReferenceSequenceCallback(t.refSeqId,t.refSeqStart,t.refSeqStart+t.refSeqSpan-1);if(e.length!==t.refSeqSpan)throw new s.CramArgumentError("seqFetch callback returned a reference sequence of the wrong length");return{seq:e,start:t.refSeqStart,end:t.refSeqStart+t.refSeqSpan-1,span:t.refSeqSpan}}}getAllRecords(){return this.getRecords((()=>!0))}async _fetchRecords(){const{majorVersion:e}=await this.file.getDefinition(),t=await this.container.getCompressionScheme();if(void 0===t)throw new Error("compression scheme undefined");const i=await this.getHeader(),r=await this._getBlocksContentIdIndex();if(e>1&&this.file.options.checkSequenceMD5&&(0,l.isMappedSliceHeader)(i.parsedContent)&&i.parsedContent.refSeqId>=0&&"0000000000000000"!==i.parsedContent.md5?.join("")){const e=await this.getReferenceRegion();if(e){const{seq:t,start:r,end:o}=e,n=(0,h.sequenceMD5)(t),a=i.parsedContent.md5?.map((e=>(e<16?"0":"")+e.toString(16))).join("");if(n!==a)throw new s.CramMalformedError(`MD5 checksum reference mismatch for ref ${i.parsedContent.refSeqId} pos ${r}..${o}. recorded MD5: ${a}, calculated MD5: ${n}`)}}const n=await this.getCoreDataBlock(),u={lastAlignmentStart:(0,l.isMappedSliceHeader)(i.parsedContent)?i.parsedContent.refSeqStart:0,coreBlock:{bitPosition:7,bytePosition:0},externalBlocks:{map:new Map,getCursor(e){let t=this.map.get(e);return void 0===t&&(t={bitPosition:7,bytePosition:0},this.map.set(e,t)),t}}},f=e=>{const i=t.getCodecForDataSeries(e);if(!i)throw new s.CramMalformedError(`no codec defined for ${e} data series`);return i.decode(this,n,r,u)},p=new Array(i.parsedContent.numRecords);for(let s=0;s=0&&p[i]&&d(p,e,t,p[i])}}return p}async getRecords(e){const t=this.container.filePosition+this.containerPosition;let i=this.file.featureCache.get(t.toString());i||(i=this._fetchRecords(),this.file.featureCache.set(t.toString(),i));const r=(await i).filter(e);if(r.length&&this.file.fetchReferenceSequenceCallback){const e=await this.getHeader();if((0,l.isMappedSliceHeader)(e.parsedContent)&&(e.parsedContent.refSeqId>=0||-2===e.parsedContent.refSeqId)){const t=e.parsedContent.refSeqId>=0?e.parsedContent.refSeqId:void 0,i=await this.container.getCompressionScheme();if(void 0===i)throw new Error("compression scheme undefined");const s={};for(const e of r){const i=void 0!==t?t:e.sequenceId;let r=s[i];r||(r={id:i,start:e.alignmentStart,end:Number.NEGATIVE_INFINITY,seq:null},s[i]=r);const o=e.alignmentStart+(e.lengthOnRef||e.readLength)-1;o>r.end&&(r.end=o),e.alignmentStart{-1!==e.id&&e.start<=e.end&&this.file.fetchReferenceSequenceCallback&&(e.seq=await this.file.fetchReferenceSequenceCallback(e.id,e.start,e.end))})));for(const e of r){const r=s[void 0!==t?t:e.sequenceId];if(r?.seq){const t=r.seq;e.addReferenceSequence({...r,seq:t},i)}}}}return r}}t.default=u,"getHeader getBlocks _getBlocksContentIdIndex".split(" ").forEach((e=>{(0,h.tinyMemoize)(u,e)}))},588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={CRAM_FLAG_PRESERVE_QUAL_SCORES:1,CRAM_FLAG_DETACHED:2,CRAM_FLAG_MATE_DOWNSTREAM:4,CRAM_FLAG_NO_SEQ:8,CRAM_FLAG_MASK:15,CRAM_M_REVERSE:1,CRAM_M_UNMAP:2,BAM_FPAIRED:1,BAM_FPROPER_PAIR:2,BAM_FUNMAP:4,BAM_FMUNMAP:8,BAM_FREVERSE:16,BAM_FMREVERSE:32,BAM_FREAD1:64,BAM_FREAD2:128,BAM_FSECONDARY:256,BAM_FQCFAIL:512,BAM_FDUP:1024,BAM_FSUPPLEMENTARY:2048,BAM_CMATCH:0,BAM_CINS:1,BAM_CDEL:2,BAM_CREF_SKIP:3,BAM_CSOFT_CLIP:4,BAM_CHARD_CLIP:5,BAM_CPAD:6,BAM_CEQUAL:7,BAM_CDIFF:8,BAM_CBACK:9,BAM_CIGAR_STR:"MIDNSHP:XB",BAM_CIGAR_SHIFT:4,BAM_CIGAR_MASK:15,BAM_CIGAR_TYPE:246183}},632:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6761),n=i(6272);class a extends s.default{constructor(e,t){if(super(e,t),"int"!==this.dataType)throw new n.CramUnimplementedError(`${this.dataType} decoding not yet implemented by GAMMA codec`)}decode(e,t,i,r){let s=1;for(;0===(0,o.getBits)(t.content,r.coreBlock,1);)s+=1;return((0,o.getBits)(t.content,r.coreBlock,s-1)|1<{function t(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}e.exports=function(e){return null!=e&&(t(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&t(e.slice(0,0))}(e)||!!e._isBuffer)}},772:()=>{},807:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6761),n=i(6272);class a extends s.default{constructor(e,t){if(super(e,t),"int"!==this.dataType)throw new n.CramUnimplementedError(`${this.dataType} decoding not yet implemented by BETA codec`)}decode(e,t,i,r){return(0,o.getBits)(t.content,r.coreBlock,this.parameters.length)-this.parameters.offset}}t.default=a},870:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e,t,i){const r=u(e),s=f(t),o=new d(r,s);for(;!("eof"in r)||!r.eof();)if(o._init_block())o._read_bunzip();else{const e=o.reader.read(32)>>>0;if(e!==o.streamCRC&&h(c.DATA_ERROR,"Bad stream CRC (got "+o.streamCRC.toString(16)+" expected "+e.toString(16)+")"),!i||!("eof"in r)||r.eof())break;o._start_bunzip(r,s)}if("getBuffer"in s)return s.getBuffer()};const s=r(i(78)),o=r(i(8761)),n=r(i(6612)),a=function(e,t){const i=e[t];for(let i=t;i>0;i--)e[i]=e[i-1];return e[0]=i,i},c={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},l={};l[c.LAST_BLOCK]="Bad file checksum",l[c.NOT_BZIP_DATA]="Not bzip data",l[c.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",l[c.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",l[c.DATA_ERROR]="Data error",l[c.OUT_OF_MEMORY]="Out of memory",l[c.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";const h=function(e,t){let i=l[e]||"unknown error";t&&(i+=": "+t);const r=new TypeError(i);throw r.errorCode=e,r};class d{constructor(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)}_init_block(){return this._get_next_block()?(this.blockCRC=new o.default,!0):(this.writeCount=-1,!1)}_start_bunzip(e,t){const i=new Uint8Array(4);4===e.read(i,0,4)&&"BZh"===String.fromCharCode(i[0],i[1],i[2])||h(c.NOT_BZIP_DATA,"bad magic");const r=i[3]-48;(r<1||r>9)&&h(c.NOT_BZIP_DATA,"level out of range"),this.reader=new s.default(e),this.dbufSize=1e5*r,this.nextoutput=0,this.outputStream=t,this.streamCRC=0}_get_next_block(){let e,t,i;const r=this.reader,s=r.pi();if("177245385090"===s)return!1;"314159265359"!==s&&h(c.NOT_BZIP_DATA),this.targetBlockCRC=r.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,r.read(1)&&h(c.OBSOLETE_INPUT);const o=r.read(24);o>this.dbufSize&&h(c.DATA_ERROR,"initial position out of bounds");let n=r.read(16),l=new Uint8Array(256),d=0;for(e=0;e<16;e++)if(n&1<<15-e){const s=16*e;for(i=r.read(16),t=0;t<16;t++)i&1<<15-t&&(l[d++]=s+t)}const u=r.read(3);(u<2||u>6)&&h(c.DATA_ERROR);const f=r.read(15);0===f&&h(c.DATA_ERROR);const p=new Uint8Array(256);for(e=0;e=u&&h(c.DATA_ERROR);g[e]=a(p,t)}let m,w=d+2,b=[];for(t=0;t20)&&h(c.DATA_ERROR),r.read(1);)r.read(1)?n--:n++;t[e]=n}var F,v;for(F=v=t[0],e=1;ev?v=t[e]:t[e]=f&&h(c.DATA_ERROR),m=b[g[x++]]),e=m.minLen,t=r.read(e);e>m.maxLen&&h(c.DATA_ERROR),!(t<=m.limit[e]);e++)t=t<<1|r.read(1);t-=m.base[e],(t<0||t>=258)&&h(c.DATA_ERROR);const i=m.permute[t];if(0!==i&&1!==i){if(C)for(C=0,_+n>this.dbufSize&&h(c.DATA_ERROR),A=l[p[0]],y[A]+=n;n--;)k[_++]=A;if(i>d)break;_>=this.dbufSize&&h(c.DATA_ERROR),e=i-1,A=a(p,e),A=l[A],y[A]++,k[_++]=A}else C||(C=1,n=0),n+=0===i?C:2*C,C<<=1}for((o<0||o>=_)&&h(c.DATA_ERROR),t=0,e=0;e<256;e++)i=t+y[e],y[e]=t,t=i;for(e=0;e<_;e++)A=255&k[e],k[y[A]]|=e<<8,y[A]++;let I=0,S=0,E=0;return _&&(I=k[o],S=255&I,I>>=8,E=-1),this.writePos=I,this.writeCurrent=S,this.writeCount=_,this.writeRun=E,!0}_read_bunzip(e,t){let i,r,s;if(this.writeCount<0)return 0;let o=this.dbuf,n=this.writePos,a=this.writeCurrent,l=this.writeCount,d=(this.outputsize,this.writeRun);for(;l;){for(l--,r=a,n=o[n],a=255&n,n>>=8,3===d++?(i=a,s=r,a=-1):(i=1,s=a),this.blockCRC.updateCRCRun(s,i);i--;)this.outputStream.writeByte(s),this.nextoutput++;a!=r&&(d=0)}return this.writeCount=l,this.blockCRC.getCRC()!==this.targetBlockCRC&&h(c.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput}}const u=function(e){if("readByte"in e)return e;const t=new n.default;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},f=function(e){const t=new n.default;let i=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),i=!1;else{if("writeByte"in e)return e;t.buffer=e,i=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(i&&this.pos>=this.buffer.length){const e=new Uint8Array(2*this.buffer.length);e.set(this.buffer),this.buffer=e}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!i)throw new TypeError("outputsize does not match decoded input");const e=new Uint8Array(this.pos);e.set(this.buffer.slice(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};t.default=d},1064:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.blob=e,this.size=e.size}async read(e,t=0){if(!e)return new Uint8Array(0);const i=t,r=i+e;return new Uint8Array(await this.blob.slice(i,r).arrayBuffer())}async readFile(e){const t="string"==typeof e?e:e?.encoding;if("utf8"===t)return this.blob.text();if(t)throw new Error(`unsupported encoding: ${t}`);return new Uint8Array(await this.blob.arrayBuffer())}async stat(){return{size:this.size}}async close(){}}},1307:function(e,t,i){var r;r=e=>(()=>{var t=[,e=>{e.exports="data:application/wasm;base64,AGFzbQEAAAABOApgAX8Bf2ABfwBgAABgA39/fwF/YAABf2ACf38AYAN/f34BfmACf38Bf2AEf39/fwF/YAN/f38AAyEgAAABAgMDAwMEAQUAAgMCBgcIBwUDAAMHAQcABwcBAwkFAwEAAgYIAX8BQfCgBAsHTgUGbWVtb3J5AgAOY3JlYXRlX2NvbnRleHQACA9kZXN0cm95X2NvbnRleHQACQxzdXBwbHlfaW5wdXQACg9nZXRfbmV4dF9vdXRwdXQACwqNYCDfAgEFf0EAIQECQCAAQQdqIgJBEEkNAEEBIQEgAkEDdiIDQQJGDQBBAiEBIAJBIEkNAEEDIQEgA0EERg0AQQQhASACQTBJDQBBBSEBIANBBkYNAEEGIQEgAkHIAEkNAEEHIQEgAkHYAEkNAEEIIQEgAkGIAUkNAEEJIQEgAkGIAkkNACAAEIGAgIAAIgBBCGpBACAAGw8LAkACQCABQQJ0QcCIgIAAaiIEKAIAIgANAEEAIQACQAJAQQAoAuSIgIAAIgJFDQBBACACKAIANgLkiICAAAwBC0EAEIGAgIAAIgJFDQILIAJBgIB8cSIAIAJBCHZB/wFxIgJyIAE6AAAgAkEIdCAAckGAAmohAEEAIQJBACABQQJ0QYCIgIAAaigCACIDayEFIAMhAQNAIAAgBWoiACACNgIAIAAhAiABIANqIgFBgQJJDQALIAQgADYCAAsgBCAAKAIANgIACyAAC+4HAQd/AkACQAJAAkACQEEALQC0iICAAEUNAEEAQQA6ALSIgIAAQQAoArCIgIAAIgFFDQFBsIiAgAAhAgNAAkACQCABQQhqIgMgASgCBCIEaiIFQQh2Qf8BcSIGDQAgASECDAELAkADQCAFQYCAfHEgBmotAABB/gFHDQFBsIiAgAAhBgNAIAYiBygCACIGIAVHDQALIAcgBSgCADYCACABIAQgBSgCBGpBCGoiBDYCBCAHIAIgAiAFRhshAiADIARqIgVBCHZB/wFxIgYNAAsLIAIoAgAhAgsgAigCACIBDQALC0EAKAKwiICAACIFRQ0AIABBhwJqQYB+cSEDQX8hAkGwiICAACEEQQAhAUGwiICAACEGA0AgBiEHAkAgBSIGKAIEIgUgAEkNACAFIAJPDQAgBSECIAchBCAGIQEgBUEIaiADRw0AIAchBCAFIQIgBiEBDAQLIAYoAgAiBQ0ACyABDQIMAQtBsIiAgAAhBAs/AEEQdCEBIABBiAJqIQdBACEDAkACQEEAKAK4iICAACICRQ0AQQAhBSABIQYMAQtBACABQfCghIAAQf//A2pBgIB8cSIGayICNgK4iICAACACIQULAkAgByAFTQ0AIAcgBWsiByACQQF2IgIgAiAHSRtB//8DaiIHQRB2QABBf0YNAkEAQQAoAriIgIAAIAdBgIB8cSIDajYCuIiAgAALIAZFDQEgBkH/AToAASAGQQAoArCIgIAANgKAAiAGQYQCaiADIAVqQYCAfHFB+H1qIgI2AgAgBkGAAmohAQsgAUGAgHxxIgYgAUEIdkH/AXFyQf8BOgAAIAQgASgCADYCAAJAIAIgAGtBgH5xIgUNACABDwsgASEDAkAgBiABQQhqIgQgAmoiByAFQX9zakGAgHxxRg0AIARB//8DcSEFAkAgAEH3/QNLDQAgBiAEQQh2Qf8BcWpB/gE6AAAgAUEAKAKwiICAADYCACABQYCABCAFayIFNgIEQQAgATYCsIiAgAAQg4CAgAAgBkGEggRqIAIgBWtB+H1qIgU2AgAgBkGBgARqQf8BOgAAIAZBgIIEaiEDIAUgAGtBgH5xIQUMAQsgAiAFaiAAIAVqQX9qQYCAfHFrQYCAfGohBSABIQMLIAMgAygCBCAFazYCBCAFQfgBaiEGIAcgBWtBCHZB/wFxIQUCQANAIAYiB0GAfmohBiAFIgQNAUEBIQUgB0H4AUcNAAsLAkAgB0H4AUYNACACIAFqIAZrQYCAfHEiBSAEakH+AToAACAFIARBCHRqIgVBACgCsIiAgAA2AgAgBSAGNgIEQQAgBTYCsIiAgAAQg4CAgAALIAMPC0EAC3wBAn8CQCAARQ0AAkAgAEGAgHxxIABBCHZB/wFxciIBLQAAIgJB/wFHDQAgAEF4aiIAQQAoArCIgIAANgIAQQAgADYCsIiAgAAgAUH+AToAAEEAQQE6ALSIgIAADwsgACACQQJ0QcCIgIAAaiICKAIANgIAIAIgADYCAAsLawECfwJAQQAoArCIgIAAIgAoAgRB/wFLDQAgAEGAgHxxIgEgAEEIdkH/AXEiAHJBCToAAEEAQQAoArCIgIAAKAIANgKwiICAACABIABBCHRyIgBBACgC5IiAgAA2AgBBACAANgLkiICAAAsLTgECfwJAIAAgAUYNACACRQ0AA0ACQCAALQAAIgMgAS0AACIERg0AQQFBfyADIARLGw8LIAFBAWohASAAQQFqIQAgAkF/aiICDQALC0EAC3gBAX8CQAJAIAAgAU8NACACRQ0BIAAhAwNAIAMgAS0AADoAACABQQFqIQEgA0EBaiEDIAJBf2oiAg0ADAILCyAAIAFNDQAgAkUNACABQX9qIQEgAEF/aiEDA0AgAyACaiABIAJqLQAAOgAAIAJBf2oiAg0ACwsgAAssAQF/AkAgAkUNACAAIQMDQCADIAE6AAAgA0EBaiEDIAJBf2oiAg0ACwsgAAuCAQEBfwJAAkAgAEEDcQ0AIAEgAnJBA3ENACACQQRJDQEgAkECdiECIAAhAwNAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIAJBf2oiAg0ADAILCyACRQ0AIAAhAwNAIAMgAS0AADoAACABQQFqIQEgA0EBaiEDIAJBf2oiAg0ACwsgAAuIAQECfwJAQQAtAOiIgIAADQBBAEEBOgDoiICAABCMgICAABCOgICAAAtBoIAIEICAgIAAIgBBgIAENgIAQQJBgICAIBCXgICAACEBIABBFGpCgICAgICAwAA3AgAgAEEQaiAAQaCABGo2AgAgAEEIakIANwMAIAAgAEEgajYCBCAAIAE2AhwgAAsVACAAKAIcEJiAgIAAIAAQgoCAgAALFgAgAEEMaiABNgIAIABBCGpBADYCAAsbACAAKAIcIABBBGogAEEMaigCAEUQloCAgAALVAEDf0EAIQADQEEIIQEgACECA0BBACACQQFxa0GghuLtfnEgAkEBdnMhAiABQX9qIgENAAsgAEECdEHwiICAAGogAjYCACAAQQFqIgBBgAJHDQALC0oAIAJBf3MhAgJAIAFFDQADQCACQf8BcSAALQAAc0ECdEHwiICAAGooAgAgAkEIdnMhAiAAQQFqIQAgAUF/aiIBDQALCyACQX9zC10DAX4BfwF+QgAhAANAQQghASAAIQIDQEIAIAJCAYN9QsKenLzd8pW2SYMgAkIBiIUhAiABQX9qIgENAAsgAKdBA3RB8JCAgABqIAI3AwAgAEIBfCIAQoACUg0ACwtLACACQn+FIQICQCABRQ0AA0AgAkL/AYMgADEAAIWnQQN0QfCQgIAAaikDACACQgiIhSECIABBAWohACABQX9qIgENAAsLIAJCf4UL1RACDH8CfgJAAkAgACgCJEUNACAAKAIAIQIMAQtBACECIABBADoAKCAAQgA3AwAgAEIANwMYIABByABqQQBB5AAQhoCAgAAaIABBrAFqQQw2AgALIAAgASgCBCIDNgIQIABBsAFqIQQgAEHgAGohBSAAQcgAaiEGIABBtgFqIQcgAEGoAWohCCABKAIQIQkCQAJAAkACQANAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIOCgECAAQFBgcICQoPCyABKAIAIQogACgCqAEhAiAAKAKsASELIAEoAgQhDCABKAIIIQ0MAgsgCCAAKAKoASIMakEIaiABKAIAIAEoAgQiAmogASgCCCACayICIAAoAqwBIAxrIgwgAiAMSRsiAhCHgICAABogASABKAIEIAJqNgIEQQAhDCAAQQAgACgCqAEgAmoiAiACIAAoAqwBIgtGGzYCqAEgAiALRw0RIABBATYCAAJAIARBqIiAgABBBhCEgICAAEUNAEEFIQwMEgsgB0ECQQAQjYCAgAAgACgAuAFHDRBBBiEMIActAAANESAAIAAtALcBIgI2AiAgAkEESw0RQQEgAnRBE3FFDRELIAEoAgQiDCABKAIIIg1GDQ4CQCABKAIAIgogDGotAAAiCw0AIAAgDDYCECABIAxBAWo2AgRBBiECDAwLQQAhAiAAQQA2AqgBIABBAjYCACAAIAtBAnRBBGoiCzYCrAEgACALNgJACyAIIAJqQQhqIAogDGogDSAMayIMIAsgAmsiAiAMIAJJGyICEIeAgIAAGiABIAIgASgCBGo2AgRBACEMIABBACAAKAKoASACaiICIAIgACgCrAEiC0YbNgKoASACIAtHDQ8gACACQXxqIgI2AqwBQQchDCAEIAJBABCNgICAACAAIAAoAqwBIgtqQbABaigAAEcNDyAAQQI2AqgBIAAtALEBIgJBP3ENDAJAAkAgAkHAAHFFDQAgACAEIAggCxCRgICAAEEBRw0RIAAgACkDCDcDMCAALQCxASECDAELIABCfzcDMAtCfyEOAkAgAkEYdEEYdUF/Sg0AIAAgBCAIIAAoAqwBEJGAgIAAQQFHDRAgACkDCCEOCyAAIA43AzggACgCrAEiDSAAKAKoASICa0ECSQ0PIAAgAkEBaiIKNgKoASAIIAJqQQhqLQAAQSFHDQwgACACQQJqIgs2AqgBIAggCmpBCGotAABBAUcNDCANIAtGDQ8gACACQQNqNgKoASAAKAKwCSAIIAtqQQhqLQAAEJyAgIAAIgwNDyAAKAKoASIMIAAoAqwBIgIgDCACSxshDQJAA0AgDSAMRg0BIAggDEEBaiICNgIAIAQgDGohCyACIQwgCy0AAA0ODAALCyAGQgA3AwAgAEEANgKoASAAQQM2AgAgBkEIakIANwMACyAAIAEoAgQ2AhAgACABKAIQNgIUIAAoArAJIAEQmYCAgAAhDCAAIAApA0ggASgCBCAAKAIQa618Ig43A0ggACAAKQNQIAEoAhAgACgCFCICayILrXwiDzcDUCAOIAApAzBWDQ0gDyAAKQM4Vg0NAkACQAJAAkAgACgCIEF/ag4EAAMDAQMLIAEoAgwgAmogCyAAKAIYEI2AgIAArSEODAELIAEoAgwgAmogCyAAKQMYEI+AgIAAIQ4LIAAgDjcDGAsgDEEBRw0OAkAgACkDMCIOQn9RDQAgDiAGKQMAUg0OCwJAIAApAzgiDkJ/UQ0AQQchDCAOIAApA1BSDQ8LIAAgACkDSCAANQJAfCAAKQNgfCIPNwNgQgQhDgJAAkACQCAAKAIgQX9qDgQBAgIAAgtCCCEOCyAFIA4gD3w3AwALIAAgACkDaCAAKQNQfDcDaCAAIAVBGCAAKAJwEI2AgIAANgJwIABBBDYCACAAIAApA1hCAXw3A1gLAkAgBikDACIOQgODUA0AIA5CAXwhDiABKAIEIQwgASgCCCELA0AgCyAMRg0NIAEgDEEBaiICNgIEIAEoAgAgDGotAAANDiAGIA43AwAgDkIDgyEPIA5CAXwhDiACIQwgD0IAUg0ACwsgAEEFNgIAC0EBIQIgACgCIEF/ag4EBgcHBQcLIAAgARCSgICAACIMQQFHDQsgAEEHNgIAC0EAIAAoAhBrIQggAEGAAWopAwAhDiABKAIEIQwCQANAIA4gCCAMaq18QgODUA0BAkAgDCABKAIIRw0AIAAgARCTgICAAAwLCyABIAxBAWoiAjYCBCABKAIAIAxqIQsgAiEMIAstAAANCwwACwsgACABEJOAgIAAQQchDCAFIABBkAFqQRgQhICAgAANCiAAQQg2AgALIAAgAUEgEJSAgIAAIgxBAUcNCSAAQQk2AgBBDCELIABBDDYCrAEMAQsgACgCrAEhCwsgAEGoAWogACgCqAEiDGpBCGogASgCACABKAIEIgJqIAEoAgggAmsiAiALIAxrIgwgAiAMSRsiAhCHgICAABogASABKAIEIAJqNgIEQQAhDCAAQQAgACgCqAEgAmoiAiACIAAoAqwBIgtGGzYCqAEgAiALRw0HIAAQlYCAgAAhDAwHC0EBIQIgACABQcAAEJSAgIAAIgxBAUcNBgwBC0EBIQIgACABQSAQlICAgAAiDEEBRw0FCyAAIAI2AgAMAAsLQQYhDAwCC0EAIQwMAQtBByEMCwJAAkAgACgCJA0AAkACQCAMDgIAAwELQQdBCCABKAIEIAEoAghGGyEMCyABIAk2AhAgASADNgIEIAwPCwJAIAwNACADIAEoAgRHDQAgCSABKAIQRw0AIAAtACghASAAQQE6ACggAUEDdA8LIABBADoAKAsgDAuaAQEDfwJAIAAoAgQiBA0AIABCADcDCAsgAigCACEFA0ACQCAFIANJDQBBAA8LIAEgBWotAAAhBiACIAVBAWoiBTYCACAAIAZB/wBxrSAErYYgACkDCIQ3AwgCQAJAIAZBgAFxDQACQCAGDQBBByEGIAQNAgsgAEEANgIEQQEPC0EHIQYgACAEQQdqIgQ2AgQgBEE/Rw0BCwsgBguhAgIDfwF+IABBkAFqIQIgAUEEaiEDA0ACQCAAIAEoAgAgAyABKAIIEJGAgIAAIgRBAUYNACAAQYABaiIDIAMpAwAgASgCBCAAKAIQIgNrIgKtfDcDACAAIAMgASgCAGogAiAAKAIYEI2AgIAArTcDGCAEDwsCQAJAAkACQAJAIAAoAngOAwACAQMLIAAgACkDCCIFNwOIAQJAIAUgACkDWFENAEEHDwsgAEEBNgJ4DAMLIAAgACkDmAEgACkDCHw3A5gBIAAgAkEYIAAoAqABEI2AgIAANgKgASAAQQE2AnggACAAKQOIAUJ/fCIFNwOIAQwCCyAAQQI2AnggACAAKQOQASAAKQMIfDcDkAELIAApA4gBIQULIAVCAFINAAtBAQtAAQJ/IABBgAFqIgIgAikDACABKAIEIAAoAhAiAmsiA618NwMAIAAgAiABKAIAaiADIAAoAhgQjYCAgACtNwMYC3wBBH8gASgCBCEDIAEoAgghBANAAkAgBCADRw0AQQAPCyABIANBAWoiBTYCBAJAIAEoAgAgA2otAAAgACkDGCAAKAIEIgOtiKdB/wFxRg0AQQcPCyAAIANBCGoiBjYCBCAFIQMgBiACSQ0ACyAAQQA2AgQgAEIANwMYQQELbwEBf0EHIQECQCAAQboBai8AAEHZtAFHDQAgAEG0AWpBBkEAEI2AgIAAIABBsAFqKAAARw0AIABBgAFqKQMAQgKIIAA1ALQBUg0AIABBuAFqLQAADQBBAUEHIAAoAiAgAEG5AWotAABGGyEBCyABC7QCAQR/AkACQCAAKAIkRQ0AIAAoAgAhAwwBC0EAIQMgAEEAOgAoIABCADcDACAAQgA3AxggAEHIAGpBAEHkABCGgICAABogAEGsAWpBDDYCAEEBIQILIABByABqIQQCQAJAA0ACQCADQQpHDQAgASgCBCIDIAEoAggiBUYNAiABKAIAIQYCQANAIAYgA2otAAANASABIANBAWoiAzYCBCAAIAAoAgRBAWpBA3E2AgQgBSADRg0EDAALCwJAIAAoAgRFDQBBBw8LIAAoAiRFDQAgAEEAOgAoIABCADcDACAAQgA3AxggBEEAQeQAEIaAgIAAGiAAQQw2AqwBCyAAIAEQkICAgAAiA0EBRw0CQQohAyAAQQo2AgAMAAsLAkAgAg0AQQAPC0EHQQEgACgCBBshAwsgAwt1AQF/AkBBuAkQgICAgAAiAkUNACACIAA2AiQgAiAAIAEQm4CAgAAiADYCsAkCQCAARQ0AIAJBADoAKCACQgA3AwAgAkIANwMYIAJByABqQQBB5AAQhoCAgAAaIAJBrAFqQQw2AgAgAg8LIAIQgoCAgAALQQALHgACQCAARQ0AIAAoArAJEJ2AgIAAIAAQgoCAgAALC4ARAQx/IABB6N0BaiECIABB1ABqIQMgAEEcaiIEQQhqIQUCQAJAA0AgACgCQCEGAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgASgCBCIHIAEoAggiCEkNACAGQQdGDQEMEgsgBg4JAQIDBAUGBwAJDwsgACgCTCEGDAcLQQEhCSABIAdBAWo2AgQgASgCACAHai0AACIHRQ0IAkACQCAHQd8BSw0AIAdBAUcNAQsgAEGAAjsBUAJAIAAoAjwNACAAIAEoAgwgASgCECIGajYCGCAAIAEoAhQgBms2AiwLIARCADcCACAFQgA3AgAMCwsgAC0AUEUNCgwOCyABIAdBAWo2AgQgASgCACAHai0AACEHIABBAjYCQCAAIAdBCHQgACgCSGo2AkgMDAsgASAHQQFqNgIEIAEoAgAgB2otAAAhByAAQQM2AkAgACAHIAAoAkhqQQFqNgJIDAsLIAEgB0EBajYCBCABKAIAIAdqLQAAIQcgAEEENgJAIAAgB0EIdDYCTAwKCyABIAdBAWo2AgQgASgCACAHai0AACEHIAAgACgCRDYCQCAAIAcgACgCTGpBAWo2AkwMCQsgASAHQQFqNgIEQQchCSABKAIAIAdqLQAAIgdB4AFLDQNBACEGAkACQCAHQS1PDQBBACEIDAELIAdBU2oiByAHQf8BcUEtbiIIQS1sayEHIAhBAWohCAsgAEF/IAh0QX9zNgJ0AkAgB0H/AXFBCUkNACAHQXdqIgcgB0H/AXFBCW4iBkEJbGshByAGQQFqIQYLIAAgBjYCcCAAIAdB/wFxIgc2AmwgBiAHakEESw0DIANCADcCACADQQhqQgA3AgAgA0EQakEANgIAIABBfyAGdEF/czYCcEH4ACEHA0AgACAHakGACDsBACAHQQJqIgdB5N0BRw0ACyAAQQY2AkAgAEEFNgIIIABC/////w83AgALIAAoAkwiCUEFSQ0IAkAgACgCCCIHRQ0AIAdBf2ohBiABKAIEIQcgASgCCCEKA0AgCiAHRg0LIAEgB0EBaiIINgIEIAEoAgAgB2otAAAhByAAIAY2AgggACAHIAAoAgRBCHRyNgIEIAghByAGQX9qIgZBf0cNAAsLIABBBzYCQCAAIAlBe2oiBjYCTAsgACAAKAIgIgcgASgCFCABKAIQayIIIAAoAkgiCiAIIApJGyIIaiAAKAIsIgogCiAHayAISxs2AiggASgCCCIJIAEoAgQiCGshBwJAAkACQCAAKALk3QEiCg0AIAYNAUEAIQYLIABB5N0BaiILIApqQQRqIAEoAgAgCGogByAGIAprIgZBKiAKayIIIAggBksbIgYgBiAHSxsiBxCHgICAABoCQAJAIAcgACgC5N0BIghqIgYgACgCTEcNACALIAhqIAdqQQRqQQBBPyAGaxCGgICAABogACgC5N0BIAdqIQYMAQsCQCAGQRRLDQAgACAGNgLk3QEgASABKAIEIAdqNgIEDAMLIAZBa2ohBgsgAEEANgIQIAAgAjYCDCAAIAY2AhRBByEJIAAQmoCAgABFDQMgACgCECIIIAAoAuTdASIKIAdqSw0DIAAgACgCTCAIayIGNgJMAkAgCiAITQ0AIAAgCiAIayIHNgLk3QEgAiALIAhqQQRqIAcQhYCAgAAaDAILIABBADYC5N0BIAEgASgCBCAIIApraiIINgIEIAEoAggiCSAIayEHCwJAIAdBFUkNACAAIAg2AhAgACABKAIANgIMIAAgCUFraiAIIAZqIAcgBkEVakkbNgIUQQchCSAAEJqAgIAARQ0DIAAoAkwiByAAKAIQIgggASgCBGsiBkkNAyABIAg2AgQgACAHIAZrIgY2AkwgASgCCCAIayIHQRRLDQELIAIgASgCACAIaiAGIAcgByAGSxsiBxCHgICAABogACAHNgLk3QEgASABKAIEIAdqNgIECyAAKAIgIgYgACgCHCIIayEHAkAgACgCPEUNAAJAIAYgACgCLEcNACAAQQA2AiALIAEoAgwgASgCEGogACgCGCAIaiAHEIeAgIAAGiAAKAIgIQYLIAAgBjYCHCABIAEoAhAgB2oiBjYCECAAIAAoAkggB2siBzYCSAJAIAcNAEEHIQkgACgCTA0CIAAoAmgNAiAAKAIEDQIgAEEANgJADAULQQAhCSAGIAEoAhRGDQEgASgCBCABKAIIRw0GIAAoAuTdASAAKAJMTw0GDAELIAAoAkwiCkUNAUEAIQkgCCAHTQ0AA0AgASgCFCIGIAEoAhAiC00NASAAIAogCiAAKAIsIAAoAiAiDGsiDSAIIAdrIgggBiALayIGIAggBkkbIgYgBiANSxsiBiAGIApLGyIGazYCTCAMIAAoAhhqIAEoAgAgB2ogBhCFgICAABogACAAKAIgIAZqIgc2AiACQCAAKAIkIAdPDQAgACAHNgIkCwJAIAAoAjxFDQACQCAHIAAoAixHDQAgAEEANgIgCyABKAIMIAEoAhBqIAEoAgAgASgCBGogBhCFgICAABogACgCICEHCyAAIAc2AhwgASABKAIQIAZqNgIQIAEgASgCBCAGaiIHNgIEIAAoAkwiCkUNAiABKAIIIgggB0sNAAsLIAkPCyAAQQA2AkAMAwsgB0EYdEEYdUF/Sg0BIABBATYCQCAAIAdBEHRBgID8AHE2AkgCQCAHQcABSQ0AIABBBTYCRCAAQQA6AFEMAwsgAC0AUQ0DIABBBjYCRCAHQaABSQ0CIANCADcCACADQRBqQQA2AgAgA0EIakIANwIAQfgAIQcDQCAAIAdqQYAIOwEAIAdBAmoiB0Hk3QFHDQALCyAAQQU2AgggAEL/////DzcCAAwBCyAHQQJLDQEgAEKDgICAgAE3AkAMAAsLQQcPC0EAC/8XARJ/IABBGGohAQJAIABBIGooAgAiAiAAQShqKAIAIgNPDQAgAEHoAGoiBCgCAEUNACABIAQgACgCVBCegICAABogACgCKCEDIAAoAiAhAgsCQCACIANPDQAgAEHcDWohBSAAQegAaiEGIABB4BVqIQcgAEHUAGohCANAIAAoAhAiCSAAKAIUSw0BIAAgACgCZCIKQQV0aiAAKAJ0IAJxIgtBAXRqIgxB+ABqIQ0CQAJAIAAoAgAiBEGAgIAISQ0AIAAoAgQhDgwBCyAAIARBCHQiBDYCACAAIAlBAWoiAzYCECAAIAAoAgRBCHQgACgCDCAJai0AAHIiDjYCBCADIQkLAkACQCAOIARBC3YgDS8BACIPbCIDTw0AIAAgAzYCACANIA9BgBAgD2tBBXZqOwEAIAJBf2ohBAJAIAINACAAKAIsIARqIQQLAkACQCAAKAIkIg8NAEEAIQQMAQsgACgCGCAEai0AACEECyAAKAJwIAJxIAAoAmwiDXQgBEEIIA1rdmohDAJAAkAgCkEGSw0AQQEhBANAIAAgDEGADGxqIARBAXQiBGpB5B1qIQ0CQAJAIANB////B00NACADIQoMAQsgACADQQh0Igo2AgAgACAJQQFqIgM2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQgAyEJCwJAAkAgDiAKQQt2IA0vAQAiD2wiA0kNACAAIA4gA2siDjYCBCAAIAogA2siAzYCACANIA8gD0EFdms7AQAgBEEBciEEDAELIAAgAzYCACANIA9BgBAgD2tBBXZqOwEACyAEQYACSQ0ADAILCyACIAAoAlQiDUF/c2ohBAJAIAIgDUsNACAAKAIsIARqIQQLAkACQCAPDQBBACEQDAELIAAoAhggBGotAAAhEAtBASEEQYACIQ0DQCAAIAxBgAxsaiAQQQF0IhAgDXEiESANaiAEakEBdGpB5B1qIQ8CQAJAIANB////B00NACADIQsMAQsgACADQQh0Igs2AgAgACAJQQFqIgM2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQgAyEJCwJAAkAgDiALQQt2IA8vAQAiCmwiA08iEg0AIAAgAzYCACAKQYAQIAprQQV2aiEKDAELIAAgDiADayIONgIEIAAgCyADayIDNgIAIAogCkEFdmshCkEAIQ0LIA8gCjsBACANIBFzIQ0gBEEBdCASciIEQYACSQ0ACwsgACACQQFqNgIgIAAoAhggAmogBDoAAAJAIAAoAiQgACgCICICTw0AIAAgAjYCJAtBACEDAkAgACgCZCIEQQRJDQACQCAEQQlLDQAgBEF9aiEDDAELIARBemohAwsgACADNgJkDAELIAAgDiADayIONgIEIAAgBCADayIDNgIAIA0gDyAPQQV2azsBACAAIApBAXRqIg9B+ANqIQQCQAJAIANB////B00NACAJIQoMAQsgACADQQh0IgM2AgAgACAJQQFqIgo2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQLAkACQCAOIANBC3YgBC8BACINbCIJSQ0AIAAgDiAJayIONgIEIAAgAyAJayIDNgIAIAQgDSANQQV2azsBACAPQZAEaiENAkACQCADQf///wdNDQAgCiEQDAELIAAgA0EIdCIDNgIAIAAgCkEBaiIQNgIQIAAgDkEIdCAAKAIMIApqLQAAciIONgIECwJAAkAgDiADQQt2IA0vAQAiCWwiBE8NACANIAlBgBAgCWtBBXZqOwEAIAxB2ARqIQMCQCAEQf///wdLDQAgACAEQQh0IgQ2AgAgACAQQQFqNgIQIAAgDkEIdCAAKAIMIBBqLQAAciIONgIECwJAIA4gBEELdiADLwEAIg1sIglJDQAgACAOIAlrNgIEIAAgBCAJazYCACADIA0gDUEFdms7AQAMAgsgAyANQYAQIA1rQQV2ajsBACAAIAk2AgAgAEEBNgJoIABBCUELIAAoAmRBB0kbNgJkDAMLIAAgDiAEayIONgIEIA0gCSAJQQV2azsBACAPQagEaiENAkACQCADIARrIgNB////B00NACAQIQoMAQsgACADQQh0IgM2AgAgACAQQQFqIgo2AhAgACAOQQh0IAAoAgwgEGotAAByIg42AgQLAkACQCAOIANBC3YgDS8BACIEbCIJTw0AIAAgCTYCACANIARBgBAgBGtBBXZqOwEAIAAoAlghAwwBCyAAIA4gCWsiDjYCBCANIAQgBEEFdms7AQAgD0HABGohBAJAIAMgCWsiA0H///8HSw0AIAAgA0EIdCIDNgIAIAAgCkEBajYCECAAIA5BCHQgACgCDCAKai0AAHIiDjYCBAsCQAJAIA4gA0ELdiAELwEAIg1sIglPDQAgACAJNgIAIAQgDUGAECANa0EFdmo7AQAgACgCXCEDDAELIAAgDiAJazYCBCAAIAMgCWs2AgAgACgCYCEDIAAgACgCXDYCYCAEIA0gDUEFdms7AQALIAAgACgCWDYCXAsgACAAKAJUNgJYIAAgAzYCVAsgAEEIQQsgACgCZEEHSRs2AmQgACAHIAsQn4CAgAAMAQsgBCANQYAQIA1rQQV2ajsBACAAIAk2AgAgACAAKAJcNgJgIAAgACkCVDcCWCAAQQdBCiAAKAJkQQdJGzYCZCAAIAUgCxCfgICAACAAKAJoIgNBfmpBAyADQQZJGyEKIAAoAgAhA0EBIQ4DQCAAIApBB3RqIA5BAXQiDmpB2AdqIQ0CQAJAIANBgICACEkNACAAKAIEIQQMAQsgACADQQh0IgM2AgAgACAAKAIQIgRBAWo2AhAgACAAKAIEQQh0IAQgACgCDGotAAByIgQ2AgQLAkACQCAEIANBC3YgDS8BACIJbCIPSQ0AIAAgBCAPayIENgIEIAAgAyAPayIDNgIAIA0gCSAJQQV2azsBACAOQQFyIQ4MAQsgACAPNgIAIA0gCUGAECAJa0EFdmo7AQAgDyEDCyAOQcAASQ0ACwJAIA5BQGoiCUEDSw0AIAAgCTYCVAwBCyAAIA5BAXFBAnIiDTYCVCAJQQF2IQ8CQCAJQQ1LDQAgACANIA9Bf2oiDHQiCzYCVEEBIQ0gCCALQQF0akGEC2ohEEE/IA5rIRFBACEPA0AgECARIA1qQQF0aiEOAkACQCADQf///wdNDQAgAyEKDAELIAAgA0EIdCIKNgIAIAAgACgCECIDQQFqNgIQIAAgBEEIdCADIAAoAgxqLQAAciIENgIECwJAAkAgBCAKQQt2IA4vAQAiCWwiA0kNACAAIAQgA2siBDYCBCAAIAogA2siAzYCACAOIAkgCUEFdms7AQAgAEEBIA90IAtqIgs2AlQgDUEBdEEBciENDAELIAAgAzYCACAOIAlBgBAgCWtBBXZqOwEAIA1BAXQhDQsgDCAPQQFqIg9HDQAMAgsLIA9Be2ohDgNAAkAgA0H///8HSw0AIAAgA0EIdCIDNgIAIAAgACgCECIJQQFqNgIQIARBCHQgCSAAKAIMai0AAHIhBAsgACADQQF2IgM2AgAgACAEIANrIgRBH3UiCSANQQF0akEBaiINNgJUIAAgCSADcSAEaiIENgIEIA5Bf2oiDg0ACyAAIA1BBHQiCzYCVEEAIQ9BASEOA0AgACAOQQF0Ig5qQbwNaiENAkACQCADQf///wdNDQAgAyEKDAELIAAgA0EIdCIKNgIAIAAgACgCECIDQQFqNgIQIAAgBEEIdCADIAAoAgxqLQAAciIENgIECwJAAkAgBCAKQQt2IA0vAQAiCWwiA0kNACAAIAQgA2siBDYCBCAAIAogA2siAzYCACANIAkgCUEFdms7AQAgAEEBIA90IAtqIgs2AlQgDkEBciEODAELIAAgAzYCACANIAlBgBAgCWtBBXZqOwEACyAPQQFqIg9BBEcNAAsLAkAgASAGIAAoAlQQnoCAgAANAEEADwsgACgCICECCyACIAAoAihJDQALC0EBIQMCQCAAKAIAIgRB////B0sNACAAIARBCHQ2AgBBASEDIAAgACgCECIEQQFqNgIQIAAgACgCBEEIdCAEIAAoAgxqLQAAcjYCBAsgAwtwAQF/AkBBqN4BEICAgIAAIgJFDQAgAkE0aiABNgIAIAJBPGogADYCAAJAAkACQCAAQX9qDgIAAQILIAIgARCAgICAACIANgIYIAANASACEIKAgIAADAILIAJBADYCGCACQThqQQA2AgALIAIPC0EAC9IBAQJ/QQYhAgJAIAFBJ0sNACAAQTBqIAFBAXFBAnIgAUEBdkELanQiATYCAAJAAkAgAEE8aigCACIDRQ0AQQQhAiABIABBNGooAgBLDQIgAEEsaiABNgIAIANBAkcNACAAQThqIgMoAgAgAU8NACAAIAE2AjggACgCGBCCgICAACAAIAAoAjAQgICAgAAiATYCGCABDQBBAyECDAELQQAhAiAAQQA2AkAgAEHQAGpBAToAACAAQegAakEANgIAIABB5N0BaiEDCyADQQA2AgALIAILIwACQCAAQTxqKAIARQ0AIAAoAhgQgoCAgAALIAAQgoCAgAAL9QEBBH9BACEDAkAgACgCDCACTQ0AIAAoAhggAk0NACABIAEoAgAiBCAAKAIQIAAoAggiBWsiBiAEIAYgBEkbIgRrNgIAIAUgAkF/c2ohAQJAIAUgAksNACAAKAIUIAFqIQELIAAoAgAiAiABai0AACEGQQEhAyAAIAVBAWo2AgggAiAFaiAGOgAAAkAgBEF/aiICRQ0AA0AgACgCACIFQQAgAUEBaiIBIAEgACgCFEYbIgFqLQAAIQQgACAAKAIIIgZBAWo2AgggBSAGaiAEOgAAIAJBf2oiAg0ACwsgACgCDCAAKAIIIgFPDQAgACABNgIMCyADC8gEAQd/AkACQCAAKAIAIgNBgICACEkNACAAKAIEIQQMAQsgACADQQh0IgM2AgAgACAAKAIQIgVBAWo2AhAgACAAKAIEQQh0IAUgACgCDGotAAByIgQ2AgQLAkACQCAEIANBC3YgAS8BACIGbCIFTw0AIAEgBkGAECAGa0EFdmo7AQAgASACQQR0akEEaiEHQQghCEECIQkMAQsgACAEIAVrIgQ2AgQgASAGIAZBBXZrOwEAAkAgAyAFayIDQf///wdLDQAgACADQQh0IgM2AgAgACAAKAIQIgVBAWo2AhAgACAEQQh0IAUgACgCDGotAAByIgQ2AgQLAkAgBCADQQt2IAEvAQIiBmwiBU8NACABIAZBgBAgBmtBBXZqOwECIAEgAkEEdGpBhAJqIQdBCCEIQQohCQwBCyAAIAQgBWsiBDYCBCABIAYgBkEFdms7AQIgAUGEBGohByADIAVrIQVBgAIhCEESIQkLIABB6ABqIAk2AgBBASEBA0AgByABQQF0IgFqIQMCQAJAIAVB////B00NACAFIQIMAQsgACAFQQh0IgI2AgAgACAAKAIQIgVBAWo2AhAgACAEQQh0IAUgACgCDGotAAByIgQ2AgQLAkACQCAEIAJBC3YgAy8BACIGbCIFSQ0AIAAgBCAFayIENgIEIAAgAiAFayIFNgIAIAMgBiAGQQV2azsBACABQQFyIQEMAQsgACAFNgIAIAMgBkGAECAGa0EFdmo7AQALIAEgCEkNAAsgAEHoAGogASAIayAJajYCAAsLNQEAQYAICy4IAAAAEAAAABgAAAAgAAAAKAAAADAAAABAAAAAUAAAAIAAAAAAAQAA/Td6WFoA"},t=>{t.exports=e}],i={};function r(e){var s=i[e];if(void 0!==s)return s.exports;var o=i[e]={exports:{}};return t[e](o,o.exports,r),o.exports}r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{r.r(s),r.d(s,{XzReadableStream:()=>o});var e=r(1);const t=globalThis.ReadableStream||r(2).ReadableStream;class i{constructor(e){this.exports=e.exports,this.memory=this.exports.memory,this.ptr=this.exports.create_context(),this._refresh(),this.bufSize=this.mem32[0],this.inStart=this.mem32[1]-this.ptr,this.inEnd=this.inStart+this.bufSize,this.outStart=this.mem32[4]-this.ptr}supplyInput(e){this._refresh(),this.mem8.subarray(this.inStart,this.inEnd).set(e,0),this.exports.supply_input(this.ptr,e.byteLength),this._refresh()}getNextOutput(){const e=this.exports.get_next_output(this.ptr);if(this._refresh(),0!==e&&1!==e)throw new Error(`get_next_output failed with error code ${e}`);return{outChunk:this.mem8.slice(this.outStart,this.outStart+this.mem32[5]),finished:1===e}}needsMoreInput(){return this.mem32[2]===this.mem32[3]}outputBufferIsFull(){return this.mem32[5]===this.bufSize}resetOutputBuffer(){this.outPos=this.mem32[5]=0}dispose(){this.exports.destroy_context(this.ptr),this.exports=null}_refresh(){this.memory.buffer!==this.mem8?.buffer&&(this.mem8=new Uint8Array(this.memory.buffer,this.ptr),this.mem32=new Uint32Array(this.memory.buffer,this.ptr))}}class o extends t{static _moduleInstancePromise;static _moduleInstance;static async _getModuleInstance(){const t=e.replace("data:application/wasm;base64,",""),i=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer,r=await WebAssembly.instantiate(i,{});o._moduleInstance=r.instance}constructor(e){let t,r=null;const s=e.getReader();super({async start(e){o._moduleInstance||await(o._moduleInstancePromise||(o._moduleInstancePromise=o._getModuleInstance())),t=new i(o._moduleInstance)},async pull(e){if(t.needsMoreInput()){if(null===r||0===r.byteLength){const{done:e,value:t}=await s.read();e||(r=t)}const e=Math.min(t.bufSize,r.byteLength);t.supplyInput(r.subarray(0,e)),r=r.subarray(e)}const i=t.getNextOutput();e.enqueue(i.outChunk),t.resetOutputBuffer(),i.finished&&(t.dispose(),e.close())},cancel:()=>(t.dispose(),s.cancel())})}}})(),s})(),e.exports=r(i(772))},1308:(e,t)=>{let i=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];"undefined"!=typeof Int32Array&&(i=new Int32Array(i)),t.A=(e,t)=>{let r=0===t?0:-1^t;for(let t=0;t>>8;return-1^r}},1447:(e,t,i)=>{var r=i(9805),s=i(3269),o=i(4823),n=i(7293),a=i(1998),c=-2,l=12,h=30;function d(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r.Buf32(852),t.distcode=t.distdyn=new r.Buf32(592),t.sane=1,t.back=-1,0):c}function p(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,f(e)):c}function g(e,t){var i,r;return e&&e.state?(r=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?c:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,p(e))):c}function m(e,t){var i,r;return e?(r=new u,e.state=r,r.window=null,0!==(i=g(e,t))&&(e.state=null),i):c}var w,b,F=!0;function v(e){if(F){var t;for(w=new r.Buf32(512),b=new r.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(1,e.lens,0,288,w,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(2,e.lens,0,32,b,0,e.work,{bits:5}),F=!1}e.lencode=w,e.lenbits=9,e.distcode=b,e.distbits=5}function y(e,t,i,s){var o,n=e.state;return null===n.window&&(n.wsize=1<=n.wsize?(r.arraySet(n.window,t,i-n.wsize,n.wsize,0),n.wnext=0,n.whave=n.wsize):((o=n.wsize-n.wnext)>s&&(o=s),r.arraySet(n.window,t,i-s,o,n.wnext),(s-=o)?(r.arraySet(n.window,t,i-s,s,0),n.wnext=s,n.whave=n.wsize):(n.wnext+=o,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,i.check=o(i.check,P,2,0),b=0,F=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){e.msg="incorrect header check",i.mode=h;break}if(8!=(15&b)){e.msg="unknown compression method",i.mode=h;break}if(F-=4,B=8+(15&(b>>>=4)),0===i.wbits)i.wbits=B;else if(B>i.wbits){e.msg="invalid window size",i.mode=h;break}i.dmax=1<>8&1),512&i.flags&&(P[0]=255&b,P[1]=b>>>8&255,i.check=o(i.check,P,2,0)),b=0,F=0,i.mode=3;case 3:for(;F<32;){if(0===m)break e;m--,b+=u[p++]<>>8&255,P[2]=b>>>16&255,P[3]=b>>>24&255,i.check=o(i.check,P,4,0)),b=0,F=0,i.mode=4;case 4:for(;F<16;){if(0===m)break e;m--,b+=u[p++]<>8),512&i.flags&&(P[0]=255&b,P[1]=b>>>8&255,i.check=o(i.check,P,2,0)),b=0,F=0,i.mode=5;case 5:if(1024&i.flags){for(;F<16;){if(0===m)break e;m--,b+=u[p++]<>>8&255,i.check=o(i.check,P,2,0)),b=0,F=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&((_=i.length)>m&&(_=m),_&&(i.head&&(B=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),r.arraySet(i.head.extra,u,p,_,B)),512&i.flags&&(i.check=o(i.check,u,_,p)),m-=_,p+=_,i.length-=_),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===m)break e;_=0;do{B=u[p+_++],i.head&&B&&i.length<65536&&(i.head.name+=String.fromCharCode(B))}while(B&&_>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=l;break;case 10:for(;F<32;){if(0===m)break e;m--,b+=u[p++]<>>=7&F,F-=7&F,i.mode=27;break}for(;F<3;){if(0===m)break e;m--,b+=u[p++]<>>=1)){case 0:i.mode=14;break;case 1:if(v(i),i.mode=20,6===t){b>>>=2,F-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=h}b>>>=2,F-=2;break;case 14:for(b>>>=7&F,F-=7&F;F<32;){if(0===m)break e;m--,b+=u[p++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=h;break}if(i.length=65535&b,b=0,F=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(_=i.length){if(_>m&&(_=m),_>w&&(_=w),0===_)break e;r.arraySet(f,u,p,_,g),m-=_,p+=_,w-=_,g+=_,i.length-=_;break}i.mode=l;break;case 17:for(;F<14;){if(0===m)break e;m--,b+=u[p++]<>>=5,F-=5,i.ndist=1+(31&b),b>>>=5,F-=5,i.ncode=4+(15&b),b>>>=4,F-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=h;break}i.have=0,i.mode=18;case 18:for(;i.have>>=3,F-=3}for(;i.have<19;)i.lens[H[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,L={bits:i.lenbits},D=a(0,i.lens,0,19,i.lencode,0,i.work,L),i.lenbits=L.bits,D){e.msg="invalid code lengths set",i.mode=h;break}i.have=0,i.mode=19;case 19:for(;i.have>>16&255,E=65535&z,!((I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>>=I,F-=I,i.lens[i.have++]=E;else{if(16===E){for(T=I+2;F>>=I,F-=I,0===i.have){e.msg="invalid bit length repeat",i.mode=h;break}B=i.lens[i.have-1],_=3+(3&b),b>>>=2,F-=2}else if(17===E){for(T=I+3;F>>=I)),b>>>=3,F-=3}else{for(T=I+7;F>>=I)),b>>>=7,F-=7}if(i.have+_>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=h;break}for(;_--;)i.lens[i.have++]=B}}if(i.mode===h)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=h;break}if(i.lenbits=9,L={bits:i.lenbits},D=a(1,i.lens,0,i.nlen,i.lencode,0,i.work,L),i.lenbits=L.bits,D){e.msg="invalid literal/lengths set",i.mode=h;break}if(i.distbits=6,i.distcode=i.distdyn,L={bits:i.distbits},D=a(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,L),i.distbits=L.bits,D){e.msg="invalid distances set",i.mode=h;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(m>=6&&w>=258){e.next_out=g,e.avail_out=w,e.next_in=p,e.avail_in=m,i.hold=b,i.bits=F,n(e,C),g=e.next_out,f=e.output,w=e.avail_out,p=e.next_in,u=e.input,m=e.avail_in,b=i.hold,F=i.bits,i.mode===l&&(i.back=-1);break}for(i.back=0;S=(z=i.lencode[b&(1<>>16&255,E=65535&z,!((I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>N)])>>>16&255,E=65535&z,!(N+(I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>>=N,F-=N,i.back+=N}if(b>>>=I,F-=I,i.back+=I,i.length=E,0===S){i.mode=26;break}if(32&S){i.back=-1,i.mode=l;break}if(64&S){e.msg="invalid literal/length code",i.mode=h;break}i.extra=15&S,i.mode=22;case 22:if(i.extra){for(T=i.extra;F>>=i.extra,F-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;S=(z=i.distcode[b&(1<>>16&255,E=65535&z,!((I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>N)])>>>16&255,E=65535&z,!(N+(I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>>=N,F-=N,i.back+=N}if(b>>>=I,F-=I,i.back+=I,64&S){e.msg="invalid distance code",i.mode=h;break}i.offset=E,i.extra=15&S,i.mode=24;case 24:if(i.extra){for(T=i.extra;F>>=i.extra,F-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=h;break}i.mode=25;case 25:if(0===w)break e;if(_=C-w,i.offset>_){if((_=i.offset-_)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=h;break}_>i.wnext?(_-=i.wnext,x=i.wsize-_):x=i.wnext-_,_>i.length&&(_=i.length),k=i.window}else k=f,x=g-i.offset,_=i.length;_>w&&(_=w),w-=_,i.length-=_;do{f[g++]=k[x++]}while(--_);0===i.length&&(i.mode=21);break;case 26:if(0===w)break e;f[g++]=i.length,w--,i.mode=21;break;case 27:if(i.wrap){for(;F<32;){if(0===m)break e;m--,b|=u[p++]<{var r={};(0,i(9805).assign)(r,i(3303),i(7083),i(9681)),e.exports=r},1739:function(e,t,i){var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),n=0;n{var r=i(9805),s=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var n=new r.Buf8(256),a=0;a<256;a++)n[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&s))return String.fromCharCode.apply(null,r.shrinkBuf(e,t));for(var i="",n=0;n>>6,t[n++]=128|63&i):i<65536?(t[n++]=224|i>>>12,t[n++]=128|i>>>6&63,t[n++]=128|63&i):(t[n++]=240|i>>>18,t[n++]=128|i>>>12&63,t[n++]=128|i>>>6&63,t[n++]=128|63&i);return t},t.buf2binstring=function(e){return c(e,e.length)},t.binstring2buf=function(e){for(var t=new r.Buf8(e.length),i=0,s=t.length;i4)l[r++]=65533,i+=o-1;else{for(s&=2===o?31:3===o?15:7;o>1&&i1?l[r++]=65533:s<65536?l[r++]=s:(s-=65536,l[r++]=55296|s>>10&1023,l[r++]=56320|1023&s)}return c(l,r)},t.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+n[e[i]]>t?i:t}},1998:(e,t,i)=>{var r=i(9805),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(e,t,i,c,l,h,d,u){var f,p,g,m,w,b,F,v,y,A=u.bits,C=0,_=0,x=0,k=0,I=0,S=0,E=0,N=0,M=0,R=0,B=null,D=0,L=new r.Buf16(16),T=new r.Buf16(16),z=null,P=0;for(C=0;C<=15;C++)L[C]=0;for(_=0;_=1&&0===L[k];k--);if(I>k&&(I=k),0===k)return l[h++]=20971520,l[h++]=20971520,u.bits=1,0;for(x=1;x0&&(0===e||1!==k))return-1;for(T[1]=0,C=1;C<15;C++)T[C+1]=T[C]+L[C];for(_=0;_852||2===e&&M>592)return 1;for(;;){F=C-E,d[_]b?(v=z[P+d[_]],y=B[D+d[_]]):(v=96,y=0),f=1<>E)+(p-=f)]=F<<24|v<<16|y}while(0!==p);for(f=1<>=1;if(0!==f?(R&=f-1,R+=f):R=0,_++,0===--L[C]){if(C===k)break;C=t[i+d[_]]}if(C>I&&(R&m)!==g){for(0===E&&(E=I),w+=x,N=1<<(S=C-E);S+E852||2===e&&M>592)return 1;l[g=R&m]=I<<24|S<<16|w-h}}return 0!==R&&(l[w+R]=C-E<<24|64<<16),u.bits=I,0}},2151:e=>{var t={utf8:{stringToBytes:function(e){return t.bin.stringToBytes(unescape(encodeURIComponent(e)))},bytesToString:function(e){return decodeURIComponent(escape(t.bin.bytesToString(e)))}},bin:{stringToBytes:function(e){for(var t=[],i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.unzip=function(e){return(0,r.inflate)(e)};const r=i(1668)},2324:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e=256){this.total_freq=e,this.max_sym=e-1,this.S=[],this.F=[];for(let e=0;e<=this.max_sym;e++)this.S[e]=e,this.F[e]=1}ModelDecode(e,t){const i=t.RangeGetFrequency(this.total_freq);let r=0,s=0;for(;r+this.F[s]<=i;)r+=this.F[s++];t.RangeDecode(e,r,this.F[s],this.total_freq),this.F[s]+=16,this.total_freq+=16,this.total_freq>65519&&this.ModelRenormalise();const o=this.S[s];if(s>0&&this.F[s]>this.F[s-1]){let e=this.F[s];this.F[s]=this.F[s-1],this.F[s-1]=e,e=this.S[s],this.S[s]=this.S[s-1],this.S[s-1]=e}return o}ModelRenormalise(){this.total_freq=0;for(let e=0;e<=this.max_sym;e++)this.F[e]-=Math.floor(this.F[e]/2),this.total_freq+=this.F[e]}ModelEncode(e,t,i){let r=0;for(var s=0;this.S[s]!=i;s++)r+=this.F[s];if(t.RangeEncode(e,r,this.F[s],this.total_freq),this.F[s]+=16,this.total_freq+=16,this.total_freq>65519&&this.ModelRenormalise(),i=this.S[s],s>0&&this.F[s]>this.F[s-1]){let e=this.F[s];this.F[s]=this.F[s-1],this.F[s-1]=e,e=this.S[s],this.S[s]=this.S[s-1],this.S[s-1]=e}}}},2549:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TWO_PWR_56_DBL=t.TWO_PWR_24_DBL=t.TWO_PWR_64_DBL=t.TWO_PWR_32_DBL=t.TWO_PWR_16_DBL=void 0,t.itf8Size=function(e){return-128&e?-16384&e?-2097152&e?-268435456&e?5:4:3:2:1},t.parseItf8=function(e,t){let i=t;const r=e[i];let s;return r<128?(s=r,i+=1):r<192?(s=(63&r)<<8|e[i+1],i+=2):r<224?(s=(31&r)<<16|e[i+1]<<8|e[i+2],i+=3):r<240?(s=(15&r)<<24|e[i+1]<<16|e[i+2]<<8|e[i+3],i+=4):(s=(15&r)<<28|e[i+1]<<20|e[i+2]<<12|e[i+3]<<4|15&e[i+4],i+=5),[s,i-t]},t.parseLtf8=function(e,i){let r=i;const s=e[r];let o;return s<128?(o=s,r+=1):s<192?(o=16383&(s<<8|e[r+1]),r+=2):s<224?(o=(63&s)<<16|e[r+1]<<8|e[r+2],r+=3):s<240?(o=(31&s)<<24|e[r+1]<<16|e[r+2]<<8|e[r+3],r+=4):s<248?(o=(15&e[r])*t.TWO_PWR_32_DBL+(e[r+1]<<24|e[r+2]<<16|e[r+3]<<8|e[r+4]),r+=5):s<252?(o=((7&e[r])<<8|e[r+1])*t.TWO_PWR_32_DBL+(e[r+2]<<24|e[r+3]<<16|e[r+4]<<8|e[r+5]),r+=6):s<254?(o=((3&e[r])<<16|e[r+1]<<8|e[r+2])*t.TWO_PWR_32_DBL+(e[r+3]<<24|e[r+4]<<16|e[r+5]<<8|e[r+6]),r+=7):s<255?(o=(e[r+1]<<24|e[r+2]<<16|e[r+3]<<8|e[r+4])*t.TWO_PWR_32_DBL+(e[r+5]<<24|e[r+6]<<16|e[r+7]<<8|e[r+8]),r+=8):(o=e[r+1]*t.TWO_PWR_56_DBL+(e[r+2]<<24|e[r+3]<<16|e[r+4]<<8|e[r+5])*t.TWO_PWR_32_DBL+(e[r+6]<<24|e[r+7]<<16|e[r+8]<<8|e[r+9]),r+=9),[o,r-i]},t.parseItem=function(e,t,i=0,r=0){const{offset:s,value:o}=t(e,i);return{...o,_endPosition:s+r,_size:s-i}},t.tinyMemoize=function(e,t){const i=e.prototype[t],r=`_memo_${t}`;e.prototype[t]=function(){if(!(r in this)){const e=i.call(this);this[r]=e,Promise.resolve(e).catch((()=>{delete this[r]}))}return this[r]}},t.sequenceMD5=function(e){return(0,s.default)(e.toUpperCase().replaceAll(/[^\u0021-\u007e]/g,""))};const s=r(i(3503));t.TWO_PWR_16_DBL=65536,t.TWO_PWR_32_DBL=t.TWO_PWR_16_DBL*t.TWO_PWR_16_DBL,t.TWO_PWR_64_DBL=t.TWO_PWR_32_DBL*t.TWO_PWR_32_DBL,t.TWO_PWR_24_DBL=1<<24,t.TWO_PWR_56_DBL=t.TWO_PWR_24_DBL*t.TWO_PWR_32_DBL},2616:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(9846);t.default=class{constructor(e,t={}){this.filename=e}async read(e,t=0){const i=new Uint8Array(e),s=await(0,r.open)(this.filename,"r"),o=await s.read(i,0,e,t);return await s.close(),o.buffer.subarray(0,o.bytesRead)}async readFile(e){const t=await(0,r.readFile)(this.filename,e);return"string"==typeof t?t:new Uint8Array(t)}async stat(){return(0,r.stat)(this.filename)}async close(){}}},2660:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e,t){return function(e,t){const i=e.ReadUint7(),r=function(e){const t={max_sym:0};if(5!=e.ReadByte())return void console.error("Invalid FQZComp version number");const i=e.ReadByte(),r=i&g?e.ReadByte():1;let s=i.nparam>1?i.nparam-1:0;const o=new Array(256);if(i&m)s=e.ReadByte(),a(e,o,256);else{for(var n=0;n0&&(t.sel=new o.default(e.max_sel+1)),t}(r),h=new s.default(e);h.RangeStartDecode(e);const d=new Uint8Array(i),u={qctx:0,prevq:0,delta:0,p:0,s:0,x:0,len:0,is_dup:0,rec:0};let f=0;for(;f0&&l.dup.ModelDecode(e,h)){for(let e=0;e>4,t.qshift=15&i,i=e.ReadByte(),t.qloc=i>>4,t.sloc=15&i,i=e.ReadByte(),t.ploc=i>>4,t.dloc=15&i,t.qmap=new Array(256),t.pflags&d)for(var r=0;r0&&t.pflags&p)a(e,t.qtab,256);else for(r=0;r<256;r++)t.qtab[r]=r;return t.ptab=new Array(1024),t.pflags&u&&a(e,t.ptab,1024),t.dtab=new Array(256),t.pflags&f&&a(e,t.dtab,256),t}function v(e,t,i,r,s,o){s.s=i.max_sel>0?r.sel.ModelDecode(e,t):0,s.x=i.stab[s.s];const n=i.params[s.x];if(n.fixed_len>=0){var a=r.len[0].ModelDecode(e,t);a|=r.len[1].ModelDecode(e,t)<<8,a|=r.len[2].ModelDecode(e,t)<<16,a|=r.len[3].ModelDecode(e,t)<<24,n.fixed_len>0&&(n.fixed_len=-a)}else a=-n.fixed_len;s.len=a,i.do_rev&&(o[s.rec]=r.rev.ModelDecode(e,t)),s.is_dup=0,n.pflags&c&&r.dup.ModelDecode(e,t)&&(s.is_dup=1),s.p=a,s.delta=0,s.qctx=0,s.prevq=0,s.rec++}},2670:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i=0){if(0===e.length)return t.fill(0),t;const r=new h(e,i),d=r.get();if(0!==d&&1!==d)throw new s.CramMalformedError(`Invalid rANS order ${d}`);if(r.getInt()!==r.remaining()-l)throw new s.CramMalformedError("Incorrect input length.");const u=r.getInt(),f=new h(t||new Uint8Array(u));if(f.length{(0,n.tinyMemoize)(l,e)}))},2867:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i,r){const n=t.remaining();let a=e.getInt(),c=e.getInt(),l=e.getInt(),h=e.getInt();const d=n>>2;let u=0,f=d,p=2*d,g=3*d,m=0,w=0,b=0,F=0;for(;u{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t=0,i=0){0!==i?(this.buf=new Uint8Array(i),this.length=i):(this.buf=e,this.length=e.length),this.dataView=new DataView(this.buf.buffer),this.pos=t}EOF(){return this.pos>=this.length}ReadData(e){const t=this.buf.slice(this.pos,this.pos+e);return this.pos+=e,t}ReadByte(){const e=this.buf[this.pos];return this.pos++,e}ReadChar(){const e=this.buf[this.pos];return this.pos++,String.fromCharCode(e)}ReadUint16(){let e=this.ReadByte();return e|=this.ReadByte()<<8,e}ReadUint32(){const e=this.dataView.getInt32(this.pos,!0);return this.pos+=4,e}ReadString(){let e,t="";do{e=this.buf[this.pos++],e&&(t+=String.fromCharCode(e))}while(e);return t}ReadUint7(){let e,t=0;do{e=this.ReadByte(),t=t<<7|127&e}while(128&e);return t}ReadITF8(){let e=this.buf[this.pos];return this.pos++,e>=240?(e=(15&e)<<28,e+=(this.buf[this.pos+0]<<20)+(this.buf[this.pos+1]<<12)+(this.buf[this.pos+2]<<4)+(this.buf[this.pos+3]>>4),this.pos+=4):e>=224?(e=(15&e)<<24,e+=(this.buf[this.pos+0]<<16)+(this.buf[this.pos+1]<<8)+(0|this.buf[this.pos+2]),this.pos+=3):e>=192?(e=(31&e)<<16,e+=(this.buf[this.pos+0]<<8)+(0|this.buf[this.pos+1]),this.pos+=2):e>=128&&(e=(63&e)<<8,e+=this.buf[this.pos],this.pos++),e}}},3269:e=>{e.exports=function(e,t,i,r){for(var s=65535&e,o=e>>>16&65535,n=0;0!==i;){i-=n=i>2e3?2e3:i;do{o=o+(s=s+t[r++]|0)|0}while(--n);s%=65521,o%=65521}return s|o<<16}},3303:(e,t,i)=>{var r=i(8411),s=i(9805),o=i(1996),n=i(4674),a=i(4442),c=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=s.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=r.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(0!==i)throw new Error(n[i]);if(t.header&&r.deflateSetHeader(this.strm,t.header),t.dictionary){var h;if(h="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,0!==(i=r.deflateSetDictionary(this.strm,h)))throw new Error(n[i]);this._dict_set=!0}}function h(e,t){var i=new l(t);if(i.push(e,!0),i.err)throw i.msg||n[i.err];return i.result}l.prototype.push=function(e,t){var i,n,a=this.strm,l=this.options.chunkSize;if(this.ended)return!1;n=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=o.string2buf(e):"[object ArrayBuffer]"===c.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(l),a.next_out=0,a.avail_out=l),1!==(i=r.deflate(a,n))&&0!==i)return this.onEnd(i),this.ended=!0,!1;0!==a.avail_out&&(0!==a.avail_in||4!==n&&2!==n)||("string"===this.options.to?this.onData(o.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((a.avail_in>0||0===a.avail_out)&&1!==i);return 4===n?(i=r.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,0===i):2!==n||(this.onEnd(0),a.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},t.Deflate=l,t.deflate=h,t.deflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},t.gzip=function(e,t){return(t=t||{}).gzip=!0,h(e,t)}},3503:(e,t,i)=>{var r,s,o,n,a;r=i(3939),s=i(2151).utf8,o=i(652),n=i(2151).bin,(a=function(e,t){e.constructor==String?e=t&&"binary"===t.encoding?n.stringToBytes(e):s.stringToBytes(e):o(e)?e=Array.prototype.slice.call(e,0):Array.isArray(e)||e.constructor===Uint8Array||(e=e.toString());for(var i=r.bytesToWords(e),c=8*e.length,l=1732584193,h=-271733879,d=-1732584194,u=271733878,f=0;f>>24)|4278255360&(i[f]<<24|i[f]>>>8);i[c>>>5]|=128<>>9<<4)]=c;var p=a._ff,g=a._gg,m=a._hh,w=a._ii;for(f=0;f>>0,h=h+F>>>0,d=d+v>>>0,u=u+y>>>0}return r.endian([l,h,d,u])})._ff=function(e,t,i,r,s,o,n){var a=e+(t&i|~t&r)+(s>>>0)+n;return(a<>>32-o)+t},a._gg=function(e,t,i,r,s,o,n){var a=e+(t&r|i&~r)+(s>>>0)+n;return(a<>>32-o)+t},a._hh=function(e,t,i,r,s,o,n){var a=e+(t^i^r)+(s>>>0)+n;return(a<>>32-o)+t},a._ii=function(e,t,i,r,s,o,n){var a=e+(i^(t|~r))+(s>>>0)+n;return(a<>>32-o)+t},a._blocksize=16,a._digestsize=16,e.exports=function(e,t){if(null==e)throw new Error("Illegal argument "+e);var i=r.wordsToBytes(a(e,t));return t&&t.asBytes?i:t&&t.asString?n.bytesToString(i):r.bytesToHex(i)}},3665:(e,t,i)=>{var r=i(9805);function s(e){for(var t=e.length;--t>=0;)e[t]=0}var o=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],n=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],c=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],l=new Array(576);s(l);var h=new Array(60);s(h);var d=new Array(512);s(d);var u=new Array(256);s(u);var f=new Array(29);s(f);var p,g,m,w=new Array(30);function b(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}function F(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function v(e){return e<256?d[e]:d[256+(e>>>7)]}function y(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function A(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1}function x(e,t,i){var r,s,o=new Array(16),n=0;for(r=1;r<=15;r++)o[r]=n=n+i[r-1]<<1;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=_(o[a]++,a))}}function k(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function I(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function S(e,t,i,r){var s=2*t,o=2*i;return e[s]>1;i>=1;i--)E(e,o,i);s=c;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],E(e,o,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,o[2*s]=o[2*i]+o[2*r],e.depth[s]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,o[2*i+1]=o[2*r+1]=s,e.heap[1]=s++,E(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,s,o,n,a,c=t.dyn_tree,l=t.max_code,h=t.stat_desc.static_tree,d=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,p=t.stat_desc.max_length,g=0;for(o=0;o<=15;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(o=c[2*c[2*(r=e.heap[i])+1]+1]+1)>p&&(o=p,g++),c[2*r+1]=o,r>l||(e.bl_count[o]++,n=0,r>=f&&(n=u[r-f]),a=c[2*r],e.opt_len+=a*(o+n),d&&(e.static_len+=a*(h[2*r+1]+n)));if(0!==g){do{for(o=p-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[p]--,g-=2}while(g>0);for(o=p;0!==o;o--)for(r=e.bl_count[o];0!==r;)(s=e.heap[--i])>l||(c[2*s+1]!==o&&(e.opt_len+=(o-c[2*s+1])*c[2*s],c[2*s+1]=o),r--)}}(e,t),x(o,l,e.bl_count)}function R(e,t,i){var r,s,o=-1,n=t[1],a=0,c=7,l=4;for(0===n&&(c=138,l=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=n,n=t[2*(r+1)+1],++a>=7;r<30;r++)for(w[r]=s<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),M(e,e.l_desc),M(e,e.d_desc),n=function(e){var t;for(R(e,e.dyn_ltree,e.l_desc.max_code),R(e,e.dyn_dtree,e.d_desc.max_code),M(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*c[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),s=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=s&&(s=o)):s=o=i+5,i+4<=s&&-1!==t?L(e,t,i,r):4===e.strategy||o===s?(A(e,2+(r?1:0),3),N(e,l,h)):(A(e,4+(r?1:0),3),function(e,t,i,r){var s;for(A(e,t-257,5),A(e,i-1,5),A(e,r-4,4),s=0;s>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(u[i]+256+1)]++,e.dyn_dtree[2*v(t)]++),e.last_lit===e.lit_bufsize-1},t._tr_align=function(e){A(e,2,3),C(e,256,l),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},3939:e=>{var t,i;t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i={rotl:function(e,t){return e<>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&i.rotl(e,8)|4278255360&i.rotl(e,24);for(var t=0;t0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],i=0,r=0;i>>5]|=e[i]<<24-r%32;return t},wordsToBytes:function(e){for(var t=[],i=0;i<32*e.length;i+=8)t.push(e[i>>>5]>>>24-i%32&255);return t},bytesToHex:function(e){for(var t=[],i=0;i>>4).toString(16)),t.push((15&e[i]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],i=0;i>>6*(3-o)&63)):i.push("=");return i.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/gi,"");for(var i=[],r=0,s=0;r>>6-2*s);return i}},e.exports=i},4056:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6761),n=i(6272);class a extends s.default{constructor(e,t){if(super(e,t),this.codes={},this.codeBook={},this.sortedCodes=[],this.sortedValuesByBitCode=[],this.sortedBitCodes=[],this.sortedBitLengthsByBitCode=[],this.bitCodeToValue=[],!["byte","int"].includes(this.dataType))throw new TypeError(`${this.dataType} decoding not yet implemented by HUFFMAN_INT codec`);this.buildCodeBook(),this.buildCodes(),this.buildCaches(),0===this.sortedCodes[0].bitLength&&(this._decode=this._decodeZeroLengthCode)}buildCodeBook(){let e=new Array(this.parameters.numCodes);for(let t=0;te.bitLength-t.bitLength||e.symbol-t.symbol)),this.codeBook={},e.forEach((e=>{this.codeBook[e.bitLength]||(this.codeBook[e.bitLength]=[]),this.codeBook[e.bitLength].push(e.symbol)}))}buildCodes(){this.codes={};let e=0,t=-1;Object.entries(this.codeBook).forEach((([i,r])=>{const s=Number.parseInt(i,10);r.forEach((i=>{const r={bitLength:s,value:i,bitCode:0};t+=1;const o=s-e;if(t<<=o,r.bitCode=t,e+=o,function(e){let t=e-(e>>1)&1431655765;return t=(858993459&t)+(t>>2&858993459),16843009*(t+(t>>4)&252645135)>>24}(t)>s)throw new n.CramMalformedError("Symbol out of range");this.codes[i]=r}))}))}buildCaches(){this.sortedCodes=Object.values(this.codes).sort(((e,t)=>e.bitLength-t.bitLength||e.bitCode-t.bitCode)),this.sortedValuesByBitCode=this.sortedCodes.map((e=>e.value)),this.sortedBitCodes=this.sortedCodes.map((e=>e.bitCode)),this.sortedBitLengthsByBitCode=this.sortedCodes.map((e=>e.bitLength));const e=Math.max(...this.sortedBitCodes);this.bitCodeToValue=new Array(e+1).fill(-1);for(let e=0;e-1&&this.sortedBitLengthsByBitCode[i]===t)return this.sortedValuesByBitCode[i];for(let i=e;this.sortedCodes[i+1].bitLength===t&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t){this.parameters=e,this.dataType=t}}},4442:e=>{e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},4562:function(e,t,i){var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),n=0;ne.charCodeAt(0))))};const c=a(i(9505)),l=n(i(2660)),h=n(i(8594)),d=n(i(9313)),u=n(i(1739))},4652:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.low=0,this.range=4294967295,this.code=0,this.FFnum=0,this.carry=0,this.cache=0}RangeStartDecode(e){for(let t=0;t<5;t++)this.code=(this.code<<8)+e.ReadByte();this.code&=4294967295,this.code>>>=0}RangeGetFrequency(e){return this.range=Math.floor(this.range/e),Math.floor(this.code/this.range)}RangeDecode(e,t,i,r){for(this.code-=t*this.range,this.range*=i;this.range<1<<24;)this.range*=256,this.code=256*this.code+e.ReadByte()}RangeShiftLow(e){if(this.low<4278190080|this.carry){for(e.WriteByte(this.cache+this.carry);this.FFnum;)e.WriteByte(this.carry-1),this.FFnum--;this.cache=this.low>>>24,this.carry=0}else this.FFnum++;this.low<<=8,this.low>>>=0}RangeEncode(e,t,i,r){const s=this.low;for(this.range=Math.floor(this.range/r),this.low+=t*this.range,this.low>>>=0,this.range*=i,this.low{e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},4823:e=>{var t=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();e.exports=function(e,i,r,s){var o=t,n=s+r;e^=-1;for(var a=s;a>>8^o[255&(e^i[a])];return-1^e}},4997:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.CramRecord=void 0;var s=i(7480);Object.defineProperty(t,"CramRecord",{enumerable:!0,get:function(){return r(s).default}});var o=i(8751);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}})},5011:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseHeaderText=function(e){const t=e.split(/\r?\n/),i=[];for(const e of t){const[t,...r]=e.split(/\t/);t&&i.push({tag:t.slice(1),data:r.map((e=>{const t=e.indexOf(":");return-1!==t?{tag:e.slice(0,t),value:e.slice(t+1)}:{tag:e,value:""}}))})}return i}},5159:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.IndexedCramFile=t.CraiIndex=t.CramFile=t.CramRecord=void 0;var s=i(4997);Object.defineProperty(t,"CramRecord",{enumerable:!0,get:function(){return s.CramRecord}}),Object.defineProperty(t,"CramFile",{enumerable:!0,get:function(){return r(s).default}});var o=i(6638);Object.defineProperty(t,"CraiIndex",{enumerable:!0,get:function(){return r(o).default}});var n=i(8223);Object.defineProperty(t,"IndexedCramFile",{enumerable:!0,get:function(){return r(n).default}})},6268:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readStatsO0=function(e,t,i){let r=0,s=0,c=255&e.get();do{null==t.fc[c]&&(t.fc[c]=new n.default.FC),t.fc[c].F=255&e.get(),t.fc[c].F>=128&&(t.fc[c].F&=-129,t.fc[c].F=(127&t.fc[c].F)<<8|255&e.get()),t.fc[c].C=s,n.default.symbolInit(i[c],t.fc[c].C,t.fc[c].F),t.R||(t.R=new Array(o.TOTFREQ)),t.R.fill(c,s,s+t.fc[c].F),s+=t.fc[c].F,0===r&&c+1===(255&e.getByteAt(e.position()))?(c=255&e.get(),r=255&e.get()):0!==r?(r-=1,c+=1):c=255&e.get()}while(0!==c);a(s=128&&(t[s].fc[h].F&=-129,t[s].fc[h].F=(127&t[s].fc[h].F)<<8|255&e.get()),t[s].fc[h].C=l,0===t[s].fc[h].F&&(t[s].fc[h].F=o.TOTFREQ),null==i[s][h]&&(i[s][h]=new n.default.RansDecSymbol),n.default.symbolInit(i[s][h],t[s].fc[h].C,t[s].fc[h].F),null==t[s].R&&(t[s].R=new Array(o.TOTFREQ)),t[s].R.fill(h,l,l+t[s].fc[h].F),l+=t[s].fc[h].F,a(l<=o.TOTFREQ),0===c&&h+1===(255&e.getByteAt(e.position()))?(h=255&e.get(),c=255&e.get()):0!==c?(c-=1,h+=1):h=255&e.get()}while(0!==h);0===r&&s+1===(255&e.getByteAt(e.position()))?(s=255&e.get(),r=255&e.get()):0!==r?(r-=1,s+=1):s=255&e.get()}while(0!==s)};const s=i(6272),o=i(7151),n=r(i(9301));function a(e){if(!e)throw new s.CramMalformedError("assertion failed")}},6272:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CramArgumentError=t.CramSizeLimitError=t.CramMalformedError=t.CramUnimplementedError=t.CramError=void 0;class i extends Error{}t.CramError=i;class r extends Error{}t.CramUnimplementedError=r,t.CramMalformedError=class extends i{},t.CramSizeLimitError=class extends i{},t.CramArgumentError=class extends i{}},6612:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{readByte(){throw new Error("abstract method readByte() not implemented")}read(e,t,i){let r=0;for(;r{Object.defineProperty(t,"__esModule",{value:!0});const r=i(6272),s=i(6727),o=i(2169);function n(e,t){const[i,r,s,o,n,a]=t,c=i;e[c]||(e[c]=[]),e[c].push({start:r,span:s,containerStart:o,sliceStart:n,sliceBytes:a})}t.default=class{constructor(e){this.filehandle=(0,s.open)(e.url,e.path,e.filehandle)}async parseIndex(){const e={},t=31===(i=await this.filehandle.readFile())[0]&&139===i[1]?(0,o.unzip)(i):i;var i;const s=new DataView(t.buffer);if(t.length>4&&21578050===s.getUint32(0,!0))throw new r.CramMalformedError("invalid .crai index file. note: file appears to be a .bai index. this is technically legal but please open a github issue if you need support");let a=[],c="";for(const i of t)if(i>=48&&i<=57||!c&&45===i)c+=String.fromCharCode(i);else if(9===i)a.push(Number.parseInt(c,10)),c="";else if(10===i)a.push(Number.parseInt(c,10)),c="",n(e,a),a=[];else if(13!==i&&32!==i)throw new r.CramMalformedError("invalid .crai index file");return c&&a.push(Number.parseInt(c,10)),6===a.length&&n(e,a),Object.entries(e).forEach((([t,i])=>{const r=i;e[t]=r.sort(((e,t)=>e.start-t.start||e.span-t.span))})),e}getIndex(){return this.parseIndexP||(this.parseIndexP=this.parseIndex().catch((e=>{throw this.parseIndexP=void 0,e}))),this.parseIndexP}async hasDataForReferenceSequence(e){return!!(await this.getIndex())[e]}async getEntriesForRange(e,t,i){const r=(await this.getIndex())[e];if(!r)return[];const s=e=>{const r=e.start,s=e.start+e.span;return r>i?-1:s<=t?1:0},o=[];for(const e of r)0===s(e)&&o.push(e);return o}}},6727:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteFile=t.LocalFile=void 0,t.open=function(e,t,i){if(i)return i;if(e)return new r.RemoteFile(e);if(t)return new r.LocalFile(t);throw new Error("no url, path, or filehandle provided, cannot open")};const r=i(8301);var s=i(8301);Object.defineProperty(t,"LocalFile",{enumerable:!0,get:function(){return s.LocalFile}}),Object.defineProperty(t,"RemoteFile",{enumerable:!0,get:function(){return s.RemoteFile}})},6761:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CramBufferOverrunError=void 0,t.getBits=function(e,t,r){let s=0;if(t.bytePosition+(7-t.bitPosition+r)/8>e.length)throw new i("read error during decoding. the file seems to be truncated.");for(let i=r;i;i--)s<<=1,s|=e[t.bytePosition]>>t.bitPosition&1,t.bitPosition-=1,t.bitPosition<0&&(t.bytePosition+=1),t.bitPosition&=7;return s};class i extends Error{}t.CramBufferOverrunError=i},6951:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatUint8Array=function(e){const t=new Uint8Array(function(e){let t=0;for(const i of e)t+=i.length;return t}(e));let i=0;for(const r of e)t.set(r,i),i+=r.length;return t}},7083:(e,t,i)=>{var r=i(1447),s=i(9805),o=i(1996),n=i(9681),a=i(4674),c=i(4442),l=i(7414),h=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var i=r.inflateInit2(this.strm,t.windowBits);if(i!==n.Z_OK)throw new Error(a[i]);if(this.header=new l,r.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===h.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=r.inflateSetDictionary(this.strm,t.dictionary))!==n.Z_OK))throw new Error(a[i])}function u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(e,t){var i,a,c,l,d,u=this.strm,f=this.options.chunkSize,p=this.options.dictionary,g=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?n.Z_FINISH:n.Z_NO_FLUSH,"string"==typeof e?u.input=o.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?u.input=new Uint8Array(e):u.input=e,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new s.Buf8(f),u.next_out=0,u.avail_out=f),(i=r.inflate(u,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&p&&(i=r.inflateSetDictionary(this.strm,p)),i===n.Z_BUF_ERROR&&!0===g&&(i=n.Z_OK,g=!1),i!==n.Z_STREAM_END&&i!==n.Z_OK)return this.onEnd(i),this.ended=!0,!1;u.next_out&&(0!==u.avail_out&&i!==n.Z_STREAM_END&&(0!==u.avail_in||a!==n.Z_FINISH&&a!==n.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(u.output,u.next_out),l=u.next_out-c,d=o.buf2string(u.output,c),u.next_out=l,u.avail_out=f-l,l&&s.arraySet(u.output,u.output,c,l,0),this.onData(d)):this.onData(s.shrinkBuf(u.output,u.next_out)))),0===u.avail_in&&0===u.avail_out&&(g=!0)}while((u.avail_in>0||0===u.avail_out)&&i!==n.Z_STREAM_END);return i===n.Z_STREAM_END&&(a=n.Z_FINISH),a===n.Z_FINISH?(i=r.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===n.Z_OK):a!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),u.avail_out=0,!0)},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===n.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},t.Inflate=d,t.inflate=u,t.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},t.ungzip=u},7151:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TOTFREQ=t.TF_SHIFT=t.RANS_BYTE_L=void 0,t.TF_SHIFT=12,t.TOTFREQ=4096,t.RANS_BYTE_L=1<<23},7293:e=>{e.exports=function(e,t){var i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_,x,k;i=e.state,r=e.next_in,x=e.input,s=r+(e.avail_in-5),o=e.next_out,k=e.output,n=o-(t-e.avail_out),a=o+(e.avail_out-257),c=i.dmax,l=i.wsize,h=i.whave,d=i.wnext,u=i.window,f=i.hold,p=i.bits,g=i.lencode,m=i.distcode,w=(1<>>=v=F>>>24,p-=v,0==(v=F>>>16&255))k[o++]=65535&F;else{if(!(16&v)){if(64&v){if(32&v){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}F=g[(65535&F)+(f&(1<>>=v,p-=v),p<15&&(f+=x[r++]<>>=v=F>>>24,p-=v,16&(v=F>>>16&255)){if(A=65535&F,p<(v&=15)&&(f+=x[r++]<c){e.msg="invalid distance too far back",i.mode=30;break e}if(f>>>=v,p-=v,A>(v=o-n)){if((v=A-v)>h&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(C=0,_=u,0===d){if(C+=l-v,v2;)k[o++]=_[C++],k[o++]=_[C++],k[o++]=_[C++],y-=3;y&&(k[o++]=_[C++],y>1&&(k[o++]=_[C++]))}else{C=o-A;do{k[o++]=k[C++],k[o++]=k[C++],k[o++]=k[C++],y-=3}while(y>2);y&&(k[o++]=k[C++],y>1&&(k[o++]=k[C++]))}break}if(64&v){e.msg="invalid distance code",i.mode=30;break e}F=m[(65535&F)+(f&(1<>3,f&=(1<<(p-=y<<3))-1,e.next_in=r,e.next_out=o,e.avail_in=r{class t{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this.oldCache=this.cache,this.cache=new Map)}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){const t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){return this.cache.has(e)?this.cache.get(e):this.oldCache.has(e)?this.oldCache.get(e):void 0}delete(e){const t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.cache)yield e;for(const e of this.oldCache){const[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(const t of this.oldCache.keys())this.cache.has(t)||e++;return this._size+e}}e.exports=t},7414:e=>{e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},7480:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MateFlagsDecoder=t.CramFlagsDecoder=t.BamFlagsDecoder=t.MateFlags=t.CramFlags=t.BamFlags=void 0;const s=r(i(588)),o={a:0,A:0,c:1,C:1,g:2,G:2,t:3,T:3,n:4,N:4};function n(e){const t={};for(const[i,r]of e)t[`is${r}`]=e=>!!(e&i),t[`set${r}`]=e=>e|i;return t}t.BamFlags=[[1,"Paired"],[2,"ProperlyPaired"],[4,"SegmentUnmapped"],[8,"MateUnmapped"],[16,"ReverseComplemented"],[32,"MateReverseComplemented"],[64,"Read1"],[128,"Read2"],[256,"Secondary"],[512,"FailedQc"],[1024,"Duplicate"],[2048,"Supplementary"]],t.CramFlags=[[1,"PreservingQualityScores"],[2,"Detached"],[4,"WithMateDownstream"],[8,"DecodeSequenceAsStar"]],t.MateFlags=[[1,"OnNegativeStrand"],[2,"Unmapped"]],t.BamFlagsDecoder=n(t.BamFlags),t.CramFlagsDecoder=n(t.CramFlags),t.MateFlagsDecoder=n(t.MateFlags),t.default=class{constructor({flags:e,cramFlags:t,readLength:i,mappingQuality:r,lengthOnRef:s,qualityScores:o,mateRecordNumber:n,readBases:a,readFeatures:c,mateToUse:l,readGroupId:h,readName:d,sequenceId:u,uniqueId:f,templateSize:p,alignmentStart:g,tags:m}){this.flags=e,this.cramFlags=t,this.readLength=i,this.mappingQuality=r,this.lengthOnRef=s,this.qualityScores=o,a&&(this.readBases=a),this.readGroupId=h,this.readName=d,this.sequenceId=u,this.uniqueId=f,this.templateSize=p,this.alignmentStart=g,this.tags=m,c&&(this.readFeatures=c),l&&(this.mate={flags:l.mateFlags,readName:l.mateReadName,sequenceId:l.mateSequenceId,alignmentStart:l.mateAlignmentStart}),n&&(this.mateRecordNumber=n)}isPaired(){return!!(this.flags&s.default.BAM_FPAIRED)}isProperlyPaired(){return!!(this.flags&s.default.BAM_FPROPER_PAIR)}isSegmentUnmapped(){return!!(this.flags&s.default.BAM_FUNMAP)}isMateUnmapped(){return!!(this.flags&s.default.BAM_FMUNMAP)}isReverseComplemented(){return!!(this.flags&s.default.BAM_FREVERSE)}isMateReverseComplemented(){return!!(this.flags&s.default.BAM_FMREVERSE)}isRead1(){return!!(this.flags&s.default.BAM_FREAD1)}isRead2(){return!!(this.flags&s.default.BAM_FREAD2)}isSecondary(){return!!(this.flags&s.default.BAM_FSECONDARY)}isFailedQc(){return!!(this.flags&s.default.BAM_FQCFAIL)}isDuplicate(){return!!(this.flags&s.default.BAM_FDUP)}isSupplementary(){return!!(this.flags&s.default.BAM_FSUPPLEMENTARY)}isDetached(){return!!(this.cramFlags&s.default.CRAM_FLAG_DETACHED)}hasMateDownStream(){return!!(this.cramFlags&s.default.CRAM_FLAG_MATE_DOWNSTREAM)}isPreservingQualityScores(){return!!(this.cramFlags&s.default.CRAM_FLAG_PRESERVE_QUAL_SCORES)}isUnknownBases(){return!!(this.cramFlags&s.default.CRAM_FLAG_NO_SEQ)}getReadBases(){if(!this.readBases&&this._refRegion){const e=function(e,t){if(!e.lengthOnRef&&!e.readLength)return null;if(e.isUnknownBases())return null;const i=e.alignmentStart-t.start;if(!e.readFeatures)return t.seq.slice(i,i+(e.lengthOnRef||0)).toUpperCase();let r="",s=i,o=0;for(;r.lengththis.mate.alignmentStart&&o>0&&(o=-o),o>0?(s[0]=e,s[1]=i,s[2]=t,s[3]=r):(s[2]=e,s[3]=i,s[0]=t,s[1]=r),s.join("")}return null}addReferenceSequence(e,t){this.readFeatures&&this.readFeatures.forEach((i=>{"X"===i.code&&function(e,t,i,r){const s=r.refPos-t.start,n=t.seq.charAt(s);n&&(r.ref=n);let a=o[n];void 0===a&&(a=4);const c=i.substitutionMatrix[a][r.data];c&&(r.sub=c)}(0,e,t,i)})),!this.readBases&&e.start<=this.alignmentStart&&e.end>=this.alignmentStart+(this.lengthOnRef||this.readLength)-1&&(this._refRegion=e)}toJSON(){const e={};return Object.keys(this).forEach((t=>{t.startsWith("_")||(e[t]=this[t])})),e.readBases=this.getReadBases(),e}}},7580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cramFileDefinition=s,t.cramBlockHeader=o,t.cramBlockCrc32=n,t.cramTagDictionary=c,t.cramPreservationMap=l,t.isMappedSliceHeader=function(e){return"number"==typeof e.refSeqId},t.getSectionParsers=function(e){return{cramFileDefinition:s(),cramBlockHeader:o(),cramBlockCrc32:n(),cramDataSeriesEncodingMap:p(),cramTagEncodingMap:g(),cramCompressionHeader:{parser:(e,t)=>{const{value:i,offset:r}=l().parser(e,t);t=r;const{value:s,offset:o}=p().parser(e,t);t=o;const{value:n,offset:a}=g().parser(e,t);return t=a,{value:{dataSeriesEncoding:h(s),preservation:h(i),tagEncoding:h(n)},offset:t}}},cramEncoding:{parser:(e,t)=>f(e,t)},cramUnmappedSliceHeader:d(e),cramMappedSliceHeader:u(e),cramContainerHeader1:m(e),cramContainerHeader2:w(e)}};const r=i(2549);function s(){return{parser:(e,t=0)=>{const i=new DataView(e.buffer,e.byteOffset,e.length),r=new TextDecoder("utf8");let s=0;const o=r.decode(e.subarray(s,s+4));s+=4;const n=i.getUint8(s);s+=1;const a=i.getUint8(s);s+=1;const c=r.decode(e.subarray(s,s+20)).replaceAll("\0","");return s+=20,{value:{magic:o,majorVersion:n,minorVersion:a,fileId:c},offset:s}},maxLength:26}}function o(){return{parser:(e,t=0)=>{const i=e,s=new DataView(i.buffer,i.byteOffset,i.length);let o=0;const n=s.getUint8(o),a=["raw","gzip","bzip2","lzma","rans","rans4x16","arith","fqzcomp","tok3"][n];if(!a)throw new Error(`compression method number ${n} not implemented`);o+=1;const c=s.getUint8(o),l=["FILE_HEADER","COMPRESSION_HEADER","MAPPED_SLICE_HEADER","UNMAPPED_SLICE_HEADER","EXTERNAL_DATA","CORE_DATA"][c];if(!l)throw new Error(`invalid block content type id ${c}`);o+=1;const[h,d]=(0,r.parseItf8)(e,o);o+=d;const[u,f]=(0,r.parseItf8)(e,o);o+=f;const[p,g]=(0,r.parseItf8)(e,o);return o+=g,{offset:o,value:{uncompressedSize:p,compressedSize:u,contentId:h,contentType:l,compressionMethod:a}}},maxLength:17}}function n(){return{parser:(e,t)=>{const i=e,r=new DataView(i.buffer,i.byteOffset,i.length).getUint32(t,!0);return{offset:t+=4,value:{crc32:r}}},maxLength:4}}function a(e,t,i){const r=new TextDecoder("utf8").decode(e.subarray(t,i)),s=[];for(let e=0;e{const[i,s]=(0,r.parseItf8)(e,t);t+=s;const o=e.subarray(t,t+i);t+=i;const n=[];let c=0,l=0;for(;lc&&n.push(a(o,c,l)),{value:{size:i,ents:n},offset:t}}}}function l(){return{parser:(e,t)=>{const i=e,s=new DataView(i.buffer,i.byteOffset,i.length),[o,n]=(0,r.parseItf8)(e,t);t+=n;const[a,l]=(0,r.parseItf8)(e,t);t+=l;const h=[];for(let i=0;i{const[s,o]=(0,r.parseItf8)(t,i);i+=o;let n=0;if(e>=3){const[e,s]=(0,r.parseLtf8)(t,i);i+=s,n=e}else if(2===e){const[e,s]=(0,r.parseItf8)(t,i);i+=s,n=e}else console.warn("recordCounter=0");const[a,c]=(0,r.parseItf8)(t,i);i+=c;const[l,h]=(0,r.parseItf8)(t,i);i+=h;const d=[];for(let e=0;e=2&&(u=[...t.subarray(i,i+16)],i+=16),{value:{recordCounter:n,md5:u,contentIds:d,numContentIds:l,numBlocks:a,numRecords:s},offset:i}},maxLength:e=>40+5*e}}function u(e){return{parser:(t,i)=>{const[s,o]=(0,r.parseItf8)(t,i);i+=o;const[n,a]=(0,r.parseItf8)(t,i);i+=a;const[c,l]=(0,r.parseItf8)(t,i);i+=l;const[h,d]=(0,r.parseItf8)(t,i);i+=d;let u=0;if(e>=3){const[e,s]=(0,r.parseLtf8)(t,i);i+=s,u=e}else if(2===e){const[e,s]=(0,r.parseItf8)(t,i);i+=s,u=e}else console.warn("majorVersion is <2, recordCounter set to 0");const[f,p]=(0,r.parseItf8)(t,i);i+=p;const[g,m]=(0,r.parseItf8)(t,i);i+=m;const w=[];for(let e=0;e=2&&(v=[...t.subarray(i,i+16)],i+=16),{value:{md5:v,numBlocks:f,numRecords:h,numContentIds:g,refSeqSpan:c,refSeqId:s,refSeqStart:n,recordCounter:u,refBaseBlockId:b,contentIds:w},offset:i}},maxLength:e=>60+5*e}}function f(e,t){const i=e,s=new DataView(i.buffer,i.byteOffset,i.length),[o,n]=(0,r.parseItf8)(e,t);t+=n;const[a,c]=(0,r.parseItf8)(e,t);t+=c;const l={};if(0===o);else if(1===o){const[i,s]=(0,r.parseItf8)(e,t);l.blockContentId=i,t+=s}else if(2===o){const[i,s]=(0,r.parseItf8)(e,t);l.offset=i,t+=s;const[o,n]=(0,r.parseItf8)(e,t);l.M=o,t+=n}else if(3===o){const i=(0,r.parseItf8)(e,t),s=i[0];t+=i[1];const o=[];for(let i=0;i{const[i,s]=(0,r.parseItf8)(e,t);t+=s;const[o,n]=(0,r.parseItf8)(e,t);t+=n;const a=[];for(let i=0;i{const[i,s]=(0,r.parseItf8)(e,t);t+=s;const[o,n]=(0,r.parseItf8)(e,t);t+=n;const a=[];for(let i=0;i>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(255&i),{value:n,offset:c}=f(e,t);t=c,a.push({key:o,value:n})}return{value:{mapSize:i,ents:a,mapCount:o},offset:t}}}}function m(e){return{maxLength:52,parser:(t,i)=>{const s=t,o=new DataView(s.buffer,s.byteOffset,s.length).getInt32(i,!0);i+=4;const[n,a]=(0,r.parseItf8)(t,i);i+=a;const[c,l]=(0,r.parseItf8)(t,i);i+=l;const[h,d]=(0,r.parseItf8)(t,i);i+=d;const[u,f]=(0,r.parseItf8)(t,i);i+=f;let p,g=0;if(e>=3){const[e,s]=(0,r.parseLtf8)(t,i);g=e,i+=s}else if(2===e){const[e,s]=(0,r.parseItf8)(t,i);g=e,i+=s}else console.warn("setting recordCounter=0");if(e>1){const[e,s]=(0,r.parseLtf8)(t,i);p=e,i+=s}const[m,w]=(0,r.parseItf8)(t,i);i+=w;const[b,F]=(0,r.parseItf8)(t,i);return{value:{length:o,refSeqId:n,refSeqStart:c,alignmentSpan:h,numBlocks:m,numLandmarks:b,numBases:p,recordCounter:g,numRecords:u},offset:i+=F}}}}function w(e){return{parser:(t,i)=>{const s=t,o=new DataView(s.buffer,s.byteOffset,s.length),[n,a]=(0,r.parseItf8)(t,i);i+=a;const c=[];for(let e=0;e=3&&(l=o.getUint32(i,!0),i+=4),{value:{...void 0===l?{}:{crc32:l},numLandmarks:n,landmarks:c},offset:i}},maxLength:e=>5+5*e+4}}},7593:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7934:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(2549);class n extends s.default{constructor(e,t,i){super(e,t),this.instantiateCodec=i}decode(e,t,i,r){const s=this._getLengthCodec().decode(e,t,i,r)||0,o=this._getDataCodec(),n=new Uint8Array(s);for(let a=0;a{(0,o.tinyMemoize)(n,e)}))},8006:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6272),n=i(6761);class a extends s.default{decode(e,t,i,r){const{blockContentId:s}=this.parameters,n=i[s];if(!n)throw new o.CramMalformedError(`no block found with content ID ${s}`);const a=r.externalBlocks.getCursor(s);return this._decodeByteArray(n,a)}_decodeByteArray(e,t){const i=e.content,{stopByte:r}=this.parameters,s=t.bytePosition;let o=t.bytePosition;for(;i[o]!==r&&othis.getRecordsInSlice(r,(r=>r.sequenceId===e&&r.alignmentStart<=i&&void 0!==r.lengthOnRef&&r.alignmentStart+r.lengthOnRef-1>=t)))));let c=Array.prototype.concat(...a);if(r.viewAsPairs){const e={},t={};for(const i of c){const r=i.readName;if(void 0===r)throw new Error("readName undefined");const s=i.uniqueId;e[r]||(e[r]=0),e[r]+=1,t[s]=1}const i={};Object.entries(e).forEach((([e,t])=>{1===t&&(i[e]=!0)}));const o=[];for(const e of c){const t=e.readName;if(void 0===t)throw new Error("readName undefined");if(i[t]&&e.mate&&(e.mate.sequenceId===s||r.pairAcrossChr)&&Math.abs(e.alignmentStart-e.mate.alignmentStart)e.toString().localeCompare(t.toString()))).filter(((e,t,i)=>!t||e.toString()!==i[t-1].toString()));const l=[];for(const e of a){let r=this.cram.featureCache.get(e.toString());r||(r=this.getRecordsInSlice(e,(()=>!0)),this.cram.featureCache.set(e.toString(),r));const s=r.then((e=>{const r=[];for(const s of e){if(void 0===s.readName)throw new Error("readName undefined");i[s.readName]&&!t[s.uniqueId]&&r.push(s)}return r}));l.push(s)}const h=await Promise.all(l);if(h.length){const e=h.reduce(((e,t)=>e.concat(t)));c=c.concat(e)}}return c}getRecordsInSlice({containerStart:e,sliceStart:t,sliceBytes:i},r){return this.cram.getContainerAtPosition(e).getSlice(t,i).getRecords(r)}hasDataForReferenceSequence(e){return this.index.hasDataForReferenceSequence(e)}}},8301:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalFile=t.RemoteFile=t.BlobFile=void 0,t.fromUrl=c,t.open=function(e,t,i,r={}){if(void 0!==i)return i;if(void 0!==e)return c(e,r);if(void 0!==t)return new n.default(t,r);throw new Error("no url, path, or filehandle provided, cannot open")};const n=o(i(2616)),a=o(i(8485));function c(e,t={}){return new a.default(e,t)}s(i(7593),t);var l=i(1064);Object.defineProperty(t,"BlobFile",{enumerable:!0,get:function(){return o(l).default}});var h=i(8485);Object.defineProperty(t,"RemoteFile",{enumerable:!0,get:function(){return o(h).default}});var d=i(2616);Object.defineProperty(t,"LocalFile",{enumerable:!0,get:function(){return o(d).default}})},8411:(e,t,i)=>{var r,s=i(9805),o=i(3665),n=i(3269),a=i(4823),c=i(4674),l=-2,h=258,d=262,u=103,f=113,p=666;function g(e,t){return e.msg=c[t],t}function m(e){return(e<<1)-(e>4?9:0)}function w(e){for(var t=e.length;--t>=0;)e[t]=0}function b(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(s.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function F(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,b(e.strm)}function v(e,t){e.pending_buf[e.pending++]=t}function y(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function A(e,t,i,r){var o=e.avail_in;return o>r&&(o=r),0===o?0:(e.avail_in-=o,s.arraySet(t,e.input,e.next_in,o,i),1===e.state.wrap?e.adler=n(e.adler,t,o,i):2===e.state.wrap&&(e.adler=a(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)}function C(e,t){var i,r,s=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match,c=e.strstart>e.w_size-d?e.strstart-(e.w_size-d):0,l=e.window,u=e.w_mask,f=e.prev,p=e.strstart+h,g=l[o+n-1],m=l[o+n];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(l[(i=t)+n]===m&&l[i+n-1]===g&&l[i]===l[o]&&l[++i]===l[o+1]){o+=2,i++;do{}while(l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&on){if(e.match_start=t,n=r,r>=a)break;g=l[o+n-1],m=l[o+n]}}}while((t=f[t&u])>c&&0!==--s);return n<=e.lookahead?n:e.lookahead}function _(e){var t,i,r,o,n,a=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=a+(a-d)){s.arraySet(e.window,e.window,a,a,0),e.match_start-=a,e.strstart-=a,e.block_start-=a,t=i=e.hash_size;do{r=e.head[--t],e.head[t]=r>=a?r-a:0}while(--i);t=i=a;do{r=e.prev[--t],e.prev[t]=r>=a?r-a:0}while(--i);o+=a}if(0===e.strm.avail_in)break;if(i=A(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=3)for(n=e.strstart-e.insert,e.ins_h=e.window[n],e.ins_h=(e.ins_h<=3&&(e.ins_h=(e.ins_h<=3)if(r=o._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=3&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=(e.ins_h<15&&(a=2,r-=16),o<1||o>9||8!==i||r<8||r>15||t<0||t>9||n<0||n>4)return g(e,l);8===r&&(r=9);var c=new S;return e.state=c,c.strm=e,c.wrap=a,c.gzhead=null,c.w_bits=r,c.w_size=1<e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(_(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+i;if((0===e.strstart||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,F(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-d&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(F(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(F(e,!1),e.strm.avail_out),1)})),new I(4,4,8,4,x),new I(4,5,16,8,x),new I(4,6,32,32,x),new I(4,4,16,16,k),new I(8,16,32,32,k),new I(8,16,128,128,k),new I(8,32,128,256,k),new I(32,128,258,1024,k),new I(32,258,258,4096,k)],t.deflateInit=function(e,t){return M(e,t,8,15,8,0)},t.deflateInit2=M,t.deflateReset=N,t.deflateResetKeep=E,t.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?l:(e.state.gzhead=t,0):l},t.deflate=function(e,t){var i,s,n,c;if(!e||!e.state||t>5||t<0)return e?g(e,l):l;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||s.status===p&&4!==t)return g(e,0===e.avail_out?-5:l);if(s.strm=e,i=s.last_flush,s.last_flush=t,42===s.status)if(2===s.wrap)e.adler=0,v(s,31),v(s,139),v(s,8),s.gzhead?(v(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),v(s,255&s.gzhead.time),v(s,s.gzhead.time>>8&255),v(s,s.gzhead.time>>16&255),v(s,s.gzhead.time>>24&255),v(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),v(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(v(s,255&s.gzhead.extra.length),v(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=a(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(v(s,0),v(s,0),v(s,0),v(s,0),v(s,0),v(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),v(s,3),s.status=f);else{var d=8+(s.w_bits-8<<4)<<8;d|=(s.strategy>=2||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(d|=32),d+=31-d%31,s.status=f,y(s,d),0!==s.strstart&&(y(s,e.adler>>>16),y(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(n=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),b(e),n=s.pending,s.pending!==s.pending_buf_size));)v(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){n=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),b(e),n=s.pending,s.pending===s.pending_buf_size)){c=1;break}c=s.gzindexn&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),0===c&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){n=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),b(e),n=s.pending,s.pending===s.pending_buf_size)){c=1;break}c=s.gzindexn&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),0===c&&(s.status=u)}else s.status=u;if(s.status===u&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&b(e),s.pending+2<=s.pending_buf_size&&(v(s,255&e.adler),v(s,e.adler>>8&255),e.adler=0,s.status=f)):s.status=f),0!==s.pending){if(b(e),0===e.avail_out)return s.last_flush=-1,0}else if(0===e.avail_in&&m(t)<=m(i)&&4!==t)return g(e,-5);if(s.status===p&&0!==e.avail_in)return g(e,-5);if(0!==e.avail_in||0!==s.lookahead||0!==t&&s.status!==p){var A=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(_(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(F(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?1:2}(s,t):3===s.strategy?function(e,t){for(var i,r,s,n,a=e.window;;){if(e.lookahead<=h){if(_(e),e.lookahead<=h&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=a[s=e.strstart-1])===a[++s]&&r===a[++s]&&r===a[++s]){n=e.strstart+h;do{}while(r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=o._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(F(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?1:2}(s,t):r[s.level].func(s,t);if(3!==A&&4!==A||(s.status=p),1===A||3===A)return 0===e.avail_out&&(s.last_flush=-1),0;if(2===A&&(1===t?o._tr_align(s):5!==t&&(o._tr_stored_block(s,0,0,!1),3===t&&(w(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),b(e),0===e.avail_out))return s.last_flush=-1,0}return 4!==t?0:s.wrap<=0?1:(2===s.wrap?(v(s,255&e.adler),v(s,e.adler>>8&255),v(s,e.adler>>16&255),v(s,e.adler>>24&255),v(s,255&e.total_in),v(s,e.total_in>>8&255),v(s,e.total_in>>16&255),v(s,e.total_in>>24&255)):(y(s,e.adler>>>16),y(s,65535&e.adler)),b(e),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?0:1)},t.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==u&&t!==f&&t!==p?g(e,l):(e.state=null,t===f?g(e,-3):0):l},t.deflateSetDictionary=function(e,t){var i,r,o,a,c,h,d,u,f=t.length;if(!e||!e.state)return l;if(2===(a=(i=e.state).wrap)||1===a&&42!==i.status||i.lookahead)return l;for(1===a&&(e.adler=n(e.adler,t,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(w(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new s.Buf8(i.w_size),s.arraySet(u,t,f-i.w_size,i.w_size,0),t=u,f=i.w_size),c=e.avail_in,h=e.next_in,d=e.input,e.avail_in=f,e.next_in=0,e.input=t,_(i);i.lookahead>=3;){r=i.strstart,o=i.lookahead-2;do{i.ins_h=(i.ins_h<{function i(e){return("object"==typeof e&&null!==e&&"message"in e?e.message:`${e}`).replace(/\.$/,"")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t={}){this.baseOverrides={},this.url=e;const i=t.fetch||globalThis.fetch.bind(globalThis);t.overrides&&(this.baseOverrides=t.overrides),this.fetchImplementation=i}async fetch(e,t){let r;try{r=await this.fetchImplementation(e,t)}catch(s){if(!`${s}`.includes("Failed to fetch"))throw new Error(`${i(s)} fetching ${e}`,{cause:s});console.warn(`generic-filehandle: refetching ${e} to attempt to work around chrome CORS header caching bug`);try{r=await this.fetchImplementation(e,{...t,cache:"reload"})}catch(t){throw new Error(`${i(t)} fetching ${e}`,{cause:t})}}return r}async read(e,t,i={}){const{headers:r={},signal:s,overrides:o={}}=i;e<1/0?r.range=`bytes=${t}-${t+e}`:e===1/0&&0!==t&&(r.range=`bytes=${t}-`);const n=await this.fetch(this.url,{...this.baseOverrides,...o,headers:{...r,...o.headers,...this.baseOverrides.headers},method:"GET",redirect:"follow",mode:"cors",signal:s});if(!n.ok)throw new Error(`HTTP ${n.status} fetching ${this.url}`);if(200===n.status&&0===t||206===n.status){const t=await n.arrayBuffer(),i=n.headers.get("content-range"),r=/\/(\d+)$/.exec(i||"");return r?.[1]&&(this._stat={size:parseInt(r[1],10)}),new Uint8Array(t.slice(0,e))}throw 200===n.status?new Error(`${this.url} fetch returned status 200, expected 206`):new Error(`HTTP ${n.status} fetching ${this.url}`)}async readFile(e={}){let t,i;"string"==typeof e?(t=e,i={}):(t=e.encoding,i=e,delete i.encoding);const{headers:r={},signal:s,overrides:o={}}=i,n=await this.fetch(this.url,{headers:r,method:"GET",redirect:"follow",mode:"cors",signal:s,...this.baseOverrides,...o});if(200!==n.status)throw new Error(`HTTP ${n.status} fetching ${this.url}`);if("utf8"===t)return n.text();if(t)throw new Error(`unsupported encoding: ${t}`);return new Uint8Array(await n.arrayBuffer())}async stat(){if(!this._stat&&(await this.read(10,0),!this._stat))throw new Error(`unable to determine size of file at ${this.url}`);return this._stat}async close(){}}},8594:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e){const t=new s.default(e),i=t.ReadByte(),r=(t.ReadUint32(),t.ReadUint32());return 0==i?function(e,t){const i=new Array(256),r=new Array(256);h(e,i,r);const s=a(r),n=new Array(4);for(var d=0;d<4;d++)n[d]=e.ReadUint32();const u=new Uint8Array(t);for(d=0;d0?(o--,r++):(r=e.ReadByte(),r==s+1&&(o=e.ReadByte())),s=r}while(0!=r)}(e,i,r);const s=new Array(256);for(var d=0;d<256;d++)s[d]=a(r[d]);const u=new Array(4),f=new Array(4);for(var p=0;p<4;p++)u[p]=e.ReadUint32(),f[p]=0;const g=new Uint8Array(t),m=Math.floor(t/4);for(d=0;d=e[i+1];)i++;return i}function a(e){const t=new Array(4096);let i=0;for(let r=0;r<4096;r++){for(;r>=e[i+1];)i++;t[r]=i}return t}function c(e,t,i){return i*(e>>12)+(4095&e)-t}function l(e,t){for(;t<1<<23;)t=(t<<8)+e.ReadByte();return t}function h(e,t,i){for(var r=0;r<256;r++)t[r]=0;let s=e.ReadByte(),o=s,n=0;do{const i=e.ReadITF8();t[s]=i,n>0?(n--,s++):(s=e.ReadByte(),s==o+1&&(n=e.ReadByte())),o=s}while(0!=s);for(i[0]=0,r=0;r<=255;r++)i[r+1]=i[r]+t[r]}},8700:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(6272),s=i(1609),o={BF:"int",CF:"int",RI:"int",RL:"int",AP:"int",RG:"int",MF:"int",NS:"int",NP:"int",TS:"int",NF:"int",TC:"byte",TN:"int",FN:"int",FC:"byte",FP:"int",BS:"byte",IN:"byteArray",SC:"byteArray",DL:"int",BA:"byte",BB:"byteArray",RS:"int",PD:"int",HC:"int",MQ:"int",RN:"byteArray",QS:"byte",QQ:"byteArray",TL:"int"};t.default=class{constructor(e){this.dataSeriesCodecCache={},this.tagCodecCache={},this.tagEncoding={},this.readNamesIncluded=e.preservation.RN,this.APdelta=e.preservation.AP,this.referenceRequired=!!e.preservation.RR,this.tagIdsDictionary=e.preservation.TD,this.substitutionMatrix=function(e){const t=new Array(5);for(let e=0;e<5;e+=1)t[e]=new Array(4);return t[0][e[0]>>6&3]="C",t[0][e[0]>>4&3]="G",t[0][e[0]>>2&3]="T",t[0][3&e[0]]="N",t[1][e[1]>>6&3]="A",t[1][e[1]>>4&3]="G",t[1][e[1]>>2&3]="T",t[1][3&e[1]]="N",t[2][e[2]>>6&3]="A",t[2][e[2]>>4&3]="C",t[2][e[2]>>2&3]="T",t[2][3&e[2]]="N",t[3][e[3]>>6&3]="A",t[3][e[3]>>4&3]="C",t[3][e[3]>>2&3]="G",t[3][3&e[3]]="N",t[4][e[4]>>6&3]="A",t[4][e[4]>>4&3]="C",t[4][e[4]>>2&3]="G",t[4][3&e[4]]="T",t}(e.preservation.SM),this.dataSeriesEncoding=e.dataSeriesEncoding,this.tagEncoding=e.tagEncoding}getCodecForTag(e){const t=this.tagCodecCache[e];if(t)return t;{const t=this.tagEncoding[e];if(!t)throw new Error("Error, no tag encoding");const i=(0,s.instantiateCodec)(t,"byteArray");return this.tagCodecCache[e]=i,i}}getTagNames(e){return this.tagIdsDictionary[e]}getCodecForDataSeries(e){let t=this.dataSeriesCodecCache[e];if(void 0===t){const i=this.dataSeriesEncoding[e];if(i){const n=o[e];if(!n)throw new r.CramMalformedError(`data series name ${e} not defined in file compression header`);t=(0,s.instantiateCodec)(i,n),this.dataSeriesCodecCache[e]=t}}return t}toJSON(){const e={};return Object.keys(this).forEach((t=>{t.endsWith("Cache")||(e[t]=this[t])})),e}}},8751:function(e,t,i){var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),n=0;n0)throw new Error("Detected big-endian machine, may be unable to run")}read(e,t){return this.file.read(e,t)}async getDefinition(){const{maxLength:e,parser:t}=(0,F.cramFileDefinition)(),i=t(await this.file.read(e,0)).value;if(2!==i.majorVersion&&3!==i.majorVersion)throw new d.CramUnimplementedError(`CRAM version ${i.majorVersion} not supported`);return i}async getSamHeader(){const e=await this.getContainerById(0);if(!e)throw new d.CramMalformedError("file contains no containers");const t=(await e.getFirstBlock()).content,i=new DataView(t.buffer).getInt32(0,!0),r=new TextDecoder("utf8").decode(t.subarray(4,4+i));return this.header=r,(0,g.parseHeaderText)(r)}async getHeaderText(){return await this.getSamHeader(),this.header}async getContainerById(e){const{majorVersion:t}=await this.getDefinition();let i,r=(0,F.getSectionParsers)(t).cramFileDefinition.maxLength;for(let t=0;t<=e;t++){i=this.getContainerAtPosition(r);const e=await i.getHeader();if(0===t){r=e._endPosition;for(let t=0;t>>0;if(o!==i)throw new d.CramMalformedError(`crc mismatch in ${r}: recorded CRC32 = ${i}, but calculated CRC32 = ${o}`)}async containerCount(){const{majorVersion:e}=await this.getDefinition();let t=0,i=(0,F.getSectionParsers)(e).cramFileDefinition.maxLength;try{for(;;){const e=await this.getContainerAtPosition(i).getHeader();if(0===t){i=e._endPosition;for(let t=0;t=3){const t=await this._parseSection(i.cramBlockCrc32,s+r.compressedSize);a.crc32=t.crc32,this.validateChecksums&&await this.checkCrc32(e,r._size+r.compressedSize,t.crc32,"block data"),a._endPosition=t._endPosition,a._size=a.compressedSize+i.cramBlockCrc32.maxLength}else a._endPosition=s+a.compressedSize,a._size=a.compressedSize;return a}}t.default=y,"getDefinition getSectionParsers getSamHeader".split(" ").forEach((e=>{(0,v.tinyMemoize)(y,e)}))},8761:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=new Uint32Array([0,79764919,159529838,222504665,319059676,398814059,445009330,507990021,638119352,583659535,797628118,726387553,890018660,835552979,1015980042,944750013,1276238704,1221641927,1167319070,1095957929,1595256236,1540665371,1452775106,1381403509,1780037320,1859660671,1671105958,1733955601,2031960084,2111593891,1889500026,1952343757,2552477408,2632100695,2443283854,2506133561,2334638140,2414271883,2191915858,2254759653,3190512472,3135915759,3081330742,3009969537,2905550212,2850959411,2762807018,2691435357,3560074640,3505614887,3719321342,3648080713,3342211916,3287746299,3467911202,3396681109,4063920168,4143685023,4223187782,4286162673,3779000052,3858754371,3904687514,3967668269,881225847,809987520,1023691545,969234094,662832811,591600412,771767749,717299826,311336399,374308984,453813921,533576470,25881363,88864420,134795389,214552010,2023205639,2086057648,1897238633,1976864222,1804852699,1867694188,1645340341,1724971778,1587496639,1516133128,1461550545,1406951526,1302016099,1230646740,1142491917,1087903418,2896545431,2825181984,2770861561,2716262478,3215044683,3143675388,3055782693,3001194130,2326604591,2389456536,2200899649,2280525302,2578013683,2640855108,2418763421,2498394922,3769900519,3832873040,3912640137,3992402750,4088425275,4151408268,4197601365,4277358050,3334271071,3263032808,3476998961,3422541446,3585640067,3514407732,3694837229,3640369242,1762451694,1842216281,1619975040,1682949687,2047383090,2127137669,1938468188,2001449195,1325665622,1271206113,1183200824,1111960463,1543535498,1489069629,1434599652,1363369299,622672798,568075817,748617968,677256519,907627842,853037301,1067152940,995781531,51762726,131386257,177728840,240578815,269590778,349224269,429104020,491947555,4046411278,4126034873,4172115296,4234965207,3794477266,3874110821,3953728444,4016571915,3609705398,3555108353,3735388376,3664026991,3290680682,3236090077,3449943556,3378572211,3174993278,3120533705,3032266256,2961025959,2923101090,2868635157,2813903052,2742672763,2604032198,2683796849,2461293480,2524268063,2284983834,2364738477,2175806836,2238787779,1569362073,1498123566,1409854455,1355396672,1317987909,1246755826,1192025387,1137557660,2072149281,2135122070,1912620623,1992383480,1753615357,1816598090,1627664531,1707420964,295390185,358241886,404320391,483945776,43990325,106832002,186451547,266083308,932423249,861060070,1041341759,986742920,613929101,542559546,756411363,701822548,3316196985,3244833742,3425377559,3370778784,3601682597,3530312978,3744426955,3689838204,3819031489,3881883254,3928223919,4007849240,4037393693,4100235434,4180117107,4259748804,2310601993,2373574846,2151335527,2231098320,2596047829,2659030626,2470359227,2550115596,2947551409,2876312838,2788305887,2733848168,3165939309,3094707162,3040238851,2985771188]);t.default=class{constructor(){this.crc=4294967295}getCRC(){return~this.crc>>>0}updateCRC(e){this.crc=this.crc<<8^i[255&(this.crc>>>24^e)]}updateCRCRun(e,t){for(;t-- >0;)this.crc=this.crc<<8^i[255&(this.crc>>>24^e)]}}},8930:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6272),n=i(2549),a=i(6761);class c extends s.default{constructor(e,t){if(super(e,t),"int"===this.dataType)this._decodeData=this._decodeInt;else{if("byte"!==this.dataType)throw new o.CramUnimplementedError(`${this.dataType} decoding not yet implemented by EXTERNAL codec`);this._decodeData=this._decodeByte}}decode(e,t,i,r){const{blockContentId:s}=this.parameters,o=i[s];return o?this._decodeData(o,r.externalBlocks.getCursor(s)):void 0}_decodeInt(e,t){const[i,r]=(0,n.parseItf8)(e.content,t.bytePosition);return t.bytePosition=t.bytePosition+r,i}_decodeByte(e,t){if(t.bytePosition>=e.content.length)throw new a.CramBufferOverrunError("attempted to read beyond end of block. this file seems truncated.");return e.content[t.bytePosition++]}}t.default=c},9301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(6272),s=i(7151);class o{constructor(){this.F=void 0,this.C=void 0}}function n(e,t,i,r){return i*(e>>r)+(e&(1<>o)+(e&(1<=e[i+1];)i++;return i}function a(e,t){const i=1<=e[s+1];)s++;r[t]=s}return r}function c(e,t,i,r){return i*(e>>r)+(e&(1<o),n[o]=h(e,s[o]);const a=new Uint8Array(t);for(o=0;o>4;var h=e;if(1&p){const t=e.ReadUint7(),i=e.ReadUint7();var p=new s.default(e.ReadData(i));h=new s.default(u(p,t,4))}const g=new Array(256),m=new Array(256);!function(e,t,i,r){for(var s=0;s<256;s++){t[s]=new Array(256),i[s]=new Array(256);for(var o=0;o<256;o++)t[s][o]=0}const n=d(e);for(s=0;s<256;s++){if(!n[s])continue;let a=0;for(o=0;o<256;o++)n[o]&&(a>0?a--:(t[s][o]=e.ReadUint7(),0==t[s][o]&&(a=e.ReadByte())));for(f(t[s],r),i[s][0]=0,o=0;o<256;o++)i[s][o+1]=i[s][o]+t[s][o]}}(h,g,m,r);const w=new Array(256);for(var b=0;b<256;b++)w[b]=a(m[b],r);const F=new Array(i),v=new Array(i);for(var y=0;y>=1}else if(i<=4)for(n=0;n>=2;else if(i<=16)for(n=0;n>=4;return s}(x,v,y,F)),x}function d(e){const t=new Array(256);for(let e=0;e<256;e++)t[e]=0;let i=0,r=e.ReadByte(),s=r;do{t[r]=1,i>0?(i--,r++):(r=e.ReadByte(),r==s+1&&(i=e.ReadByte())),s=r}while(0!=r);return t}function u(e,t,i){const r=new Array(256),s=new Array(256);!function(e,t,i){for(var r=0;r<256;r++)t[r]=0;const s=d(e);for(r=0;r<256;r++)s[r]>0&&(t[r]=e.ReadUint7());for(f(t,12),i[0]=0,r=0;r<=255;r++)i[r+1]=i[r]+t[r]}(e,r,s);const n=a(s,12),h=new Array(i);for(var u=0;u>=1}}else if(this.nsym<=4)for(s=0,o=0;s>=2;else{if(!(this.nsym<=16))return e;for(s=0,o=0;s>=4}return r}packMeta(e){const t=new a.default("",0,1024),i=new Array(256);for(var r=0;ro),n[o]=this.decodeStream(e,s[o]);const a=new Uint8Array(t);for(o=0;o{e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},9685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i,c,l,h,d,u,f){let p=t("BF");const g=t("CF");if(!(0,o.isMappedSliceHeader)(c.parsedContent))throw new Error("slice header not mapped");const m=u>1&&-2===c.parsedContent.refSeqId?t("RI"):c.parsedContent.refSeqId,w=t("RL");let b=t("AP");i.APdelta&&(b+=d.lastAlignmentStart),d.lastAlignmentStart=b;const F=t("RG");let v,y,A,C;if(i.readNamesIncluded&&(v=n(t("RN"))),s.CramFlagsDecoder.isDetached(g)){const e=t("MF");let r;i.readNamesIncluded||(r=n(t("RN")),v=r);const o=t("NS"),a=t("NP");(e||o>-1)&&(y={mateFlags:e,mateSequenceId:o,mateAlignmentStart:a,mateReadName:r}),A=t("TS"),s.MateFlagsDecoder.isUnmapped(e)&&(p=s.BamFlagsDecoder.setMateUnmapped(p)),s.MateFlagsDecoder.isOnNegativeStrand(e)&&(p=s.BamFlagsDecoder.setMateReverseComplemented(p))}else s.CramFlagsDecoder.isWithMateDownstream(g)&&(C=t("NF")+f+1);const _=t("TL");if(_<0)throw new r.CramMalformedError("invalid TL index");const x={},k=i.getTagNames(_),I=k.length;for(let t=0;t1?"SC":"IN"],X:["number","BS"],D:["number","DL"],I:["string","IN"],i:["character","BA"],b:["string","BB"],q:["numArray","QQ"],Q:["number","QS"],H:["number","HC"],P:["number","PD"],N:["number","RS"]}[t];if(!h)throw new r.CramMalformedError(`invalid read feature code "${t}"`);let d=l(h);const u={B:["number","QS"]}[t];u&&(d=[d,l(u)]),n+=s;const f=n;a+=s;const p=a;"D"===t||"N"===t?a+=d:"I"===t||"S"===t?a-=d.length:"i"===t&&(a-=1),c[e]={code:t,pos:f,refPos:p,data:d}}return c}(b,e,t,0,u)),E=w,S)for(const{code:e,data:t}of S)"D"===e||"N"===e?E+=t:"I"===e||"S"===e?E-=t.length:"i"===e&&(E-=1);if(Number.isNaN(E)&&(console.warn(`${v||`${m}:${b}`} record has invalid read features`),E=w),N=t("MQ"),s.CramFlagsDecoder.isPreservingQualityScores(g)){M=new Array(w);for(let e=0;e{var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)r(i,s)&&(e[s]=i[s])}}return e},t.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var s={arraySet:function(e,t,i,r,s){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+r),s);else for(var o=0;o{}},sf={},function e(t){var i=sf[t];if(void 0!==i)return i.exports;var r=sf[t]={exports:{}};return rf[t].call(r.exports,r,r.exports,e),r.exports}(5159));class nf{constructor(e,t){this.position=0,this.url=e,this.config=t,x(e)||!1===t.cacheFetches?this.useCache=!1:(this.useCache=!0,this.cache=new af({fetch:(e,t)=>this._fetch(e,t),fetchSize:t.fetchSize||1e4}))}async _fetch(e,t){const i={start:e,size:t};return await Rr.loadArrayBuffer(this.url,ts(this.config,{range:i}))}async read(e,t=0){let i;return i=this.useCache?await this.cache.get(t,e):await this._fetch(t,e),new Uint8Array(i)}async readFile(){const e=await Rr.loadArrayBuffer(this.url,ts(this.config));return new Uint8Array(e)}}class af{maxChunkCount=5;chunks=[];constructor({fetch:e,fetchSize:t=3e4}){this.fetch=e,this.fetchSize=t}async get(e,t){const i=e+t;for(let r of this.chunks)if(r.contains(e,i)){const i=e-r.start;return r.buffer.slice(i,i+t)}const r=Math.max(t,this.fetchSize),s=Math.max(0,e-1e3),o=e+r+1e3,n=await this.fetch(s,o-s),a=new cf(s,o,n);this.chunks.length>this.maxChunkCount&&this.chunks.shift(),this.chunks.push(a);const c=e-a.start,l=c+t;return n.slice(c,l)}}class cf{constructor(e,t,i){this.start=e,this.end=t,this.buffer=i}contains(e,t){return e>=this.start&&t<=this.end}}class lf{chrAliasTable=new Map;constructor(e,t,i){this.config=e,this.browser=i,this.genome=t,this.cramFile=new of.CramFile({filehandle:e.fileHandle?e.fileHandle:new nf(e.url,e),seqFetch:e.seqFetch||async function(e,t,i){const r=this.genome,s=await this.getHeader(),o=r.getChromosomeName(s.indexToChr[e]);return this.genome.getSequence(o,t-1,i)}.bind(this),checkSequenceMD5:void 0===e.checkSequenceMD5||e.checkSequenceMD5});const r=e.indexFileHandle?e.indexFileHandle:new nf(e.indexURL,e);this.indexedCramFile=new of.IndexedCramFile({cram:this.cramFile,index:new of.CraiIndex({filehandle:r}),fetchSizeLimit:e.fetchSizeLimit||1e9}),Qu.setReaderDefaults(this,e)}async getHeader(){if(!this.header){const e=await this.cramFile.getSamHeader(),t={},i=[],r=[];for(let s of e)if("SQ"===s.tag){for(let e of s.data)if("SN"===e.tag){const r=e.value;t[r]=i.length,i.push(r);break}}else"RG"===s.tag&&r.push(s.data);this.header={indexToChr:i,chrToIndex:t,chrNames:Object.keys(t),readGroups:r}}return this.header}async#_(e){if(await this.getHeader(),this.chrAliasTable.has(e)&&void 0===(e=this.chrAliasTable.get(e)))return;let t=this.header.chrToIndex[e];if(void 0===t){const i=await this.genome.getAliasRecord(e);let r;if(i){const e=Object.keys(i).filter((e=>"start"!==e&&"end"!==e)).map((e=>i[e])).filter((e=>void 0!==this.header.chrToIndex[e]));e.length>0&&(r=e[0],t=this.header.chrToIndex[e[0]])}this.chrAliasTable.set(e,r)}return t}async readAlignments(e,t,i){const r=await this.getHeader(),s=await this.#_(e),o=new fu(e,t,i,this.config);if(void 0===s)return o;try{const e=await this.indexedCramFile.getRecordsForRange(s,t,i);for(let a of e){const e=a.sequenceId,c=a.alignmentStart,l=c+a.lengthOnRef;if(e<0)continue;if(e>s||c>i)return;if(e=0&&(t="Sequence mismatch. Is this the correct genome for the loaded CRAM?"),this.browser.alert.present(new Error(t)),e}function n(e,t){const i=new Eu;if(i.chr=t[e.sequenceId],i.start=e.alignmentStart-1,i.lengthOnRef=e.lengthOnRef,i.flags=e.flags,i.strand=!(16&e.flags),i.fragmentLength=e.templateLength||e.templateSize,i.mq=e.mappingQuality,i.end=e.alignmentStart+e.lengthOnRef,i.readGroupId=e.readGroupId,e.mate&&void 0!==e.mate.sequenceId){const r=void 0!==e.mate.flags?!(1&e.mate.flags):!(32&e.flags);i.mate={chr:t[e.mate.sequenceId],position:e.mate.alignmentStart,strand:r}}return i.seq=e.getReadBases(),i.qual=e.qualityScores,i.tagDict=e.tags,i.readName=e.readName,function(e,t){const i=[];let r,s,o=0,n="";if(t.scStart=t.start,t.scLengthOnRef=t.lengthOnRef,e.readFeatures)for(let a of e.readFeatures){const e=a.code,c=a.data,l=a.pos-1,h=a.refPos-1;switch(e){case"S":case"I":case"i":case"N":case"D":if(l>o){const e=l-o;i.push(new zu({start:h-e,seqOffset:o,len:e,type:"M"})),o+=e,n+=e+"M"}if("S"===e){let r=h;t.scLengthOnRef+=c.length,0===l&&(t.scStart-=c.length,r-=c.length);const s=c.length;i.push(new zu({start:r,seqOffset:o,len:s,type:"S"})),o+=s,n+=s+e}else if("I"===e||"i"===e){void 0===r&&(r=[]);const t="i"===e?1:c.length;r.push(new zu({start:h,len:t,seqOffset:o,type:"I"})),o+=t,n+=t+e}else"D"!==e&&"N"!==e||(s||(s=[]),s.push({start:h,len:c,type:e}),n+=c+e);break;case"H":case"P":n+=c+e}}const a=e.readLength-o;a>0&&(i.push(new zu({start:e.alignmentStart+e.lengthOnRef-a-1,seqOffset:o,len:a,type:"M"})),n+=a+"M");t.blocks=i,t.insertions=r,t.gaps=s,t.cigar=n}(e,i),i.mate&&i.start>i.mate.position&&i.fragmentLength>0&&(i.fragmentLength=-i.fragmentLength),Qu.setPairOrientation(i),i}}}const hf=2291137574,df=2273964779,uf=[84,68,70,52],ff=new Uint8Array([66,65,77,1]),pf=[67,82,65,77],gf=[31,139],mf=new Set(["narrowpeak","broadpeak","regionpeak","peaks","bedgraph","wig","gff3","gff","gtf","fusionjuncspan","refflat","seg","aed","bed","bedMethyl","vcf","bb","bigbed","biginteract","biggenepred","bignarrowpeak","bw","bigwig","bam","tdf","refgene","genepred","genepredext","bedpe","bp","snp","rmsk","cram","gwas","maf","mut","hiccups","fasta","fa","fna","pytor","hic","qtl"]);function wf(e,t){const i=Math.min(e.length,t.length);if(0==i)return!1;for(let r=0;r=this.start&&e.end<=this.end}overlaps(e){return e.chr===this.chr&&!(e.endthis.end)}extend(e){e.chr===this.chr&&(this.start=Math.min(e.start,this.start),this.end=Math.max(e.end,this.end))}getLocusString(){if("all"===this.chr)return"all";{const e=F(Math.floor(this.start)+1),t=F(Math.round(this.end));return`${this.chr}:${e}-${t}`}}static fromLocusString(e){if("all"===e)return new vf({chr:"all"});const t=e.split(":"),i=t[0],r=t[1].split("-"),s=Number.parseInt(r[0].replace(/,/g,""))-1,o=Number.parseInt(r[1].replace(/,/g,""));return new vf({chr:i,start:s,end:o})}} + */function ah(e,t){var i,r=Object.keys(t);for(i=0;i0){"path"===this.__currentElement.nodeName&&(this.__currentElementsToStyle||(this.__currentElementsToStyle={element:t,children:[]}),this.__currentElementsToStyle.children.push(this.__currentElement),this.__applyCurrentDefaultPath());var i=this.__createElement("g");t.appendChild(i),this.__currentElement=i}var r=this.__currentElement.getAttribute("transform");r?r+=" ":r="",r+=e,this.__currentElement.setAttribute("transform",r)}addTrackGroupWithTranslationAndClipRect(e,t,i,r,s,o){const n=e+"_clip_rect";let a=this.__createElement("clipPath",{id:n});this.__defs.appendChild(a),a.appendChild(this.__createElement("rect",{x:"0",y:o.toString(),width:r.toString(),height:s.toString()}));let c=this.__createElement("g");this.__rootGroup.appendChild(c),c.setAttribute("transform",ah("translate({x},{y})",{x:t,y:i})),c.setAttribute("id",e+"_group"),c.setAttribute("clip-path",ah("url(#{id})",{id:n})),this.__currentElement=c}scale(e,t){void 0===t&&(t=e),this.__addTransform(ah("scale({x},{y})",{x:e,y:t}))}rotate(e){var t=180*e/Math.PI;this.__addTransform(ah("rotate({angle},{cx},{cy})",{angle:t,cx:0,cy:0}))}translate(e,t){this.__addTransform(ah("translate({x},{y})",{x:e,y:t}))}transform(e,t,i,r,s,o){this.__addTransform(ah("matrix({a},{b},{c},{d},{e},{f})",{a:e,b:t,c:i,d:r,e:s,f:o}))}beginPath(){var e;this.__currentDefaultPath="",this.__currentPosition={},e=this.__createElement("path",{},!0),this.__closestGroupOrSvg().appendChild(e),this.__currentElement=e}__applyCurrentDefaultPath(){var e=this.__currentElement;"path"===e.nodeName?e.setAttribute("d",this.__currentDefaultPath):console.error("Attempted to apply path command to node",e.nodeName)}__addPathCommand(e){this.__currentDefaultPath+=" ",this.__currentDefaultPath+=e}moveTo(e,t){"path"!==this.__currentElement.nodeName&&this.beginPath(),this.__currentPosition={x:e,y:t},this.__addPathCommand(ah("M {x} {y}",{x:e,y:t}))}closePath(){this.__currentDefaultPath&&this.__addPathCommand("Z")}lineTo(e,t){this.__currentPosition={x:e,y:t},this.__currentDefaultPath&&this.__currentDefaultPath.indexOf("M")>-1?this.__addPathCommand(ah("L {x} {y}",{x:e,y:t})):this.__addPathCommand(ah("M {x} {y}",{x:e,y:t}))}bezierCurveTo(e,t,i,r,s,o){this.__currentPosition={x:s,y:o},this.__addPathCommand(ah("C {cp1x} {cp1y} {cp2x} {cp2y} {x} {y}",{cp1x:e,cp1y:t,cp2x:i,cp2y:r,x:s,y:o}))}quadraticCurveTo(e,t,i,r){this.__currentPosition={x:i,y:r},this.__addPathCommand(ah("Q {cpx} {cpy} {x} {y}",{cpx:e,cpy:t,x:i,y:r}))}arcTo(e,t,i,r,s){var o=this.__currentPosition&&this.__currentPosition.x,n=this.__currentPosition&&this.__currentPosition.y;if(void 0!==o&&void 0!==n){if(s<0)throw new Error("IndexSizeError: The radius provided ("+s+") is negative.");if(o===e&&n===t||e===i&&t===r||0===s)this.lineTo(e,t);else{var a=hh([o-e,n-t]),c=hh([i-e,r-t]);if(a[0]*c[1]!==a[1]*c[0]){var l=a[0]*c[0]+a[1]*c[1],h=Math.acos(Math.abs(l)),d=hh([a[0]+c[0],a[1]+c[1]]),u=s/Math.sin(h/2),f=e+u*d[0],p=t+u*d[1],g=[-a[1],a[0]],m=[c[1],-c[0]],w=function(e){var t=e[0];return e[1]>=0?Math.acos(t):-Math.acos(t)},b=w(g),F=w(m);this.lineTo(f+g[0]*s,p+g[1]*s),this.arc(f,p,s,b,F)}else this.lineTo(e,t)}}}stroke(){"path"===this.__currentElement.nodeName&&this.__currentElement.setAttribute("paint-order","fill stroke markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("stroke")}fill(){"path"===this.__currentElement.nodeName&&this.__currentElement.setAttribute("paint-order","stroke fill markers"),this.__applyCurrentDefaultPath(),this.__applyStyleToCurrentElement("fill")}rect(e,t,i,r){"path"!==this.__currentElement.nodeName&&this.beginPath(),this.moveTo(e,t),this.lineTo(e+i,t),this.lineTo(e+i,t+r),this.lineTo(e,t+r),this.lineTo(e,t),this.closePath()}fillRect(e,t,i,r){r<0&&(t+=r,r=-r),i<0&&(e+=i,i=-i);var s,o,n,a={x:e,y:t,width:i,height:r};(!this.viewbox||(s=this.viewbox,o=a,s.xo.x&&s.yo.y))&&(n=this.__createElement("rect",a,!0),this.__closestGroupOrSvg().appendChild(n),this.__currentElement=n,this.__applyStyleToCurrentElement("fill"))}strokeRect(e,t,i,r){var s;s=this.__createElement("rect",{x:e,y:t,width:i,height:r},!0),this.__closestGroupOrSvg().appendChild(s),this.__currentElement=s,this.__applyStyleToCurrentElement("stroke")}strokeEllipse(e,t,i,r,s,o,n,a){this.__ellipse(e,t,i,r,s,o,n,a,"stroke")}fillEllipse(e,t,i,r,s,o,n,a){this.__ellipse(e,t,i,r,s,o,n,a,"fill")}__ellipse(e,t,i,r,s,o,n,a,c){const l={cx:e,cy:t,rx:i,ry:r},h=this.__createElement("ellipse",l,!0);this.__closestGroupOrSvg().appendChild(h),this.__currentElement=h,this.__applyStyleToCurrentElement(c)}__clearCanvas(){for(var e=this.__closestGroupOrSvg().getAttribute("transform"),t=this.__root.childNodes[1],i=t.childNodes,r=i.length-1;r>=0;r--)i[r]&&t.removeChild(i[r]);this.__currentElement=t,this.__groupStack=[],e&&this.__addTransform(e)}clearRect(e,t,i,r){if(0!==e||0!==t||i!==this.width||r!==this.height){var s,o=this.__closestGroupOrSvg();s=this.__createElement("rect",{x:e,y:t,width:i,height:r,fill:"#FFFFFF"},!0),o.appendChild(s)}else this.__clearCanvas()}createLinearGradient(e,t,i,r){var s=this.__createElement("linearGradient",{id:ch(this.__ids),x1:e+"px",x2:i+"px",y1:t+"px",y2:r+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(s),new fh(s,this)}createRadialGradient(e,t,i,r,s,o){var n=this.__createElement("radialGradient",{id:ch(this.__ids),cx:r+"px",cy:s+"px",r:o+"px",fx:e+"px",fy:t+"px",gradientUnits:"userSpaceOnUse"},!1);return this.__defs.appendChild(n),new fh(n,this)}__parseFont(){var e=/^\s*(?=(?:(?:[-a-z]+\s*){0,2}(italic|oblique))?)(?=(?:(?:[-a-z]+\s*){0,2}(small-caps))?)(?=(?:(?:[-a-z]+\s*){0,2}(bold(?:er)?|lighter|[1-9]00))?)(?:(?:normal|\1|\2|\3)\s*){0,3}((?:xx?-)?(?:small|large)|medium|smaller|larger|[.\d]+(?:\%|in|[cem]m|ex|p[ctx]))(?:\s*\/\s*(normal|[.\d]+(?:\%|in|[cem]m|ex|p[ctx])))?\s*([-,\'\"\sa-z0-9]+?)\s*$/i.exec(this.font),t={style:e[1]||"normal",size:e[4]||"10px",family:e[6]||"sans-serif",weight:e[3]||"normal",decoration:e[2]||"normal",href:null};return"underline"===this.__fontUnderline&&(t.decoration="underline"),this.__fontHref&&(t.href=this.__fontHref),t}__wrapTextLink(e,t){if(e.href){var i=this.__createElement("a");return i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href",e.href),i.appendChild(t),i}return t}__applyText(e,t,i,r){var s,o,n=this.__parseFont(),a=this.__closestGroupOrSvg(),c=this.__createElement("text",{"font-family":n.family,"font-size":n.size,"font-style":n.style,"font-weight":n.weight,"text-decoration":n.decoration,x:t,y:i,"text-anchor":(s=this.textAlign,o={left:"start",right:"end",center:"middle",start:"start",end:"end"},o[s]||o.start),"dominant-baseline":lh(this.textBaseline)},!0);c.appendChild(this.__document.createTextNode(e)),this.__currentElement=c,this.__applyStyleToCurrentElement(r),a.appendChild(this.__wrapTextLink(n,c))}fillText(e,t,i){this.__applyText(e,t,i,"fill")}strokeText(e,t,i){this.__applyText(e,t,i,"stroke")}measureText(e){return this.__ctx.font=this.font,this.__ctx.measureText(e)}arc(e,t,i,r,s,o){if(r!==s){(r%=2*Math.PI)===(s%=2*Math.PI)&&(s=(s+2*Math.PI-.001*(o?-1:1))%(2*Math.PI));var n=e+i*Math.cos(s),a=t+i*Math.sin(s),c=e+i*Math.cos(r),l=t+i*Math.sin(r),h=o?0:1,d=0,u=s-r;u<0&&(u+=2*Math.PI),d=o?u>Math.PI?0:1:u>Math.PI?1:0,this.lineTo(c,l),this.__addPathCommand(ah("A {rx} {ry} {xAxisRotation} {largeArcFlag} {sweepFlag} {endX} {endY}",{rx:i,ry:i,xAxisRotation:0,largeArcFlag:d,sweepFlag:h,endX:n,endY:a})),this.__currentPosition={x:n,y:a}}}clip(){var e=this.__closestGroupOrSvg(),t=this.__createElement("clipPath"),i=ch(this.__ids),r=this.__createElement("g");this.__applyCurrentDefaultPath(),e.removeChild(this.__currentElement),t.setAttribute("id",i),t.appendChild(this.__currentElement),this.__defs.appendChild(t),e.setAttribute("clip-path",ah("url(#{id})",{id:i})),e.appendChild(r),this.__currentElement=r}drawImage(){var e,t,i,r,s,o,n,a,c,l,h,d,u,f=Array.prototype.slice.call(arguments),p=f[0],g=0,m=0;if(3===f.length)e=f[1],t=f[2],i=s=p.width,r=o=p.height;else if(5===f.length)e=f[1],t=f[2],i=f[3],r=f[4],s=p.width,o=p.height;else{if(9!==f.length)throw new Error("Invalid number of arguments passed to drawImage: "+arguments.length);g=f[1],m=f[2],s=f[3],o=f[4],e=f[5],t=f[6],i=f[7],r=f[8]}n=this.__closestGroupOrSvg(),this.__currentElement;var w="translate("+e+", "+t+")";if(p instanceof gh){if((a=p.getSvg().cloneNode(!0)).childNodes&&a.childNodes.length>1){for(c=a.childNodes[0];c.childNodes.length;)u=c.childNodes[0].getAttribute("id"),this.__ids[u]=u,this.__defs.appendChild(c.childNodes[0]);if(l=a.childNodes[1]){var b,F=l.getAttribute("transform");b=F?F+" "+w:w,l.setAttribute("transform",b),n.appendChild(l)}}}else"CANVAS"!==p.nodeName&&"IMG"!==p.nodeName||((h=this.__createElement("image")).setAttribute("width",i),h.setAttribute("height",r),h.setAttribute("preserveAspectRatio","none"),(g||m||s!==p.width||o!==p.height)&&((d=this.__document.createElement("canvas")).width=i,d.height=r,d.getContext("2d").drawImage(p,g,m,s,o,0,0,i,r),p=d),h.setAttribute("transform",w),h.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","CANVAS"===p.nodeName?p.toDataURL():p.getAttribute("src")),n.appendChild(h))}createPattern(e,t){let i,r=this.__document.__createElement("pattern"),s=ch(this.__ids);return r.setAttribute("id",s),r.setAttribute("width",e.width),r.setAttribute("height",e.height),"CANVAS"===e.nodeName||"IMG"===e.nodeName?(i=this.__createElement("image"),i.setAttribute("width",e.width),i.setAttribute("height",e.height),i.setAttributeNS("http://www.w3.org/1999/xlink","xlink:href","CANVAS"===e.nodeName?e.toDataURL():e.getAttribute("src")),r.appendChild(i),this.__defs.appendChild(r)):e instanceof gh&&(r.appendChild(e.__root.childNodes[1]),this.__defs.appendChild(r)),new ph(r,this)}setLineDash(e){e&&e.length>0?this.lineDash=e.join(","):this.lineDash=null}drawFocusRing(){}createImageData(){}getImageData(){}putImageData(){}globalCompositeOperation(){}setTransform(){}}function mh(e){if(e.startsWith("GCF")||e.startsWith("GCA")&&e.length>=13){return"https://hgdownload.soe.ucsc.edu/hubs/"+e.substring(0,3)+"/"+e.substring(4,7)+"/"+e.substring(7,10)+"/"+e.substring(10,13)+"/"+e+"/hub.txt"}}const wh=new Set(["visibility","priority","group"]),bh=new Set(["track","type","shortLabel","longLabel","bigDataUrl","parent","superTrack","priority","view","compositeContainer","compositeTrack"]);class Fh{properties=new Map;constructor(e,t){this.type=e,this.name=t}setProperty(e,t){this.properties.set(e,t)}getProperty(e){return this.properties.has("noInherit")?this.properties.get(e):this.parent&&wh.has(e)&&this.parent.hasProperty(e)?this.parent.getProperty(e):this.properties.has(e)?this.properties.get(e):this.parent&&!bh.has(e)?this.parent.getProperty(e):void 0}hasProperty(e){return null!==this.getProperty(e)&&void 0!==this.getProperty(e)}hasOwnProperty(e){return this.properties.has(e)}getOwnProperty(e){return this.properties.get(e)}removeProperty(e){this.properties.delete(e)}get format(){const e=this.getProperty("type");if(e)return function(e){const t=e.indexOf(" ");return t>0?e.substring(0,t):e}(e)}get displayMode(){let e=this.getProperty("visibility");if(!e)return"COLLAPSED";switch(e=e.toLowerCase(),e){case"dense":default:return"COLLAPSED";case"pack":return"EXPANDED";case"squish":return"SQUISHED"}}}class vh{constructor(e,t,i,r){this.name=e,this.priority=i,this.label=t,this.defaultOpen=r,this.tracks=[],this.children=[]}isEmpty(){return 0===this.tracks.length&&(!this.children||0===this.children.length||this.children.every((e=>e.isEmpty())))}map(e){this.tracks.forEach(e),this.children.forEach((t=>t.map(e)))}findTracks(e){const t=[];return this._find(t,e),t}_find(e,t){this.tracks.forEach((i=>{t(i)&&e.push(i)})),this.children.forEach((i=>i._find(e,t)))}countTracks(){return this.tracks.length+this.children.reduce(((e,t)=>e+t.countTracks()),0)}countSelectedTracks(){return this.tracks.filter((e=>e.visible)).length+this.children.reduce(((e,t)=>e+t.countSelectedTracks()),0)}trim(){this.children=this.children.filter((e=>!e.isEmpty())),this.children.forEach((e=>e.trim()))}setTrackVisibility(e){this.tracks.forEach((t=>{t.visible=e.has(t.url)})),this.children.forEach((t=>t.setTrackVisibility(e)))}}const yh=new Set(["bigbed","bigwig","biggenepred","vcftabix","refgene","bam","sampleinfo","vcf.list","ucscsnp","bed","tdf","gff","gff3","gtf","vcf","vcfphasedtrio","bigdbsnp","rmask","genepred","wig","bedgraph","interact","broadpeak","narrowpeak","gappedpeak","gistic","seg","mut, bigrmsk"]),Ah=new Set(["cytoBandIdeo","assembly","gap","gapOverlap","allGaps","cpgIslandExtUnmasked","windowMasker"]);class Ch{constructor(e,t){this.groupStanzas=t,this.trackStanzas=e}getSupportedTrackCount(){let e=0;for(const t of this.trackStanzas)!Ah.has(t.name)&&t.hasProperty("bigDataUrl")&&t.format&&yh.has(t.format.toLowerCase())&&e++;return e}getGroupedTrackConfigurations(){if(!this.groupTrackConfigs){this.groupTrackConfigs=[];const e=new Map,t=new vh("","",0,!0);this.groupTrackConfigs.push(t);const i=this.groupStanzas&&this.groupStanzas.length>0;if(i)for(const t of this.groupStanzas){const i=t.getProperty("name"),r="0"===t.getProperty("defaultIsClosed"),s=t.hasProperty("priority")?xh(t.getProperty("priority")):Number.MAX_SAFE_INTEGER-1,o=new vh(i,t.getProperty("label"),s,r);e.set(i,o),this.groupTrackConfigs.push(o)}for(let r of this.trackStanzas){const s=r.hasOwnProperty("superTrack")&&!r.hasOwnProperty("bigDataUrl")||r.hasOwnProperty("compositeTrack")||r.hasOwnProperty("view")||r.hasOwnProperty("container")&&r.getOwnProperty("container").equals("multiWig");let o;if(r.hasOwnProperty("parent")&&(o=e.get(r.getOwnProperty("parent"))),!o&&i&&r.hasProperty("group")){const t=r.getProperty("group");if(e.has(t))o=e.get(t);else{const i=new vh(t,t,1e3,!0);e.set(t,i),this.groupTrackConfigs.push(i),o=i}}if(s){const t=r.getProperty("track"),i=r.hasProperty("priority")?xh(r.getProperty("priority")):Number.MAX_SAFE_INTEGER-1,s="0"===r.getProperty("defaultIsClosed"),n=r.getOwnProperty("longLabel"),a=n&&n.length<50?n:r.getOwnProperty("shortLabel"),c=new vh(t,a,i,s);if(e.has(t))throw new Error(`Duplicate track container: ${t}`);e.set(t,c),o?o.children.push(c):this.groupTrackConfigs.push(c)}else if(!Ah.has(r.name)&&r.hasProperty("bigDataUrl")&&r.format&&yh.has(r.format.toLowerCase())){const e=this.#f(r);o?o.tracks.push(e):t.tracks.push(e)}}}return this.groupTrackConfigs.forEach((e=>e.trim())),this.groupTrackConfigs=this.groupTrackConfigs.filter((e=>!e.isEmpty())),this.groupTrackConfigs.sort(((e,t)=>e.priority-t.priority)),this.groupTrackConfigs}#p(e){return this.trackStanzas.filter((t=>yh.has(t.format)&&t.hasProperty("bigDataUrl")&&(!e||e(t)))).map((e=>this.#f(e)))}#f(e){const t=e.format,i={id:e.getProperty("track"),name:e.getProperty("shortLabel"),format:t,url:e.getProperty("bigDataUrl"),displayMode:e.displayMode};if("vcfTabix"===t&&(i.indexURL=i.url+".tbi"),e.hasProperty("longLabel")&&e.hasProperty("html")?(i.description&&(i.description+="
"),i.description=`${e.getProperty("longLabel")}`):e.hasProperty("longLabel")&&(i.description=e.getProperty("longLabel")),e.hasProperty("autoScale")&&(i.autoscale="on"===e.getProperty("autoScale").toLowerCase()),e.hasProperty("maxHeightPixels")){const t=e.getProperty("maxHeightPixels").split(":");i.maxHeight=Number.parseInt(t[0]),i.height=Number.parseInt(t[1]),i.minHeight=Number.parseInt(t[2])}if(e.hasProperty("color")){const t=e.getProperty("color");i.color=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("altColor")){const t=e.getProperty("altColor");i.altColor=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("viewLimits")){const t=e.getProperty("viewLimits").split(":");let r,s;t.length>1&&(r=Number.parseInt(t[0]),s=Number.parseInt(t[1])),Number.isNaN(s)||Number.isNaN(r)?console.warn(`Unexpected viewLimits value in track line: ${properties.viewLimits}`):(i.min=r,i.max=s)}if(e.hasProperty("itemRgb"),"hide"===e.getProperty("visibility")&&(i.visible=!1),e.hasProperty("url")&&(i.infoURL=e.getProperty("url")),e.hasProperty("searchIndex")&&(i.searchIndex=e.getProperty("searchIndex")),e.hasProperty("searchTrix")&&(i.trixURL=e.getProperty("searchTrix")),e.hasProperty("html")&&(i.html=e.getProperty("html")),e.hasProperty("group")&&(i._group=e.getProperty("group"),this.groupPriorityMap&&this.groupPriorityMap.has(i._group))){const e=this.groupPriorityMap.get(i._group)+1;i.order=e,this.groupPriorityMap.set(i._group,e)}if(e.hasProperty("metadata")&&(i.attributes=function(e){const t=new Map;let i=-1;for(;e&&e.length>0;)try{if(e.length===i)break;i=e.length;let r,s=e.indexOf("=");if(-1===s||s===e.length-1)break;const o=C(A(e.substring(0,s)));let n;if('"'===e.charAt(s+1)?(s++,r=e.indexOf('" ',s+1),n=r>0?e.substring(s+1,r):e.substring(s+1),r++):(r=e.indexOf(" ",s+1),-1===r&&(r=e.length),n=e.substring(s+1,r)),n=A(n),n.endsWith('"')&&(n=n.substring(0,n.length-1)),n.startsWith("<")&&n.endsWith(">")&&(n=_h(n)),t.set(o,n),r===e.length)break;e=r>0?e.substring(r+1).trim():""}catch(e){}return t}(e.getProperty("metadata"))),e.hasProperty("maxWindowToDraw")){let t=parseInt(e.getProperty("maxWindowToDraw"),10);t>Number.MAX_SAFE_INTEGER&&(t=Number.MAX_SAFE_INTEGER),i.visibilityWindow=t}if(e.hasProperty("maxWindowCoverage")){let t=parseInt(e.getProperty("maxWindowCoverage"),10);t>Number.MAX_SAFE_INTEGER&&(t=Number.MAX_SAFE_INTEGER),i.visibilityWindow=t}return i}}function _h(e){const t=e.indexOf(">"),i=e.indexOf("<",t);return t>0&&i>t?e.substring(t+1,i):e}function xh(e){try{const t=e.trim().split(".");let i=100*parseInt(t[0],10);return t.length>1&&(i+=10*parseInt(t[1],10)),t.length>2&&(i+=parseInt(t[2],10)),i}catch(t){return console.error(`Error parsing priority string: ${e}`,t),Number.MAX_SAFE_INTEGER}}const kh=new Map([["hg38","GCF_000001405.40"],["hg38_1kg","GCF_000001405.40"],["mm39","GCF_000001635.27"],["mm10","GCF_000001635.26"],["bosTau9","GCF_002263795.1"],["canFam4","GCF_011100685.1"],["canFam6","GCF_000002285.5"],["ce11","GCF_000002985.6"],["dm6","GCF_000001215.4"],["galGal6","GCF_000002315.6"],["gorGor6","GCF_008122165.1"],["macFas5","GCA_000364345.1"],["panTro6","GCA_002880755.3"],["rn6","GCF_000001895.5"],["rn7","GCF_015227675.2"],["sacCer3","GCF_000146045.2"],["sacCer2","GCF_000146045.2"],["susScr11","GCF_000003025.6"],["taeGut1","GCF_000002275.3"],["tetNig2","GCF_000002275.3"],["xenTro10","GCF_000002035.6"],["xenTro9","GCF_000002035.6"],["tair10","GCF_000001735.4"]]);class Ih{static supportedTypes=new Set(["bigBed","bigWig","bigGenePred","vcfTabix"]);static filterTracks=new Set(["cytoBandIdeo","assembly","gap","gapOverlap","allGaps","cpgIslandExtUnmasked","windowMasker"]);constructor(e,t,i,r,s){if(this.url=e,this.hubStanza=t,this.genomeStanzas=i,this.trackStanzas=r,this.groupStanzas=s,this.cytobandStanza=null,this.trackHubMap=new Map,r){const e=i[0].getProperty("genome");this.trackHubMap.set(e,new Ch(r,s)),this.cytobandStanza=this.trackStanzas.find((e=>"cytoBandIdeo"===e.name&&e.hasProperty("bigDataUrl")))||null}}getName(){return this.hubStanza.getProperty("hub")}getShortLabel(){return this.hubStanza.getProperty("shortLabel")}getLongLabel(){return this.hubStanza.getProperty("longLabel")}getDescriptionUrl(){return this.hubStanza.getProperty("descriptionUrl")}getGenomeConfig(e){const t=e?this.genomeStanzas.find((t=>t.getProperty("genome")===e)):this.genomeStanzas[0];if(!t)throw new Error(`Genome not found in hub: ${e}`);return this.#g(t)}#g(e){const t=e.getProperty("genome"),i=this.hubStanza.getProperty("shortLabel")||e.getProperty("scientificName")||e.getProperty("organism")||e.getProperty("description"),r={id:t,name:i+(i?` (${t})`:` ${t}`),twoBitURL:e.getProperty("twoBitPath"),nameSet:"ucsc",hubs:[this.url]};if(e.hasProperty("chromSizes")?r.chromSizesURL=e.getProperty("chromSizes"):(r.wholeGenomeView=!1,r.showChromosomeWidget=!1),e.hasProperty("defaultPos")){const t=e.getProperty("defaultPos");r.locus=t}e.hasProperty("blat")&&(r.blat=e.getProperty("blat")),e.hasProperty("chromAliasBb")&&(r.chromAliasBbURL=e.getProperty("chromAliasBb")),e.hasProperty("chromAlias")&&(r.aliasURL=e.getProperty("chromAlias")),e.hasProperty("twoBitBptURL")&&(r.twoBitBptURL=e.getProperty("twoBitBptURL")),e.hasProperty("twoBitBptUrl")&&(r.twoBitBptURL=e.getProperty("twoBitBptUrl")),this.cytobandStanza&&(r.cytobandBbURL=this.cytobandStanza.getProperty("bigDataUrl")),this.hubStanza.hasProperty("longLabel")?r.description=this.hubStanza.getProperty("longLabel").replace("/","\n"):(r.description=r.id,e.hasProperty("description")&&(r.description+=`\n${e.getProperty("description")}`),e.hasProperty("organism")&&(r.description+=`\n${e.getProperty("organism")}`),e.hasProperty("scientificName")&&(r.description+=`\n${e.getProperty("scientificName")}`),e.hasProperty("htmlPath")&&(r.infoURL=e.getProperty("htmlPath")));return r.tracks=this.#p((e=>!Ih.filterTracks.has(e.name)&&"hide"!==e.getProperty("visibility"))),r}async getGroupedTrackConfigurations(e){let t=await this.#m(e);return!t&&kh.has(e)&&(t=await this.#m(kh.get(e))),t||console.log(`Warning: no trackDB found for genomeId ${e}.`),t?t.getGroupedTrackConfigurations():[]}async#m(e){let t=this.trackHubMap.get(e);if(!t)for(let i of this.genomeStanzas)if(e===i.getProperty("genome")){try{const r=i.getProperty("trackDb"),s=await Mh(r);t=new Ch(s,this.groupStanzas),this.trackHubMap.set(e,t)}catch(e){console.error(`Error loading trackDb file: ${i.getProperty("trackDb")}`,e)}break}return t}#p(e){return this.trackStanzas.filter((t=>Ih.supportedTypes.has(t.format)&&t.hasProperty("bigDataUrl")&&(!e||e(t)))).map((e=>this.#f(e)))}#f(e){const t=e.format,i={id:e.getProperty("track"),name:e.getProperty("shortLabel"),format:t,url:e.getProperty("bigDataUrl"),displayMode:e.displayMode};if("vcfTabix"===t&&(i.indexURL=i.url+".tbi"),e.hasProperty("longLabel")&&e.hasProperty("html")?(i.description&&(i.description+="
"),i.description=`${e.getProperty("longLabel")}`):e.hasProperty("longLabel")&&(i.description=e.getProperty("longLabel")),e.hasProperty("autoScale")&&(i.autoscale="on"===e.getProperty("autoScale").toLowerCase()),e.hasProperty("maxHeightPixels")){const t=e.getProperty("maxHeightPixels").split(":");i.maxHeight=Number.parseInt(t[0]),i.height=Number.parseInt(t[1]),i.minHeight=Number.parseInt(t[2])}if(e.hasProperty("color")){const t=e.getProperty("color");i.color=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("altColor")){const t=e.getProperty("altColor");i.altColor=t.indexOf(",")>0?`rgb(${t})`:t}if(e.hasProperty("viewLimits")){const t=e.getProperty("viewLimits").split(":");let r,s;t.length>1&&(r=Number.parseInt(t[0]),s=Number.parseInt(t[1])),Number.isNaN(s)||Number.isNaN(r)?console.warn(`Unexpected viewLimits value in track line: ${e.getProperty("viewLimits")}`):(i.min=r,i.max=s)}if(e.hasProperty("itemRgb"),"hide"===e.getProperty("visibility")&&(i.visible=!1),e.hasProperty("url")&&(i.infoURL=e.getProperty("url")),e.hasProperty("searchIndex")&&(i.searchIndex=e.getProperty("searchIndex")),e.hasProperty("searchTrix")&&(i.trixURL=e.getProperty("searchTrix")),e.hasProperty("group")&&(i._group=e.getProperty("group"),this.groupPriorityMap&&this.groupPriorityMap.has(i._group))){const e=this.groupPriorityMap.get(i._group)+1;i.order=e,this.groupPriorityMap.set(i._group,e)}const r=e.hasProperty("defaultLabelFields")?e.getProperty("defaultLabelFields"):e.getProperty("labelFields");return r&&(i.labelField=r.split(",")[0]),i}}const Sh=new Set(["descriptionUrl","desriptionUrl","twoBitPath","blat","chromAliasBb","twoBitBptURL","twoBitBptUrl","htmlPath","bigDataUrl","genomesFile","trackDb","groups","include","html","searchTrix","groups","chromSizes"]),Eh=new Map;async function Nh(e){if(Eh.has(e))return Eh.get(e);const t=await Mh(e);if(t.length<1)throw new Error("Empty hub file");const i=t[0];if("hub"!==i.type)throw new Error("First stanza must be a hub stanza");let r,s;if("on"===i.getProperty("useOneFile")){if("genome"!==t[1].type)throw new Error("Unexpected hub file -- expected 'genome' stanza but found "+t[1].type);const e=t[1];if(r=[e],s=t.slice(2),e.hasOwnProperty("chromSizes")){const t=e.getProperty("chromSizes");try{await Rr.getContentLength(t)>1e5&&e.removeProperty("chromSizes")}catch(e){console.error(`Error getting content length for chromSizes ${t}`,e)}}}else{if(!i.hasProperty("genomesFile"))throw new Error("hub.txt must specify 'genomesFile'");r=await Mh(i.getProperty("genomesFile"))}const o=new Set;r.forEach((e=>{const t=e.getProperty("groups");t&&o.add(t)}));const n=[],a=Array.from(o).map((async e=>await Mh(e)));(await Promise.all(a)).forEach((e=>n.push(...e)));const c=new Ih(e,i,r,s,n);return Eh.set(e,c),c}async function Mh(e){const t=e.lastIndexOf("/"),i=e.substring(0,t+1),r=function(e){let t;if(e.startsWith("https://")||e.startsWith("http://"))try{const i=new URL(e);t=`${i.protocol}//${i.host}`}catch(e){throw console.error("Error parsing base URL host",e),e}else t="";return t}(e),s=(await Rr.loadString(e,{})).split(/\n|\r\n|\r/g),o=[];let n,a=!0;for(let e=0;e=s.length));)t=t.substring(0,t.length-1)+s[e].trim();if(t.startsWith("include")){const e=Bh(t.substring(8).trim(),r,i),s=await Mh(e);for(let e of s)o.push(e)}const c=t.indexOf(" "),l=t.substring(0,c).trim();let h=t.substring(c+1).trim();if("type"===l){const e=h.split(/\s+/);if(h=e[0],"bigWig"===h&&3===e.length){const t=e[1],i=e[2];n&&(n.setProperty("min",t),n.setProperty("max",i))}}else if(!["shortLabel","longLabel","metadata","label"].includes(l)){const e=h.split(/\s+/);h=e[0]}(Sh.has(l)||h.endsWith("URL")||h.endsWith("Url"))&&(h=Bh(h,r,i)),a&&(n=new Fh(l,h),o.push(n),a=!1),n.setProperty(l,h)}}return function(e){const t=new Map;for(let i of e)t.set(i.name,i);for(let i of e)if(i.properties.has("parent")){const e=Rh(i.properties.get("parent"));i.parent=t.get(e)}return e}(o)}function Rh(e){const t=e.indexOf(" ");return t>0?e.substring(0,t):e}function Bh(e,t,i){return e.startsWith("http://")||e.startsWith("https://")||e.startsWith("gs://")||e.startsWith("s3://")?e:e.startsWith("/")?t+e:i+e}const Dh={initializeGenomes:async function(e){if(!Dh.KNOWN_GENOMES){let t={};const i=(e,t)=>(e.forEach((function(e){t[e.id]=e})),t);if(!1!==e.loadDefaultGenomes)try{i(await Rr.loadJson("https://igv.org/genomes/genomes3.json",{timeout:2e3}),t)}catch(e){try{console.error("Error initializing default genomes:",e);i(await Rr.loadJson("https://raw.githubusercontent.com/igvteam/igv-data/refs/heads/main/genomes/web/genomes.json",{timeout:1e4}),t)}catch(t){console.error("Error initializing backup genomes:",e)}}const r=e.genomeList||e.genomes;if(r)if("string"==typeof r){i(await Rr.loadJson(r,{}),t)}else i(r,t);Dh.KNOWN_GENOMES=t}},isWholeGenomeView:function(e){return"all"===e.toLowerCase()},expandReference:async function(e,t){if(b(t)&&t.startsWith("{"))try{t=JSON.parse(t)}catch(e){}let i;if(b(t)?i=t:t.genome?i=t.genome:void 0===t.id||t.fastaURL||t.twobitURL||(i=t.id),i){let t=Dh.KNOWN_GENOMES[i];if(!t){if((i.startsWith("GCA_")||i.startsWith("GCF_"))&&i.length>=13)try{const e=mh(i);t=(await Nh(e)).getGenomeConfig(i)}catch(e){console.error(e)}t||e.present(new Error(`Unknown genome id: ${i}`),void 0)}return t}return t}};let Lh,Th,zh=0,Ph=[];class Hh extends nh{constructor(e,t,i,r){super(e,t,i,r)}initializationHelper(){this.spinnerElement=document.createElement("div"),this.spinnerElement.className="igv-loading-spinner-container",this.viewportElement.appendChild(this.spinnerElement),this.spinnerElement.appendChild(document.createElement("div")),this.overlayElement=document.createElement("div"),this.overlayElement.style.position="absolute",this.overlayElement.style.width="100%",this.overlayElement.style.height="100%",this.viewportElement.appendChild(this.overlayElement);const e=this.trackView.track;"sequence"!==e.type&&(this.zoomInNoticeElement=Hh.createZoomInNotice(this.viewportElement)),"sequence"!==e.id&&(this.trackLabelElement=document.createElement("div"),this.trackLabelElement.className="igv-track-label",this.viewportElement.appendChild(this.trackLabelElement),this.setTrackLabel(e.name||""),!1===this.browser.doShowTrackLabels&&(this.trackLabelElement.style.display="none"),this.trackView.track.height&&this.setHeight(this.trackView.track.height)),this.doRenderBucketLabels=new Set(["seg","mut"]).has(this.trackView.track.type),this.stopSpinner(),this.addMouseHandlers()}didPresentZoomInNotice(){const e=!(void 0===this.zoomInNoticeElement);return!1===e?e:"flex"===this.zoomInNoticeElement.style.display}setContentHeight(e){super.setContentHeight(e),this.featureCache&&(this.featureCache.redraw=!0)}setTrackLabel(e){this.trackLabelElement.innerHTML="",this.trackLabelElement.innerHTML=e;const t=this.trackLabelElement.textContent;this.trackLabelElement.setAttribute("title",t)}startSpinner(){this.spinnerElement&&(this.spinnerElement.style.display="flex")}stopSpinner(){this.spinnerElement&&(this.spinnerElement.style.display="none")}checkZoomIn(){if(this.trackView.track&&"sequence"===this.trackView.track.type&&this.referenceFrame.bpPerPixel>10)return this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),this.canvas=void 0,!1;if(!this.viewIsReady())return!1;if((()=>{if("all"===this.referenceFrame.chr.toLowerCase())return!this.trackView.track.supportsWholeGenome;{const e=this.trackView.track.visibilityWindow;return void 0!==e&&e>0&&this.referenceFrame.bpPerPixel*this.viewportElement.clientWidth>e}})()){if(this.canvas&&this.canvas.parentNode&&(this.canvas.parentNode.removeChild(this.canvas),this.canvas=void 0),this.trackView.track.autoHeight){const e=this.trackView.minHeight||0;this.setContentHeight(e)}return this.zoomInNoticeElement&&(this.zoomInNoticeElement.style.display="flex"),!1}return this.zoomInNoticeElement&&(this.zoomInNoticeElement.style.display="none"),!0}shift(){const e=this.referenceFrame;this.canvas&&this.canvas._data&&this.canvas._data.referenceFrame.chr===this.referenceFrame.chr&&this.canvas._data.bpPerPixel===e.bpPerPixel&&(this.canvas._data.pixelShift=Math.round((this.canvas._data.bpStart-e.start)/e.bpPerPixel),this.canvas.style.left=this.canvas._data.pixelShift+"px")}genomicRange(){return{start:this.referenceFrame.start,end:this.referenceFrame.start+this.referenceFrame.bpPerPixel*this.viewportElement.clientWidth}}setTop(e){if(super.setTop(e),this.overlayElement.style.top=`-${e}px`,this.checkZoomIn()){if(this.canvas){const t=this.viewportElement.clientHeight,i=this.canvas._data.pixelTop-e,r=i+this.canvas._data.pixelHeight;(i>0||r0)for(let r of a.roiSets){const s=await r.getFeatures(t,o,n,e.bpPerPixel);i.push({track:r,features:s})}const r=a&&a.resolutionAware,s=this.windowFunction;return this.featureCache=new Oh(t,o,n,e.bpPerPixel,c,i,r,s),this.loading=!1,this.hideMessage(),this.stopSpinner(),this.browser.fireEvent("featuresloaded",[this]),this.featureCache}}catch(e){this.trackView&&!0!==this.trackView.disposed&&(this.showMessage("Error loading track data"),this.browser.alert.present(e),console.error(e))}finally{this.loading=!1,this.stopSpinner()}}get track(){return this.trackView.track}get windowFunction(){return this.track?this.track.windowFunction:void 0}repaintDimensions(){const e=Dh.isWholeGenomeView(this.referenceFrame.chr),t=e?this.viewportElement.clientWidth:3*this.viewportElement.clientWidth,i=this.referenceFrame.bpPerPixel;return{bpStart:this.referenceFrame.start-(e?0:this.viewportElement.clientWidth*i),bpEnd:e?Number.MAX_SAFE_INTEGER:this.referenceFrame.start+2*this.viewportElement.clientWidth*i+1,pixelWidth:t}}repaint(){if(void 0===this.featureCache)return;const{features:e,roiFeatures:t}=this.featureCache,{bpStart:i,bpEnd:r,pixelWidth:s}=this.repaintDimensions(),o=this.viewportElement.clientHeight,n=this.getContentHeight(),a=t?Math.max(n,o):n,c=Math.min(a,3*o);if(0===s||0===c)return void(this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas));const l=Math.max(0,this.contentTop-Math.floor(c/3)),h=this.referenceFrame.bpPerPixel,d=Math.round((i-this.referenceFrame.start)/h),u=l-(this.contentTop||0),f=document.createElement("canvas");f.style.position="relative",f.style.display="block",f.style.width=s+"px",f.style.height=c+"px",f.style.left=d+"px",f.style.top=u+"px";const p="FILL"===this.trackView.track.displayMode||!1!==this.trackView.track.supportHiDPI?window.devicePixelRatio:1;f.width=p*s,f.height=p*c;const g=f.getContext("2d");g.scale(p,p),g.translate(0,-l);const m={context:g,contentTop:this.contentTop,pixelXOffset:d,pixelWidth:s,pixelHeight:c,pixelTop:l,bpStart:i,bpEnd:r,bpPerPixel:h,pixelShift:d,windowFunction:this.windowFunction,referenceFrame:this.referenceFrame,selection:this.selection,viewport:this,viewportWidth:this.viewportElement.clientWidth};this.draw(m,e,t),this.canvas&&this.canvas.parentNode&&this.canvas.parentNode.removeChild(this.canvas),f._data=m,this.canvas=f,this.viewportElement.appendChild(f)}refresh(){if(!this.canvas||!this.featureCache)return;const e=this.canvas._data;e.context.clearRect(0,0,this.canvas.width,this.canvas.height);const{features:t,roiFeatures:i}=this.featureCache;this.draw(e,t,i)}draw(e,t,i){if(t&&(e.features=t,this.trackView.track.draw(e)),i&&i.length>0)for(let t of i)e.features=t.features,t.track.draw(e)}containsPosition(e,t){return this.referenceFrame.chr===e&&t>=this.referenceFrame.start&&t<=this.referenceFrame.calculateEnd(this.getWidth())}isLoading(){return this.loading}savePNG(){if(!this.canvas)return;const e=this.viewportElement.clientWidth*window.devicePixelRatio,t=this.viewportElement.clientHeight*window.devicePixelRatio,i=-this.canvas.offsetLeft*window.devicePixelRatio,r=this.canvas._data,s=r?r.pixelTop:0,o=(this.contentTop-s)*window.devicePixelRatio,n=this.canvas.getContext("2d").getImageData(i,o,e,t),a=document.createElement("canvas"),c=a.getContext("2d");a.width=n.width,a.height=n.height,c.putImageData(n,0,0);k((this.trackLabelElement&&this.trackLabelElement.textContent?this.trackLabelElement.textContent:"image")+".png",a.toDataURL("image/png"))}saveSVG(){let{width:e,height:t}=this.browser.columnContainer.getBoundingClientRect();const i=new gh({width:e,height:8e3,backdropColor:"white",multiLocusGap:0,viewbox:{x:0,y:0,width:e,height:8e3}}),r={deltaX:32,deltaY:32};this.renderSVGContext(i,r,!1),i.setHeight(t);const s=(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,""),o=this.browser.referenceFrameList.indexOf(this.referenceFrame),a=i.getSerializedSvg(!0),c=URL.createObjectURL(new Blob([a],{type:"application/octet-stream"}));k(`${`${s}_referenceFrame_${o}_guid_${n()}`}.svg`,c)}renderSVGContext(e,{deltaX:t,deltaY:i},r=!0){if(!1===this.didPresentZoomInNotice()){const{width:r,height:s}=this.viewportElement.getBoundingClientRect(),o=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_referenceFrame_${this.browser.referenceFrameList.indexOf(this.referenceFrame)}_guid_${n()}`,a=t,c=i-this.contentTop,l=this.contentTop;e.saveWithTranslationAndClipRect(o,a,c,r,s,l);const{start:h,bpPerPixel:d}=this.referenceFrame,u=Math.round((h-this.referenceFrame.start)/d),f={context:e,contentTop:this.contentTop,pixelXOffset:u,pixelWidth:r,pixelHeight:s,pixelTop:l,bpStart:h,bpEnd:h+r*d,bpPerPixel:d,pixelShift:u,referenceFrame:this.referenceFrame,selection:this.selection,viewport:this,viewportWidth:this.viewportElement.clientWidth},p=this.featureCache?this.featureCache.features:void 0,g=this.featureCache?this.featureCache.roiFeatures:void 0;this.draw(f,p,g),e.restore()}if(r&&this.trackLabelElement&&this.browser.doShowTrackLabels){const{x:r,y:s,width:o,height:n}=this.viewportElement.getBoundingClientRect(),{x:a,y:c,width:l,height:h}=this.trackLabelElement.getBoundingClientRect(),d=a-r,u=c-s,f=l,p=h;this.renderTrackLabelSVG(e,t+d,i+u,f,p)}}renderTrackLabelSVG(e,t,i,r,s){const o=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_track_label_guid_${n()}`,a=this.trackLabelElement.textContent,{width:c}=e.measureText(a),l=.25*(r-c),h=.7*(s-12);this.renderElementSVG(e,o,t,i,r,s,a,l,h)}renderElementSVG(e,t,i,r,s,o,n,a,c){e.saveWithTranslationAndClipRect(t,i,r,s,o,0),e.fillStyle="white",e.fillRect(0,0,s,o),e.font="12px Arial",e.fillStyle="rgb(68, 68, 68)",e.fillText(n,a,o-c),e.strokeStyle="rgb(68, 68, 68)",e.strokeRect(0,0,s,o),e.restore()}get cachedFeatures(){return this.featureCache?this.featureCache.features:[]}clearCache(){this.featureCache=void 0,this.canvas&&(this.canvas._data=void 0)}async getFeatures(e,t,i,r,s){if(this.featureCache&&this.featureCache.containsRange(t,i,r,s,this.windowFunction))return this.featureCache.features;if("function"==typeof e.getFeatures){const o=await e.getFeatures(t,i,r,s,this);return this.checkContentHeight(o),o}}needsRepaint(){if(!this.canvas)return!0;const e=this.canvas._data;return!e||this.referenceFrame.starte.bpEnd||this.referenceFrame.chr!==e.referenceFrame.chr||this.referenceFrame.bpPerPixel!==e.bpPerPixel||this.windowFunction!==e.windowFunction}needsReload(){if(!this.featureCache)return!0;const{chr:e,bpPerPixel:t}=this.referenceFrame,{bpStart:i,bpEnd:r}=this.repaintDimensions();return!this.featureCache.containsRange(e,i,r,t,this.windowFunction)}static createZoomInNotice(e){const t=document.createElement("div");t.className="igv-zoom-in-notice-container",e.appendChild(t);const i=document.createElement("div");return t.appendChild(i),i.textContent="Zoom in to see features",t.style.display="none",t}viewIsReady(){return this.browser&&this.browser.referenceFrameList&&this.referenceFrame}addMouseHandlers(){this.addViewportContextMenuHandler(this.viewportElement);const e=e=>{this.enableClick=!0,this.browser.mouseDownOnViewport(e,this),o(e)};this.viewportElement.addEventListener("mousedown",e),this.viewportElement.addEventListener("touchstart",e);const t=e=>{this.browser.dragObject||this.browser.isScrolling?(this.browser.cancelTrackPan(),this.enableClick=!1):(this.browser.cancelTrackPan(),this.browser.endTrackDrag())};if(this.viewportElement.addEventListener("mouseup",t),this.viewportElement.addEventListener("touchend",t),"function"==typeof this.trackView.track.hoverText){let e=0;this.viewportElement.addEventListener("mousemove",(t=>{const i=Date.now();if(0===t.buttons&&i-e>100){e=i;const r=this.createClickState(t);if(r){const e=this.trackView.track.hoverText(r);e?this.viewportElement.setAttribute("title",e):this.viewportElement.removeAttribute("title")}}}))}this.addViewportClickHandler(this.viewportElement),this.trackView.track.name&&"sequence"!==this.trackView.track.config.type&&this.addTrackLabelClickHandler(this.trackLabelElement)}addViewportContextMenuHandler(e){e.addEventListener("contextmenu",(e=>{if(this.browser.dragObject)return!1;const t=this.createClickState(e);if(void 0===t)return!1;e.preventDefault(),e.stopPropagation();let i=[];if("function"==typeof this.trackView.track.contextMenuItemList){const e=this.trackView.track.contextMenuItemList(t);e&&(i=e)}i.length>0&&i.push({label:document.createElement("hr")}),i.push({label:"Save Image (PNG)",click:()=>this.savePNG()}),i.push({label:"Save Image (SVG)",click:()=>this.saveSVG()}),this.browser.menuPopup.presentTrackContextMenu(e,i)}))}addViewportClickHandler(e){e.addEventListener("click",(e=>{if(this.enableClick&&this.canvas){if(3===e.which||e.ctrlKey)return;if(this.browser.dragObject||this.browser.isScrolling)return;e.preventDefault();const t=a(e,this.viewportElement).x,i=a(e,this.canvas).x,r=this.referenceFrame;Math.floor(r.start+r.toBP(i));const s=Date.now();if(s-zhe));t[this.browser.referenceFrameList.indexOf(this.referenceFrame)]=e,s=t.join(" ")}this.browser.search(s)}else e.shiftKey?this.browser.zoomWithScaleFactor(2,i,this.referenceFrame):this.browser.zoomWithScaleFactor(.5,i,this.referenceFrame)}else"function"==typeof this.trackView.track.popupData&&(Lh=setTimeout((()=>{const t=this.getPopupContent(e);if(t)if(!1===e.shiftKey){if(Th&&Th.dispose(),Ph.length>0){for(const e of Ph)e.dispose();Ph.length=0}Th=new us(this.viewportElement.parentElement,!0,void 0,(()=>{Th.dispose()})),Th.presentContentWithEvent(e,t)}else{let i=new us(this.viewportElement.parentElement,!0,void 0,(()=>{const e=Ph.indexOf(i);Ph.splice(e,1),i.dispose()}));Ph.push(i),i.presentContentWithEvent(e,t)}window.clearTimeout(Lh),Lh=void 0}),this.browser.constants.doubleClickDelay));zh=s}}))}addTrackLabelClickHandler(e){e.addEventListener("click",(e=>{e.stopPropagation(),this.removeTrackLabelPopover();const{track:t}=this.trackView;let i;if("function"==typeof t.description)i=t.description();else if(t.description){const e=document.createElement("div");e.className="igv-track-label-popover__row",e.textContent=t.description,i=e}i&&this.showTrackLabelPopover(e,i,t.name||"")}))}showTrackLabelPopover(e,t,i){const r=document.createElement("div");r.className="igv-track-label-popover";const s=document.createElement("div");s.className="igv-track-label-popover__header";const o=document.createElement("div");o.className="igv-track-label-popover__title",o.textContent=i;const n=document.createElement("div");n.className="igv-track-label-popover__close",n.setAttribute("tabindex","0"),n.setAttribute("aria-label","Close"),n.appendChild(l("times")),n.addEventListener("click",(()=>this.removeTrackLabelPopover())),s.appendChild(o),s.appendChild(n);const a=document.createElement("div");a.className="igv-track-label-popover__body",a.appendChild(t),r.appendChild(s),r.appendChild(a);const c=this.trackLabelElement.getBoundingClientRect(),h=this.browser.columnContainer.getBoundingClientRect(),d=c.left-h.left,u=c.bottom-h.top+5;r.style.left=`${d}px`,r.style.top=`${u}px`,r.style.position="absolute",this._trackLabelPopover=r,this.browser.columnContainer.appendChild(r),p(r,s,{minX:0,minY:0})}removeTrackLabelPopover(){this._trackLabelPopover&&(this._trackLabelPopover.remove(),this._trackLabelPopover=null,this._trackLabelPopoverListener&&(document.removeEventListener("mousedown",this._trackLabelPopoverListener),this._trackLabelPopoverListener=null))}createClickState(e){if(!this.canvas)return;const t=this.referenceFrame,i=a(e,this.viewportElement),r=a(e,this.canvas),s=t.start+t.toBP(i.x);return{event:e,viewport:this,referenceFrame:t,genomicLocation:s,y:i.y+this.contentTop,canvasX:r.x,canvasY:r.y}}getPopupContent(e){const t=this.createClickState(e);if(void 0===t)return;let i=this.trackView.track;const r=i.popupData(t),s=this.browser.fireEvent("trackclick",[i,r,t.genomicLocation]);let o;return void 0===s||!0===s?r&&r.length>0&&(o=r.map((e=>{if(e.name){const t=`${e.name}   ${e.value}`;return`
${t}
`}return"
"===e?e:e.html?e.html:`
${e}
`})).join("")):"string"==typeof s&&(o=s),o}dispose(){this.popover&&this.popover.dispose(),super.dispose()}}class Oh{constructor(e,t,i,r,s,o,n,a){this.chr=e,this.bpStart=t,this.bpEnd=i,this.bpPerPixel=r,this.features=s,this.roiFeatures=o,this.multiresolution=n,this.windowFunction=a}containsRange(e,t,i,r,s){if(s&&s!==this.windowFunction)return!1;const o=this.multiresolution?this.bpPerPixel/r:1;return t>=this.bpStart&&i<=this.bpEnd&&e===this.chr&&o>.5&&o<2}overlapsRange(e,t,i){return this.chr===e&&i>=this.bpStart&&t<=this.bpEnd}}const Vh=1/16,qh=function(e,t){const{r:i,g:r,b:s}=Qr[e];return`rgba(${i},${r},${s},${t})`}("nickel",Vh),Uh=qh;class Qh{constructor(e,t){if(this.url=e.url,e.name&&(this.name=e.name),this.isUserDefined=e.isUserDefined,e.featureSource)this.featureSource=e.featureSource;else if(e.features)this.featureSource=new jh(e.features,t);else{if(!e.format)throw Error("ROI configuration must define either features or file format");this.featureSource=El(e,t)}if(e.color&&!e.color.startsWith("rgba")&&(e.color=ur.addAlpha(e.color,Vh)),!0===this.isUserDefined)this.color=e.color||Uh,this.headerColor="rgba(155,185,129)";else{this.color=e.color||qh,this.headerColor="rgb(190,190,190)";const[t,i,r,s]=function(e){if(e.startsWith("rgba(")){const[t,i]=e.split("("),[r]=i.split(")");return r.split(",").map(((e,t)=>t<3?parseInt(e):parseFloat(e)))}}(this.color);this.headerColor=`rgba(${t},${i},${r},1)`}delete e.isVisible}async getFeatures(e,t,i){return this.featureSource.getFeatures({chr:e,start:t,end:i})}async getAllFeatures(){return"function"==typeof this.featureSource.getAllFeatures?await this.featureSource.getAllFeatures():{}}addFeature(e){this.featureSource.addFeature(e)}removeFeature(e){this.featureSource.removeFeature(e)}toJSON(){if(this.url)return{name:this.name,color:this.color,url:this.url,isUserDefined:this.isUserDefined,isVisible:this.isVisible};{const e=this.featureSource.getAllFeatures(),t=[];for(let i of Object.keys(e))for(let r of e[i])t.push(r);return{name:this.name,color:this.color,features:t,isUserDefined:this.isUserDefined,isVisible:this.isVisible}}}dispose(){for(let e of Object.keys(this))this[e]=void 0}}function Gh(e,t,i,r){let s=Math.round((e-i)/r);let o=Math.round((t-i)/r)-s;return o<3&&(o=3,s-=1),{x:s,width:o}}class jh{constructor(e,t){this.featureMap={},this.genome=t;for(let i of e){const e=t?t.getChromosomeName(i.chr):i.chr;let r=this.featureMap[e];r||(r=[],this.featureMap[e]=r),r.push(i)}for(let e of Object.keys(this.featureMap))this.featureMap[e].sort(((e,t)=>e.start-t.start))}async getFeatures({chr:e,start:t,end:i}){if("all"===e.toLowerCase())return await pa(this.featureMap,this.genome);{const r=this.featureMap[e];return r?r.filter((e=>e.end>t&&e.starte.start-t.start))}removeFeature({chr:e,start:t,end:i}){if(this.featureMap[e]){const r=`${e}-${t}-${i}`;this.featureMap[e]=this.featureMap[e].filter((e=>r!==`${e.chr}-${e.start}-${e.end}`)),0===this.featureMap[e].length&&delete this.featureMap[e]}}}class Wh{constructor(e,i,r,s){this.rulerViewport=e,this.rulerSweeper=t({class:"igv-ruler-sweeper"}),i.appendChild(this.rulerSweeper),this.browser=r,this.referenceFrame=s,this.isMouseHandlers=void 0,this.addBrowserObserver()}addBrowserObserver(){this.boundObserverHandler=(()=>{this.referenceFrame&&(Dh.isWholeGenomeView(this.referenceFrame.chr)?this.removeMouseHandlers():this.addMouseHandlers())}).bind(this),this.browser.on("locuschange",this.boundObserverHandler)}removeBrowserObserver(){this.browser.off("locuschange",this.boundObserverHandler)}addMouseHandlers(){if(!0===this.isMouseHandlers)return;let e,t,i,r,s,o;this.boundContentMouseDownHandler=function(o){e=!0,t=!0;const{x:n}=a(o,this.rulerViewport.contentDiv);r=i=n,s=1,this.rulerSweeper.style.display="block",this.rulerSweeper.style.backgroundColor=!0===o.shiftKey?Uh:"rgba(68, 134, 247, 0.25)",this.rulerSweeper.style.left=`${r}px`,this.rulerSweeper.style.width=`${s}px`}.bind(this),this.rulerViewport.contentDiv.addEventListener("mousedown",this.boundContentMouseDownHandler),this.boundDocumentMouseMoveHandler=function(n){let c;if(e&&t){const{x:e}=a(n,this.rulerViewport.contentDiv);c=Math.max(Math.min(e,this.rulerViewport.contentDiv.clientWidth),0),o=c-i,s=Math.abs(o),this.rulerSweeper.style.width=`${s}px`,o<0&&(r=i+o,this.rulerSweeper.style.left=`${r}px`)}}.bind(this),document.addEventListener("mousemove",this.boundDocumentMouseMoveHandler),this.boundDocumentMouseUpHandler=function(i){let o;if(!0===e&&!0===t&&(e=t=void 0,this.rulerSweeper.style.display="none",s>1)){o={start:Math.floor(this.referenceFrame.calculateEnd(r)),end:Math.floor(this.referenceFrame.calculateEnd(r+s))};!0===i.shiftKey?this.browser.roiManager.updateUserDefinedROISet(Object.assign({chr:this.referenceFrame.chr},o)):(rs(this.browser.genome.getChromosome(this.referenceFrame.chr).bpLength,o,this.browser.minimumBases()),function(e,t,i){e.start=Math.round(t.start),e.end=Math.round(t.end),e.bpPerPixel=(e.end-e.start)/i}(this.referenceFrame,o,this.rulerViewport.contentDiv.clientWidth),this.browser.updateViews(this.referenceFrame))}}.bind(this),document.addEventListener("mouseup",this.boundDocumentMouseUpHandler),this.isMouseHandlers=!0}removeMouseHandlers(){this.rulerViewport.contentDiv.removeEventListener("mousedown",this.boundContentMouseDownHandler),document.removeEventListener("mousemove",this.boundDocumentMouseMoveHandler),document.removeEventListener("mouseup",this.boundDocumentMouseUpHandler),this.isMouseHandlers=!1}dispose(){this.removeBrowserObserver(),this.removeMouseHandlers(),this.rulerSweeper.remove()}}function $h(e){if(Kh[e])return Kh[e];if(Kh["chr"+e]){const t=Kh["chr"+e];return Kh[e]=t,t}{const t=ur.randomRGB(0,255);return Kh[e]=t,t}}const Kh={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0)",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};let Yh,Zh;class Xh extends Hh{constructor(e,t,i,r){super(e,t,i,r)}get contentDiv(){return this.viewportElement}initializationHelper(){this.multiLocusCloseButton=document.createElement("div"),this.multiLocusCloseButton.className="igv-multi-locus-close-button",this.viewportElement.appendChild(this.multiLocusCloseButton);const e=l("times-circle");this.multiLocusCloseButton.appendChild(e),this.multiLocusCloseButton.addEventListener("click",(()=>{this.browser.removeMultiLocusPanel(this.referenceFrame)})),this.rulerLabel=document.createElement("div"),this.rulerLabel.className="igv-multi-locus-ruler-label",this.viewportElement.appendChild(this.rulerLabel);const t=document.createElement("div");this.rulerLabel.appendChild(t),this.rulerLabel.addEventListener("click",(async e=>{e.stopPropagation(),await this.browser.gotoMultilocusPanel(this.referenceFrame)})),this.tooltip=document.createElement("div"),this.tooltip.className="igv-ruler-tooltip",this.tooltip.style.height=`${this.viewportElement.clientHeight}px`,this.viewportElement.appendChild(this.tooltip),this.tooltipContent=document.createElement("div"),this.tooltip.appendChild(this.tooltipContent),this.rulerSweeper=new Wh(this,this.viewportElement.parentElement,this.browser,this.referenceFrame),this.attachMouseHandlers(Dh.isWholeGenomeView(this.referenceFrame.chr)),this.tooltip.style.display="none",this.dismissLocusLabel()}presentLocusLabel(e){this.multiLocusCloseButton.style.display="block",this.rulerLabel.style.display="block",this.rulerLabel.style.backgroundColor=$h(this.referenceFrame.chr);const t=this.rulerLabel.querySelector("div"),{width:i}=this.rulerLabel.getBoundingClientRect();t.innerHTML=`${this.referenceFrame.getMultiLocusLabel(e)}`;const{width:r}=t.getBoundingClientRect();r/i>.5&&(t.innerHTML=`${this.referenceFrame.getMultiLocusLabelBPLengthOnly(e)}`)}dismissLocusLabel(){this.rulerLabel.style.display="none",this.multiLocusCloseButton.style.display="none"}attachMouseHandlers(e){!0===e?(this.viewportElement.addEventListener("click",(e=>{const{x:t}=a(e,this.viewportElement),i=Math.round(this.referenceFrame.start+this.referenceFrame.toBP(t));let r;const{chr:s}=this.browser.genome.getChromosomeCoordinate(i);if(1===this.browser.referenceFrameList.length)r=s;else{const e=this.browser.referenceFrameList.indexOf(this.referenceFrame),t=this.browser.referenceFrameList.map((({locusSearchString:e})=>e));t[e]=s,r=t.join(" ")}this.browser.search(r)})),this.viewportElement.style.cursor="pointer"):this.viewportElement.style.cursor="default"}mouseMove(e){if(this.browser.doShowCursorGuide){void 0===Zh?(Zh=this,this.tooltip.style.display="block"):Zh.guid!==this.guid?(Zh.tooltip&&(Zh.tooltip.style.display="none"),this.tooltip.style.display="block",Zh=this):this.tooltip.style.display="block";if(this.browser.isMultiLocusWholeGenomeView()||Dh.isWholeGenomeView(this.referenceFrame.chr))return void(this.tooltip.style.display="none");const{x:t}=a(e,this.viewportElement),{start:i,end:r,bpPerPixel:s}=this.referenceFrame,o=Math.round(.5+i+Math.max(0,t)*s);this.tooltipContent.textContent=F(o);const n=this.tooltipContent.getBoundingClientRect(),c=this.viewportElement.getBoundingClientRect(),l=cr(t,0,c.width-n.width);return this.tooltip.style.left=`${l}px`,clearTimeout(Yh),Yh=setTimeout((()=>{this.tooltip&&(this.tooltip.style.display="none")}),1e4),{start:i,bp:o,end:r}}}startSpinner(){}stopSpinner(){}dispose(){this.rulerSweeper.dispose(),super.dispose()}}let Jh;class ed extends Hh{featureCache=new td;constructor(e,t,i,r){super(e,t,i,r)}initializationHelper(){this.canvas=document.createElement("canvas"),this.canvas.className="igv-ideogram-canvas",this.viewportElement.appendChild(this.canvas),this.ideogram_ctx=this.canvas.getContext("2d"),this.tooltip=document.createElement("div"),this.tooltip.className="igv-cytoband-tooltip",this.tooltip.style.height=`${this.viewportElement.clientHeight}px`,this.viewportElement.appendChild(this.tooltip),this.tooltipContent=document.createElement("div"),this.tooltip.appendChild(this.tooltipContent),this.tooltip.style.display="none",this.addMouseHandlers()}async getFeatures(e,t,i,r){return this.featureCache.containsRange(e)?this.featureCache.get(e):this.loadFeatures()}async loadFeatures(){const e=this.referenceFrame.chr,t=await this.referenceFrame.genome.getCytobands(e);return this.featureCache.set(e,t),t}repaint(){if(void 0===this.featureCache)return;const{width:e,height:t}=this.viewportElement.getBoundingClientRect();Co.configureHighDPICanvas(this.ideogram_ctx,e,t);const i=this.referenceFrame.chr,r=this.featureCache.get(i),s={context:this.ideogram_ctx,pixelWidth:e,pixelHeight:t,referenceFrame:this.referenceFrame,features:r};this.trackView.track.draw(s)}addMouseHandlers(){this.addViewportClickHandler(this.viewportElement),this.trackView.track.showCytobandNames&&(this.viewportElement.addEventListener("mousemove",this.mouseMove.bind(this)),this.viewportElement.addEventListener("mouseleave",this.mouseLeave.bind(this)))}mouseMove(e){const{x:t}=a(e,this.viewportElement),i=this.featureCache.get(this.referenceFrame.chr);if(i){const{width:e}=this.viewportElement.getBoundingClientRect(),r=e/i[i.length-1].end;let s=!1;for(let o=0;o=a&&t<=c){this.tooltipContent.textContent=n.name;const{width:t}=this.tooltipContent.getBoundingClientRect();const i=cr((a+c)/2-t/2,0,e-t);this.tooltip.style.left=`${i}px`,clearTimeout(Jh),Jh=setTimeout((()=>{this.tooltip&&(this.tooltip.style.display="none")}),1e4),this.tooltip.style.display="block",s=!0;break}}if(s)return}this.tooltip.style.display="none"}mouseLeave(e){this.tooltip.style.display="none"}addViewportClickHandler(e){this.boundClickHandler=function(e){const{xNormalized:t,width:i}=a(e,this.ideogram_ctx.canvas),{bpLength:r}=this.browser.genome.getChromosome(this.referenceFrame.chr),s=this.referenceFrame.bpPerPixel*i/r;let o=t;o-s/2<0&&(o=s/2);o+s/2>1&&(o=1-s/2);const n=Math.round((o-s/2)*r),c=Math.round((o+s/2)*r);this.referenceFrame.start=n,this.referenceFrame.end=c,this.referenceFrame.bpPerPixel=(c-n)/i,this.browser.updateViews(this.referenceFrame,this.browser.trackViews,!0)}.bind(this),e.addEventListener("click",this.boundClickHandler)}setWidth(e){this.viewportElement.style.width=e+"px"}renderSVGContext(e,{deltaX:t,deltaY:i},r=!0){const{width:s,height:o}=this.viewportElement.getBoundingClientRect(),a=`ideogram_referenceFrame_${this.browser.referenceFrameList.indexOf(this.referenceFrame)}_guid_${n()}`,c=t,l=this.contentTop+i,h=-this.contentTop;e.saveWithTranslationAndClipRect(a,c,l,s,o,h),this.trackView.track.draw({context:e,pixelWidth:s,pixelHeight:o,referenceFrame:this.referenceFrame,features:this.featureCache.get(this.referenceFrame.chr)}),e.restore()}startSpinner(){}stopSpinner(){}}class td{features=new Map;containsRange(e){return this.features.has(e)}set(e,t){this.features.set(e,t)}get(e){return this.features.get(e)}}function id(e,t,i,r){if("ruler"===e.track.type)return new Xh(e,t,i,r);if("ideogram"===e.track.id)return new ed(e,t,i,r);{const s=new Hh(e,t,i,r);return i.viewport=s,s}}const rd=["rgb(255, 0, 0)","rgb(0, 255, 0)","rgb(0, 0, 255)","rgb(255, 0, 255)","rgb(0, 255, 255)","rgb(128, 0, 128)","rgb(255, 165, 0)","rgb(255, 105, 180)","rgb(255, 127, 80)","rgb(220, 20, 60)","rgb(255, 99, 71)","rgb(173, 216, 230)","rgb(144, 238, 144)","rgb(224, 255, 255)","rgb(250, 250, 210)","rgb(152, 251, 152)","rgb(70, 130, 180)","rgb(102, 205, 170)"].map((e=>{const[t,i,r]=e.split(","),[s,o]=t.split("("),[n,a]=r.split(")");return[o,i,n]}));class sd{static emptySpaceReplacement="|";static colorForNA=Gr("magnesium");static sampleInfoFileHeaders=["#sampleTable","#sampleMapping","#colors"];constructor(e){e.tracks.some((e=>"function"==typeof e.getSamples)).length>0&&e.sampleInfoControl.setButtonVisibility(!0),this.initialize()}initialize(){this.sampleInfoFiles=[],this.attributeNames=[],this.sampleDictionary={},this.sampleMappingDictionary={},this.colorDictionary={},this.attributeRangeLUT={},this.initialized=!1}get attributeCount(){return this.attributeNames?this.attributeNames.length:0}isInitialized(){return this.initialized}hasAttributes(){return this.attributeCount>0}getAttributes(e){const t=this.sampleMappingDictionary[e]||e;return this.sampleDictionary[t]}getAttributeValue(e,t){const i=this.getAttributes(e);return i?i[t]:void 0}async loadSampleInfo(e){if(e.url)await this.loadSampleInfoFile(e.url);else{const t={...e};for(const[e,i]of Object.entries(t))t[e]=sd.toNumericalRepresentation(i);const[i]=Object.values(t),r=Object.keys(i);this.loadSampleInfoHelper(r,t)}this.initialized=!0}loadSampleInfoHelper(e,t){const i=function(e,t){const i={};for(const r of Object.values(t))for(const t of e){let e=r[t];void 0===i[t]&&(i[t]=[]),i[t].push(e)}const r=e=>"number"==typeof e,s=e=>"string"==typeof e;for(const e of Object.keys(i)){const t=i[e],o=new Set(t),n=Array.from(o);if(!0===n.some(s)&&!0===n.some(r)?i[e]=n.filter((e=>!s(e))):i[e]=n,!i[e].some(s)){const t=i[e].slice();i[e]=[Math.min(...t),Math.max(...t)]}}return i}(e,t);od(this.attributeRangeLUT,i);const r=new Set(this.attributeNames);for(const t of e)r.has(t)||this.attributeNames.push(t);od(this.sampleDictionary,t)}async loadSampleInfoFile(e){const t=await Rr.loadString(e);this.#w(t),this.sampleInfoFiles.push(e)}discard(){this.initialize()}getAttributeColor(e,t){let i;if("-"===t)i=Gr("snow");else if("string"==typeof t&&this.colorDictionary[t])i=this.colorDictionary[t]();else if(this.colorDictionary[e])i=this.colorDictionary[e](t);else if("string"==typeof t)i="NA"===t?sd.colorForNA:sd.stringToRGBString(t);else{const[r,s]=this.attributeRangeLUT[e],o=.2,n=Math.max((t-r)/(s-r),o),[a,c,l]=rd[Object.keys(this.attributeRangeLUT).indexOf(e)];i=`rgba(${a},${c},${l},${n})`}return i}sortSampleKeysByAttribute(e,t,i){const r=e.filter((e=>{const i=this.getAttributes(e);if(void 0===i)return!1;return"number"==typeof i[t]})),s=e.filter((e=>{const i=this.getAttributes(e);if(void 0===i)return!1;return"string"==typeof i[t]})),o=(e,r)=>{const s=this.getAttributes(e)[t],o=this.getAttributes(r)[t];return"string"==typeof s&&"string"==typeof o?i*s.localeCompare(o):"number"==typeof s&&"number"==typeof o?i*(s-o):void 0};return r.sort(o),s.sort(o),-1===i?[...r,...s]:[...s,...r]}#w(e){const t=function(e){const t={},i=e.split(/\r?\n|\r/).map((e=>e.trim())).filter((e=>""!==e));let r;sd.sampleInfoFileHeaders.includes(i[0])||(r="#sampleTable",t[r]=[]);for(const e of i)sd.sampleInfoFileHeaders.includes(e)?(r=e,t[r]=[]):r&&!1===e.startsWith("#")&&t[r].push(e);return t}(e);for(const[e,i]of Object.entries(t))switch(e){case"#sampleTable":this.#b(i);break;case"#sampleMapping":this.#F(i);break;case"#colors":this.#v(i)}}#b(e){const t=e.shift().split("\t").filter((e=>e.length>0));t.shift();const i=t.map((e=>e.split(" ").join(sd.emptySpaceReplacement))),r=e.filter((e=>e.length>0));let s;for(const e of r){const t=e.split("\t"),r=t.shift();void 0===s&&(s={}),s[r]={};for(let e=0;e{let r;switch(t){case 0:r=e.split(" ").join(sd.emptySpaceReplacement);break;case 1:r=e.includes(":")?e.split(":").map((e=>parseFloat(e))):e;break;case 2:case 3:r=`rgb(${e})`}return r},i=e.map((e=>e.split("\t").map(t))),r=i.filter((e=>3===e.length&&!e.includes("*"))).filter((([e,t,i])=>!Array.isArray(t))),s={};for(const e of r){const[t,i,r]=e;void 0===s[t]&&(s[t]={}),s[t][i.toUpperCase()]=r}for(const[e,t]of Object.entries(s)){const i=Object.assign({},t);this.colorDictionary[e]=e=>{const t=e.toUpperCase();return i[t]||Gr("snow")}}const o=i.filter((e=>Array.isArray(e[1])));for(const e of o){const[t,i]=e[1],r=e[0];if(3===e.length){const[s,o,n]=Xr(e[2]);this.colorDictionary[r]=e=>{e=cr(e,t,i);return Yr(s,o,n,(e-t)/(i-t))}}else if(4===e.length){const[t,i]=e[1],[r,s,o,n]=e;this.colorDictionary[r]=e=>{e=cr(e,t,i);return Jr(o,n,(e-t)/(i-t))}}}const n=i.filter((e=>3===e.length&&e.includes("*")));for(const e of n)if("*"===e[1]){const[t,i,r]=e;this.colorDictionary[t]=e=>{if("NA"===e)return sd.colorForNA;{const[i,s]=this.attributeRangeLUT[t],o=(e-i)/(s-i),[n,a,c]=Xr(r);return Yr(n,a,c,o)}}}else if("*"===e[0]){const[t,i,r]=e;this.colorDictionary[i]=()=>r}}static toNumericalRepresentation(e){const t=Object.assign({},e);for(const[e,i]of Object.entries(t))"string"!=typeof i||isNaN(i)||(t[e]=Number(i));return t}static stringToRGBString(e){let t=0;for(let i=0;i>8*e&255;i.push(r)}return`rgb(${i.join(", ")})`}export(){const e={},t=Object.fromEntries(Object.entries(this.sampleMappingDictionary).map((([e,t])=>[t,e])));for(const i of Object.keys(this.sampleDictionary)){const r=t[i]||i,s=this.getAttributes(i);s&&(e[r]=s)}console.log(JSON.stringify(e,null,2))}}function od(e,t){for(const[i,r]of Object.entries(t))i in e&&e[i]===r||(e[i]=r)}const nd=16,ad=F;class cd{constructor(e){this.browser=e,this.height=40,this.name="",this.disableButtons=!0,this.ignoreTrackMenu=!0,this.order=.01*Number.MIN_SAFE_INTEGER,this.removable=!1,this.type="ruler",this.id="ruler"}async getFeatures(e,t,i){return[]}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,bpPerPixel:s,bpStart:o}){Dh.isWholeGenomeView(t.chr)?this.drawWholeGenome({context:e,pixelWidth:i,pixelHeight:r,bpPerPixel:s}):this.doDraw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,bpStart:o})}drawWholeGenome({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:r}){e.save(),Co.fillRect(e,0,0,t,i,{fillStyle:"white"});for(let t of this.browser.genome.wgChromosomeNames){let s=this.browser.genome.getCumulativeOffset(t),o=this.browser.genome.getChromosome(t).bpLength,n=Math.round(s/r),a=Math.round(o/r);this.renderChromosomeRect(e,n,0,a,i,t)}e.restore()}doDraw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,bpStart:s}){e.clearRect(0,0,i,r);const o=function(e,t){if(e<10)return new ld(1,"bp",1);const i=Math.floor(Math.log10(e));let r="bp",s=1;i>9?(r="gb",s=1e9):i>6?(r="mb",s=1e6):i>3&&(r="kb",s=1e3);const o=Math.pow(10,i-1),n=e/o,a=75,c=Math.pow(10,i-1),l=Math.pow(10,i)/2;return new ld(n0&&u+c<=d&&(Co.fillText(e,i,r,this.height-8),d=0),l>0&&Co.strokeLine(e,l,this.height-6,l,this.height-2),h=Math.floor((1+n)*o.majorTick);let f=l+(Math.round(t.toPixels(h-1-s+.5))-l)/2;f>0&&Co.strokeLine(e,f,this.height-6,f,this.height-2),++n,d+=a}while(le.measureText(n).width&&Co.fillText(e,n,t+r/2,i+s/2,{fillStyle:ur.greyScale(68)})}get supportsWholeGenome(){return!0}dispose(){}}class ld{constructor(e,t,i){this.majorTick=e,this.minorTick=e/10,this.majorUnit=t,this.unitMultiplier=i}description(e){console.log((e||"")+" tick "+ad(this.majorTick)+" label width "+ad(this.labelWidthBP)+" multiplier "+this.unitMultiplier)}}const hd=16;function dd(e,t){const i=new Set(e.attributeNames),r=t[0];if(void 0===e.getAttributes(r))return!1;{const t=Object.keys(e.getAttributes(r));for(const e of t)if(!1===i.has(e))return!1}return!0}function ud(e,t,i,r,s,o,n){if(!n||0===n.size)return;const a=t+r;e.save(),e.fillStyle="black";let c=s+8;c>t&&Co.dashedLine(e,0,c,i,c);for(const r of n.values()){if(c+=r.count*o+hd,c>a)break;c>t&&Co.dashedLine(e,0,c,i,c)}e.restore()}class fd{constructor(e,i,r){this.guid=n(),this.trackView=e,this.isIdeogram="ideogram"===e.track.type,this.browser=e.browser,this.viewport=t({class:"igv-viewport"}),i.appendChild(this.viewport),this.viewport.style.height=`${e.track.height}px`,this.isIdeogram&&(this.viewport.style.zIndex=16,this.viewport.style.overflow="visible"),this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.ctx.font="10px verdana",this.contentTop=0,this.hitList=void 0,this.setWidth(r),this.addMouseHandlers()}resizeCanvas(){const e=window.devicePixelRatio,t=this.browser.getSampleInfoViewportWidth();let i;if(this.browser.trackViews.length>1&&this.isIdeogram){const[e,t]=[this.browser.ideogramTrackView.track,this.browser.rulerTrackView.track];i=e.height+t.height}else i=this.viewport.clientHeight;if(this.canvas.width!==t*e||this.canvas.height!==i*e){const r=this.canvas;r.width=t*e,r.height=i*e,r.style.width=`${t}px`,r.style.height=`${i}px`,this.ctx=this.canvas.getContext("2d"),this.ctx.scale(e,e),this.isIdeogram&&Co.fillRect(this.ctx,0,0,this.ctx.canvas.width,this.ctx.canvas.height,{fillStyle:Gr("snow")})}}setTop(e){"function"==typeof this.trackView.track.getSamples&&(this.contentTop=e,this.repaint())}setWidth(e){this.viewport.innerWidth=e,this.resizeCanvas()}setHeight(e){const t=this.browser.getSampleInfoViewportWidth();this.viewport.style.width=`${t}px`,this.viewport.style.height=`${e}px`;const i=window.devicePixelRatio;this.canvas.width=t*i,this.canvas.height=e*i,this.canvas.style.width=`${t}px`,this.canvas.style.height=`${e}px`,this.ctx=this.canvas.getContext("2d"),this.ctx.scale(i,i),this.isIdeogram&&Co.fillRect(this.ctx,0,0,this.ctx.canvas.width,this.ctx.canvas.height,{fillStyle:Gr("snow")})}repaint(){if(this.resizeCanvas(),this.isIdeogram&&(this.browser.rulerTrackView&&this.browser.rulerTrackView.setTrackHeight(!0===this.browser.sampleInfoControl.showSampleInfo?this.calculateSampleInfoColumnHeight():40,!0),this.renderSampleInfoColumns(this.ctx)),"function"==typeof this.trackView.track.getSamples){const e=this.trackView.track.getSamples();e.names&&e.names.length>0&&this.draw({context:this.ctx,samples:e})}}calculateSampleInfoColumnHeight(){const e=this.browser.sampleInfo.attributeNames.map((e=>this.ctx.measureText(e).width));return 4+Math.min(Math.max(...e),128)}draw({context:e,samples:t}){e.clearRect(0,0,e.canvas.width,e.canvas.height),e.fillStyle=Gr("snow"),e.fillRect(0,0,e.canvas.width,e.canvas.height);const i=this.viewport.getBoundingClientRect().height,r=this.viewport.getBoundingClientRect().width;if(t&&t.names.length>0){const s=this.browser.sampleInfo.attributeNames;let o=1;const n=t.height;o=n-2*o<=1?0:1;let a=t.yOffset-this.contentTop,c=0;this.hitList={};for(const r of t.names){const l=this.browser.sampleInfo.getAttributes(r);if(l){let r=a+o;if(t.groupIndeces&&t.groups.size>0&&(r+=(t.groupIndeces[c]+1)*hd),r>i)break;if(r+n>0){const t=n-2*o,i=Object.entries(l);for(const o of i){const[i,n]=o,a=8+s.indexOf(i)*nd;e.fillStyle=this.browser.sampleInfo.getAttributeColor(i,n),e.fillRect(a,r,15,t);const c=`${Math.floor(a)}#${Math.floor(r)}#16#${Math.ceil(t)}`;this.hitList[c]=`${i}#${n}`}}}a+=n,c++}ud(e,0,r,i,t.yOffset-this.contentTop,t.height,t.groups)}}renderSampleInfoColumns(e){const t=(e,t,i,r,s,o)=>{e.save(),e.font="10px verdana",e.translate(i+s/2,r+o),e.rotate(-Math.PI/2),e.textAlign="left",e.fillStyle=Gr("lead"),e.fillText(t,2,2),e.restore()},i=this.browser.sampleInfo.attributeNames;this.hitList={};for(let r=0;r{const{marginTop:r}=window.getComputedStyle(i),{x:s,y:o}=a(e,this.browser.columnContainer.querySelector(".igv-sample-info-column"));return{x:Math.floor(s),y:Math.floor(o-parseInt(r,10))}},r=this.browser.columnContainer.querySelector(".igv-sample-info-column"),{x:s,y:o}=i(r,this.viewport);r.setAttribute("title","");for(const[e,i]of t){const[t,n,a,c]=e.split("#").map((e=>parseInt(e,10)));if(!(st+a||on+c)){r.setAttribute("title",`${i}`);break}}}else{const{x:i,y:r}=a(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,s]of t){const[t,o,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+n||ro+a)){const[e,t]=s.split("#");this.viewport.setAttribute("title",`${e.split(sd.emptySpaceReplacement).join(" ")}: ${"-"===t?"":t}`);break}}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}addMouseClickHandler(){this.boundMouseClickHandler=function(e){if(this.hitList){const t=Object.entries(this.hitList);if(this.isIdeogram){const i=(t,i)=>{const{marginTop:r}=window.getComputedStyle(i),{x:s,y:o}=a(e,this.browser.columnContainer.querySelector(".igv-sample-info-column"));return{x:Math.floor(s),y:Math.floor(o-parseInt(r,10))}},r=this.browser.columnContainer.querySelector(".igv-sample-info-column"),{x:s,y:o}=i(r,this.viewport);for(const[e,i]of t){const[t,r,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(st+n||or+a)){const e=this.browser.findTracks((e=>"function"==typeof e.sortByAttribute));for(const t of e)t.sortByAttribute(i);break}}}else{const{x:i,y:r}=a(e,this.viewport);for(const[e,s]of t){const[t,o,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+n||ro+a)){s.split("#");break}}}}}.bind(this),this.viewport.addEventListener("click",this.boundMouseClickHandler)}removeMouseHandlers(){this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler),this.viewport.removeEventListener("click",this.boundMouseClickHandler)}dispose(){this.removeMouseHandlers(),this.viewport.remove()}show(){this.viewport.style.display="block"}hide(){this.viewport.style.display="none"}}class pd{constructor(e,i,r,s){this.guid=n(),this.trackView=e,this.browser=e.browser,this.viewport=t({class:"igv-viewport"}),i.appendChild(this.viewport),e.track.height&&(this.viewport.style.height=`${e.track.height}px`),this.canvas=document.createElement("canvas"),this.viewport.appendChild(this.canvas),this.ctx=this.canvas.getContext("2d"),this.contentTop=0,this.hitList=void 0,this.setWidth(s),this.addMouseHandlers()}checkCanvas(){let e=0;!0===this.browser.showSampleNames&&(e=void 0===this.browser.sampleNameViewportWidth?0:this.browser.sampleNameViewportWidth),this.ctx.canvas.width=e*window.devicePixelRatio,this.ctx.canvas.style.width=`${e}px`,this.ctx.canvas.height=this.viewport.clientHeight*window.devicePixelRatio,this.ctx.canvas.style.height=`${this.viewport.clientHeight}px`,this.ctx.scale(window.devicePixelRatio,window.devicePixelRatio)}setTop(e){if("function"==typeof this.trackView.track.getSamples){this.contentTop=e;const t=this.trackView.track.getSamples();this.repaint(t)}}setWidth(e){this.viewport.innerWidth=e,this.checkCanvas()}async repaint(e){if(e.names.length>0&&!0===this.browser.showSampleNames&&(this.checkCanvas(),this.draw({context:this.ctx,samples:e}),void 0===this.browser.sampleNameViewportWidth)){const t=e.names.map((e=>this.ctx.measureText(e).width));this.browser.sampleNameViewportWidth=Math.min(200,4+Math.ceil(Math.max(...t))),this.browser.layoutChange()}}draw({context:e,samples:t}){if(Co.fillRect(e,0,0,e.canvas.width,t.height,{fillStyle:Gr("snow")}),t&&t.names.length>0){const i=this.viewport.getBoundingClientRect().height,r=t.height,s=r-2<=1?0:1;let o=t.yOffset-this.contentTop,n=0;this.hitList={};for(const a of t.names){const c=0;let l=o+s;if(t.groupIndeces&&t.groups.size>0&&(l+=(t.groupIndeces[n]+1)*hd),l+r>0){const t=r-2*s;gd(e,a,c+2,l,e.canvas.width,t)}if(o+=r,n++,o>i)break}ud(e,0,e.canvas.width,e.canvas.height,t.yOffset-this.contentTop,t.height,t.groups)}}renderSVGContext(e,{deltaX:t,deltaY:i}){if("function"==typeof this.trackView.track.getSamples){const r=this.trackView.track.getSamples(),s=0,{width:o,height:a}=this.viewport.getBoundingClientRect(),c=`${(this.trackView.track.name||this.trackView.track.id).replace(/\W/g,"")}_sample_names_guid_${n()}`;e.saveWithTranslationAndClipRect(c,t,i+s,o,a,-s),this.draw({context:e,samples:r}),e.restore()}}addMouseHandlers(){this.boundClickHandler=function(e){e.preventDefault();const t={label:"Name Panel Width",value:this.browser.sampleNameViewportWidth,callback:e=>{this.browser.sampleNameViewportWidth=parseInt(e),this.browser.layoutChange()}};this.browser.inputDialog.present(t,e)}.bind(this),this.viewport.addEventListener("contextmenu",this.boundClickHandler),this.boundMouseMoveHandler=function(e){if(this.hitList){const t=Object.entries(this.hitList),{x:i,y:r}=a(e,this.viewport);this.viewport.setAttribute("title","");for(const[e,s]of t){const[t,o,n,a]=e.split("#").map((e=>parseInt(e,10)));if(!(it+n||ro+a)){this.viewport.setAttribute("title",`${s}`);break}}}}.bind(this),this.viewport.addEventListener("mousemove",this.boundMouseMoveHandler)}removeMouseHandlers(){this.viewport.removeEventListener("contextmenu",this.boundClickHandler),this.viewport.removeEventListener("mousemove",this.boundMouseMoveHandler)}dispose(){this.removeMouseHandlers(),this.viewport.remove()}}function gd(e,t,i,r,s,o){const n=Math.min(o,10);e.font=`${n}px sans-serif`,e.textAlign="start",e.fillStyle=Gr("lead");const a=i,c=e.measureText(t),l=r+o/2+(c.actualBoundingBoxAscent+c.actualBoundingBoxDescent)/2;e.fillText(t,a,l)}class md{constructor(e){this.popover=t({class:"igv-menu-popup"}),e.appendChild(this.popover),this.parent=e;const i=t({class:"igv-menu-popup-header"});this.popover.appendChild(i),u(i,(()=>this.popover.style.display="none")),this.popoverContent=t(),this.popover.appendChild(this.popoverContent),p(this.popover,i),i.addEventListener("click",(e=>{e.stopPropagation(),e.preventDefault()})),this.popover.style.display="none"}presentMenuList(e,t,i){if(wd(this.parent),t.length>0){this.popoverContent.innerHTML="";const r=this.parseMenuList(e,t);for(let e of r)e.init&&e.init(),0===r.indexOf(e)&&e.element.classList.remove("igv-track-menu-border-top"),e.element.classList.contains("igv-track-menu-border-top")||e.element.classList.contains("igv-menu-popup-check-container")||"div"===e.element.tagName.toLowerCase()&&e.element.classList.add("igv-menu-popup-shim"),this.popoverContent.appendChild(e.element);this.popover.style.display="flex";const{width:s}=this.popover.getBoundingClientRect();"left"===i.gearColumnPosition?this.popover.style.right=`${s}px`:this.popover.style.left=-s+"px",this.popover.style.top="0px"}}parseMenuList(e,t){return t.map(((t,i)=>{let r;if(t.name)r=document.createElement("div"),r.textContent=t.name;else if(t.element)r=t.element;else if("string"==typeof t.label)r=document.createElement("div"),r.innerHTML=t.label;else if("string"==typeof t)if(t.startsWith("<")){const e=document.createElement("div");e.innerHTML=t,r=e.firstChild}else r=document.createElement("div"),r.textContent=t;if(0===i&&r.classList.add("igv-track-menu-border-top"),t.click||t.dialog){const i=i=>{if(i.preventDefault(),i.stopPropagation(),t.click)if(e.track.selected){const r=e.browser.getSelectedTrackViews();if(!0===t.doAllMultiSelectedTracks)t.click.call(e.track,i);else if("removeTrack"===t.menuItemType){const s=()=>{e.browser.overlayTrackButton.setVisibility(!1);for(const{track:e}of r)t.click.call(e,i)},o={html:`Are you sure you want to delete ${r.length} tracks?`,callback:s};e.browser.menuUtils.dialog.present(o,i)}else for(const{track:e}of r)t.click.call(e,i)}else t.click.call(e.track,i);else t.dialog&&t.dialog.call(e.track,i);this.popover.style.display="none"};void 0===r&&console.log("element is undefined"),r.addEventListener("click",i),r.addEventListener("touchend",(e=>i(e))),r.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}return{element:r,init:t.init||void 0}}))}presentTrackContextMenu(e,i){this.popoverContent.innerHTML="";const s=function(e,i){return e.map((e=>{let s;if("string"==typeof e&&"
"===e)s=document.createElement("hr");else if("string"==typeof e)s=t({class:"context-menu"}),s.innerHTML=e;else if("Node"==typeof e)s=e;else if("function"==typeof e.init&&e.init(),"checkbox"===e.type?s=ua("Show all bases",e.value):(s=t({class:"context-menu"}),"string"==typeof e.label&&(s.innerHTML=e.label)),e.click&&"color"!==e.type){function o(t){e.click(),r(i),t.preventDefault(),t.stopPropagation()}s.addEventListener("click",o),s.addEventListener("touchend",o),s.addEventListener("mouseup",(function(e){e.preventDefault(),e.stopPropagation()}))}return{el:s,init:e.init}}))}(i,this.popover);for(let{el:e}of s)this.popoverContent.appendChild(e);!function(e,t){t.style.display="flex";const{x:i,y:r}=a(e,t.parentNode),{width:s}=t.getBoundingClientRect(),o=i+s,{width:n}=t.parentNode.getBoundingClientRect();t.style.left=`${o>n?i-(o-n):i}px`,t.style.top=`${r}px`}(e,this.popover)}hide(){this.popover.style.display="none"}dispose(){this.popoverContent.innerHTML="",this.popover.innerHTML="",Object.keys(this).forEach((function(e){this[e]=void 0}))}}const wd=e=>{const t=e.querySelectorAll(".igv-menu-popup");for(const e of t)e.style.display="none"};class bd{constructor(e,i,r,s,o,n,a){this.browser=i,this.button=t({class:"igv-navbar-text-button"}),e.appendChild(this.button),Array.isArray(r)?(this.textContent=r[0],this.title=r[1]):this.textContent=this.title=r,this.buttonLabel=s,this.imageDictionary={image:`url("data:image/svg+xml,${encodeURIComponent(o)}")`,imageHover:`url("data:image/svg+xml,${encodeURIComponent(n)}")`},this.responsiveKey="text",this.configureButton(this.textContent,this.title),this.setState(a),i.on("navbar-resize",(e=>{this.navbarResizeHandler(e)}))}navbarResizeHandler(e){const t="igv-navbar-icon-button"===e?"image":"text";t!==this.responsiveKey&&(this.responsiveKey=t,this.configureButton(this.textContent,this.title),this.setState(void 0))}configureButton(e,t){this.groupElement=void 0,this.button.title=t,this.button.innerHTML="",this.button.style.backgroundImage="none",this.button.classList.remove("igv-navbar-icon-button"),this.button.classList.remove("igv-navbar-text-button"),"text"===this.responsiveKey?this.configureTextButton(e):this.configureIconButton()}configureTextButton(e){this.button.classList.add("igv-navbar-text-button");const t=document.createElement("div");t.innerHTML=this.buttonLabel;const i=t.firstChild;this.button.appendChild(i),this.groupElement=i.querySelector("#igv-navbar-button-group");i.querySelector("#igv-navbar-button-label").textContent=e}configureIconButton(){this.button.classList.add("igv-navbar-icon-button")}setState(e){void 0!==e&&(this.doHover=e),"text"===this.responsiveKey?this.setTextButtonState(this.doHover):this.setIconButtonState(this.doHover)}setTextButtonState(e){this.groupElement.classList.remove(...this.groupElement.classList);const t=!0===e?"igv-navbar-text-button-svg-hover":"igv-navbar-text-button-svg-inactive";this.groupElement.classList.add(t)}setIconButtonState(e){this.button.style.backgroundImage=!0===e?this.imageDictionary.imageHover:this.imageDictionary.image}show(){this.button.style.display=""}hide(){this.button.style.display="none"}setVisibility(e){!0===e?this.show():this.hide()}}const Fd='\n \n \n \n \n \n \n \n \n';class vd extends ma{static defaults={autoscale:void 0,alpha:.5,height:50};constructor(e,t,i){super(e,t),this.type="merged",this.paintAxis=Oc,this.graphType=e.graphType,this.tracks=i||[]}async postInit(){if(this.config.tracks){for(let e of this.config.tracks){const t=await this.browser.createTrack(e);t?this.tracks.push(t):console.warn("Could not create track "+e),"function"==typeof t.postInit&&await t.postInit()}this.config.tracks.every((e=>void 0!==e.autoscale||void 0!==e.max))||(this.config.autoscale=void 0===this.config.max)}for(let e of this.tracks)e.isMergedTrack=!0;if(this.config.autoscale?this.autoscale=this.config.autoscale:void 0!==this.config.max&&this.setDataRange({min:this.config.min||0,max:this.config.max}),void 0!==this.config.flipAxis)for(let e of this.tracks)e.flipAxis=this.config.flipAxis;if(void 0!==this.config.logScale)for(let e of this.tracks)e.logScale=this.config.logScale;this.resolutionAware=this.tracks.some((e=>e.resolutionAware))}set flipAxis(e){this.config.flipAxis=e;for(let t of Ad(this.tracks))t.flipAxis=e}get flipAxis(){return Ad(this.tracks).every((e=>e.flipAxis))}set logScale(e){this.config.logScale=e;for(let t of Ad(this.tracks))t.logScale=e}get logScale(){return Ad(this.tracks).every((e=>e.logScale))}get height(){return this._height}set height(e){if(this.config.height=e,this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}set autoscale(e){if(this._autoscale=e,!1===e&&this.tracks)for(let e of this.tracks)e.autoscale=!1}get autoscale(){return this._autoscale}set autoscaleGroup(e){if(this.tracks)for(let t of this.tracks)t.autoscaleGroup=e}get autoscaleGroup(){if(this.tracks&&this.tracks.length>0){const e=this.tracks[0].autoscaleGroup;return this.tracks.some((t=>e!==t.autoscaleGroup))?void 0:e}}setDataRange({min:e,max:t}){this.autoscale=!1;for(const i of Ad(this.tracks))i.dataRange={min:e,max:t},i.autoscale=!1,i.autoscaleGroup=!1}set dataRange({min:e,max:t}){for(const i of Ad(this.tracks))i.dataRange={min:e,max:t}}get dataRange(){if(this.tracks){const e=Ad(this.tracks);if(e.length>0){const t=e[0].dataRange;if(e.every((e=>e.dataRange&&e.dataRange.min===t.min&&e.dataRange.max===t.max)))return t}}}menuItemList(){const e=[];return Ad(this.tracks).length>0&&(void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:function(){this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e.push(...this.numericDataMenuItems())),e.push("
"),e.push(this.overlayTrackAlphaAdjustmentMenuItem()),e.push(this.trackSeparationMenuItem()),e}async getFeatures(e,t,i,r){const s=this.tracks.map((s=>s.getFeatures(e,t,i,r))),o=await Promise.all(s);if(o.every((e=>0===e.length)))return new yd([],[]);{const e=this.tracks.map((e=>e.name));return new yd(o,e)}}draw(e){const t=e.features;for(let i=0,r=this.tracks.length;i0&&i.push("
"),i.push(`
${t[s].trackName}
`),t[s].features.length>0){r=!1;const o=this.tracks[s].popupData(e,t[s].features);i.push(...o)}else i.push("Missing or 0 value(s)");return!0===r?[]:i}}clickedFeatures(e){const t=e.viewport.cachedFeatures;if(!t||!t.featureArrays||!Array.isArray(t.featureArrays)||0===t.featureArrays.length)return[];const i=e.genomicLocation,r=[],s=e.referenceFrame.bpPerPixel>.2?3*e.referenceFrame.bpPerPixel:.2,o=i-s,n=i+s;for(let e=0;ee.supportsWholeGenome))}getState(){const e=super.getState(),t=[];for(let e of this.tracks)t.push(e.getState());return e.tracks=t,e}updateScales(e){let t;if(this.autoscale){t=!0;let i=[];for(let t of e){if(t.featureCache&&t.featureCache.features){const e=t.referenceFrame,r=e.start,s=r+e.toBP(t.getWidth()),o=t.featureCache.features;this.autoscale&&(i.push({value:o.getMax(r,s)}),i.push({value:o.getMin(r,s)}))}const e=is(i);for(const t of Ad(this.tracks))t.dataRange=e}}else{let i=-1;for(let r of this.tracks)if(++i,r.autoscale){t=!0;let s=[];for(let t of e)if(t.featureCache&&t.featureCache.features){const e=t.referenceFrame,r=e.start,o=r+e.toBP(t.getWidth()),n=t.featureCache.features.featureArrays[i];if(n)for(let e of n)if(!(e.endo)break;s.push(e)}}r.dataRange=is(s)}}return t}overlayTrackAlphaAdjustmentMenuItem(){const e=t();return e.innerText="Set transparency",{element:e,dialog:function(e){const t={label:"Transparency",value:this.alpha,min:0,max:1,scaleFactor:1e3,callback:e=>{this.alpha=Math.max(.001,e),this.repaintViews()}};this.browser.sliderDialog.present(t,e)}}}trackSeparationMenuItem(){let e=document.createElement("div");return e.textContent="Separate tracks",{element:e,click:async function(e){const t=this.autoscale,i=this.name,r=this.tracks,s=this.browser,o=this.order;s.removeTrack(this);for(let e of r)e.order=o,t&&(e.autoscaleGroup=i),e.isMergedTrack=!1,s.addTrack(e);await s.updateViews(),s.reorderTracks()}}}}class yd{constructor(e,t){this.featureArrays=e,this.trackNames=t}getMax(e,t){let i=-Number.MAX_VALUE;for(let r of this.featureArrays)if(Array.isArray(r))for(let s of r)if(!(void 0===s.value||Number.isNaN(s.value)||s.endt)break;i=Math.max(i,s.value)}return i!==-Number.MAX_VALUE?i:100}getMin(e,t){let i=0;for(let r of this.featureArrays)if(Array.isArray(r))for(let s of r)if(void 0!==s.value&&!Number.isNaN(s.value)){if(s.endt)break;i=Math.min(i,s.value)}return i}}const Ad=e=>e?e.filter((e=>void 0!==e.dataRange||void 0!==e.autoscale||void 0!==e.autoscaleGroup)):[];class Cd extends bd{constructor(e,t){super(e,t,"Overlay Tracks",Fd,'\n Overlay Tracks\n \n \n \n \n \n \n \n \n \n \n \n \n \n','\n Overlay Tracks Hover\n \n \n \n \n \n \n \n \n \n \n \n \n \n',!1),this.button.addEventListener("mouseenter",(()=>this.setState(!0))),this.button.addEventListener("mouseleave",(()=>this.setState(!1)));this.boundMouseClickHandler=(()=>{this.setVisibility(!1),_d.call(this)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(!0)}}async function _d(e){if(!0===xd(this.browser)){const e=this.browser.getSelectedTrackViews().map((({track:e})=>e));for(const t of e)t.selected=!1;const t=[];for(let i of e)"merged"===i.type?t.push(...i.tracks):t.push(i);const i={name:"Overlay",type:"merged",autoscale:!1,alpha:.5,height:Math.max(...e.map((({height:e})=>e))),order:Math.min(...e.map((({order:e})=>e)))},r=new vd(i,this.browser,t);for(const t of e){const e=this.browser.trackViews.indexOf(t.trackView);this.browser.trackViews.splice(e,1),t.trackView.dispose()}this.browser.addTrack(r),await r.trackView.updateViews(),this.browser.reorderTracks()}}function xd(e){const t=e.getSelectedTrackViews();if(t&&t.length>1){const e=new Set(["wig","merged"]);return t.filter((({track:t})=>e.has(t.type))).length>1}return!1}const kd=new Set(["sequence","ruler","ideogram"]),Id=new Set(["ruler","sequence","ideogram"]);class Sd{constructor(e,t,i){this.namespace=`trackview-${n()}`,this.browser=e,this.track=i,i.trackView=this,this.addDOMToColumnContainer(e,t,e.referenceFrameList)}startSpinner(){this.viewports&&this.viewports.length>0&&this.viewports[0].startSpinner()}stopSpinner(){this.viewports&&this.viewports.length>0&&this.viewports[0].stopSpinner()}addDOMToColumnContainer(e,t,i){this.axis=this.createAxis(e,this.track),this.createViewports(e,t,i),this.sampleInfoViewport=new fd(this,e.columnContainer.querySelector(".igv-sample-info-column"),e.getSampleInfoViewportWidth()),this.sampleNameViewport=new pd(this,e.columnContainer.querySelector(".igv-sample-name-column"),void 0,e.getSampleNameViewportWidth()),this.createTrackScrollbar(e),this.createTrackDragHandle(e),this.createTrackGearPopup(e)}createViewports(e,t,i){this.viewports=[];const r=e.calculateViewportWidth(i.length),s=t.querySelectorAll(".igv-column");for(let e=0;e0?this.viewports[this.viewports.length-1]:void 0}createAxis(e,i){const r=e.columnContainer.querySelector(".igv-axis-column");if(!r)return;const s=t();if(this.axis=s,r.appendChild(s),s.dataset.tracktype=i.type,s.style.height=`${i.height}px`,"function"==typeof i.paintAxis){const{width:e,height:t}=s.getBoundingClientRect();this.axisCanvas=document.createElement("canvas"),this.axisCanvas.style.width=`${e}px`,this.axisCanvas.style.height=`${t}px`,s.appendChild(this.axisCanvas)}if(!1===Md.has(this.track.type)){this.trackSelectionContainer=t(),s.appendChild(this.trackSelectionContainer);const e='',i=document.createRange().createContextualFragment(e).firstChild;this.trackSelectionContainer.appendChild(i),i.checked=this.track.selected||!1,i.addEventListener("change",(e=>{e.preventDefault(),e.stopPropagation(),this.track.selected=e.target.checked,this.setDragHandleSelectionState(e.target.checked),this.browser.overlayTrackButton.setVisibility(xd(this.browser))})),this.enableTrackSelection(!1)}return s}resizeAxisCanvas(e,t){this.axis.style.width=`${e}px`,this.axis.style.height=`${t}px`,"function"==typeof this.track.paintAxis&&(this.axisCanvas.style.width=`${e}px`,this.axisCanvas.style.height=`${t}px`)}renderSVGContext(e,{deltaX:t,deltaY:i}){!function(e,t,i,r,s){if("function"==typeof t.paintAxis){const{y:o,width:a,height:c}=i.getBoundingClientRect(),l=`${(t.name||t.id).replace(/\W/g,"")}_axis_guid_${n()}`;e.saveWithTranslationAndClipRect(l,r,o+s,a,c,0),t.paintAxis(e,a,c),e.restore()}}(e,this.track,this.axisCanvas,t,i);const{width:r}=this.axis.getBoundingClientRect(),{y:s}=this.viewports[0].viewportElement.getBoundingClientRect();let o={deltaX:r+t,deltaY:s+i};for(let t of this.viewports){t.renderSVGContext(e,o);const{width:i}=t.viewportElement.getBoundingClientRect();o.deltaX+=i}if(!0===this.browser.sampleInfo.isInitialized()&&!0===this.browser.sampleInfoControl.showSampleInfo){this.sampleInfoViewport.renderSVGContext(e,o);const{width:t}=this.sampleInfoViewport.viewport.getBoundingClientRect();o.deltaX+=t}!0===this.browser.showSampleNames&&this.sampleNameViewport.renderSVGContext(e,o)}presentColorPicker(e,t){if(!1===Id.has(this.track.type)){let i,r;i="color"===e?this.track._initialColor||this.track.constructor.defaultColor:this.track._initialAltColor||this.track.constructor.defaultColor;const s=this.browser.getSelectedTrackViews();r=s.length>0&&new Set(s).has(this)?{color:e=>{for(const t of s)t.track.color=e,t.repaintViews()},altColor:e=>{for(const t of s)t.track.altColor=e,t.repaintViews()}}:{color:e=>{this.track.color=qr(e),this.repaintViews()},altColor:e=>{this.track.altColor=qr(e),this.repaintViews()}};const o="color"===e?this.track.color||this.track.constructor.defaultColor:this.track.altColor||this.track.constructor.defaultColor;this.browser.genericColorPicker.configure(i,r[e],o),this.browser.genericColorPicker.present(t)}}setTrackHeight(e,t){t||(this.track.minHeight&&(e=Math.max(this.track.minHeight,e)),this.track.maxHeight&&(e=Math.min(this.track.maxHeight,e))),this.track.height=e,this.resizeAxisCanvas(this.axis.clientWidth,this.track.height),"function"==typeof this.track.paintAxis&&this.paintAxis();for(let t of this.viewports)t.setHeight(e);if(this.sampleInfoViewport.setHeight(e),this.sampleNameViewport.viewport.style.height=`${e}px`,"function"!=typeof this.track.computePixelHeight)for(let t of this.viewports)t.setContentHeight(e);this.repaintViews(),this.updateScrollbar(),this.dragHandle.style.height=`${e}px`,this.gearContainer.style.height=`${e}px`,this.browser.fireEvent("trackheightchange",this)}updateScrollbar(){const e=this.viewports[0].viewportElement.clientHeight;if(this.outerScroll.style.height=`${e}px`,!1===kd.has(this.track.type)){const t=this.maxViewportContentHeight(),i=Math.round(e/t*e);t>e?(this.innerScroll.style.display="block",this.innerScroll.style.height=`${i}px`):this.innerScroll.style.display="none"}}setTop(e){for(let t of this.viewports)t.setTop(e);this.sampleInfoViewport.setTop(e),this.sampleNameViewport.setTop(e)}moveScroller(e){const t=this.innerScroll.offsetTop+e,i=Math.min(Math.max(0,t),this.outerScroll.clientHeight-this.innerScroll.clientHeight);this.innerScroll.style.top=`${i}px`;const r=this.maxViewportContentHeight(),s=Math.round(i*(r/this.viewports[0].viewportElement.clientHeight));this.setTop(s)}scrollByPixels(e){const t=this.viewports[0].getContentTop(),i=this.maxViewportContentHeight(),r=i-this.viewports[0].viewportElement.clientHeight,s=Math.min(Math.max(0,t+e),r);if(this.setTop(s),this.innerScroll){const e=this.viewports[0].viewportElement.clientHeight,t=Math.round(s*(e/i));this.innerScroll.style.top=`${t}px`}}repaintViews(){for(let e of this.viewports)e.isVisible()&&e.repaint();"function"==typeof this.track.paintAxis&&this.paintAxis(),this.repaintSampleInfo(),this.repaintSamples()}repaintSampleInfo(){this.sampleInfoViewport.repaint()}repaintSamples(){if("function"==typeof this.track.getSamples){const e=this.track.getSamples();e.names&&e.names.length>0&&this.sampleNameViewport.repaint(e)}}setTrackLabelName(e){this.viewports.forEach((t=>t.setTrackLabel(e)))}resize(e){for(let t of this.viewports)t.setWidth(e)}async updateViews(){if(!this.browser||!this.browser.referenceFrameList)return;const e=this.viewports.filter((e=>e.isVisible()&&e.checkZoomIn()));if(e.forEach((e=>e.shift())),this.browser.dragObject)return;const t=e.filter((e=>e.needsRepaint())),i=e.filter((e=>e=>e.needsReload()));for(let e of i)await e.loadFeatures();if(this.disposed)return;if(this.track&&"function"==typeof this.track.variantRowCount&&i.length>0){let e=0;for(let t of this.viewports)t.featureCache&&t.featureCache.features&&(e=Math.max(e,t.featureCache.features.reduce(((e,t)=>Math.max(e,t.row||0)),0)));if(this.track.nVariantRows!==e+1){this.track.variantRowCount(e+1);for(let e of this.viewports)e.checkContentHeight()}}let r;if("merged"===this.track.type)r=this.track.updateScales(e);else if(this.track.autoscale){let t=[];for(let i of e){const e=i.referenceFrame,r=e.start,s=r+e.toBP(i.getWidth());if(i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const e=i.featureCache.features.getMax(r,s);if(t.push({value:e}),"function"==typeof i.featureCache.features.getMin){const e=i.featureCache.features.getMin(r,s);t.push({value:e})}}else{const e=Vr(i.featureCache.features,r,s);for(let i of e)t.push(i)}}"function"==typeof this.track.doAutoscale?this.track.dataRange=this.track.doAutoscale(t):this.track.dataRange=is(t)}const s=this.track.autoscale||this.track.autoscaleGroup||"ruler"===this.track.type||r||this.track.groupBy;for(let i of e)t.includes(i)?i.repaint():s&&i.refresh();this.adjustTrackHeight(),this.repaintSampleInfo(),this.repaintSamples(),this.updateRulerViewportLabels()}clearCachedFeatures(){for(let e of this.viewports)e.clearCache()}updateRulerViewportLabels(){const e=this.browser.calculateViewportWidth(this.viewports.length);for(let t of this.viewports)"ruler"===this.track.type&&(this.viewports.length>1?t.presentLocusLabel(e):t.dismissLocusLabel())}async getInViewFeatures(){if(!this.browser||!this.browser.referenceFrameList)return[];let e=[];const t=this.viewports.filter((e=>e.isVisible()));for(let i of t){const t=i.referenceFrame,{chr:r,start:s,bpPerPixel:o}=i.referenceFrame,n=s+t.toBP(i.getWidth());if((!i.featureCache||!i.featureCache.containsRange(r,s,n,o))&&await i.loadFeatures(),i.featureCache&&i.featureCache.features)if("function"==typeof i.featureCache.features.getMax){const t=i.featureCache.features.getMax(s,n);e.push({value:t})}else{const t="function"==typeof i.featureCache.queryFeatures?i.featureCache.queryFeatures(r,s,n):Vr(i.featureCache.features,s,n);e=e.concat(t)}}return e}checkContentHeight(){for(let e of this.viewports)e.checkContentHeight();this.adjustTrackHeight()}adjustTrackHeight(){var e=this.maxViewportContentHeight();if(this.track.autoHeight?this.setTrackHeight(e,!1):this.track.paintAxis&&this.paintAxis(),!1===kd.has(this.track.type)){const t=this.viewports[0].getContentTop(),i=this.viewports[0].viewportElement.clientHeight,r=Math.min(0,i-e);te!==this&&void 0!==e.trackGearPopup)))t.trackGearPopup.popover.style.display="none";this.trackGearPopup.presentMenuList(this,e.menuUtils.trackMenuItemList(this),e.config)}else this.trackGearPopup.popover.style.display="none"}!1===e.config.showGearColumn&&(i.style.color="white"),this.gear.appendChild(i),this.trackGearPopup=new md(this.gear),this.boundTrackGearClickHandler=r.bind(this),this.gear.addEventListener("click",this.boundTrackGearClickHandler)}}addTrackScrollMouseHandlers(e){this.boundTrackScrollMouseDownHandler=function(t){t.stopPropagation();const{y:i}=o(t);this.innerScroll.dataset.yDown=i.toString(),this.boundColumnContainerMouseMoveHandler=function(e){e.stopPropagation();const{y:t}=o(e);this.moveScroller(t-parseInt(this.innerScroll.dataset.yDown)),this.innerScroll.dataset.yDown=t.toString()}.bind(this),e.columnContainer.addEventListener("mousemove",this.boundColumnContainerMouseMoveHandler)}.bind(this),this.innerScroll.addEventListener("mousedown",this.boundTrackScrollMouseDownHandler),this.boundColumnContainerMouseUpHandler=function(t){e.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler)}.bind(this),e.columnContainer.addEventListener("mouseup",this.boundColumnContainerMouseUpHandler),e.columnContainer.addEventListener("mouseleave",this.boundColumnContainerMouseUpHandler)}removeTrackScrollMouseHandlers(){!1===kd.has(this.track.type)&&(this.innerScroll.removeEventListener("mousedown",this.boundTrackScrollMouseDownHandler),this.browser.columnContainer.removeEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.browser.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.browser.columnContainer.removeEventListener("mouseleave",this.boundColumnContainerMouseMoveHandler))}addTrackDragMouseHandlers(e){if("sequence"===this.track.type||!1===Md.has(this.track.type)){let t;function i(i){i.preventDefault(),t=i.target,!1!==this.track.selected&&"sequence"!==this.track.type||(t.classList.remove("igv-track-drag-handle-color"),t.classList.add("igv-track-drag-handle-hover-color")),e.startTrackDrag(this)}function r(i){e.endTrackDrag(),t&&i.target!==t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(t.classList.remove("igv-track-drag-handle-hover-color"),t.classList.add("igv-track-drag-handle-color"))),t=void 0}function s(i){i.preventDefault(),void 0===t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(i.target.classList.remove("igv-track-drag-handle-color"),i.target.classList.add("igv-track-drag-handle-hover-color"))),e.updateTrackDrag(this)}function o(e){e.preventDefault(),void 0===t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(e.target.classList.remove("igv-track-drag-handle-hover-color"),e.target.classList.add("igv-track-drag-handle-color")))}this.boundTrackDragMouseDownHandler=i.bind(this),this.dragHandle.addEventListener("mousedown",this.boundTrackDragMouseDownHandler),this.boundDocumentTrackDragMouseUpHandler=r.bind(this),document.addEventListener("mouseup",this.boundDocumentTrackDragMouseUpHandler),this.boundTrackDragMouseEnterHandler=s.bind(this),this.dragHandle.addEventListener("mouseenter",this.boundTrackDragMouseEnterHandler),this.dragHandle.addEventListener("mouseout",(e=>{e.preventDefault(),void 0===t&&(!1!==this.track.selected&&"sequence"!==this.track.type||(e.target.classList.remove("igv-track-drag-handle-hover-color"),e.target.classList.add("igv-track-drag-handle-color")))})),this.boundTrackDragMouseOutHandler=o.bind(this),this.dragHandle.addEventListener("mouseout",this.boundTrackDragMouseOutHandler)}}removeTrackDragMouseHandlers(){"ideogram"===this.track.type||"ruler"===this.track.type||(this.dragHandle.removeEventListener("mousedown",this.boundTrackDragMouseDownHandler),document.removeEventListener("mouseup",this.boundDocumentTrackDragMouseUpHandler),this.dragHandle.removeEventListener("mouseup",this.boundTrackDragMouseEnterHandler),this.dragHandle.removeEventListener("mouseout",this.boundTrackDragMouseOutHandler))}removeTrackGearMouseHandlers(){!0===this.track.ignoreTrackMenu||this.gear.removeEventListener("click",this.boundTrackGearClickHandler)}removeDOMFromColumnContainer(){this.axis.remove(),this.removeViewportsFromColumnContainer(),this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove()}removeViewportsFromColumnContainer(){for(let e of this.viewports)e.viewportElement.remove()}dispose(){this.axis.remove();for(let e of this.viewports)e.dispose();this.sampleInfoViewport.dispose(),this.sampleNameViewport.dispose(),this.removeTrackScrollMouseHandlers(),this.outerScroll.remove(),this.removeTrackDragMouseHandlers(),this.dragHandle.remove(),this.removeTrackGearMouseHandlers(),this.gearContainer.remove(),"function"==typeof this.track.dispose&&this.track.dispose();for(let e of Object.keys(this))this[e]=void 0;this.alert&&this.alert.container.remove(),this.disposed=!0}paintAxis(){if("function"==typeof this.track.paintAxis){const{width:e,height:t}=this.axisCanvas.getBoundingClientRect(),i=window.devicePixelRatio||1;this.axisCanvas.height=i*t,this.axisCanvas.width=i*e;const r=this.axisCanvas.getContext("2d");if(r.scale(i,i),this.track.autoscaleGroup){if(void 0===Rd[this.track.autoscaleGroup]){const e=jr.Dark2,t=Math.floor(Math.random()*jr.Dark2.length);Rd[this.track.autoscaleGroup]=e[t]}const i=ur.addAlpha(Rd[this.track.autoscaleGroup],.75);this.track.paintAxis(r,e,t,i)}else this.track.paintAxis(r,e,t,void 0)}}maxViewportContentHeight(){return Math.max(...this.viewports.map((e=>e.getContentHeight())))}enableTrackSelection(e){const t=this.trackSelectionContainer;if(t&&!Md.has(this.track.type))if(!1!==e)t.style.display="grid";else{this.track.selected=!1;t.querySelector("[name=track-select]").checked=this.track.selected,this.dragHandle&&this.setDragHandleSelectionState(!1),t.style.display="none"}}setDragHandleSelectionState(e){const t=this.dragHandle;e?(t.classList.remove("igv-track-drag-handle-color"),t.classList.remove("igv-track-drag-handle-hover-color"),t.classList.add("igv-track-drag-handle-selected-color")):(t.classList.remove("igv-track-drag-handle-hover-color"),t.classList.remove("igv-track-drag-handle-selected-color"),t.classList.add("igv-track-drag-handle-color"))}}const Ed=new Set(["bedtype","alignment","annotation","variant","wig","interact","shoebox"]),Nd=new Set(["alignment","annotation","variant","eqtl","qtl","snp","shoebox","wig"]),Md=new Set(["sequence","ruler","ideogram"]),Rd={};class Bd{constructor(e){this.browser=e,this.initialize()}initialize(){const e=new c;e.add("...");const t={parent:this.browser.root,content:e};this.dialog=new w(t),this.browser.root.appendChild(this.dialog.elem),r(this.dialog.elem)}trackMenuItemList(e){const t=[];return"sequence"!==e.track.config.type&&t.push(function(){const e=document.createElement("div");function t(e){const t=()=>{if(void 0!==this.browser.inputDialog.value){const e=parseInt(this.browser.inputDialog.value,10);if(e>0){const t=[];this.trackView.track.selected?t.push(...this.trackView.browser.getSelectedTrackViews().map((({track:e})=>e))):t.push(this);for(const i of t)i.trackView.autoHeight=!1,void 0!==i.minHeight&&i.minHeight>e&&(i.minHeight=e),void 0!==i.maxHeight&&i.maxHeight1&&new Set(t).has(e)}(e)?t.push(...this.multiSelectMenuItems(e)):("sequence"!==e.track.config.type&&t.push(function(){const e=document.createElement("div");function t(e){const t=()=>{let e=this.browser.inputDialog.value;e=""===e||void 0===e?"untitled":e.trim(),this.name=e,this.browser.fireEvent("tracknamechange",[this])},i={label:"Track Name",value:zd(this)||"unnamed",callback:t};this.browser.inputDialog.present(i,e)}return e.textContent="Set track name",{element:e,click:t}}()),t.push(...this.defaultMenuItems(e))),!1!==e.track.removable&&(t.push("
"),t.push(function(e){const t=e.track.selected?"Remove tracks":"Remove track",i=document.createElement("div");function r(e){this.trackView.browser._removeTrack(this)}return i.textContent=t,{element:i,click:r,menuItemType:"removeTrack"}}(e))),t}defaultMenuItems(e){const t=[];return Pd(e.track)&&(t.push("
"),t.push(Dd(e,"Set track color","color")),t.push(Ld(e,"Unset track color")),"wig"!==e.track.config.type&&"annotation"!==e.track.config.type||(t.push(Dd(e,"Set alt color","altColor")),t.push(Td(e,"Unset alt color")))),e.track.menuItemList&&t.push(...e.track.menuItemList()),function(e){const t=e.track;return t&&t.config&&void 0!==t.config.visibilityWindow||t&&Nd.has(t.type)}(e)&&(t.push("
"),t.push(function(e){const t=document.createElement("div");function i(t){const i=()=>{let e=this.browser.inputDialog.value;e=""===e||void 0===e?-1:e.trim(),this.visibilityWindow=Number.parseInt(e),this.config.visibilityWindow=Number.parseInt(e),this.trackView.updateViews()},r={label:"wig"===e?"Visibility window (bp). Enter 0 for whole chromosome, -1 for whole genome.":"Visibility window (bp). Enter 0 for whole chromosome.",value:this.visibilityWindow,callback:i};this.browser.inputDialog.present(r,t)}return t.textContent="Set visibility window",{element:t,click:i}}(e.track.type))),t}multiSelectMenuItems(e){const t=[],i=e.browser.getSelectedTrackViews();var r;return!0===(r=i.map((({track:e})=>e.type)),1===[...new Set(r)].length)?(t.push(...this.defaultMenuItems(e)),"wig"===e.track.type&&(t.push("
"),t.push(function(){const e=document.createElement("div");function t(e){const t=jr.Dark2,i=Math.floor(Math.random()*t.length),r=`auto-scale-group-${n()}`;Rd[r]=t[i];const s=this.browser.getSelectedTrackViews();for(const{track:e}of s)e.autoscaleGroup=r;this.browser.updateViews()}return e.textContent="Group autoscale",{element:e,doAllMultiSelectedTracks:!0,click:t}}()))):Pd(e.track)&&(t.push("
"),t.push(Dd(e,"Set track color","color")),t.push(Ld(e,"Unset track color")),"wig"!==e.track.config.type&&"annotation"!==e.track.config.type||(t.push(Dd(e,"Set alt color","altColor")),t.push(Td(e,"Unset alt color")))),t}}function Dd(e,t,i){const r=document.createElement("div");r.textContent=t;return{element:r,click:t=>{e.presentColorPicker(i,t)}}}function Ld(e,t){const i=document.createElement("div");return i.textContent=t,{element:i,click:()=>{e.track.color=e.track._initialColor||e.track.constructor.defaultColor,e.repaintViews()}}}function Td(e,t){const i=document.createElement("div");return i.textContent=t,{element:i,click:()=>{e.track.altColor=e.track._initialAltColor||e.track.constructor.defaultColor,e.repaintViews()}}}function zd(e){return e.name}function Pd(e){return void 0===e.type||Ed.has(e.type)&&"heatmap"!==e.graphType}class Hd{constructor(e){this.parent=e,this.container=t({class:"igv-ui-generic-dialog-container"}),e.appendChild(this.container);const i=t({class:"igv-ui-generic-dialog-header"});this.container.appendChild(i),this.label=t({class:"igv-ui-generic-dialog-one-liner"}),this.container.appendChild(this.label),this.label.textContent="Unlabeled",this.input_container=t({class:"igv-ui-generic-dialog-input"}),this.container.appendChild(this.input_container),this._input=document.createElement("input"),Hd.FORM_EMBED_MODE&&Hd.captureKeyInput(this._input),this.input_container.appendChild(this._input);const s=t({class:"igv-ui-generic-dialog-ok-cancel"});this.container.appendChild(s),this.ok=t(),s.appendChild(this.ok),this.ok.textContent="OK",this.cancel=t(),s.appendChild(this.cancel),this.cancel.textContent="Cancel",r(this.container),this._input.addEventListener("keyup",(e=>{"Enter"===e.code&&("function"==typeof this.callback&&(this.callback(this._input.value),this.callback=void 0),this._input.value=void 0,r(this.container)),e.stopImmediatePropagation()})),this.ok.addEventListener("click",(()=>{"function"==typeof this.callback&&(this.callback(this._input.value),this.callback=void 0),this._input.value=void 0,r(this.container)}));const o=()=>{this._input.value="",r(this.container)};this.cancel.addEventListener("click",o),u(i,o),p(this.container,i)}get value(){return vo.sanitize(this._input.value)}present(e,t){this.label.textContent=e.label,this._input.value=e.value,this.callback=e.callback||e.click,this.container.style.display="";const{clientX:i,clientY:r}=t,{offsetWidth:s,offsetHeight:o}=this.container,{innerHeight:n}=window;let a=i-s/2,c=r-o/2;const l=document.documentElement.clientWidth-s-10;a=Math.max(10,Math.min(a,l));const h=n-o-10;c=Math.max(10,Math.min(c,h)),this.container.style.left=`${a}px`,this.container.style.top=`${c}px`}static captureKeyInput(e){e.addEventListener("mousedown",(t=>{e.focus()})),e.addEventListener("keydown",(t=>{t.preventDefault(),t.stopPropagation();const i=e.selectionStart,r=e.selectionEnd;if(1===t.key.length){const s=e.value;e.value=s.slice(0,i)+t.key+s.slice(r),e.selectionStart=e.selectionEnd=i+1}else"Backspace"===t.key?i===r&&i>0?(e.value=e.value.slice(0,i-1)+e.value.slice(i),e.selectionStart=e.selectionEnd=i-1):i{this.minimumInput.value="",this.maximumInput.value="",this.hide()})),this.minimum=document.createElement("div"),this.minimum.className="igv-generic-dialog-label-input",this.container.appendChild(this.minimum);const r=document.createElement("div");r.textContent="Minimum",this.minimum.appendChild(r),this.minimumInput=document.createElement("input"),Hd.FORM_EMBED_MODE&&Hd.captureKeyInput(this.minimumInput),this.minimum.appendChild(this.minimumInput),this.maximum=document.createElement("div"),this.maximum.className="igv-generic-dialog-label-input",this.container.appendChild(this.maximum);const s=document.createElement("div");s.textContent="Maximum",this.maximum.appendChild(s),this.maximumInput=document.createElement("input"),Hd.FORM_EMBED_MODE&&Hd.captureKeyInput(this.maximumInput),this.maximum.appendChild(this.maximumInput);const o=document.createElement("div");o.className="igv-generic-dialog-ok-cancel",this.container.appendChild(o),this.okButton=document.createElement("div"),this.okButton.textContent="OK",o.appendChild(this.okButton),this.cancelButton=document.createElement("div"),this.cancelButton.textContent="Cancel",o.appendChild(this.cancelButton),this.cancelButton.addEventListener("click",(()=>{this.minimumInput.value="",this.maximumInput.value="",this.hide()})),p(this.container,i),this.container.style.display="none"}configure(e){let t;if(Array.isArray(e)){t={min:Number.MAX_SAFE_INTEGER,max:-Number.MAX_SAFE_INTEGER};for(const i of e)i.track.dataRange&&(t.min=Math.min(i.track.dataRange.min,t.min),t.max=Math.max(i.track.dataRange.max,t.max))}else t=e.track.dataRange;t&&(this.minimumInput.value=t.min,this.maximumInput.value=t.max),this.minimumInput.onkeyup=null,this.minimumInput.onkeyup=t=>{13===t.keyCode&&this.processResults(e),t.stopImmediatePropagation()},this.maximumInput.onkeyup=null,this.maximumInput.onkeyup=t=>{13===t.keyCode&&(t.stopImmediatePropagation(),this.processResults(e))},this.okButton.onclick=null,this.okButton.onclick=()=>{this.processResults(e)}}processResults(e){const t=this.minimumInput.value.trim(),i=this.maximumInput.value.trim();if(""!==t&&""!==i){const r=Number(t),s=Number(i);if(isNaN(r)||isNaN(s))this.browser.alert.present(new Error("Must input numeric values"),void 0);else{const t=Array.isArray(e)?e:[e];for(const e of t)e.track.setDataRange({min:r,max:s})}this.minimumInput.value="",this.maximumInput.value=""}this.hide()}hide(){this.container.style.top="20%",this.container.style.left="75%",this.container.style.display="none"}present(e){this.container.style.display="flex";const{clientX:t,clientY:i}=e,{offsetWidth:r,offsetHeight:s}=this.container,{innerHeight:o}=window;let n=t-r/2,a=i-s/2;const c=document.documentElement.clientWidth-r-10;n=Math.max(10,Math.min(n,c));const l=o-s-10;a=Math.max(10,Math.min(a,l)),this.container.style.left=`${n}px`,this.container.style.top=`${a}px`}}class Vd{constructor({parent:e,top:i,left:r,width:s,height:o,border:n,closeHandler:a}){const c=t({class:"igv-ui-generic-container"});e.appendChild(c),this.container=c,void 0!==s&&(this.container.style.width=`${s}px`),void 0!==o&&(this.container.style.height=`${o}px`),n&&(this.container.style.border=n);const l=t();this.container.appendChild(l),u(l,(e=>{"function"==typeof a&&a(e),this.hide()})),p(this.container,l),this.hide()}show(){this.container.style.display="flex"}hide(){this.container.style.display="none"}dispose(){this.container.parent&&this.container.parent.removeChild(this.container)}}class qd extends Vd{static maxRecentColors=10;constructor({parent:e,width:i}){super({parent:e,width:i,border:"1px solid gray"}),this.container.classList.add("igv-ui-colorpicker-container"),this.colorSwatchContainer=t(),this.container.appendChild(this.colorSwatchContainer),this.moreColorsContainer=t(),this.container.appendChild(this.moreColorsContainer),this.recentColorsSwatches=t(),this.container.appendChild(this.recentColorsSwatches),this.recentColors=[],this.moreColorsPresentationColor=void 0}configure(e,i,r){this.moreColorsPresentationColor=r,this.colorSwatchContainer.innerHTML="",this.recentColorsSwatches.innerHTML="";const s=Object.values(Ur);for(const e of s){const r=t({class:"igv-ui-color-swatch"});this.colorSwatchContainer.appendChild(r),this.decorateSwatch(r,e,i)}if(this.recentColors.length>0)for(const e of this.recentColors){const r=t({class:"igv-ui-color-swatch"});this.recentColorsSwatches.appendChild(r),this.decorateSwatch(r,e,i)}this.decorateMoreColorsButton(this.moreColorsContainer,i)}decorateSwatch(e,t,i){e.style.backgroundColor=t,e.addEventListener("click",(e=>{e.stopPropagation(),i(t),this.moreColorsPresentationColor=t})),e.addEventListener("touchend",(e=>{e.stopPropagation(),i(t),this.moreColorsPresentationColor=t}))}decorateMoreColorsButton(e,t){e.innerText="More Colors ...",e.addEventListener("click",(i=>{i.stopPropagation(),this.createAndPresentMoreColorsPicker(e,(e=>t(e)))}))}updateRecentColorsSwatches(e){this.recentColorsSwatches.innerHTML="";for(const i of this.recentColors){const r=t({class:"igv-ui-color-swatch"});this.recentColorsSwatches.appendChild(r),this.decorateSwatch(r,i,e)}}createAndPresentMoreColorsPicker(e,t){let i;e.innerHTML="",e.innerText="More Colors ...";const r=document.createElement("div");r.style.position="absolute",e.appendChild(r);const{width:s,height:o}=e.getBoundingClientRect();r.style.right="0px",r.style.top="0px",r.style.width=`${s}px`,r.style.height=`${o}px`,r.addEventListener("click",(e=>{e.stopPropagation()})),i=new cl;const n={parent:r,popup:"top",editor:!1,editorFormat:"rgb",alpha:!1,color:this.moreColorsPresentationColor};i.setOptions(n),i.setColor(this.moreColorsPresentationColor,!0),i.onOpen=()=>{console.log("picker - onOpen")},i.onChange=t=>e.style.backgroundColor=t.rgba,i.onDone=e=>{const s=e.hex.substring(0,7);this.recentColors.unshift(s);const o=this.recentColors.slice(0);this.recentColors=[...new Set(o)].slice(0,qd.maxRecentColors),t(s),this.updateRecentColorsSwatches(t),this.moreColorsPresentationColor=s,i.destroy(),r.remove()},i.show()}present(e){this.show();const{clientX:t,clientY:i}=e,{offsetWidth:r,offsetHeight:s}=this.container,{innerHeight:o}=window;let n=t-r/2,a=i;const c=document.documentElement.clientWidth-r-10;n=Math.max(10,Math.min(n,c));const l=o-s-10;a=Math.max(10,Math.min(a,l)),this.container.style.left=`${n}px`,this.container.style.top=`${a}px`}}class Ud{constructor(e){this.dialog=new Ao(e)}present(e,t){this.dialog.present(e,t)}}function Qd(e){if(e)switch(e.toLowerCase()){case"bw":case"bigwig":case"wig":case"bedgraph":case"tdf":return"wig";case"vcf":return"variant";case"seg":return"seg";case"mut":case"maf":return"mut";case"bam":case"cram":return"alignment";case"hiccups":case"bedpe":case"bedpe-loop":case"biginteract":return"interact";case"bp":return"arc";case"gwas":return"gwas";case"bed":case"bigbed":case"bb":case"biggenepred":case"bignarrowpeak":return"bedtype";case"fasta":return"sequence";case"pytor":return"cnvpytor";case"qtl":return"qtl";default:return"annotation"}}function Gd(e){e.featureType&&(e.type=e.type||e.featureType,e.featureType=void 0),"junctions"===e.type?e.type="junction":"bed"===e.type?(e.type="annotation",e.format=e.format||"bed"):"annotations"===e.type?e.type="annotation":"alignments"===e.type?e.type="alignment":"bam"===e.type?(e.type="alignment",e.format="bam"):"vcf"===e.type?(e.type="variant",e.format="vcf"):"t2d"===e.type?e.type="gwas":"FusionJuncSpan"!==e.type||e.format?"aed"===e.type&&(e.type="annotation",e.format=e.format||"aed"):e.format="fusionjuncspan"}var jd=Object.freeze({__proto__:null,inferTrackType:Qd,translateDeprecatedTypes:Gd});const Wd={threshold:2e3,r:0,g:0,b:255};class $d{constructor(e){e=e||Wd,this.threshold=e.threshold,this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[],this.nbins=2e3,this.binsize=this.threshold/this.nbins}setThreshold(e){this.threshold=e,this.cache=[],this.binsize=this.threshold/this.nbins}getThreshold(){return this.threshold}setColorComponents(e){this.r=e.r,this.g=e.g,this.b=e.b,this.cache=[]}getColorComponents(){return{r:this.r,g:this.g,b:this.b}}equals(e){return JSON.stringify(this)===JSON.stringify(e)}getColor(e){const t=Math.floor(Math.min(this.threshold,e)/this.binsize);if(void 0===this.cache[t]){const i=(cr(e,0,this.threshold)-0)/(this.threshold-0);this.cache[t]=`rgba(${this.r},${this.g},${this.b}, ${i})`}return this.cache[t]}stringify(){return this.threshold+","+this.r+","+this.g+","+this.b}static parse(e){var t,i;return e.startsWith("R:")?(t=e.substring(2).split(":"),(i=new RatioColorScale(Number.parseFloat(t[0]))).positiveScale=r(t[1]),i.negativeScale=r(t[2]),i):r(e);function r(e){var t,i;return t={threshold:(i=e.split(","))[0],r:i[1],g:i[2],b:i[3]},new $d(t)}}}const Kd="None";class Yd extends ma{static defaults={type:"seg",groupBy:Kd,isLog:void 0,displayMode:"EXPANDED",height:300,maxHeight:500,squishedRowHeight:2,expandedRowHeight:13};constructor(e,t){super(e,t),this.groups=new Map}init(e){if(super.init(e),"maf"===this.type&&(this.type="mut"),this.sortDirections=new Map,this.sampleKeys=[],this.groups=new Map,this.sampleHeight=this.squishedRowHeight,e.samples){for(let t of e.samples)this.sampleKeys.push(t);this.explicitSamples=!0}e.color?this.color=e.color:e.colorTable?this.colorTable=new $r(e.colorTable):"mut"===this.type?this.colorTable=new $r(Jd):(this.posColorScale=new Gc(e.posColorScale||Zd),this.negColorScale=new Gc(e.negColorScale||Xd));const t=Object.assign({},this.config);t.maxWGCount=t.maxWGCount||Number.MAX_SAFE_INTEGER,this.featureSource=El(t,this.browser.genome),this.initialSort=e.sort}async postInit(){"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader(),this.disposed)||(this.header&&this.setTrackProperties(this.header),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this.didTrackDragEnd=void 0,this.browser.on("trackdragend",(()=>this.didTrackDragEnd=!0)))}menuItemList(){const e=[];if(!0===dd(this.browser.sampleInfo,this.sampleKeys)){e.push("
"),e.push("Sort by attribute:");for(const r of this.browser.sampleInfo.attributeNames){if(this.sampleKeys.some((e=>{const t=this.browser.sampleInfo.getAttributes(e);return t&&t[r]}))){const s=document.createElement("div");function o(){this.sortByAttribute(r)}s.innerHTML=`  ${r.split(sd.emptySpaceReplacement).join(" ")}`,e.push({element:s,click:o})}}}e.push("
"),e.push("Group by attribute:");for(const n of[Kd,...this.browser.sampleInfo.attributeNames]){let a=!1;a=Kd===n?Kd===this.groupBy:n===this.groupBy;const c=ua(n,a);e.push({element:c,click:function(){this.groupByAttribute(n)}})}const t={SQUISHED:"Squish",EXPANDED:"Expand",FILL:"Fill"};e.push("
"),e.push("DisplayMode:");const i="seg"===this.type?["SQUISHED","EXPANDED","FILL"]:["SQUISHED","EXPANDED"];for(let l of i)e.push({element:ua(t[l],l===this.displayMode),click:function(){this.displayMode=l,this.config.displayMode=l,this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.createGroupLabels()}});return e}hasSamples(){return!0}getSamples(){const e=Kd!==this.groupBy?this.sampleKeys.map((e=>this.getGroupIndex(e))):void 0;return{names:this.sampleKeys,height:this.sampleHeight,yOffset:0,groups:this.groups,groupIndeces:e,groupMarginHeight:hd}}filter(e){const t=this._trackFilterObjects||[];if(0===t.length)return!0;for(const i of t){const t=(i.scores||{})[e];if("seg"===this.type){if(">"===i.op){if(!(t>i.value))return!1}else if("<"===i.op&&!(t0){const t=this._trackFilterObjects.map((e=>{const{scores:t,...i}=e;return i}));e.filters=t}return e}async getFeatures(e,t,i){const r=await this.featureSource.getFeatures({chr:e,start:t,end:i});if(this.updateSampleKeys(r),this.initialSort){const s=this.initialSort;if(void 0===s.option||"VALUE"===s.option.toUpperCase()){const o=s.chr===e&&s.start>=t&&s.end<=i?r:void 0;this.sortByValue(s,o)}else if("ATTRIBUTE"===s.option.toUpperCase()&&s.attribute){const e="DESC"===s.direction?1:-1;this.sortByAttribute(s.attribute,e)}this.initialSort=void 0}return r}draw({context:e,pixelTop:t,pixelWidth:i,pixelHeight:r,features:s,bpPerPixel:o,bpStart:n}){if(Co.fillRect(e,0,t,i,r,{fillStyle:"rgb(255, 255, 255)"}),s&&s.length>0){if(this.checkForLog(s),"shoebox"===this.type&&!this.sbColorScale){const e=this.featureSource.hicFile.percentile95||2e3;this.sbColorScale=new $d({threshold:e,r:0,g:0,b:255})}const a={};let c;switch(this.sampleKeys.forEach((function(e,t){a[e]=t})),this.displayMode){case"FILL":this.sampleHeight=(r-(this.groups.size+1)*hd)/this.sampleKeys.length,c=0;break;case"SQUISHED":this.sampleHeight=this.squishedRowHeight,c=0;break;default:this.sampleHeight=this.expandedRowHeight,c=1}const l=this.sampleHeight;for(let e of s)e.pixelRect=void 0;const h=t+r,d=n+i*o+1,u=o;this.sampleYStart=void 0;for(let i of s){if(i.endd)continue;const r=i.sampleKey||i.sample;i.row=a[r];let s=i.row*l;this.groups.size>1&&(s+=(this.getGroupIndex(r)+1)*hd),void 0===this.sampleYStart&&(this.sampleYStart=s);if(s+lh)continue;const o=Math.max(i.start,n);let f=Math.round((o-n)/u);const p=Math.min(i.end,d),g=Math.round((p-n)/u);let m,w,b=Math.max(1,g-f);if(this.color?m="function"==typeof this.color?this.color(i):this.color:this.colorTable&&(m=this.colorTable.getColor(i.value.toLowerCase())),"mut"===this.type)w=l-2*c,b<3&&(b=3,f-=1);else{let e=i.value;this.isLog||(e=lr(e/2)),m=e<-.1?this.negColorScale.getColor(e):e>.1?this.posColorScale.getColor(e):"white";let t=l;if(l<.25){const i=.1+2*Math.abs(e);t=Math.min(1,i*l)}w=t-2*c}i.pixelRect={x:f,y:s,w:b,h:w},e.fillStyle=m,e.fillRect(f,s,b,w)}Kd!==this.groupBy&&ud(e,t,i,r,0,this.sampleHeight,this.groups)}}getGroupIndex(e){const t=this.browser.sampleInfo.getAttributeValue(e,this.groupBy)||"";return this.groups.has(t)?this.groups.get(t).index:this.groups.size}checkForLog(e){if(void 0===this.isLog){this.isLog=!1;for(let t of e)if(t.value<0)return void(this.isLog=!0)}}computePixelHeight(e){if(!e)return 0;const t="SQUISHED"===this.displayMode?this.squishedRowHeight:this.expandedRowHeight;return this.sampleKeys.length*t+(this.groups.size>1?(this.groups.size+1)*hd:0)}async sortByValue(e,t){const i=e.chr,r=void 0!==e.position?e.position-1:e.start,s=void 0===e.end?r+1:e.end,o=await this.computeRegionScores({chr:i,start:r,end:s},t),n="ASC"===e.direction?1:-1;this.sampleKeys.sort((function(e,t){let i=o[e],r=o[t];return i||(i=n*Number.MAX_VALUE),r||(r=n*Number.MAX_VALUE),i===r?0:i>r?n:-1*n})),Kd!==this.groupBy&&(this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,this.groupBy,1)),this.config.sort=e,this.trackView.repaintViews()}async computeRegionScores(e,t){const i=e.chr;let r,s;if(e.position?(r=e.position-1,s=r+1):(r=e.start,s=e.end),t||(t=await this.featureSource.getFeatures({chr:i,start:r,end:s})),!t)return;this.updateSampleKeys(t);const o={},n=s-r+1;for(let e of t){if(e.ends)break;const t=e.sampleKey||e.sample;if("mut"===this.type)o[t]=(o[t]||0)+1;else{const i=Math.max(r,e.start),a=(Math.min(s,e.end)-i)/n;o[t]=(o[t]||0)+a*e.value}}return o}sortByAttribute(e,t){t=t||this.sortDirections.get(e)||1,this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,e,t),Kd!==this.groupBy&&(this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,this.groupBy,1)),this.config.sort={option:"ATTRIBUTE",attribute:e,direction:1===t?"ASC":"DESC"},this.sortDirections.set(e,-1*t),this.trackView.repaintViews()}groupByAttribute(e){if(this.groupBy=e,this.groups.clear(),Kd!==e){this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,e,1);const t=this.sampleKeys;for(let i of t){const t=this.browser.sampleInfo.getAttributeValue(i,e)||"";t&&(this.groups.has(t)?this.groups.get(t).count+=1:this.groups.set(t,{index:this.groups.size,count:1}))}}this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.createGroupLabels()}createGroupLabels(){const e=this.trackView.getLastViewport();if(e.overlayElement.innerHTML="",0===this.groups.size)return;let t;switch(this.displayMode){case"EXPANDED":t=this.expandedRowHeight;break;case"SQUISHED":t=this.squishedRowHeight;break;default:t=(e.viewportElement.getBoundingClientRect().height-(this.groups.size-1)*hd)/this.sampleKeys.length}let i=hd;for(const r of this.groups.keys()){const s=document.createElement("div");s.className="igv-attribute-group-label",e.overlayElement.appendChild(s),s.innerText=r,s.style.top=`${i}px`,i+=this.groups.get(r).count*t+hd}}clickedFeatures(e){const t=super.clickedFeatures(e),i=e.y;return t.filter((function(e){const t=e.pixelRect;return t&&i>=t.y&&i<=t.y+t.h}))}hoverText(e){const t=this.clickedFeatures(e);if(t&&t.length>0)return`${t[0].sample}: ${t[0].value}`}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){i.length>0&&(i.push("
"),i.push("
"));const t=e._f||e,r="function"==typeof t.popupData?t.popupData(this.type,this.browser.genome.id):this.extractPopupData(t);Array.prototype.push.apply(i,r)}return i}contextMenuItemList(e){const{genomicLocation:t,referenceFrame:i,viewport:r,event:s}=e,o=e=>{const t=r.cachedFeatures;this.sortByValue(e,t)},n=i.toBP(2.5),a=["DESC","ASC"].map((e=>{const r="DESC"===e?"descending":"ascending";return{label:"seg"===this.type||"shoebox"===this.type?`Sort by value (${r})`:`Sort by count (${r})`,click:()=>{const r={option:"VALUE",direction:e,chr:i.chr,start:Math.floor(t-n),end:Math.floor(t+n)};o(r)}}}));return a.push("
"),a}get supportsWholeGenome(){return(!1===this.config.indexed||!this.config.indexURL)&&!1!==this.config.supportsWholeGenome}updateSampleKeys(e){if(this.explicitSamples)return;let t=!1;const i=new Set(this.sampleKeys);for(let r of e){const e=r.sampleKey||r.sample;if(!i.has(e)){const r=this.sampleKeys;r.push(e),this.sampleKeys=r,i.add(e),t=!0}}t&&Kd!==this.groupBy&&this.groupByAttribute(this.groupBy)}}const Zd={low:.1,high:1.5,lowColor:"rgb(255,255,255)",highColor:"rgb(255,0,0)"},Xd={low:-1.5,high:-.1,lowColor:"rgb(0,0,255)",highColor:"rgb(255,255,255)"},Jd={indel:"rgb(0,200,0)","targeted region":"rgb(236,155,43)",truncating:"rgb(\t150,0,0)","non-coding transcript":"rgb(0,0,150)",synonymous:"rgb(109,165,95)",silent:"rgb(109,135,80)",missense_mutation:"rgb(72,130,187)",missense:"rgb(72,130,187)","splice site":"rgb(143,83,155)",splice_region:"rgb(143,83,155)",nonsense:"rgb(216, 57,81)",nonsense_mutation:"rgb(216, 57,81)",frame_shift_del:"rgb(226,135,65)",frame_shift_ins:"rgb(226,135,65)",in_frame_del:"rgb(247,235,94)",in_frame_ins:"rgb(247,235,94)","*other*":"rgb(159,91,50)"};class eu{constructor(e){this.paired=!0,this.firstAlignment=e,this.chr=e.chr,this.readName=e.readName,e.startt.start?this.connectingEnd=e.start:this.connectingStart=e.start+e.lengthOnRef,this.start=Math.min(t.start,e.start),this.end=Math.max(t.start+t.lengthOnRef,e.start+e.lengthOnRef),this.lengthOnRef=this.end-this.start,this.scStart=Math.min(t.scStart,e.scStart);const i=Math.max(t.scStart+t.scLengthOnRef,e.scStart+e.scLengthOnRef);this.scLengthOnRef=i-this.scStart}containsLocation(e,t){const i=t?this.scStart:this.start,r=t?this.scLengthOnRef:this.lengthOnRef;return e>=i&&e<=i+r}alignmentContaining(e,t){return this.firstAlignment.containsLocation(e,t)?this.firstAlignment:this.secondAlignment&&this.secondAlignment.containsLocation(e,t)?this.secondAlignment:void 0}popupData(e,t,i){let r=this.firstAlignment.popupData(e,t,i);return this.secondAlignment&&(r.push("-------------------------------"),r=r.concat(this.secondAlignment.popupData(e,t,i))),r}isPaired(){return!0}isMateMapped(){return!0}isProperPair(){return this.firstAlignment.isProperPair()}get fragmentLength(){return Math.abs(this.firstAlignment.fragmentLength)}get firstOfPairStrand(){return this.firstAlignment.firstOfPairStrand}get pairOrientation(){return this.firstAlignment.pairOrientation}hasTag(e){return this.firstAlignment.hasTag(e)||this.secondAlignment&&this.secondAlignment.hasTag(e)}getGroupValue({option:e,tag:t}){switch(e){case"strand":return this.isNegativeStrand()?"-":"+";case"FIRST_IN_PAIR_STRAND":return this.isPaired()?this.isFirstOfPair()?this.isNegativeStrand()?"-":"+":this.isSecondOfPair()?this.isNegativeStrand()?"+":"-":void 0:void 0;case"START":return this.start;case"INSERT_SIZE":return this.fragmentLength;case"MATE_CHR":return this.mate?this.mate.chr:void 0;case"MQ":return this.mq;case"ALIGNED_READ_LENGTH":return this.lengthOnRef;case"TAG":return this.tags()[t];case"PHASE":return this.tags().HP;case"READ_ORDER":return this.isPaired()&&this.isFirstOfPair()?"FIRST":this.isPaired()&&this.isSecondOfPair()?"SECOND":"";default:return}}}class tu{static instances=new Map;static getKey(e,t,i){const r=""+e+t+i;return tu.instances.has(r)||tu.instances.set(r,new tu(e,t,i)),tu.instances.get(r)}constructor(e,t,i){this.base=e,this.strand=t,this.modification=i,this.canonicalBase="+"===this.strand?this.base:Io(this.base)}getCanonicalBase(){}toString(){return""+this.base+this.strand+this.modification}static compare(e,t){const i=e.modification,r=t.modification;return i===r?e.strand.charAt(0)-t.strand.charAt(0):iu.has(i)&iu.has(r)?iu.get(i)-iu.get(r):iu.has(i)?1:iu.has(r)?-1:i>r?1:-1}}const iu=new Map(["NONE_C","NONE_T","NONE_G","NONE_A","m","h","f","c","C","g","e","b","T","U","a","A","o","G","n","N"].map(((e,t)=>[e,t])));class ru{constructor(e,t,i,r){this.base=e,this.modification=i,this.strand=t,this.likelihoods=r,this.canonicalBase="+"==this.strand?this.base:Io(this.base),this.key=tu.getKey(e,t,i)}containsPosition(e){return this.likelihoods.has(e)}is5mC(){return this.modification.equals("m")&&("C"===this.base&&"+"===this.strand||"G"===this.base&&"-"===this.strand)}fullName(){return su.get(this.modification)||this.modification}}const su=new Map;su.set("m","5mC"),su.set("h","5hmC"),su.set("f","5fC"),su.set("c","5caC"),su.set("g","5hmU"),su.set("e","5fU"),su.set("b","5caU"),su.set("a","6mA"),su.set("o","8xoG"),su.set("n","Xao"),su.set("C","Unknown C"),su.set("T","Unknown T"),su.set("A","Unknown A"),su.set("G","Unknown G"),su.set("N","Unknown");const ou=new Map([["m","5mC"],["h","5hmC"],["f","5fC"],["c","5caC"],["g","5hmU"],["e","5fU"],["b","5caU"],["a","6mA"],["o","8xoG"],["n","Xao"],["C","Unknown C"],["T","Unknown T"],["A","Unknown A"],["G","Unknown G"],["N","Unknown"]]),nu=new Set;function au(e){return ou.has(e)?ou.get(e):"Uknown"}function cu(e){if(!e)return!1;const t=e.length;if(0==t)return!1;for(let i=0;i"9")return!1}return!0}function lu(e){return e<0?e+256:e}class hu{allModifications=new Set;simplexModifications=new Set;maxLikelihoods=new Map;nomodLikelihoods=new Map;lastThreshold;incrementCounts(e){if(!e.blocks)return;const t=e.getBaseModificationSets();if(t)for(let i of e.blocks)if("S"!==i.type)for(let e=0;en&&(o=e.canonicalBase,n=c,r=t)}}if(0!=o){const t=i.start+e,s=tu.getKey(o,"+","NONE_"+o);this.allModifications.add(s);const c=(e,t,i,r)=>{let s=r.get(i);s||(s=new Map,r.set(i,s));let o=s.get(e);o||(o=[],s.set(e,o)),o.push(t)};c(t,n,r,this.maxLikelihoods),a>n?c(t,a,s,this.nomodLikelihoods):c(t,n,r,this.nomodLikelihoods)}}}getCount(e,t,i,r){this.lastThreshold=i;const s=255*i,o=r?this.nomodLikelihoods.get(t):this.maxLikelihoods.get(t);if(!o)return 0;const n=o.get(e);if(n){let e=0;for(let t of n){lu(t)>=s&&e++}return e}return 0}getLikelihoodSum(e,t,i,r){this.lastThreshold=i;const s=255*i,o=(r?this.nomodLikelihoods.get(t):this.maxLikelihoods.get(t)).get(e);if(o){let e=0;for(let t of o){const i=lu(t);i>=s&&(e+=i)}return e}return 0}popupData(e,t){const i=[];i.push("Modifications with likelihood > "+100*this.lastThreshold+"%");for(let r of this.maxLikelihoods.keys()){if(this.maxLikelihoods.get(r).has(e)){let s="basemod2"===t;const o=this.getCount(e,r,this.lastThreshold,s);if(o>0){const t=this.getLikelihoodSum(e,r,this.lastThreshold,s)/o*.3921568,n=au(r.modification);i.push(n+" ("+r.base+r.strand+"): "+o+" @ average likelihood "+Math.round(t)+"%")}}}return i}computeSimplex(){const e=new Set(Array.from(this.allModifications).filter((e=>"-"===e.strand)).map((e=>e.modification)));for(let t of this.allModifications)"+"!==t.strand||e.has(t.modification)||(this.simplexModifications.add(t.modification),this.simplexModifications.add("NONE_"+t.getCanonicalBase()))}}class du{constructor(){this.alignments=[],this.score=void 0}findAlignment(e,t=!1){const i=(e,i)=>i>=e.start&&i=o.start&&e0?h-=e:0===h&&(h=1)}return h}(o,s,e);case"strand":return o.strand?1:-1;case"START":return o.start;case"TAG":return o.tags()[i];case"READ_NAME":return o.readName;case"INSERT_SIZE":return-Math.abs(o.fragmentLength);case"GAP_SIZE":return-o.gapSizeAt(e);case"MATE_CHR":return o.mate?o.mate.chr:Number.MAX_VALUE;case"MQ":return void 0===o.mq?Number.MAX_VALUE:-o.mq;case"ALIGNED_READ_LENGTH":return-o.lengthOnRef;default:return Number.MAX_VALUE}}}var uu={fr:{F1R2:"LR",F2R1:"LR",F1F2:"LL",F2F1:"LL",R1R2:"RR",R2R1:"RR",R1F2:"RL",R2F1:"RL"},rf:{R1F2:"LR",R2F1:"LR",R1R2:"LL",R2R1:"LL",F1F2:"RR",F2F1:"RR",F1R2:"RL",F2R1:"RL"},ff:{F2F1:"LR",R1R2:"LR",F2R1:"LL",R1F2:"LL",R2F1:"RR",F1R2:"RR",R2R1:"RL",F1F2:"RL"}};class fu{#y=[];baseModificationKeys=new Set;constructor(e,t,i,{samplingWindowSize:r,samplingDepth:s,alleleFreqThreshold:o,colorBy:n}){this.alleleFreqThreshold=void 0===o?.2:o,this.samplingWindowSize=r||100,this.samplingDepth=s||1e3,this.chr=e,this.start=Math.floor(t),this.end=Math.ceil(i),this.length=i-t,this.coverageMap=new gu(e,t,i,this.alleleFreqThreshold),this.downsampledIntervals=[],n&&n.startsWith("basemod")&&(this.baseModCounts=new hu),this.alignments=[],this.pairsCache=new Map,this.downsampledReads=new Set,this.currentBucket=new pu(this.start,this.start+this.samplingWindowSize,this),this.hasPairs=!1}pack({viewAsPairs:e,showSoftClips:t,expectedPairOrientation:i,groupBy:r,displayMode:s}){let o=this.allAlignments();o=e?function(e){const t=new Map,i=e.map((e=>{if(Fu(e)){let i=t.get(e.readName);return i?(i.setSecondAlignment(e),t.delete(e.readName),i):(i=new eu(e),t.set(e.readName,i),i)}return e}));return i}(o):function(e){return e.flatMap((e=>e instanceof eu?[e.firstAlignment,e.secondAlignment].filter(Boolean):[e]))}(o),this.packAlignmentRows(o,t,i,r,s),this.alignments&&delete this.alignments}packAlignmentRows(e,t,i,r,s){this.#y=[];const o=(e,i)=>{e.sort((function(e,i){return t?e.scStart-i.scStart:e.start-i.start}));const r=new bu(i);let s,o=0,n=0;const a=new Set,c=()=>{s=new du,r.push(s),o=0,n=0,a.clear()};for(c();e.length>0;)if(n>=0&&n(t?e.scStart:e.start)>o),n)}else e=e.filter((e=>!a.has(e))),c();return r},n=(e,t)=>{e.sort((function(e,t){return e.start-t.start}));const i=new bu(t),{start:r,end:s}=this.viewport.genomicRange();for(let t of e)if(t.ends)this.#y.push(t);else{const e=new du;e.alignments.push(t),i.push(e)}return i};if(!e||0===e.length)return new Map;{const t=new Map;if(r)for(let s of e){const e=yu(s,r,i)||"";t.has(e)||t.set(e,[]),t.get(e).push(s)}else t.set("",e);const a=new Map,c=Array.from(t.keys()).sort(function(e){switch(e){case"pairOrientation":return function(){const e=["LL","RR","RL","LR",""];return(t,i)=>e.indexOf(t)-e.indexOf(i)}();case"strand":case"firstOfPairStrand":return _u;default:return e&&e.startsWith("base:")?Cu:xu}}(r));for(let e of c){const i=t.get(e),r="FULL"===s?n(i,e):o(i,e);a.set(e,r)}this.packedGroups=a}}push(e){this.hasPairs=this.hasPairs||e.isPaired(),this.coverageMap.incCounts(e);const t=e.getBaseModificationSets();if(t)for(let e of t)this.baseModificationKeys.add(e.key);this.baseModCounts&&this.baseModCounts.incrementCounts(e),this.downsampledReads.has(e.readName)?this.currentBucket.downsampledCount++:(e.start>=this.currentBucket.end&&(this.finishBucket(),this.currentBucket=new pu(e.start,e.start+this.samplingWindowSize,this)),this.currentBucket.addAlignment(e))}finish(){void 0!==this.currentBucket&&this.finishBucket(),this.hasAlignments=this.alignments.length>0,this.alignments.sort((function(e,t){return e.start-t.start})),this.baseModCounts&&this.baseModCounts.computeSimplex(),delete this.currentBucket,delete this.pairsCache,delete this.downsampledReads}contains(e,t,i){return this.chr===e&&this.start<=t&&this.end>=i}hasDownsampledIntervals(){return this.downsampledIntervals&&this.downsampledIntervals.length>0}finishBucket(){this.alignments=this.alignments.concat(this.currentBucket.alignments),this.currentBucket.downsampledCount>0&&this.downsampledIntervals.push(new wu(this.currentBucket.start,this.currentBucket.end,this.currentBucket.downsampledCount))}allAlignments(){if(this.alignments)return this.alignments;if(this.packedGroups){const e=Array.from(this.packedGroups.values()).flatMap((e=>e.rows.flatMap((e=>e.alignments))));if(this.#y&&this.#y.length>0)for(let t of this.#y)e.push(t);return e}return[]}getMax(e,t){return this.coverageMap.getMax(e,t)}sortRows(e){if(this.packedGroups)for(let t of this.packedGroups.values())t.sortRows(e,this)}}class pu{constructor(e,t,{samplingDepth:i,downsampledReads:r,pairsCache:s}){this.start=e,this.end=t,this.alignments=[],this.downsampledCount=0,this.samplingDepth=i,this.downsampledReads=r,this.pairsCache=s,this.hasPairs=!1}addAlignment(e){this.hasPairs=this.hasPairs||e.isPaired();const t=this.hasPairs?Math.ceil(this.samplingDepth/2):this.samplingDepth;if(Fu(e)){const t=this.pairsCache.get(e.readName);if(t)return t.setSecondAlignment(e),void this.pairsCache.delete(e.readName)}if(this.alignments.lengtht)break;const o=this.coverage[s];r>=e&&o&&(i=Math.max(i,o.total))}return i}incCounts(e){var t=this;if(void 0===e.blocks?i(e):e.blocks.forEach((function(e){i(e)})),e.gaps)for(let i of e.gaps)if("D"===i.type){const e=i.start-t.bpStart;for(let r=e;r=this.coverage.length)return 0;const r=this.coverage[i];switch(t){case"A":case"a":return r.posA;case"C":case"c":return r.posC;case"T":case"t":return r.posT;case"G":case"g":return r.posG;case"N":case"n":return r.posN;default:return 0}}getNegCount(e,t){const i=e-this.bpStart;if(i<0||i>=this.coverage.length)return 0;const r=this.coverage[i];switch(t){case"A":case"a":return r.negA;case"C":case"c":return r.negC;case"T":case"t":return r.negT;case"G":case"g":return r.negG;case"N":case"n":return r.negN;default:return 0}}getCount(e,t){return this.getPosCount(e,t)+this.getNegCount(e,t)}getTotalCount(e){const t=e-this.bpStart;return t>=0&&t=t}}class wu{constructor(e,t,i){this.start=e,this.end=t,this.counts=i}popupData(e){return[{name:"start",value:Math.floor(this.start+1)},{name:"end",value:this.end},{name:"# downsampled:",value:this.counts}]}}class bu{pixelTop=0;pixelBottom=0;rows=[];constructor(e){this.name=this.name}push(e){this.rows.push(e)}get length(){return this.rows.length}sortRows(e,t){const i=[],r=[];for(let t of this.rows){void 0!==t.findAlignment(e.position,e.sortAsPairs)?i.push(t):r.push(t)}i.sort(((i,r)=>{const s=e.direction,o=i.getSortValue(e,t),n=r.getSortValue(e,t);if(void 0===n&&void 0!==n)return 1;if(void 0!==o&&void 0===n)return-1;const a=o>n?1:o>1);t(e[i])?s=i:r=i}return s}function yu(e,t,i){let r,s,o;if(t.startsWith("tag:"))r=t.substring(4),t="tag";else if(t.startsWith("base:")){const e=t.split(":");3===e.length&&(t="base",s=e[1],o=Number.parseInt(e[2].replaceAll(",",""))-1)}switch(t){case"strand":return e.strand?"+":"-";case"firstOfPairStrand":const t=e.firstOfPairStrand;return void 0===t?"":t?"+":"-";case"mateChr":return e.mate&&e.isMateMapped()?e.mate.chr:"";case"pairOrientation":return uu[i][e.pairOrientation]||"";case"chimeric":return e.tags().SA?"chimeric":"";case"supplementary":return e.isSupplementary?"supplementary":"";case"readOrder":return e.isPaired()&&e.isFirstOfPair()?"first":e.isPaired()&&e.isSecondOfPair()?"second":"";case"phase":return e.tags().HP||"";case"tag":return e.tags()[r]||"";case"base":if(e.chr===s&&e.start<=o&&e.end>o){const t=e.readBaseAt(o);return t||"GAP"}return"";default:return}}const Au=new Map([["A",1],["T",2],["C",3],["G",4],["N",5],["GAP",5],["",7]]);function Cu(e,t){return Au.has(e)&&Au.has(t)?Au.get(e)-Au.get(t):e.localeCompare(t,void 0,{sensitivity:"base"})}function _u(e,t){return e===t?0:e&&t?-e.localeCompare(t):e?1:-1}function xu(e,t){if(e||t){if(e){if(t){if(e===t)return 0;if(ss(e)&&(ss(t),1))return Number.parseFloat(e)-Number.parseFloat(t);{let i=e.toString(),r=t.toString();return i.localeCompare(r,void 0,{sensitivity:"base"})}}return-1}return 1}return 0}class ku{constructor(e){const t=e.split(",");this.chr=t[0],this.start=parseInt(t[1]),this.strand=t[2].charAt(0),this.mapQ=parseInt(t[4]),this.numMismatches=parseInt(t[5]),this.lenOnRef=function(e){let t=0,i="";for(let r=0;r47&&s<58)i+=e.charAt(r);else{switch(s){case 78:case 68:case 77:case 61:case 88:t+=parseInt(i.toString())}i=""}}return t}(t[3])}printString(){return this.chr+":"+F(this.start)+"-"+F(this.start+this.lenOnRef)+" ("+this.strand+") = "+F(this.lenOnRef)+"bp @MAPQ: "+this.mapQ+" NM: "+this.numMismatches}}function Iu(e){return e.split(";").filter((e=>e.length>0)).map((e=>new ku(e)))}const Su={c:1,C:1,s:2,S:2,i:4,I:4,f:4};class Eu{constructor(){this.hidden=!1}isMapped(){return!(4&this.flags)}isPaired(){return!!(1&this.flags)}isProperPair(){return!!(2&this.flags)}isFirstOfPair(){return!!(64&this.flags)}isSecondOfPair(){return!!(128&this.flags)}isSecondary(){return!!(256&this.flags)}isSupplementary(){return!!(2048&this.flags)}isFailsVendorQualityCheck(){return!!(512&this.flags)}isDuplicate(){return!!(1024&this.flags)}isMateMapped(){return!(8&this.flags)}isNegativeStrand(){return!!(16&this.flags)}isMateNegativeStrand(){return!!(32&this.flags)}hasTag(e){const t=this.tagDict||function(e){let t=0;const i=e.length,r={};for(;t=i&&e<=i+r}popupData(e,t,i){const r=[];if(e=Math.floor(e),this.insertions){const t=this.seq;for(let i of this.insertions){var s=i.start;if(e===s||e===s-1)return r.push({name:"Insertion",value:t.substr(i.seqOffset,i.len)}),r.push({name:"Location",value:s}),r}}r.push({name:"Read Name",value:this.readName}),r.push("
"),r.push({name:"Alignment Start",value:F(1+this.start),borderTop:!0}),r.push({name:"Read Strand",value:!0===this.strand?"(+)":"(-)",borderTop:!0});let o=this.cigar;if(o&&o.length>50){const e=25;o=`${o.substring(0,e-2)} ... ${o.substring(o.length-e+2)}`}r.push({name:"Cigar",value:o}),r.push({name:"Mapping Quality",value:this.mq}),r.push({name:"Secondary",value:c(this.isSecondary())}),r.push({name:"Supplementary",value:c(this.isSupplementary())}),r.push({name:"Duplicate",value:c(this.isDuplicate())}),r.push({name:"Failed QC",value:c(this.isFailsVendorQualityCheck())}),this.isPaired()&&(r.push("
"),r.push({name:"First in Pair",value:!this.isSecondOfPair(),borderTop:!0}),r.push({name:"Mate is Mapped",value:c(this.isMateMapped())}),this.pairOrientation&&r.push({name:"Pair Orientation",value:this.pairOrientation}),this.isMateMapped()&&(r.push({name:"Mate Chromosome",value:this.mate.chr}),r.push({name:"Mate Start",value:this.mate.position+1}),r.push({name:"Mate Strand",value:!0===this.mate.strand?"(+)":"(-)"}),r.push({name:"Insert Size",value:this.fragmentLength})));const n=this.tags();if(n.hasOwnProperty("SA")){r.push("
"),r.push({name:"Supplementary Alignments",value:""});const e=Iu(n.SA);if(e){r.push("
    ");for(let t of e)r.push(`
  • ${t.printString()}
  • `);r.push("
")}}r.push("
");for(let e in n)i?.has(e)?r.push({name:e,value:n[e]}):i?t.add(e):t.has(e)||r.push({name:e,value:n[e]});t&&t.size>0&&r.push({name:"Hidden Tags",value:Array.from(t).join(", ")}),r.push("
"),r.push({name:"Genomic Location: ",value:F(1+e)}),r.push({name:"Read Base:",value:this.readBaseAt(e)}),r.push({name:"Base Quality:",value:this.readBaseQualityAt(e)});const a=this.getBaseModificationSets();if(a){const t=this.positionToReadIndex(e);if(void 0!==t){let e=!1;for(let i of a)if(i.containsPosition(t)){e||(r.push("
"),r.push("Base modifications:"),e=!0);const s=Math.round(100/255*lu(i.likelihoods.get(t)));r.push(`${i.fullName()} @ likelihood = ${s}%`)}}}return r;function c(e){return e?"Yes":"No"}}readBaseAt(e){const t=Mu(this.blocks,e);if(t){if("*"===this.seq)return"*";{const i=t.seqIndexAt(e);return this.seq[i]}}}readBaseQualityAt(e){const t=Mu(this.blocks,e);if(t){if("*"===this.qual)return 30;{const i=t.seqIndexAt(e);return i>=0&&this.qual&&i=t.start&&e1)if(cu(e))h.push(e);else for(let t=0;t=r.start&&t>1)+r;a+4=t)return!1;if("B"!==String.fromCharCode(e[a+2])||"I"!==String.fromCharCode(e[a+3]))return!1;var l=ju(e,a+4),h=a+8;if(h+4*l>t)return!1;var d="",u=0;o.length=0,a=h;for(var f=0;f>4,m=Vu[15&p];"M"!==m&&"EQ"!==m&&"X"!==m&&"D"!==m&&"N"!==m&&"="!==m||(u+=g),d=d+g+m,o.push({len:g,ltr:m})}return s.cigar=d,s.lengthOnRef=u,!0},decodeBamRecords:function(e,t,i,r,s,o,n,a){for(;te.length)return;if(p<0){t=u;continue}if(void 0!==s&&(p>s||p===s&&g>n))return!0;if(void 0!==s&&p>8,b=255&m,F=ju(e,t+16),v=(4294901760&F)>>16,y=65535&F,A=ju(e,t+20),C=ju(e,t+24),_=ju(e,t+28),x=ju(e,t+32);let k=[];for(let i=0;i>4,h=Vu[15&c];"M"!==h&&"EQ"!==h&&"X"!==h&&"D"!==h&&"N"!==h&&"="!==h||(I+=l),S=S+l+h,E+=4,M={len:l,ltr:h},N.push(M)}if(f.chr=r[p],f.start=g,f.flags=v,f.strand=!(16&v),f.readName=k,f.cigar=S,f.lengthOnRef=I,f.fragmentLength=x,f.mq=w,Qu.bam_tag2cigar(e,u,E,A,f,N),f.end=f.start+f.lengthOnRef,f.end>1;for(let t=0;t>4]),R.push(Ou[15&d])}R=R.slice(0,A).join(""),E+=B;const D=[];for(let t=0;t=0&&(f.mate={chr:r[C],position:_,strand:!(32&v)}),f.seq=R,f.qual=D;const L=new Uint8Array(e.buffer.slice(E,u));f.tagDict=Ku(L),this.setPairOrientation(f),(void 0===a||a.pass(f))&&(Gu(f,N),i.push(f)),t=u}},decodeSamRecords:function(e,t,i,r,s,o){var n,a,c,l,h,d,u,f,p,g;for(l=(n=v(e)).length,a=0;as)break;if(f=0,(g=Wu(p.cigar)).forEach((function(e){var t=e.len,i=e.ltr;"M"!==i&&"EQ"!==i&&"X"!==i&&"D"!==i&&"N"!==i&&"="!==i||(f+=t)})),p.lengthOnRef=f,!(p.start+fUu&&(console.log("Warning: attempt to set sampling depth > maximum value of "+Uu),e.samplingDepth=Uu)},setPairOrientation:function(e){if(e.isMapped()&&e.mate&&e.isMateMapped()&&e.mate.chr===e.chr){var t=e.strand?"F":"R",i=e.mate,r=i.strand?"F":"R",s=" ",o=" ";e.isFirstOfPair()?(s="1",o="2"):e.isSecondOfPair()&&(s="2",o="1");var n=[],a=e.fragmentLength,c=e.end-e.start;if(0===a)a=(e.start0?(n[0]=t,n[1]=s,n[2]=r,n[3]=o):(n[2]=t,n[3]=s,n[0]=r,n[1]=o),e.pairOrientation=n.join("")}}};function Gu(e,t){const i=[];let r,s,o=0,n=e.start;e.scStart=e.start,e.scLengthOnRef=e.lengthOnRef;for(let a of t){let t;switch(a.ltr){case"H":case"P":break;case"S":t=n,e.scLengthOnRef+=a.len,0===i.length&&(e.scStart-=a.len,t-=a.len),i.push(new zu({start:t,seqOffset:o,len:a.len,type:"S"})),o+=a.len;break;case"N":case"D":void 0===s&&(s=[]),s.push({start:n,len:a.len,type:a.ltr}),n+=a.len;break;case"I":void 0===r&&(r=[]),r.push(new zu({start:n,len:a.len,seqOffset:o,type:"I"})),o+=a.len;break;case"M":case"EQ":case"=":case"X":i.push(new zu({start:n,seqOffset:o,len:a.len,type:"M"})),o+=a.len,n+=a.len;break;default:console.log("Error processing cigar element: "+a.len+a.ltr)}}e.blocks=i,e.insertions=r,e.gaps=s}function ju(e,t){return e[t+3]<<24|e[t+2]<<16|e[t+1]<<8|e[t]}function Wu(e){var t,i,r,s,o,n,a,c,l;for(t=[],i=[],o=null,s=e.length,r=0;r=48&&l<=57?i.push(n):(a=n,c=Number.parseInt(i.join("")),i=[],null!==o&&o.ltr===a?o.len+=c:(o={len:c,ltr:a},t.push(o)));return t}function $u(e){var t={};return e.forEach((function(e){var i=e.split(":");t[i[0]]=i[2]})),t}function Ku(e){let t=0;const i=e.length,r={},s=new DataView(e.buffer);for(;t=0?atob(r):decodeURI(r);const s=new Uint8Array(r.length);for(var o=0;o"start"!==e&&"end"!==e)).map((e=>i[e])).filter((e=>t.has(e)));e.length>0&&(r=e[0])}return this.chrAliasTable.set(e,r),r}return e}}class Zu{chrAliasTable=new Map;constructor(e,t){this.config=e,this.genome=t,this.bamPath=e.url,this.baiPath=e.indexURL,Qu.setReaderDefaults(this,e),this._blockLoader=new Xa(e)}async readAlignments(e,t,i){const r=await this.#_(e),s=new fu(e,t,i,this.config);if(void 0===r)return s;{const e=(await this.getIndex()).chunksForRange(r,t,i);if(!e||0===e.length)return s;for(let o of e){const e=await this._blockLoader.getData(o.minv,o.maxv);if(Qu.decodeBamRecords(e,o.minv.offset,s,this.header.chrNames,r,t,i,this.filter))break}return s.finish(),s}}async#_(e){if(await this.getHeader(),this.chrAliasTable.has(e)&&void 0===(e=this.chrAliasTable.get(e)))return;let t=this.header.chrToIndex[e];if(void 0===t){const i=await this.genome.getAliasRecord(e);let r;if(i){const e=Object.keys(i).filter((e=>"start"!==e&&"end"!==e)).map((e=>i[e])).filter((e=>void 0!==this.header.chrToIndex[e]));e.length>0&&(r=e[0],t=this.header.chrToIndex[e[0]])}this.chrAliasTable.set(e,r)}return t}async getHeader(){if(!this.header){const e=this.genome,t=await this.getIndex();let i;if(t.firstBlockPosition){const e=ts(this.config,{range:{start:t.firstBlockPosition,size:26}}),r=ir(await Rr.loadArrayBuffer(this.bamPath,e));i=t.firstBlockPosition+r}else i=64e3;const r=ts(this.config,{range:{start:0,size:i}});this.header=await Qu.readHeader(this.bamPath,r,e)}return this.header}async getIndex(){return this.index||(this.index=await ja(this.baiPath,this.config)),this.index}async getChrIndex(){if(this.chrToIndex)return this.chrToIndex;{const e=await this.getHeader();return this.chrToIndex=e.chrToIndex,this.indexToChr=e.chrNames,this.chrNames=new Set(e.chrNames),this.chrToIndex}}}class Xu{constructor(e,t){this.config=e,this.genome=t;const i={};e.sources.sequences.forEach((function(r){const s=t?t.getChromosomeName(r):r;i[s]=function(e,t,i){const r={url:e.sources.url.replace("$CHR",i)};e.sources.indexURL&&(r.indexURL=e.sources.indexURL.replace("$CHR",i));const s=Object.assign(e,r);return new Zu(s,t)}(e,t,r)})),this.bamReaders=i,Qu.setReaderDefaults(this,e)}async readAlignments(e,t,i){if(this.bamReaders.hasOwnProperty(e)){let r=this.bamReaders[e];return await r.readAlignments(e,t,i)}return new fu(e,t,i,this.config)}}const Ju=function(e,t){this.config=e,this.genome=t,Qu.setReaderDefaults(this,e)};function ef(){const e=this,t=this.genome;if(this.header)return Promise.resolve(this.header);{const i=this.config.url+"?file="+this.config.alignmentFile+"&options=-b,-H",r=ts(this.config);return Qu.readHeader(i,r,t).then((function(t){return e.header=t,t}))}}Ju.prototype.readAlignments=function(e,t,i){var r=this;return ef.call(r).then((function(s){var o,n;return o=s.chrAliasTable.hasOwnProperty(e)?s.chrAliasTable[e]:e,n=r.config.url+"?reference="+r.config.referenceFile+"&file="+r.config.alignmentFile+"®ion="+o+":"+t+"-"+i,Rr.loadString(n,ts(r.config)).then((function(n){var a;return s.chrToIndex[o],a=new fu(e,t,i,r.config),Qu.decodeSamRecords(n,a,o,t,i,r.filter),a}))}))};class tf extends hc{chrNames=new Set;constructor(e,t){super(e,t),Qu.setReaderDefaults(this,e)}async readAlignments(e,t,i){if("all"===e)return[];if(!this.header){const e=tr((await this.readHeaderData()).buffer);this.header=Qu.decodeBamHeader(e,this.genome);for(let e of this.header.chrNames)this.chrNames.add(e);this.chromAliasManager=this.genome?new fc(this.header.chrNames,this.genome):null}let r=e;if(this.chrNames.size>0&&!this.chrNames.has(e)&&this.chromAliasManager&&(r=await this.chromAliasManager.getAliasName(e)),!this.chrNames.has(r))return console.warn("Chromosome "+e+" not found in BAM header"),new fu(e,t,i,this.config);const s=tr((await this.readData(r,t,i)).buffer);this.header=Qu.decodeBamHeader(s,this.genome);const o=this.header.chrToIndex[e],n=new fu(e,t,i,this.config);return Qu.decodeBamRecords(s,this.header.size,n,this.header.chrNames,o,t,i,this.filter),n.finish(),n}} +/*! For license information please see cram-bundle.js.LICENSE.txt */var rf,sf,of=(rf={24:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.toHex=function(e){let t="";for(let i=0,s=e.length;i>>4&15]}${i[15&e]}`},78:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(24),s=[0,1,3,7,15,31,63,127,255];t.default=class{constructor(e){this.stream=e,this.bitOffset=0,this.curByte=0,this.hasByte=!1}_ensureByte(){this.hasByte||(this.curByte=this.stream.readByte(),this.hasByte=!0)}read(e){let t=0;for(;e>0;){this._ensureByte();const i=8-this.bitOffset;if(e>=i)t<<=i,t|=s[i]&this.curByte,this.hasByte=!1,this.bitOffset=0,e-=i;else{t<<=e;const r=i-e;t|=(this.curByte&s[e]<>r,this.bitOffset+=e,e=0}}return t}seek(e){const t=e%8,i=(e-t)/8;this.bitOffset=t,this.stream.seek(i),this.hasByte=!1}pi(){const e=new Uint8Array(6);for(let t=0;t{const r=i(1308).A;e.exports=r,e.exports.default=r},500:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=i(6272),o=i(6761),n=r(i(588)),a=r(i(9685)),c=r(i(7480)),l=i(7580),h=i(2549);function d(e,t,i,r){const o=!!(r.mate||void 0!==r.mateRecordNumber&&r.mateRecordNumber!==t);i.readName||(i.readName=String(i.uniqueId),r.readName=i.readName),i.mate={sequenceId:r.sequenceId,alignmentStart:r.alignmentStart,uniqueId:r.uniqueId},r.readName&&(i.mate.readName=r.readName),r.mate||void 0!==r.mateRecordNumber||(r.mate={sequenceId:i.sequenceId,alignmentStart:i.alignmentStart,uniqueId:i.uniqueId},i.readName&&(r.mate.readName=i.readName)),i.flags|=n.default.BAM_FPAIRED,r.flags&n.default.BAM_FUNMAP&&(i.flags|=n.default.BAM_FMUNMAP),i.flags&n.default.BAM_FUNMAP&&(r.flags|=n.default.BAM_FMUNMAP),r.flags&n.default.BAM_FREVERSE&&(i.flags|=n.default.BAM_FMREVERSE),i.flags&n.default.BAM_FREVERSE&&(r.flags|=n.default.BAM_FMREVERSE),void 0===i.templateLength&&(o?function(e,t,i){const r=function t(i){const r=[i];if(void 0!==i.mateRecordNumber&&i.mateRecordNumber>=0){const o=e[i.mateRecordNumber];if(!o)throw new s.CramMalformedError("intra-slice mate record not found, this file seems malformed");r.push(...t(o))}return r}(i),o=r.map((e=>e.alignmentStart)),n=r.map((e=>e.alignmentStart+e.readLength-1)),a=Math.max(...n)-Math.min(...o)+1;a>=0&&r.forEach((e=>{if(void 0!==e.templateLength)throw new s.CramMalformedError("mate pair group has some members that have template lengths already, this file seems malformed");e.templateLength=a}))}(e,0,i):function(e,t){const i=Math.min(e.alignmentStart,t.alignmentStart),r=Math.max(e.alignmentStart+e.readLength-1,t.alignmentStart+t.readLength-1)-i+1;e.templateLength=r,t.templateLength=r}(i,r)),i.mateRecordNumber=void 0}class u{constructor(e,t,i){this.container=e,this.containerPosition=t,this.sliceSize=i,this.file=e.file}async getHeader(){const{majorVersion:e}=await this.file.getDefinition(),t=(0,l.getSectionParsers)(e),i=await this.container.getHeader(),r=await this.file.readBlock(i._endPosition+this.containerPosition);if("MAPPED_SLICE_HEADER"===r.contentType){const e=(0,h.parseItem)(r.content,t.cramMappedSliceHeader.parser,0,i._endPosition);return{...r,parsedContent:e}}if("UNMAPPED_SLICE_HEADER"===r.contentType){const e=(0,h.parseItem)(r.content,t.cramUnmappedSliceHeader.parser,0,i._endPosition);return{...r,parsedContent:e}}throw new s.CramMalformedError(`error reading slice header block, invalid content type ${r.contentType}`)}async getBlocks(){const e=await this.getHeader();let t=e._endPosition;const i=new Array(e.parsedContent.numBlocks);for(let e=0;e{"EXTERNAL_DATA"===e.contentType&&(t[e.contentId]=e)})),t}async getBlockByContentId(e){return(await this._getBlocksContentIdIndex())[e]}async getReferenceRegion(){const e=new TextDecoder("utf8"),t=(await this.getHeader()).parsedContent;if(!(0,l.isMappedSliceHeader)(t))throw new Error("slice header not mapped");if(t.refSeqId<0)return;const i=await this.container.getCompressionScheme();if(void 0===i)throw new Error("compression scheme undefined");if(t.refBaseBlockId>=0){const i=await this.getBlockByContentId(t.refBaseBlockId);if(!i)throw new s.CramMalformedError("embedded reference specified, but reference block does not exist");return{seq:e.decode(i.data),start:t.refSeqStart,end:t.refSeqStart+t.refSeqSpan-1,span:t.refSeqSpan}}if(i.referenceRequired||this.file.fetchReferenceSequenceCallback){if(!this.file.fetchReferenceSequenceCallback)throw new Error("reference sequence not embedded, and seqFetch callback not provided, cannot fetch reference sequence");const e=await this.file.fetchReferenceSequenceCallback(t.refSeqId,t.refSeqStart,t.refSeqStart+t.refSeqSpan-1);if(e.length!==t.refSeqSpan)throw new s.CramArgumentError("seqFetch callback returned a reference sequence of the wrong length");return{seq:e,start:t.refSeqStart,end:t.refSeqStart+t.refSeqSpan-1,span:t.refSeqSpan}}}getAllRecords(){return this.getRecords((()=>!0))}async _fetchRecords(){const{majorVersion:e}=await this.file.getDefinition(),t=await this.container.getCompressionScheme();if(void 0===t)throw new Error("compression scheme undefined");const i=await this.getHeader(),r=await this._getBlocksContentIdIndex();if(e>1&&this.file.options.checkSequenceMD5&&(0,l.isMappedSliceHeader)(i.parsedContent)&&i.parsedContent.refSeqId>=0&&"0000000000000000"!==i.parsedContent.md5?.join("")){const e=await this.getReferenceRegion();if(e){const{seq:t,start:r,end:o}=e,n=(0,h.sequenceMD5)(t),a=i.parsedContent.md5?.map((e=>(e<16?"0":"")+e.toString(16))).join("");if(n!==a)throw new s.CramMalformedError(`MD5 checksum reference mismatch for ref ${i.parsedContent.refSeqId} pos ${r}..${o}. recorded MD5: ${a}, calculated MD5: ${n}`)}}const n=await this.getCoreDataBlock(),u={lastAlignmentStart:(0,l.isMappedSliceHeader)(i.parsedContent)?i.parsedContent.refSeqStart:0,coreBlock:{bitPosition:7,bytePosition:0},externalBlocks:{map:new Map,getCursor(e){let t=this.map.get(e);return void 0===t&&(t={bitPosition:7,bytePosition:0},this.map.set(e,t)),t}}},f=e=>{const i=t.getCodecForDataSeries(e);if(!i)throw new s.CramMalformedError(`no codec defined for ${e} data series`);return i.decode(this,n,r,u)},p=new Array(i.parsedContent.numRecords);for(let s=0;s=0&&p[i]&&d(p,e,t,p[i])}}return p}async getRecords(e){const t=this.container.filePosition+this.containerPosition;let i=this.file.featureCache.get(t.toString());i||(i=this._fetchRecords(),this.file.featureCache.set(t.toString(),i));const r=(await i).filter(e);if(r.length&&this.file.fetchReferenceSequenceCallback){const e=await this.getHeader();if((0,l.isMappedSliceHeader)(e.parsedContent)&&(e.parsedContent.refSeqId>=0||-2===e.parsedContent.refSeqId)){const t=e.parsedContent.refSeqId>=0?e.parsedContent.refSeqId:void 0,i=await this.container.getCompressionScheme();if(void 0===i)throw new Error("compression scheme undefined");const s={};for(const e of r){const i=void 0!==t?t:e.sequenceId;let r=s[i];r||(r={id:i,start:e.alignmentStart,end:Number.NEGATIVE_INFINITY,seq:null},s[i]=r);const o=e.alignmentStart+(e.lengthOnRef||e.readLength)-1;o>r.end&&(r.end=o),e.alignmentStart{-1!==e.id&&e.start<=e.end&&this.file.fetchReferenceSequenceCallback&&(e.seq=await this.file.fetchReferenceSequenceCallback(e.id,e.start,e.end))})));for(const e of r){const r=s[void 0!==t?t:e.sequenceId];if(r?.seq){const t=r.seq;e.addReferenceSequence({...r,seq:t},i)}}}}return r}}t.default=u,"getHeader getBlocks _getBlocksContentIdIndex".split(" ").forEach((e=>{(0,h.tinyMemoize)(u,e)}))},588:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default={CRAM_FLAG_PRESERVE_QUAL_SCORES:1,CRAM_FLAG_DETACHED:2,CRAM_FLAG_MATE_DOWNSTREAM:4,CRAM_FLAG_NO_SEQ:8,CRAM_FLAG_MASK:15,CRAM_M_REVERSE:1,CRAM_M_UNMAP:2,BAM_FPAIRED:1,BAM_FPROPER_PAIR:2,BAM_FUNMAP:4,BAM_FMUNMAP:8,BAM_FREVERSE:16,BAM_FMREVERSE:32,BAM_FREAD1:64,BAM_FREAD2:128,BAM_FSECONDARY:256,BAM_FQCFAIL:512,BAM_FDUP:1024,BAM_FSUPPLEMENTARY:2048,BAM_CMATCH:0,BAM_CINS:1,BAM_CDEL:2,BAM_CREF_SKIP:3,BAM_CSOFT_CLIP:4,BAM_CHARD_CLIP:5,BAM_CPAD:6,BAM_CEQUAL:7,BAM_CDIFF:8,BAM_CBACK:9,BAM_CIGAR_STR:"MIDNSHP:XB",BAM_CIGAR_SHIFT:4,BAM_CIGAR_MASK:15,BAM_CIGAR_TYPE:246183}},632:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6761),n=i(6272);class a extends s.default{constructor(e,t){if(super(e,t),"int"!==this.dataType)throw new n.CramUnimplementedError(`${this.dataType} decoding not yet implemented by GAMMA codec`)}decode(e,t,i,r){let s=1;for(;0===(0,o.getBits)(t.content,r.coreBlock,1);)s+=1;return((0,o.getBits)(t.content,r.coreBlock,s-1)|1<{function t(e){return!!e.constructor&&"function"==typeof e.constructor.isBuffer&&e.constructor.isBuffer(e)}e.exports=function(e){return null!=e&&(t(e)||function(e){return"function"==typeof e.readFloatLE&&"function"==typeof e.slice&&t(e.slice(0,0))}(e)||!!e._isBuffer)}},772:()=>{},807:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6761),n=i(6272);class a extends s.default{constructor(e,t){if(super(e,t),"int"!==this.dataType)throw new n.CramUnimplementedError(`${this.dataType} decoding not yet implemented by BETA codec`)}decode(e,t,i,r){return(0,o.getBits)(t.content,r.coreBlock,this.parameters.length)-this.parameters.offset}}t.default=a},870:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e,t,i){const r=u(e),s=f(t),o=new d(r,s);for(;!("eof"in r)||!r.eof();)if(o._init_block())o._read_bunzip();else{const e=o.reader.read(32)>>>0;if(e!==o.streamCRC&&h(c.DATA_ERROR,"Bad stream CRC (got "+o.streamCRC.toString(16)+" expected "+e.toString(16)+")"),!i||!("eof"in r)||r.eof())break;o._start_bunzip(r,s)}if("getBuffer"in s)return s.getBuffer()};const s=r(i(78)),o=r(i(8761)),n=r(i(6612)),a=function(e,t){const i=e[t];for(let i=t;i>0;i--)e[i]=e[i-1];return e[0]=i,i},c={OK:0,LAST_BLOCK:-1,NOT_BZIP_DATA:-2,UNEXPECTED_INPUT_EOF:-3,UNEXPECTED_OUTPUT_EOF:-4,DATA_ERROR:-5,OUT_OF_MEMORY:-6,OBSOLETE_INPUT:-7,END_OF_BLOCK:-8},l={};l[c.LAST_BLOCK]="Bad file checksum",l[c.NOT_BZIP_DATA]="Not bzip data",l[c.UNEXPECTED_INPUT_EOF]="Unexpected input EOF",l[c.UNEXPECTED_OUTPUT_EOF]="Unexpected output EOF",l[c.DATA_ERROR]="Data error",l[c.OUT_OF_MEMORY]="Out of memory",l[c.OBSOLETE_INPUT]="Obsolete (pre 0.9.5) bzip format not supported.";const h=function(e,t){let i=l[e]||"unknown error";t&&(i+=": "+t);const r=new TypeError(i);throw r.errorCode=e,r};class d{constructor(e,t){this.writePos=this.writeCurrent=this.writeCount=0,this._start_bunzip(e,t)}_init_block(){return this._get_next_block()?(this.blockCRC=new o.default,!0):(this.writeCount=-1,!1)}_start_bunzip(e,t){const i=new Uint8Array(4);4===e.read(i,0,4)&&"BZh"===String.fromCharCode(i[0],i[1],i[2])||h(c.NOT_BZIP_DATA,"bad magic");const r=i[3]-48;(r<1||r>9)&&h(c.NOT_BZIP_DATA,"level out of range"),this.reader=new s.default(e),this.dbufSize=1e5*r,this.nextoutput=0,this.outputStream=t,this.streamCRC=0}_get_next_block(){let e,t,i;const r=this.reader,s=r.pi();if("177245385090"===s)return!1;"314159265359"!==s&&h(c.NOT_BZIP_DATA),this.targetBlockCRC=r.read(32)>>>0,this.streamCRC=(this.targetBlockCRC^(this.streamCRC<<1|this.streamCRC>>>31))>>>0,r.read(1)&&h(c.OBSOLETE_INPUT);const o=r.read(24);o>this.dbufSize&&h(c.DATA_ERROR,"initial position out of bounds");let n=r.read(16),l=new Uint8Array(256),d=0;for(e=0;e<16;e++)if(n&1<<15-e){const s=16*e;for(i=r.read(16),t=0;t<16;t++)i&1<<15-t&&(l[d++]=s+t)}const u=r.read(3);(u<2||u>6)&&h(c.DATA_ERROR);const f=r.read(15);0===f&&h(c.DATA_ERROR);const p=new Uint8Array(256);for(e=0;e=u&&h(c.DATA_ERROR);g[e]=a(p,t)}let m,w=d+2,b=[];for(t=0;t20)&&h(c.DATA_ERROR),r.read(1);)r.read(1)?n--:n++;t[e]=n}var F,v;for(F=v=t[0],e=1;ev?v=t[e]:t[e]=f&&h(c.DATA_ERROR),m=b[g[x++]]),e=m.minLen,t=r.read(e);e>m.maxLen&&h(c.DATA_ERROR),!(t<=m.limit[e]);e++)t=t<<1|r.read(1);t-=m.base[e],(t<0||t>=258)&&h(c.DATA_ERROR);const i=m.permute[t];if(0!==i&&1!==i){if(C)for(C=0,_+n>this.dbufSize&&h(c.DATA_ERROR),A=l[p[0]],y[A]+=n;n--;)k[_++]=A;if(i>d)break;_>=this.dbufSize&&h(c.DATA_ERROR),e=i-1,A=a(p,e),A=l[A],y[A]++,k[_++]=A}else C||(C=1,n=0),n+=0===i?C:2*C,C<<=1}for((o<0||o>=_)&&h(c.DATA_ERROR),t=0,e=0;e<256;e++)i=t+y[e],y[e]=t,t=i;for(e=0;e<_;e++)A=255&k[e],k[y[A]]|=e<<8,y[A]++;let I=0,S=0,E=0;return _&&(I=k[o],S=255&I,I>>=8,E=-1),this.writePos=I,this.writeCurrent=S,this.writeCount=_,this.writeRun=E,!0}_read_bunzip(e,t){let i,r,s;if(this.writeCount<0)return 0;let o=this.dbuf,n=this.writePos,a=this.writeCurrent,l=this.writeCount,d=(this.outputsize,this.writeRun);for(;l;){for(l--,r=a,n=o[n],a=255&n,n>>=8,3===d++?(i=a,s=r,a=-1):(i=1,s=a),this.blockCRC.updateCRCRun(s,i);i--;)this.outputStream.writeByte(s),this.nextoutput++;a!=r&&(d=0)}return this.writeCount=l,this.blockCRC.getCRC()!==this.targetBlockCRC&&h(c.DATA_ERROR,"Bad block CRC (got "+this.blockCRC.getCRC().toString(16)+" expected "+this.targetBlockCRC.toString(16)+")"),this.nextoutput}}const u=function(e){if("readByte"in e)return e;const t=new n.default;return t.pos=0,t.readByte=function(){return e[this.pos++]},t.seek=function(e){this.pos=e},t.eof=function(){return this.pos>=e.length},t},f=function(e){const t=new n.default;let i=!0;if(e)if("number"==typeof e)t.buffer=new Uint8Array(e),i=!1;else{if("writeByte"in e)return e;t.buffer=e,i=!1}else t.buffer=new Uint8Array(16384);return t.pos=0,t.writeByte=function(e){if(i&&this.pos>=this.buffer.length){const e=new Uint8Array(2*this.buffer.length);e.set(this.buffer),this.buffer=e}this.buffer[this.pos++]=e},t.getBuffer=function(){if(this.pos!==this.buffer.length){if(!i)throw new TypeError("outputsize does not match decoded input");const e=new Uint8Array(this.pos);e.set(this.buffer.slice(0,this.pos)),this.buffer=e}return this.buffer},t._coerced=!0,t};t.default=d},1064:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.blob=e,this.size=e.size}async read(e,t=0){if(!e)return new Uint8Array(0);const i=t,r=i+e;return new Uint8Array(await this.blob.slice(i,r).arrayBuffer())}async readFile(e){const t="string"==typeof e?e:e?.encoding;if("utf8"===t)return this.blob.text();if(t)throw new Error(`unsupported encoding: ${t}`);return new Uint8Array(await this.blob.arrayBuffer())}async stat(){return{size:this.size}}async close(){}}},1307:function(e,t,i){var r;r=e=>(()=>{var t=[,e=>{e.exports="data:application/wasm;base64,AGFzbQEAAAABOApgAX8Bf2ABfwBgAABgA39/fwF/YAABf2ACf38AYAN/f34BfmACf38Bf2AEf39/fwF/YAN/f38AAyEgAAABAgMDAwMEAQUAAgMCBgcIBwUDAAMHAQcABwcBAwkFAwEAAgYIAX8BQfCgBAsHTgUGbWVtb3J5AgAOY3JlYXRlX2NvbnRleHQACA9kZXN0cm95X2NvbnRleHQACQxzdXBwbHlfaW5wdXQACg9nZXRfbmV4dF9vdXRwdXQACwqNYCDfAgEFf0EAIQECQCAAQQdqIgJBEEkNAEEBIQEgAkEDdiIDQQJGDQBBAiEBIAJBIEkNAEEDIQEgA0EERg0AQQQhASACQTBJDQBBBSEBIANBBkYNAEEGIQEgAkHIAEkNAEEHIQEgAkHYAEkNAEEIIQEgAkGIAUkNAEEJIQEgAkGIAkkNACAAEIGAgIAAIgBBCGpBACAAGw8LAkACQCABQQJ0QcCIgIAAaiIEKAIAIgANAEEAIQACQAJAQQAoAuSIgIAAIgJFDQBBACACKAIANgLkiICAAAwBC0EAEIGAgIAAIgJFDQILIAJBgIB8cSIAIAJBCHZB/wFxIgJyIAE6AAAgAkEIdCAAckGAAmohAEEAIQJBACABQQJ0QYCIgIAAaigCACIDayEFIAMhAQNAIAAgBWoiACACNgIAIAAhAiABIANqIgFBgQJJDQALIAQgADYCAAsgBCAAKAIANgIACyAAC+4HAQd/AkACQAJAAkACQEEALQC0iICAAEUNAEEAQQA6ALSIgIAAQQAoArCIgIAAIgFFDQFBsIiAgAAhAgNAAkACQCABQQhqIgMgASgCBCIEaiIFQQh2Qf8BcSIGDQAgASECDAELAkADQCAFQYCAfHEgBmotAABB/gFHDQFBsIiAgAAhBgNAIAYiBygCACIGIAVHDQALIAcgBSgCADYCACABIAQgBSgCBGpBCGoiBDYCBCAHIAIgAiAFRhshAiADIARqIgVBCHZB/wFxIgYNAAsLIAIoAgAhAgsgAigCACIBDQALC0EAKAKwiICAACIFRQ0AIABBhwJqQYB+cSEDQX8hAkGwiICAACEEQQAhAUGwiICAACEGA0AgBiEHAkAgBSIGKAIEIgUgAEkNACAFIAJPDQAgBSECIAchBCAGIQEgBUEIaiADRw0AIAchBCAFIQIgBiEBDAQLIAYoAgAiBQ0ACyABDQIMAQtBsIiAgAAhBAs/AEEQdCEBIABBiAJqIQdBACEDAkACQEEAKAK4iICAACICRQ0AQQAhBSABIQYMAQtBACABQfCghIAAQf//A2pBgIB8cSIGayICNgK4iICAACACIQULAkAgByAFTQ0AIAcgBWsiByACQQF2IgIgAiAHSRtB//8DaiIHQRB2QABBf0YNAkEAQQAoAriIgIAAIAdBgIB8cSIDajYCuIiAgAALIAZFDQEgBkH/AToAASAGQQAoArCIgIAANgKAAiAGQYQCaiADIAVqQYCAfHFB+H1qIgI2AgAgBkGAAmohAQsgAUGAgHxxIgYgAUEIdkH/AXFyQf8BOgAAIAQgASgCADYCAAJAIAIgAGtBgH5xIgUNACABDwsgASEDAkAgBiABQQhqIgQgAmoiByAFQX9zakGAgHxxRg0AIARB//8DcSEFAkAgAEH3/QNLDQAgBiAEQQh2Qf8BcWpB/gE6AAAgAUEAKAKwiICAADYCACABQYCABCAFayIFNgIEQQAgATYCsIiAgAAQg4CAgAAgBkGEggRqIAIgBWtB+H1qIgU2AgAgBkGBgARqQf8BOgAAIAZBgIIEaiEDIAUgAGtBgH5xIQUMAQsgAiAFaiAAIAVqQX9qQYCAfHFrQYCAfGohBSABIQMLIAMgAygCBCAFazYCBCAFQfgBaiEGIAcgBWtBCHZB/wFxIQUCQANAIAYiB0GAfmohBiAFIgQNAUEBIQUgB0H4AUcNAAsLAkAgB0H4AUYNACACIAFqIAZrQYCAfHEiBSAEakH+AToAACAFIARBCHRqIgVBACgCsIiAgAA2AgAgBSAGNgIEQQAgBTYCsIiAgAAQg4CAgAALIAMPC0EAC3wBAn8CQCAARQ0AAkAgAEGAgHxxIABBCHZB/wFxciIBLQAAIgJB/wFHDQAgAEF4aiIAQQAoArCIgIAANgIAQQAgADYCsIiAgAAgAUH+AToAAEEAQQE6ALSIgIAADwsgACACQQJ0QcCIgIAAaiICKAIANgIAIAIgADYCAAsLawECfwJAQQAoArCIgIAAIgAoAgRB/wFLDQAgAEGAgHxxIgEgAEEIdkH/AXEiAHJBCToAAEEAQQAoArCIgIAAKAIANgKwiICAACABIABBCHRyIgBBACgC5IiAgAA2AgBBACAANgLkiICAAAsLTgECfwJAIAAgAUYNACACRQ0AA0ACQCAALQAAIgMgAS0AACIERg0AQQFBfyADIARLGw8LIAFBAWohASAAQQFqIQAgAkF/aiICDQALC0EAC3gBAX8CQAJAIAAgAU8NACACRQ0BIAAhAwNAIAMgAS0AADoAACABQQFqIQEgA0EBaiEDIAJBf2oiAg0ADAILCyAAIAFNDQAgAkUNACABQX9qIQEgAEF/aiEDA0AgAyACaiABIAJqLQAAOgAAIAJBf2oiAg0ACwsgAAssAQF/AkAgAkUNACAAIQMDQCADIAE6AAAgA0EBaiEDIAJBf2oiAg0ACwsgAAuCAQEBfwJAAkAgAEEDcQ0AIAEgAnJBA3ENACACQQRJDQEgAkECdiECIAAhAwNAIAMgASgCADYCACABQQRqIQEgA0EEaiEDIAJBf2oiAg0ADAILCyACRQ0AIAAhAwNAIAMgAS0AADoAACABQQFqIQEgA0EBaiEDIAJBf2oiAg0ACwsgAAuIAQECfwJAQQAtAOiIgIAADQBBAEEBOgDoiICAABCMgICAABCOgICAAAtBoIAIEICAgIAAIgBBgIAENgIAQQJBgICAIBCXgICAACEBIABBFGpCgICAgICAwAA3AgAgAEEQaiAAQaCABGo2AgAgAEEIakIANwMAIAAgAEEgajYCBCAAIAE2AhwgAAsVACAAKAIcEJiAgIAAIAAQgoCAgAALFgAgAEEMaiABNgIAIABBCGpBADYCAAsbACAAKAIcIABBBGogAEEMaigCAEUQloCAgAALVAEDf0EAIQADQEEIIQEgACECA0BBACACQQFxa0GghuLtfnEgAkEBdnMhAiABQX9qIgENAAsgAEECdEHwiICAAGogAjYCACAAQQFqIgBBgAJHDQALC0oAIAJBf3MhAgJAIAFFDQADQCACQf8BcSAALQAAc0ECdEHwiICAAGooAgAgAkEIdnMhAiAAQQFqIQAgAUF/aiIBDQALCyACQX9zC10DAX4BfwF+QgAhAANAQQghASAAIQIDQEIAIAJCAYN9QsKenLzd8pW2SYMgAkIBiIUhAiABQX9qIgENAAsgAKdBA3RB8JCAgABqIAI3AwAgAEIBfCIAQoACUg0ACwtLACACQn+FIQICQCABRQ0AA0AgAkL/AYMgADEAAIWnQQN0QfCQgIAAaikDACACQgiIhSECIABBAWohACABQX9qIgENAAsLIAJCf4UL1RACDH8CfgJAAkAgACgCJEUNACAAKAIAIQIMAQtBACECIABBADoAKCAAQgA3AwAgAEIANwMYIABByABqQQBB5AAQhoCAgAAaIABBrAFqQQw2AgALIAAgASgCBCIDNgIQIABBsAFqIQQgAEHgAGohBSAAQcgAaiEGIABBtgFqIQcgAEGoAWohCCABKAIQIQkCQAJAAkACQANAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAIAIOCgECAAQFBgcICQoPCyABKAIAIQogACgCqAEhAiAAKAKsASELIAEoAgQhDCABKAIIIQ0MAgsgCCAAKAKoASIMakEIaiABKAIAIAEoAgQiAmogASgCCCACayICIAAoAqwBIAxrIgwgAiAMSRsiAhCHgICAABogASABKAIEIAJqNgIEQQAhDCAAQQAgACgCqAEgAmoiAiACIAAoAqwBIgtGGzYCqAEgAiALRw0RIABBATYCAAJAIARBqIiAgABBBhCEgICAAEUNAEEFIQwMEgsgB0ECQQAQjYCAgAAgACgAuAFHDRBBBiEMIActAAANESAAIAAtALcBIgI2AiAgAkEESw0RQQEgAnRBE3FFDRELIAEoAgQiDCABKAIIIg1GDQ4CQCABKAIAIgogDGotAAAiCw0AIAAgDDYCECABIAxBAWo2AgRBBiECDAwLQQAhAiAAQQA2AqgBIABBAjYCACAAIAtBAnRBBGoiCzYCrAEgACALNgJACyAIIAJqQQhqIAogDGogDSAMayIMIAsgAmsiAiAMIAJJGyICEIeAgIAAGiABIAIgASgCBGo2AgRBACEMIABBACAAKAKoASACaiICIAIgACgCrAEiC0YbNgKoASACIAtHDQ8gACACQXxqIgI2AqwBQQchDCAEIAJBABCNgICAACAAIAAoAqwBIgtqQbABaigAAEcNDyAAQQI2AqgBIAAtALEBIgJBP3ENDAJAAkAgAkHAAHFFDQAgACAEIAggCxCRgICAAEEBRw0RIAAgACkDCDcDMCAALQCxASECDAELIABCfzcDMAtCfyEOAkAgAkEYdEEYdUF/Sg0AIAAgBCAIIAAoAqwBEJGAgIAAQQFHDRAgACkDCCEOCyAAIA43AzggACgCrAEiDSAAKAKoASICa0ECSQ0PIAAgAkEBaiIKNgKoASAIIAJqQQhqLQAAQSFHDQwgACACQQJqIgs2AqgBIAggCmpBCGotAABBAUcNDCANIAtGDQ8gACACQQNqNgKoASAAKAKwCSAIIAtqQQhqLQAAEJyAgIAAIgwNDyAAKAKoASIMIAAoAqwBIgIgDCACSxshDQJAA0AgDSAMRg0BIAggDEEBaiICNgIAIAQgDGohCyACIQwgCy0AAA0ODAALCyAGQgA3AwAgAEEANgKoASAAQQM2AgAgBkEIakIANwMACyAAIAEoAgQ2AhAgACABKAIQNgIUIAAoArAJIAEQmYCAgAAhDCAAIAApA0ggASgCBCAAKAIQa618Ig43A0ggACAAKQNQIAEoAhAgACgCFCICayILrXwiDzcDUCAOIAApAzBWDQ0gDyAAKQM4Vg0NAkACQAJAAkAgACgCIEF/ag4EAAMDAQMLIAEoAgwgAmogCyAAKAIYEI2AgIAArSEODAELIAEoAgwgAmogCyAAKQMYEI+AgIAAIQ4LIAAgDjcDGAsgDEEBRw0OAkAgACkDMCIOQn9RDQAgDiAGKQMAUg0OCwJAIAApAzgiDkJ/UQ0AQQchDCAOIAApA1BSDQ8LIAAgACkDSCAANQJAfCAAKQNgfCIPNwNgQgQhDgJAAkACQCAAKAIgQX9qDgQBAgIAAgtCCCEOCyAFIA4gD3w3AwALIAAgACkDaCAAKQNQfDcDaCAAIAVBGCAAKAJwEI2AgIAANgJwIABBBDYCACAAIAApA1hCAXw3A1gLAkAgBikDACIOQgODUA0AIA5CAXwhDiABKAIEIQwgASgCCCELA0AgCyAMRg0NIAEgDEEBaiICNgIEIAEoAgAgDGotAAANDiAGIA43AwAgDkIDgyEPIA5CAXwhDiACIQwgD0IAUg0ACwsgAEEFNgIAC0EBIQIgACgCIEF/ag4EBgcHBQcLIAAgARCSgICAACIMQQFHDQsgAEEHNgIAC0EAIAAoAhBrIQggAEGAAWopAwAhDiABKAIEIQwCQANAIA4gCCAMaq18QgODUA0BAkAgDCABKAIIRw0AIAAgARCTgICAAAwLCyABIAxBAWoiAjYCBCABKAIAIAxqIQsgAiEMIAstAAANCwwACwsgACABEJOAgIAAQQchDCAFIABBkAFqQRgQhICAgAANCiAAQQg2AgALIAAgAUEgEJSAgIAAIgxBAUcNCSAAQQk2AgBBDCELIABBDDYCrAEMAQsgACgCrAEhCwsgAEGoAWogACgCqAEiDGpBCGogASgCACABKAIEIgJqIAEoAgggAmsiAiALIAxrIgwgAiAMSRsiAhCHgICAABogASABKAIEIAJqNgIEQQAhDCAAQQAgACgCqAEgAmoiAiACIAAoAqwBIgtGGzYCqAEgAiALRw0HIAAQlYCAgAAhDAwHC0EBIQIgACABQcAAEJSAgIAAIgxBAUcNBgwBC0EBIQIgACABQSAQlICAgAAiDEEBRw0FCyAAIAI2AgAMAAsLQQYhDAwCC0EAIQwMAQtBByEMCwJAAkAgACgCJA0AAkACQCAMDgIAAwELQQdBCCABKAIEIAEoAghGGyEMCyABIAk2AhAgASADNgIEIAwPCwJAIAwNACADIAEoAgRHDQAgCSABKAIQRw0AIAAtACghASAAQQE6ACggAUEDdA8LIABBADoAKAsgDAuaAQEDfwJAIAAoAgQiBA0AIABCADcDCAsgAigCACEFA0ACQCAFIANJDQBBAA8LIAEgBWotAAAhBiACIAVBAWoiBTYCACAAIAZB/wBxrSAErYYgACkDCIQ3AwgCQAJAIAZBgAFxDQACQCAGDQBBByEGIAQNAgsgAEEANgIEQQEPC0EHIQYgACAEQQdqIgQ2AgQgBEE/Rw0BCwsgBguhAgIDfwF+IABBkAFqIQIgAUEEaiEDA0ACQCAAIAEoAgAgAyABKAIIEJGAgIAAIgRBAUYNACAAQYABaiIDIAMpAwAgASgCBCAAKAIQIgNrIgKtfDcDACAAIAMgASgCAGogAiAAKAIYEI2AgIAArTcDGCAEDwsCQAJAAkACQAJAIAAoAngOAwACAQMLIAAgACkDCCIFNwOIAQJAIAUgACkDWFENAEEHDwsgAEEBNgJ4DAMLIAAgACkDmAEgACkDCHw3A5gBIAAgAkEYIAAoAqABEI2AgIAANgKgASAAQQE2AnggACAAKQOIAUJ/fCIFNwOIAQwCCyAAQQI2AnggACAAKQOQASAAKQMIfDcDkAELIAApA4gBIQULIAVCAFINAAtBAQtAAQJ/IABBgAFqIgIgAikDACABKAIEIAAoAhAiAmsiA618NwMAIAAgAiABKAIAaiADIAAoAhgQjYCAgACtNwMYC3wBBH8gASgCBCEDIAEoAgghBANAAkAgBCADRw0AQQAPCyABIANBAWoiBTYCBAJAIAEoAgAgA2otAAAgACkDGCAAKAIEIgOtiKdB/wFxRg0AQQcPCyAAIANBCGoiBjYCBCAFIQMgBiACSQ0ACyAAQQA2AgQgAEIANwMYQQELbwEBf0EHIQECQCAAQboBai8AAEHZtAFHDQAgAEG0AWpBBkEAEI2AgIAAIABBsAFqKAAARw0AIABBgAFqKQMAQgKIIAA1ALQBUg0AIABBuAFqLQAADQBBAUEHIAAoAiAgAEG5AWotAABGGyEBCyABC7QCAQR/AkACQCAAKAIkRQ0AIAAoAgAhAwwBC0EAIQMgAEEAOgAoIABCADcDACAAQgA3AxggAEHIAGpBAEHkABCGgICAABogAEGsAWpBDDYCAEEBIQILIABByABqIQQCQAJAA0ACQCADQQpHDQAgASgCBCIDIAEoAggiBUYNAiABKAIAIQYCQANAIAYgA2otAAANASABIANBAWoiAzYCBCAAIAAoAgRBAWpBA3E2AgQgBSADRg0EDAALCwJAIAAoAgRFDQBBBw8LIAAoAiRFDQAgAEEAOgAoIABCADcDACAAQgA3AxggBEEAQeQAEIaAgIAAGiAAQQw2AqwBCyAAIAEQkICAgAAiA0EBRw0CQQohAyAAQQo2AgAMAAsLAkAgAg0AQQAPC0EHQQEgACgCBBshAwsgAwt1AQF/AkBBuAkQgICAgAAiAkUNACACIAA2AiQgAiAAIAEQm4CAgAAiADYCsAkCQCAARQ0AIAJBADoAKCACQgA3AwAgAkIANwMYIAJByABqQQBB5AAQhoCAgAAaIAJBrAFqQQw2AgAgAg8LIAIQgoCAgAALQQALHgACQCAARQ0AIAAoArAJEJ2AgIAAIAAQgoCAgAALC4ARAQx/IABB6N0BaiECIABB1ABqIQMgAEEcaiIEQQhqIQUCQAJAA0AgACgCQCEGAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkACQAJAAkAgASgCBCIHIAEoAggiCEkNACAGQQdGDQEMEgsgBg4JAQIDBAUGBwAJDwsgACgCTCEGDAcLQQEhCSABIAdBAWo2AgQgASgCACAHai0AACIHRQ0IAkACQCAHQd8BSw0AIAdBAUcNAQsgAEGAAjsBUAJAIAAoAjwNACAAIAEoAgwgASgCECIGajYCGCAAIAEoAhQgBms2AiwLIARCADcCACAFQgA3AgAMCwsgAC0AUEUNCgwOCyABIAdBAWo2AgQgASgCACAHai0AACEHIABBAjYCQCAAIAdBCHQgACgCSGo2AkgMDAsgASAHQQFqNgIEIAEoAgAgB2otAAAhByAAQQM2AkAgACAHIAAoAkhqQQFqNgJIDAsLIAEgB0EBajYCBCABKAIAIAdqLQAAIQcgAEEENgJAIAAgB0EIdDYCTAwKCyABIAdBAWo2AgQgASgCACAHai0AACEHIAAgACgCRDYCQCAAIAcgACgCTGpBAWo2AkwMCQsgASAHQQFqNgIEQQchCSABKAIAIAdqLQAAIgdB4AFLDQNBACEGAkACQCAHQS1PDQBBACEIDAELIAdBU2oiByAHQf8BcUEtbiIIQS1sayEHIAhBAWohCAsgAEF/IAh0QX9zNgJ0AkAgB0H/AXFBCUkNACAHQXdqIgcgB0H/AXFBCW4iBkEJbGshByAGQQFqIQYLIAAgBjYCcCAAIAdB/wFxIgc2AmwgBiAHakEESw0DIANCADcCACADQQhqQgA3AgAgA0EQakEANgIAIABBfyAGdEF/czYCcEH4ACEHA0AgACAHakGACDsBACAHQQJqIgdB5N0BRw0ACyAAQQY2AkAgAEEFNgIIIABC/////w83AgALIAAoAkwiCUEFSQ0IAkAgACgCCCIHRQ0AIAdBf2ohBiABKAIEIQcgASgCCCEKA0AgCiAHRg0LIAEgB0EBaiIINgIEIAEoAgAgB2otAAAhByAAIAY2AgggACAHIAAoAgRBCHRyNgIEIAghByAGQX9qIgZBf0cNAAsLIABBBzYCQCAAIAlBe2oiBjYCTAsgACAAKAIgIgcgASgCFCABKAIQayIIIAAoAkgiCiAIIApJGyIIaiAAKAIsIgogCiAHayAISxs2AiggASgCCCIJIAEoAgQiCGshBwJAAkACQCAAKALk3QEiCg0AIAYNAUEAIQYLIABB5N0BaiILIApqQQRqIAEoAgAgCGogByAGIAprIgZBKiAKayIIIAggBksbIgYgBiAHSxsiBxCHgICAABoCQAJAIAcgACgC5N0BIghqIgYgACgCTEcNACALIAhqIAdqQQRqQQBBPyAGaxCGgICAABogACgC5N0BIAdqIQYMAQsCQCAGQRRLDQAgACAGNgLk3QEgASABKAIEIAdqNgIEDAMLIAZBa2ohBgsgAEEANgIQIAAgAjYCDCAAIAY2AhRBByEJIAAQmoCAgABFDQMgACgCECIIIAAoAuTdASIKIAdqSw0DIAAgACgCTCAIayIGNgJMAkAgCiAITQ0AIAAgCiAIayIHNgLk3QEgAiALIAhqQQRqIAcQhYCAgAAaDAILIABBADYC5N0BIAEgASgCBCAIIApraiIINgIEIAEoAggiCSAIayEHCwJAIAdBFUkNACAAIAg2AhAgACABKAIANgIMIAAgCUFraiAIIAZqIAcgBkEVakkbNgIUQQchCSAAEJqAgIAARQ0DIAAoAkwiByAAKAIQIgggASgCBGsiBkkNAyABIAg2AgQgACAHIAZrIgY2AkwgASgCCCAIayIHQRRLDQELIAIgASgCACAIaiAGIAcgByAGSxsiBxCHgICAABogACAHNgLk3QEgASABKAIEIAdqNgIECyAAKAIgIgYgACgCHCIIayEHAkAgACgCPEUNAAJAIAYgACgCLEcNACAAQQA2AiALIAEoAgwgASgCEGogACgCGCAIaiAHEIeAgIAAGiAAKAIgIQYLIAAgBjYCHCABIAEoAhAgB2oiBjYCECAAIAAoAkggB2siBzYCSAJAIAcNAEEHIQkgACgCTA0CIAAoAmgNAiAAKAIEDQIgAEEANgJADAULQQAhCSAGIAEoAhRGDQEgASgCBCABKAIIRw0GIAAoAuTdASAAKAJMTw0GDAELIAAoAkwiCkUNAUEAIQkgCCAHTQ0AA0AgASgCFCIGIAEoAhAiC00NASAAIAogCiAAKAIsIAAoAiAiDGsiDSAIIAdrIgggBiALayIGIAggBkkbIgYgBiANSxsiBiAGIApLGyIGazYCTCAMIAAoAhhqIAEoAgAgB2ogBhCFgICAABogACAAKAIgIAZqIgc2AiACQCAAKAIkIAdPDQAgACAHNgIkCwJAIAAoAjxFDQACQCAHIAAoAixHDQAgAEEANgIgCyABKAIMIAEoAhBqIAEoAgAgASgCBGogBhCFgICAABogACgCICEHCyAAIAc2AhwgASABKAIQIAZqNgIQIAEgASgCBCAGaiIHNgIEIAAoAkwiCkUNAiABKAIIIgggB0sNAAsLIAkPCyAAQQA2AkAMAwsgB0EYdEEYdUF/Sg0BIABBATYCQCAAIAdBEHRBgID8AHE2AkgCQCAHQcABSQ0AIABBBTYCRCAAQQA6AFEMAwsgAC0AUQ0DIABBBjYCRCAHQaABSQ0CIANCADcCACADQRBqQQA2AgAgA0EIakIANwIAQfgAIQcDQCAAIAdqQYAIOwEAIAdBAmoiB0Hk3QFHDQALCyAAQQU2AgggAEL/////DzcCAAwBCyAHQQJLDQEgAEKDgICAgAE3AkAMAAsLQQcPC0EAC/8XARJ/IABBGGohAQJAIABBIGooAgAiAiAAQShqKAIAIgNPDQAgAEHoAGoiBCgCAEUNACABIAQgACgCVBCegICAABogACgCKCEDIAAoAiAhAgsCQCACIANPDQAgAEHcDWohBSAAQegAaiEGIABB4BVqIQcgAEHUAGohCANAIAAoAhAiCSAAKAIUSw0BIAAgACgCZCIKQQV0aiAAKAJ0IAJxIgtBAXRqIgxB+ABqIQ0CQAJAIAAoAgAiBEGAgIAISQ0AIAAoAgQhDgwBCyAAIARBCHQiBDYCACAAIAlBAWoiAzYCECAAIAAoAgRBCHQgACgCDCAJai0AAHIiDjYCBCADIQkLAkACQCAOIARBC3YgDS8BACIPbCIDTw0AIAAgAzYCACANIA9BgBAgD2tBBXZqOwEAIAJBf2ohBAJAIAINACAAKAIsIARqIQQLAkACQCAAKAIkIg8NAEEAIQQMAQsgACgCGCAEai0AACEECyAAKAJwIAJxIAAoAmwiDXQgBEEIIA1rdmohDAJAAkAgCkEGSw0AQQEhBANAIAAgDEGADGxqIARBAXQiBGpB5B1qIQ0CQAJAIANB////B00NACADIQoMAQsgACADQQh0Igo2AgAgACAJQQFqIgM2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQgAyEJCwJAAkAgDiAKQQt2IA0vAQAiD2wiA0kNACAAIA4gA2siDjYCBCAAIAogA2siAzYCACANIA8gD0EFdms7AQAgBEEBciEEDAELIAAgAzYCACANIA9BgBAgD2tBBXZqOwEACyAEQYACSQ0ADAILCyACIAAoAlQiDUF/c2ohBAJAIAIgDUsNACAAKAIsIARqIQQLAkACQCAPDQBBACEQDAELIAAoAhggBGotAAAhEAtBASEEQYACIQ0DQCAAIAxBgAxsaiAQQQF0IhAgDXEiESANaiAEakEBdGpB5B1qIQ8CQAJAIANB////B00NACADIQsMAQsgACADQQh0Igs2AgAgACAJQQFqIgM2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQgAyEJCwJAAkAgDiALQQt2IA8vAQAiCmwiA08iEg0AIAAgAzYCACAKQYAQIAprQQV2aiEKDAELIAAgDiADayIONgIEIAAgCyADayIDNgIAIAogCkEFdmshCkEAIQ0LIA8gCjsBACANIBFzIQ0gBEEBdCASciIEQYACSQ0ACwsgACACQQFqNgIgIAAoAhggAmogBDoAAAJAIAAoAiQgACgCICICTw0AIAAgAjYCJAtBACEDAkAgACgCZCIEQQRJDQACQCAEQQlLDQAgBEF9aiEDDAELIARBemohAwsgACADNgJkDAELIAAgDiADayIONgIEIAAgBCADayIDNgIAIA0gDyAPQQV2azsBACAAIApBAXRqIg9B+ANqIQQCQAJAIANB////B00NACAJIQoMAQsgACADQQh0IgM2AgAgACAJQQFqIgo2AhAgACAOQQh0IAAoAgwgCWotAAByIg42AgQLAkACQCAOIANBC3YgBC8BACINbCIJSQ0AIAAgDiAJayIONgIEIAAgAyAJayIDNgIAIAQgDSANQQV2azsBACAPQZAEaiENAkACQCADQf///wdNDQAgCiEQDAELIAAgA0EIdCIDNgIAIAAgCkEBaiIQNgIQIAAgDkEIdCAAKAIMIApqLQAAciIONgIECwJAAkAgDiADQQt2IA0vAQAiCWwiBE8NACANIAlBgBAgCWtBBXZqOwEAIAxB2ARqIQMCQCAEQf///wdLDQAgACAEQQh0IgQ2AgAgACAQQQFqNgIQIAAgDkEIdCAAKAIMIBBqLQAAciIONgIECwJAIA4gBEELdiADLwEAIg1sIglJDQAgACAOIAlrNgIEIAAgBCAJazYCACADIA0gDUEFdms7AQAMAgsgAyANQYAQIA1rQQV2ajsBACAAIAk2AgAgAEEBNgJoIABBCUELIAAoAmRBB0kbNgJkDAMLIAAgDiAEayIONgIEIA0gCSAJQQV2azsBACAPQagEaiENAkACQCADIARrIgNB////B00NACAQIQoMAQsgACADQQh0IgM2AgAgACAQQQFqIgo2AhAgACAOQQh0IAAoAgwgEGotAAByIg42AgQLAkACQCAOIANBC3YgDS8BACIEbCIJTw0AIAAgCTYCACANIARBgBAgBGtBBXZqOwEAIAAoAlghAwwBCyAAIA4gCWsiDjYCBCANIAQgBEEFdms7AQAgD0HABGohBAJAIAMgCWsiA0H///8HSw0AIAAgA0EIdCIDNgIAIAAgCkEBajYCECAAIA5BCHQgACgCDCAKai0AAHIiDjYCBAsCQAJAIA4gA0ELdiAELwEAIg1sIglPDQAgACAJNgIAIAQgDUGAECANa0EFdmo7AQAgACgCXCEDDAELIAAgDiAJazYCBCAAIAMgCWs2AgAgACgCYCEDIAAgACgCXDYCYCAEIA0gDUEFdms7AQALIAAgACgCWDYCXAsgACAAKAJUNgJYIAAgAzYCVAsgAEEIQQsgACgCZEEHSRs2AmQgACAHIAsQn4CAgAAMAQsgBCANQYAQIA1rQQV2ajsBACAAIAk2AgAgACAAKAJcNgJgIAAgACkCVDcCWCAAQQdBCiAAKAJkQQdJGzYCZCAAIAUgCxCfgICAACAAKAJoIgNBfmpBAyADQQZJGyEKIAAoAgAhA0EBIQ4DQCAAIApBB3RqIA5BAXQiDmpB2AdqIQ0CQAJAIANBgICACEkNACAAKAIEIQQMAQsgACADQQh0IgM2AgAgACAAKAIQIgRBAWo2AhAgACAAKAIEQQh0IAQgACgCDGotAAByIgQ2AgQLAkACQCAEIANBC3YgDS8BACIJbCIPSQ0AIAAgBCAPayIENgIEIAAgAyAPayIDNgIAIA0gCSAJQQV2azsBACAOQQFyIQ4MAQsgACAPNgIAIA0gCUGAECAJa0EFdmo7AQAgDyEDCyAOQcAASQ0ACwJAIA5BQGoiCUEDSw0AIAAgCTYCVAwBCyAAIA5BAXFBAnIiDTYCVCAJQQF2IQ8CQCAJQQ1LDQAgACANIA9Bf2oiDHQiCzYCVEEBIQ0gCCALQQF0akGEC2ohEEE/IA5rIRFBACEPA0AgECARIA1qQQF0aiEOAkACQCADQf///wdNDQAgAyEKDAELIAAgA0EIdCIKNgIAIAAgACgCECIDQQFqNgIQIAAgBEEIdCADIAAoAgxqLQAAciIENgIECwJAAkAgBCAKQQt2IA4vAQAiCWwiA0kNACAAIAQgA2siBDYCBCAAIAogA2siAzYCACAOIAkgCUEFdms7AQAgAEEBIA90IAtqIgs2AlQgDUEBdEEBciENDAELIAAgAzYCACAOIAlBgBAgCWtBBXZqOwEAIA1BAXQhDQsgDCAPQQFqIg9HDQAMAgsLIA9Be2ohDgNAAkAgA0H///8HSw0AIAAgA0EIdCIDNgIAIAAgACgCECIJQQFqNgIQIARBCHQgCSAAKAIMai0AAHIhBAsgACADQQF2IgM2AgAgACAEIANrIgRBH3UiCSANQQF0akEBaiINNgJUIAAgCSADcSAEaiIENgIEIA5Bf2oiDg0ACyAAIA1BBHQiCzYCVEEAIQ9BASEOA0AgACAOQQF0Ig5qQbwNaiENAkACQCADQf///wdNDQAgAyEKDAELIAAgA0EIdCIKNgIAIAAgACgCECIDQQFqNgIQIAAgBEEIdCADIAAoAgxqLQAAciIENgIECwJAAkAgBCAKQQt2IA0vAQAiCWwiA0kNACAAIAQgA2siBDYCBCAAIAogA2siAzYCACANIAkgCUEFdms7AQAgAEEBIA90IAtqIgs2AlQgDkEBciEODAELIAAgAzYCACANIAlBgBAgCWtBBXZqOwEACyAPQQFqIg9BBEcNAAsLAkAgASAGIAAoAlQQnoCAgAANAEEADwsgACgCICECCyACIAAoAihJDQALC0EBIQMCQCAAKAIAIgRB////B0sNACAAIARBCHQ2AgBBASEDIAAgACgCECIEQQFqNgIQIAAgACgCBEEIdCAEIAAoAgxqLQAAcjYCBAsgAwtwAQF/AkBBqN4BEICAgIAAIgJFDQAgAkE0aiABNgIAIAJBPGogADYCAAJAAkACQCAAQX9qDgIAAQILIAIgARCAgICAACIANgIYIAANASACEIKAgIAADAILIAJBADYCGCACQThqQQA2AgALIAIPC0EAC9IBAQJ/QQYhAgJAIAFBJ0sNACAAQTBqIAFBAXFBAnIgAUEBdkELanQiATYCAAJAAkAgAEE8aigCACIDRQ0AQQQhAiABIABBNGooAgBLDQIgAEEsaiABNgIAIANBAkcNACAAQThqIgMoAgAgAU8NACAAIAE2AjggACgCGBCCgICAACAAIAAoAjAQgICAgAAiATYCGCABDQBBAyECDAELQQAhAiAAQQA2AkAgAEHQAGpBAToAACAAQegAakEANgIAIABB5N0BaiEDCyADQQA2AgALIAILIwACQCAAQTxqKAIARQ0AIAAoAhgQgoCAgAALIAAQgoCAgAAL9QEBBH9BACEDAkAgACgCDCACTQ0AIAAoAhggAk0NACABIAEoAgAiBCAAKAIQIAAoAggiBWsiBiAEIAYgBEkbIgRrNgIAIAUgAkF/c2ohAQJAIAUgAksNACAAKAIUIAFqIQELIAAoAgAiAiABai0AACEGQQEhAyAAIAVBAWo2AgggAiAFaiAGOgAAAkAgBEF/aiICRQ0AA0AgACgCACIFQQAgAUEBaiIBIAEgACgCFEYbIgFqLQAAIQQgACAAKAIIIgZBAWo2AgggBSAGaiAEOgAAIAJBf2oiAg0ACwsgACgCDCAAKAIIIgFPDQAgACABNgIMCyADC8gEAQd/AkACQCAAKAIAIgNBgICACEkNACAAKAIEIQQMAQsgACADQQh0IgM2AgAgACAAKAIQIgVBAWo2AhAgACAAKAIEQQh0IAUgACgCDGotAAByIgQ2AgQLAkACQCAEIANBC3YgAS8BACIGbCIFTw0AIAEgBkGAECAGa0EFdmo7AQAgASACQQR0akEEaiEHQQghCEECIQkMAQsgACAEIAVrIgQ2AgQgASAGIAZBBXZrOwEAAkAgAyAFayIDQf///wdLDQAgACADQQh0IgM2AgAgACAAKAIQIgVBAWo2AhAgACAEQQh0IAUgACgCDGotAAByIgQ2AgQLAkAgBCADQQt2IAEvAQIiBmwiBU8NACABIAZBgBAgBmtBBXZqOwECIAEgAkEEdGpBhAJqIQdBCCEIQQohCQwBCyAAIAQgBWsiBDYCBCABIAYgBkEFdms7AQIgAUGEBGohByADIAVrIQVBgAIhCEESIQkLIABB6ABqIAk2AgBBASEBA0AgByABQQF0IgFqIQMCQAJAIAVB////B00NACAFIQIMAQsgACAFQQh0IgI2AgAgACAAKAIQIgVBAWo2AhAgACAEQQh0IAUgACgCDGotAAByIgQ2AgQLAkACQCAEIAJBC3YgAy8BACIGbCIFSQ0AIAAgBCAFayIENgIEIAAgAiAFayIFNgIAIAMgBiAGQQV2azsBACABQQFyIQEMAQsgACAFNgIAIAMgBkGAECAGa0EFdmo7AQALIAEgCEkNAAsgAEHoAGogASAIayAJajYCAAsLNQEAQYAICy4IAAAAEAAAABgAAAAgAAAAKAAAADAAAABAAAAAUAAAAIAAAAAAAQAA/Td6WFoA"},t=>{t.exports=e}],i={};function r(e){var s=i[e];if(void 0!==s)return s.exports;var o=i[e]={exports:{}};return t[e](o,o.exports,r),o.exports}r.d=(e,t)=>{for(var i in t)r.o(t,i)&&!r.o(e,i)&&Object.defineProperty(e,i,{enumerable:!0,get:t[i]})},r.o=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),r.r=e=>{"undefined"!=typeof Symbol&&Symbol.toStringTag&&Object.defineProperty(e,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(e,"__esModule",{value:!0})};var s={};return(()=>{r.r(s),r.d(s,{XzReadableStream:()=>o});var e=r(1);const t=globalThis.ReadableStream||r(2).ReadableStream;class i{constructor(e){this.exports=e.exports,this.memory=this.exports.memory,this.ptr=this.exports.create_context(),this._refresh(),this.bufSize=this.mem32[0],this.inStart=this.mem32[1]-this.ptr,this.inEnd=this.inStart+this.bufSize,this.outStart=this.mem32[4]-this.ptr}supplyInput(e){this._refresh(),this.mem8.subarray(this.inStart,this.inEnd).set(e,0),this.exports.supply_input(this.ptr,e.byteLength),this._refresh()}getNextOutput(){const e=this.exports.get_next_output(this.ptr);if(this._refresh(),0!==e&&1!==e)throw new Error(`get_next_output failed with error code ${e}`);return{outChunk:this.mem8.slice(this.outStart,this.outStart+this.mem32[5]),finished:1===e}}needsMoreInput(){return this.mem32[2]===this.mem32[3]}outputBufferIsFull(){return this.mem32[5]===this.bufSize}resetOutputBuffer(){this.outPos=this.mem32[5]=0}dispose(){this.exports.destroy_context(this.ptr),this.exports=null}_refresh(){this.memory.buffer!==this.mem8?.buffer&&(this.mem8=new Uint8Array(this.memory.buffer,this.ptr),this.mem32=new Uint32Array(this.memory.buffer,this.ptr))}}class o extends t{static _moduleInstancePromise;static _moduleInstance;static async _getModuleInstance(){const t=e.replace("data:application/wasm;base64,",""),i=Uint8Array.from(atob(t),(e=>e.charCodeAt(0))).buffer,r=await WebAssembly.instantiate(i,{});o._moduleInstance=r.instance}constructor(e){let t,r=null;const s=e.getReader();super({async start(e){o._moduleInstance||await(o._moduleInstancePromise||(o._moduleInstancePromise=o._getModuleInstance())),t=new i(o._moduleInstance)},async pull(e){if(t.needsMoreInput()){if(null===r||0===r.byteLength){const{done:e,value:t}=await s.read();e||(r=t)}const e=Math.min(t.bufSize,r.byteLength);t.supplyInput(r.subarray(0,e)),r=r.subarray(e)}const i=t.getNextOutput();e.enqueue(i.outChunk),t.resetOutputBuffer(),i.finished&&(t.dispose(),e.close())},cancel:()=>(t.dispose(),s.cancel())})}}})(),s})(),e.exports=r(i(772))},1308:(e,t)=>{let i=[0,1996959894,3993919788,2567524794,124634137,1886057615,3915621685,2657392035,249268274,2044508324,3772115230,2547177864,162941995,2125561021,3887607047,2428444049,498536548,1789927666,4089016648,2227061214,450548861,1843258603,4107580753,2211677639,325883990,1684777152,4251122042,2321926636,335633487,1661365465,4195302755,2366115317,997073096,1281953886,3579855332,2724688242,1006888145,1258607687,3524101629,2768942443,901097722,1119000684,3686517206,2898065728,853044451,1172266101,3705015759,2882616665,651767980,1373503546,3369554304,3218104598,565507253,1454621731,3485111705,3099436303,671266974,1594198024,3322730930,2970347812,795835527,1483230225,3244367275,3060149565,1994146192,31158534,2563907772,4023717930,1907459465,112637215,2680153253,3904427059,2013776290,251722036,2517215374,3775830040,2137656763,141376813,2439277719,3865271297,1802195444,476864866,2238001368,4066508878,1812370925,453092731,2181625025,4111451223,1706088902,314042704,2344532202,4240017532,1658658271,366619977,2362670323,4224994405,1303535960,984961486,2747007092,3569037538,1256170817,1037604311,2765210733,3554079995,1131014506,879679996,2909243462,3663771856,1141124467,855842277,2852801631,3708648649,1342533948,654459306,3188396048,3373015174,1466479909,544179635,3110523913,3462522015,1591671054,702138776,2966460450,3352799412,1504918807,783551873,3082640443,3233442989,3988292384,2596254646,62317068,1957810842,3939845945,2647816111,81470997,1943803523,3814918930,2489596804,225274430,2053790376,3826175755,2466906013,167816743,2097651377,4027552580,2265490386,503444072,1762050814,4150417245,2154129355,426522225,1852507879,4275313526,2312317920,282753626,1742555852,4189708143,2394877945,397917763,1622183637,3604390888,2714866558,953729732,1340076626,3518719985,2797360999,1068828381,1219638859,3624741850,2936675148,906185462,1090812512,3747672003,2825379669,829329135,1181335161,3412177804,3160834842,628085408,1382605366,3423369109,3138078467,570562233,1426400815,3317316542,2998733608,733239954,1555261956,3268935591,3050360625,752459403,1541320221,2607071920,3965973030,1969922972,40735498,2617837225,3943577151,1913087877,83908371,2512341634,3803740692,2075208622,213261112,2463272603,3855990285,2094854071,198958881,2262029012,4057260610,1759359992,534414190,2176718541,4139329115,1873836001,414664567,2282248934,4279200368,1711684554,285281116,2405801727,4167216745,1634467795,376229701,2685067896,3608007406,1308918612,956543938,2808555105,3495958263,1231636301,1047427035,2932959818,3654703836,1088359270,936918e3,2847714899,3736837829,1202900863,817233897,3183342108,3401237130,1404277552,615818150,3134207493,3453421203,1423857449,601450431,3009837614,3294710456,1567103746,711928724,3020668471,3272380065,1510334235,755167117];"undefined"!=typeof Int32Array&&(i=new Int32Array(i)),t.A=(e,t)=>{let r=0===t?0:-1^t;for(let t=0;t>>8;return-1^r}},1447:(e,t,i)=>{var r=i(9805),s=i(3269),o=i(4823),n=i(7293),a=i(1998),c=-2,l=12,h=30;function d(e){return(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24)}function u(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new r.Buf16(320),this.work=new r.Buf16(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}function f(e){var t;return e&&e.state?(t=e.state,e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new r.Buf32(852),t.distcode=t.distdyn=new r.Buf32(592),t.sane=1,t.back=-1,0):c}function p(e){var t;return e&&e.state?((t=e.state).wsize=0,t.whave=0,t.wnext=0,f(e)):c}function g(e,t){var i,r;return e&&e.state?(r=e.state,t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?c:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,p(e))):c}function m(e,t){var i,r;return e?(r=new u,e.state=r,r.window=null,0!==(i=g(e,t))&&(e.state=null),i):c}var w,b,F=!0;function v(e){if(F){var t;for(w=new r.Buf32(512),b=new r.Buf32(32),t=0;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(a(1,e.lens,0,288,w,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;a(2,e.lens,0,32,b,0,e.work,{bits:5}),F=!1}e.lencode=w,e.lenbits=9,e.distcode=b,e.distbits=5}function y(e,t,i,s){var o,n=e.state;return null===n.window&&(n.wsize=1<=n.wsize?(r.arraySet(n.window,t,i-n.wsize,n.wsize,0),n.wnext=0,n.whave=n.wsize):((o=n.wsize-n.wnext)>s&&(o=s),r.arraySet(n.window,t,i-s,o,n.wnext),(s-=o)?(r.arraySet(n.window,t,i-s,s,0),n.wnext=s,n.whave=n.wsize):(n.wnext+=o,n.wnext===n.wsize&&(n.wnext=0),n.whave>>8&255,i.check=o(i.check,P,2,0),b=0,F=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&b)<<8)+(b>>8))%31){e.msg="incorrect header check",i.mode=h;break}if(8!=(15&b)){e.msg="unknown compression method",i.mode=h;break}if(F-=4,B=8+(15&(b>>>=4)),0===i.wbits)i.wbits=B;else if(B>i.wbits){e.msg="invalid window size",i.mode=h;break}i.dmax=1<>8&1),512&i.flags&&(P[0]=255&b,P[1]=b>>>8&255,i.check=o(i.check,P,2,0)),b=0,F=0,i.mode=3;case 3:for(;F<32;){if(0===m)break e;m--,b+=u[p++]<>>8&255,P[2]=b>>>16&255,P[3]=b>>>24&255,i.check=o(i.check,P,4,0)),b=0,F=0,i.mode=4;case 4:for(;F<16;){if(0===m)break e;m--,b+=u[p++]<>8),512&i.flags&&(P[0]=255&b,P[1]=b>>>8&255,i.check=o(i.check,P,2,0)),b=0,F=0,i.mode=5;case 5:if(1024&i.flags){for(;F<16;){if(0===m)break e;m--,b+=u[p++]<>>8&255,i.check=o(i.check,P,2,0)),b=0,F=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&((_=i.length)>m&&(_=m),_&&(i.head&&(B=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Array(i.head.extra_len)),r.arraySet(i.head.extra,u,p,_,B)),512&i.flags&&(i.check=o(i.check,u,_,p)),m-=_,p+=_,i.length-=_),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===m)break e;_=0;do{B=u[p+_++],i.head&&B&&i.length<65536&&(i.head.name+=String.fromCharCode(B))}while(B&&_>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=l;break;case 10:for(;F<32;){if(0===m)break e;m--,b+=u[p++]<>>=7&F,F-=7&F,i.mode=27;break}for(;F<3;){if(0===m)break e;m--,b+=u[p++]<>>=1)){case 0:i.mode=14;break;case 1:if(v(i),i.mode=20,6===t){b>>>=2,F-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=h}b>>>=2,F-=2;break;case 14:for(b>>>=7&F,F-=7&F;F<32;){if(0===m)break e;m--,b+=u[p++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=h;break}if(i.length=65535&b,b=0,F=0,i.mode=15,6===t)break e;case 15:i.mode=16;case 16:if(_=i.length){if(_>m&&(_=m),_>w&&(_=w),0===_)break e;r.arraySet(f,u,p,_,g),m-=_,p+=_,w-=_,g+=_,i.length-=_;break}i.mode=l;break;case 17:for(;F<14;){if(0===m)break e;m--,b+=u[p++]<>>=5,F-=5,i.ndist=1+(31&b),b>>>=5,F-=5,i.ncode=4+(15&b),b>>>=4,F-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=h;break}i.have=0,i.mode=18;case 18:for(;i.have>>=3,F-=3}for(;i.have<19;)i.lens[H[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,L={bits:i.lenbits},D=a(0,i.lens,0,19,i.lencode,0,i.work,L),i.lenbits=L.bits,D){e.msg="invalid code lengths set",i.mode=h;break}i.have=0,i.mode=19;case 19:for(;i.have>>16&255,E=65535&z,!((I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>>=I,F-=I,i.lens[i.have++]=E;else{if(16===E){for(T=I+2;F>>=I,F-=I,0===i.have){e.msg="invalid bit length repeat",i.mode=h;break}B=i.lens[i.have-1],_=3+(3&b),b>>>=2,F-=2}else if(17===E){for(T=I+3;F>>=I)),b>>>=3,F-=3}else{for(T=I+7;F>>=I)),b>>>=7,F-=7}if(i.have+_>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=h;break}for(;_--;)i.lens[i.have++]=B}}if(i.mode===h)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=h;break}if(i.lenbits=9,L={bits:i.lenbits},D=a(1,i.lens,0,i.nlen,i.lencode,0,i.work,L),i.lenbits=L.bits,D){e.msg="invalid literal/lengths set",i.mode=h;break}if(i.distbits=6,i.distcode=i.distdyn,L={bits:i.distbits},D=a(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,L),i.distbits=L.bits,D){e.msg="invalid distances set",i.mode=h;break}if(i.mode=20,6===t)break e;case 20:i.mode=21;case 21:if(m>=6&&w>=258){e.next_out=g,e.avail_out=w,e.next_in=p,e.avail_in=m,i.hold=b,i.bits=F,n(e,C),g=e.next_out,f=e.output,w=e.avail_out,p=e.next_in,u=e.input,m=e.avail_in,b=i.hold,F=i.bits,i.mode===l&&(i.back=-1);break}for(i.back=0;S=(z=i.lencode[b&(1<>>16&255,E=65535&z,!((I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>N)])>>>16&255,E=65535&z,!(N+(I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>>=N,F-=N,i.back+=N}if(b>>>=I,F-=I,i.back+=I,i.length=E,0===S){i.mode=26;break}if(32&S){i.back=-1,i.mode=l;break}if(64&S){e.msg="invalid literal/length code",i.mode=h;break}i.extra=15&S,i.mode=22;case 22:if(i.extra){for(T=i.extra;F>>=i.extra,F-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;S=(z=i.distcode[b&(1<>>16&255,E=65535&z,!((I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>N)])>>>16&255,E=65535&z,!(N+(I=z>>>24)<=F);){if(0===m)break e;m--,b+=u[p++]<>>=N,F-=N,i.back+=N}if(b>>>=I,F-=I,i.back+=I,64&S){e.msg="invalid distance code",i.mode=h;break}i.offset=E,i.extra=15&S,i.mode=24;case 24:if(i.extra){for(T=i.extra;F>>=i.extra,F-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=h;break}i.mode=25;case 25:if(0===w)break e;if(_=C-w,i.offset>_){if((_=i.offset-_)>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=h;break}_>i.wnext?(_-=i.wnext,x=i.wsize-_):x=i.wnext-_,_>i.length&&(_=i.length),k=i.window}else k=f,x=g-i.offset,_=i.length;_>w&&(_=w),w-=_,i.length-=_;do{f[g++]=k[x++]}while(--_);0===i.length&&(i.mode=21);break;case 26:if(0===w)break e;f[g++]=i.length,w--,i.mode=21;break;case 27:if(i.wrap){for(;F<32;){if(0===m)break e;m--,b|=u[p++]<{var r={};(0,i(9805).assign)(r,i(3303),i(7083),i(9681)),e.exports=r},1739:function(e,t,i){var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),n=0;n{var r=i(9805),s=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){s=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var n=new r.Buf8(256),a=0;a<256;a++)n[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;function c(e,t){if(t<65534&&(e.subarray&&o||!e.subarray&&s))return String.fromCharCode.apply(null,r.shrinkBuf(e,t));for(var i="",n=0;n>>6,t[n++]=128|63&i):i<65536?(t[n++]=224|i>>>12,t[n++]=128|i>>>6&63,t[n++]=128|63&i):(t[n++]=240|i>>>18,t[n++]=128|i>>>12&63,t[n++]=128|i>>>6&63,t[n++]=128|63&i);return t},t.buf2binstring=function(e){return c(e,e.length)},t.binstring2buf=function(e){for(var t=new r.Buf8(e.length),i=0,s=t.length;i4)l[r++]=65533,i+=o-1;else{for(s&=2===o?31:3===o?15:7;o>1&&i1?l[r++]=65533:s<65536?l[r++]=s:(s-=65536,l[r++]=55296|s>>10&1023,l[r++]=56320|1023&s)}return c(l,r)},t.utf8border=function(e,t){var i;for((t=t||e.length)>e.length&&(t=e.length),i=t-1;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+n[e[i]]>t?i:t}},1998:(e,t,i)=>{var r=i(9805),s=[3,4,5,6,7,8,9,10,11,13,15,17,19,23,27,31,35,43,51,59,67,83,99,115,131,163,195,227,258,0,0],o=[16,16,16,16,16,16,16,16,17,17,17,17,18,18,18,18,19,19,19,19,20,20,20,20,21,21,21,21,16,72,78],n=[1,2,3,4,5,7,9,13,17,25,33,49,65,97,129,193,257,385,513,769,1025,1537,2049,3073,4097,6145,8193,12289,16385,24577,0,0],a=[16,16,16,16,17,17,18,18,19,19,20,20,21,21,22,22,23,23,24,24,25,25,26,26,27,27,28,28,29,29,64,64];e.exports=function(e,t,i,c,l,h,d,u){var f,p,g,m,w,b,F,v,y,A=u.bits,C=0,_=0,x=0,k=0,I=0,S=0,E=0,N=0,M=0,R=0,B=null,D=0,L=new r.Buf16(16),T=new r.Buf16(16),z=null,P=0;for(C=0;C<=15;C++)L[C]=0;for(_=0;_=1&&0===L[k];k--);if(I>k&&(I=k),0===k)return l[h++]=20971520,l[h++]=20971520,u.bits=1,0;for(x=1;x0&&(0===e||1!==k))return-1;for(T[1]=0,C=1;C<15;C++)T[C+1]=T[C]+L[C];for(_=0;_852||2===e&&M>592)return 1;for(;;){F=C-E,d[_]b?(v=z[P+d[_]],y=B[D+d[_]]):(v=96,y=0),f=1<>E)+(p-=f)]=F<<24|v<<16|y}while(0!==p);for(f=1<>=1;if(0!==f?(R&=f-1,R+=f):R=0,_++,0===--L[C]){if(C===k)break;C=t[i+d[_]]}if(C>I&&(R&m)!==g){for(0===E&&(E=I),w+=x,N=1<<(S=C-E);S+E852||2===e&&M>592)return 1;l[g=R&m]=I<<24|S<<16|w-h}}return 0!==R&&(l[w+R]=C-E<<24|64<<16),u.bits=I,0}},2151:e=>{var t={utf8:{stringToBytes:function(e){return t.bin.stringToBytes(unescape(encodeURIComponent(e)))},bytesToString:function(e){return decodeURIComponent(escape(t.bin.bytesToString(e)))}},bin:{stringToBytes:function(e){for(var t=[],i=0;i{Object.defineProperty(t,"__esModule",{value:!0}),t.unzip=function(e){return(0,r.inflate)(e)};const r=i(1668)},2324:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e=256){this.total_freq=e,this.max_sym=e-1,this.S=[],this.F=[];for(let e=0;e<=this.max_sym;e++)this.S[e]=e,this.F[e]=1}ModelDecode(e,t){const i=t.RangeGetFrequency(this.total_freq);let r=0,s=0;for(;r+this.F[s]<=i;)r+=this.F[s++];t.RangeDecode(e,r,this.F[s],this.total_freq),this.F[s]+=16,this.total_freq+=16,this.total_freq>65519&&this.ModelRenormalise();const o=this.S[s];if(s>0&&this.F[s]>this.F[s-1]){let e=this.F[s];this.F[s]=this.F[s-1],this.F[s-1]=e,e=this.S[s],this.S[s]=this.S[s-1],this.S[s-1]=e}return o}ModelRenormalise(){this.total_freq=0;for(let e=0;e<=this.max_sym;e++)this.F[e]-=Math.floor(this.F[e]/2),this.total_freq+=this.F[e]}ModelEncode(e,t,i){let r=0;for(var s=0;this.S[s]!=i;s++)r+=this.F[s];if(t.RangeEncode(e,r,this.F[s],this.total_freq),this.F[s]+=16,this.total_freq+=16,this.total_freq>65519&&this.ModelRenormalise(),i=this.S[s],s>0&&this.F[s]>this.F[s-1]){let e=this.F[s];this.F[s]=this.F[s-1],this.F[s-1]=e,e=this.S[s],this.S[s]=this.S[s-1],this.S[s-1]=e}}}},2549:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.TWO_PWR_56_DBL=t.TWO_PWR_24_DBL=t.TWO_PWR_64_DBL=t.TWO_PWR_32_DBL=t.TWO_PWR_16_DBL=void 0,t.itf8Size=function(e){return-128&e?-16384&e?-2097152&e?-268435456&e?5:4:3:2:1},t.parseItf8=function(e,t){let i=t;const r=e[i];let s;return r<128?(s=r,i+=1):r<192?(s=(63&r)<<8|e[i+1],i+=2):r<224?(s=(31&r)<<16|e[i+1]<<8|e[i+2],i+=3):r<240?(s=(15&r)<<24|e[i+1]<<16|e[i+2]<<8|e[i+3],i+=4):(s=(15&r)<<28|e[i+1]<<20|e[i+2]<<12|e[i+3]<<4|15&e[i+4],i+=5),[s,i-t]},t.parseLtf8=function(e,i){let r=i;const s=e[r];let o;return s<128?(o=s,r+=1):s<192?(o=16383&(s<<8|e[r+1]),r+=2):s<224?(o=(63&s)<<16|e[r+1]<<8|e[r+2],r+=3):s<240?(o=(31&s)<<24|e[r+1]<<16|e[r+2]<<8|e[r+3],r+=4):s<248?(o=(15&e[r])*t.TWO_PWR_32_DBL+(e[r+1]<<24|e[r+2]<<16|e[r+3]<<8|e[r+4]),r+=5):s<252?(o=((7&e[r])<<8|e[r+1])*t.TWO_PWR_32_DBL+(e[r+2]<<24|e[r+3]<<16|e[r+4]<<8|e[r+5]),r+=6):s<254?(o=((3&e[r])<<16|e[r+1]<<8|e[r+2])*t.TWO_PWR_32_DBL+(e[r+3]<<24|e[r+4]<<16|e[r+5]<<8|e[r+6]),r+=7):s<255?(o=(e[r+1]<<24|e[r+2]<<16|e[r+3]<<8|e[r+4])*t.TWO_PWR_32_DBL+(e[r+5]<<24|e[r+6]<<16|e[r+7]<<8|e[r+8]),r+=8):(o=e[r+1]*t.TWO_PWR_56_DBL+(e[r+2]<<24|e[r+3]<<16|e[r+4]<<8|e[r+5])*t.TWO_PWR_32_DBL+(e[r+6]<<24|e[r+7]<<16|e[r+8]<<8|e[r+9]),r+=9),[o,r-i]},t.parseItem=function(e,t,i=0,r=0){const{offset:s,value:o}=t(e,i);return{...o,_endPosition:s+r,_size:s-i}},t.tinyMemoize=function(e,t){const i=e.prototype[t],r=`_memo_${t}`;e.prototype[t]=function(){if(!(r in this)){const e=i.call(this);this[r]=e,Promise.resolve(e).catch((()=>{delete this[r]}))}return this[r]}},t.sequenceMD5=function(e){return(0,s.default)(e.toUpperCase().replaceAll(/[^\u0021-\u007e]/g,""))};const s=r(i(3503));t.TWO_PWR_16_DBL=65536,t.TWO_PWR_32_DBL=t.TWO_PWR_16_DBL*t.TWO_PWR_16_DBL,t.TWO_PWR_64_DBL=t.TWO_PWR_32_DBL*t.TWO_PWR_32_DBL,t.TWO_PWR_24_DBL=1<<24,t.TWO_PWR_56_DBL=t.TWO_PWR_24_DBL*t.TWO_PWR_32_DBL},2616:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(9846);t.default=class{constructor(e,t={}){this.filename=e}async read(e,t=0){const i=new Uint8Array(e),s=await(0,r.open)(this.filename,"r"),o=await s.read(i,0,e,t);return await s.close(),o.buffer.subarray(0,o.bytesRead)}async readFile(e){const t=await(0,r.readFile)(this.filename,e);return"string"==typeof t?t:new Uint8Array(t)}async stat(){return(0,r.stat)(this.filename)}async close(){}}},2660:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e,t){return function(e,t){const i=e.ReadUint7(),r=function(e){const t={max_sym:0};if(5!=e.ReadByte())return void console.error("Invalid FQZComp version number");const i=e.ReadByte(),r=i&g?e.ReadByte():1;let s=i.nparam>1?i.nparam-1:0;const o=new Array(256);if(i&m)s=e.ReadByte(),a(e,o,256);else{for(var n=0;n0&&(t.sel=new o.default(e.max_sel+1)),t}(r),h=new s.default(e);h.RangeStartDecode(e);const d=new Uint8Array(i),u={qctx:0,prevq:0,delta:0,p:0,s:0,x:0,len:0,is_dup:0,rec:0};let f=0;for(;f0&&l.dup.ModelDecode(e,h)){for(let e=0;e>4,t.qshift=15&i,i=e.ReadByte(),t.qloc=i>>4,t.sloc=15&i,i=e.ReadByte(),t.ploc=i>>4,t.dloc=15&i,t.qmap=new Array(256),t.pflags&d)for(var r=0;r0&&t.pflags&p)a(e,t.qtab,256);else for(r=0;r<256;r++)t.qtab[r]=r;return t.ptab=new Array(1024),t.pflags&u&&a(e,t.ptab,1024),t.dtab=new Array(256),t.pflags&f&&a(e,t.dtab,256),t}function v(e,t,i,r,s,o){s.s=i.max_sel>0?r.sel.ModelDecode(e,t):0,s.x=i.stab[s.s];const n=i.params[s.x];if(n.fixed_len>=0){var a=r.len[0].ModelDecode(e,t);a|=r.len[1].ModelDecode(e,t)<<8,a|=r.len[2].ModelDecode(e,t)<<16,a|=r.len[3].ModelDecode(e,t)<<24,n.fixed_len>0&&(n.fixed_len=-a)}else a=-n.fixed_len;s.len=a,i.do_rev&&(o[s.rec]=r.rev.ModelDecode(e,t)),s.is_dup=0,n.pflags&c&&r.dup.ModelDecode(e,t)&&(s.is_dup=1),s.p=a,s.delta=0,s.qctx=0,s.prevq=0,s.rec++}},2670:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i=0){if(0===e.length)return t.fill(0),t;const r=new h(e,i),d=r.get();if(0!==d&&1!==d)throw new s.CramMalformedError(`Invalid rANS order ${d}`);if(r.getInt()!==r.remaining()-l)throw new s.CramMalformedError("Incorrect input length.");const u=r.getInt(),f=new h(t||new Uint8Array(u));if(f.length{(0,n.tinyMemoize)(l,e)}))},2867:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i,r){const n=t.remaining();let a=e.getInt(),c=e.getInt(),l=e.getInt(),h=e.getInt();const d=n>>2;let u=0,f=d,p=2*d,g=3*d,m=0,w=0,b=0,F=0;for(;u{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t=0,i=0){0!==i?(this.buf=new Uint8Array(i),this.length=i):(this.buf=e,this.length=e.length),this.dataView=new DataView(this.buf.buffer),this.pos=t}EOF(){return this.pos>=this.length}ReadData(e){const t=this.buf.slice(this.pos,this.pos+e);return this.pos+=e,t}ReadByte(){const e=this.buf[this.pos];return this.pos++,e}ReadChar(){const e=this.buf[this.pos];return this.pos++,String.fromCharCode(e)}ReadUint16(){let e=this.ReadByte();return e|=this.ReadByte()<<8,e}ReadUint32(){const e=this.dataView.getInt32(this.pos,!0);return this.pos+=4,e}ReadString(){let e,t="";do{e=this.buf[this.pos++],e&&(t+=String.fromCharCode(e))}while(e);return t}ReadUint7(){let e,t=0;do{e=this.ReadByte(),t=t<<7|127&e}while(128&e);return t}ReadITF8(){let e=this.buf[this.pos];return this.pos++,e>=240?(e=(15&e)<<28,e+=(this.buf[this.pos+0]<<20)+(this.buf[this.pos+1]<<12)+(this.buf[this.pos+2]<<4)+(this.buf[this.pos+3]>>4),this.pos+=4):e>=224?(e=(15&e)<<24,e+=(this.buf[this.pos+0]<<16)+(this.buf[this.pos+1]<<8)+(0|this.buf[this.pos+2]),this.pos+=3):e>=192?(e=(31&e)<<16,e+=(this.buf[this.pos+0]<<8)+(0|this.buf[this.pos+1]),this.pos+=2):e>=128&&(e=(63&e)<<8,e+=this.buf[this.pos],this.pos++),e}}},3269:e=>{e.exports=function(e,t,i,r){for(var s=65535&e,o=e>>>16&65535,n=0;0!==i;){i-=n=i>2e3?2e3:i;do{o=o+(s=s+t[r++]|0)|0}while(--n);s%=65521,o%=65521}return s|o<<16}},3303:(e,t,i)=>{var r=i(8411),s=i(9805),o=i(1996),n=i(4674),a=i(4442),c=Object.prototype.toString;function l(e){if(!(this instanceof l))return new l(e);this.options=s.assign({level:-1,method:8,chunkSize:16384,windowBits:15,memLevel:8,strategy:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>0?t.windowBits=-t.windowBits:t.gzip&&t.windowBits>0&&t.windowBits<16&&(t.windowBits+=16),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new a,this.strm.avail_out=0;var i=r.deflateInit2(this.strm,t.level,t.method,t.windowBits,t.memLevel,t.strategy);if(0!==i)throw new Error(n[i]);if(t.header&&r.deflateSetHeader(this.strm,t.header),t.dictionary){var h;if(h="string"==typeof t.dictionary?o.string2buf(t.dictionary):"[object ArrayBuffer]"===c.call(t.dictionary)?new Uint8Array(t.dictionary):t.dictionary,0!==(i=r.deflateSetDictionary(this.strm,h)))throw new Error(n[i]);this._dict_set=!0}}function h(e,t){var i=new l(t);if(i.push(e,!0),i.err)throw i.msg||n[i.err];return i.result}l.prototype.push=function(e,t){var i,n,a=this.strm,l=this.options.chunkSize;if(this.ended)return!1;n=t===~~t?t:!0===t?4:0,"string"==typeof e?a.input=o.string2buf(e):"[object ArrayBuffer]"===c.call(e)?a.input=new Uint8Array(e):a.input=e,a.next_in=0,a.avail_in=a.input.length;do{if(0===a.avail_out&&(a.output=new s.Buf8(l),a.next_out=0,a.avail_out=l),1!==(i=r.deflate(a,n))&&0!==i)return this.onEnd(i),this.ended=!0,!1;0!==a.avail_out&&(0!==a.avail_in||4!==n&&2!==n)||("string"===this.options.to?this.onData(o.buf2binstring(s.shrinkBuf(a.output,a.next_out))):this.onData(s.shrinkBuf(a.output,a.next_out)))}while((a.avail_in>0||0===a.avail_out)&&1!==i);return 4===n?(i=r.deflateEnd(this.strm),this.onEnd(i),this.ended=!0,0===i):2!==n||(this.onEnd(0),a.avail_out=0,!0)},l.prototype.onData=function(e){this.chunks.push(e)},l.prototype.onEnd=function(e){0===e&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},t.Deflate=l,t.deflate=h,t.deflateRaw=function(e,t){return(t=t||{}).raw=!0,h(e,t)},t.gzip=function(e,t){return(t=t||{}).gzip=!0,h(e,t)}},3503:(e,t,i)=>{var r,s,o,n,a;r=i(3939),s=i(2151).utf8,o=i(652),n=i(2151).bin,(a=function(e,t){e.constructor==String?e=t&&"binary"===t.encoding?n.stringToBytes(e):s.stringToBytes(e):o(e)?e=Array.prototype.slice.call(e,0):Array.isArray(e)||e.constructor===Uint8Array||(e=e.toString());for(var i=r.bytesToWords(e),c=8*e.length,l=1732584193,h=-271733879,d=-1732584194,u=271733878,f=0;f>>24)|4278255360&(i[f]<<24|i[f]>>>8);i[c>>>5]|=128<>>9<<4)]=c;var p=a._ff,g=a._gg,m=a._hh,w=a._ii;for(f=0;f>>0,h=h+F>>>0,d=d+v>>>0,u=u+y>>>0}return r.endian([l,h,d,u])})._ff=function(e,t,i,r,s,o,n){var a=e+(t&i|~t&r)+(s>>>0)+n;return(a<>>32-o)+t},a._gg=function(e,t,i,r,s,o,n){var a=e+(t&r|i&~r)+(s>>>0)+n;return(a<>>32-o)+t},a._hh=function(e,t,i,r,s,o,n){var a=e+(t^i^r)+(s>>>0)+n;return(a<>>32-o)+t},a._ii=function(e,t,i,r,s,o,n){var a=e+(i^(t|~r))+(s>>>0)+n;return(a<>>32-o)+t},a._blocksize=16,a._digestsize=16,e.exports=function(e,t){if(null==e)throw new Error("Illegal argument "+e);var i=r.wordsToBytes(a(e,t));return t&&t.asBytes?i:t&&t.asString?n.bytesToString(i):r.bytesToHex(i)}},3665:(e,t,i)=>{var r=i(9805);function s(e){for(var t=e.length;--t>=0;)e[t]=0}var o=[0,0,0,0,0,0,0,0,1,1,1,1,2,2,2,2,3,3,3,3,4,4,4,4,5,5,5,5,0],n=[0,0,0,0,1,1,2,2,3,3,4,4,5,5,6,6,7,7,8,8,9,9,10,10,11,11,12,12,13,13],a=[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7],c=[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15],l=new Array(576);s(l);var h=new Array(60);s(h);var d=new Array(512);s(d);var u=new Array(256);s(u);var f=new Array(29);s(f);var p,g,m,w=new Array(30);function b(e,t,i,r,s){this.static_tree=e,this.extra_bits=t,this.extra_base=i,this.elems=r,this.max_length=s,this.has_stree=e&&e.length}function F(e,t){this.dyn_tree=e,this.max_code=0,this.stat_desc=t}function v(e){return e<256?d[e]:d[256+(e>>>7)]}function y(e,t){e.pending_buf[e.pending++]=255&t,e.pending_buf[e.pending++]=t>>>8&255}function A(e,t,i){e.bi_valid>16-i?(e.bi_buf|=t<>16-e.bi_valid,e.bi_valid+=i-16):(e.bi_buf|=t<>>=1,i<<=1}while(--t>0);return i>>>1}function x(e,t,i){var r,s,o=new Array(16),n=0;for(r=1;r<=15;r++)o[r]=n=n+i[r-1]<<1;for(s=0;s<=t;s++){var a=e[2*s+1];0!==a&&(e[2*s]=_(o[a]++,a))}}function k(e){var t;for(t=0;t<286;t++)e.dyn_ltree[2*t]=0;for(t=0;t<30;t++)e.dyn_dtree[2*t]=0;for(t=0;t<19;t++)e.bl_tree[2*t]=0;e.dyn_ltree[512]=1,e.opt_len=e.static_len=0,e.last_lit=e.matches=0}function I(e){e.bi_valid>8?y(e,e.bi_buf):e.bi_valid>0&&(e.pending_buf[e.pending++]=e.bi_buf),e.bi_buf=0,e.bi_valid=0}function S(e,t,i,r){var s=2*t,o=2*i;return e[s]>1;i>=1;i--)E(e,o,i);s=c;do{i=e.heap[1],e.heap[1]=e.heap[e.heap_len--],E(e,o,1),r=e.heap[1],e.heap[--e.heap_max]=i,e.heap[--e.heap_max]=r,o[2*s]=o[2*i]+o[2*r],e.depth[s]=(e.depth[i]>=e.depth[r]?e.depth[i]:e.depth[r])+1,o[2*i+1]=o[2*r+1]=s,e.heap[1]=s++,E(e,o,1)}while(e.heap_len>=2);e.heap[--e.heap_max]=e.heap[1],function(e,t){var i,r,s,o,n,a,c=t.dyn_tree,l=t.max_code,h=t.stat_desc.static_tree,d=t.stat_desc.has_stree,u=t.stat_desc.extra_bits,f=t.stat_desc.extra_base,p=t.stat_desc.max_length,g=0;for(o=0;o<=15;o++)e.bl_count[o]=0;for(c[2*e.heap[e.heap_max]+1]=0,i=e.heap_max+1;i<573;i++)(o=c[2*c[2*(r=e.heap[i])+1]+1]+1)>p&&(o=p,g++),c[2*r+1]=o,r>l||(e.bl_count[o]++,n=0,r>=f&&(n=u[r-f]),a=c[2*r],e.opt_len+=a*(o+n),d&&(e.static_len+=a*(h[2*r+1]+n)));if(0!==g){do{for(o=p-1;0===e.bl_count[o];)o--;e.bl_count[o]--,e.bl_count[o+1]+=2,e.bl_count[p]--,g-=2}while(g>0);for(o=p;0!==o;o--)for(r=e.bl_count[o];0!==r;)(s=e.heap[--i])>l||(c[2*s+1]!==o&&(e.opt_len+=(o-c[2*s+1])*c[2*s],c[2*s+1]=o),r--)}}(e,t),x(o,l,e.bl_count)}function R(e,t,i){var r,s,o=-1,n=t[1],a=0,c=7,l=4;for(0===n&&(c=138,l=3),t[2*(i+1)+1]=65535,r=0;r<=i;r++)s=n,n=t[2*(r+1)+1],++a>=7;r<30;r++)for(w[r]=s<<7,e=0;e<1<0?(2===e.strm.data_type&&(e.strm.data_type=function(e){var t,i=4093624447;for(t=0;t<=31;t++,i>>>=1)if(1&i&&0!==e.dyn_ltree[2*t])return 0;if(0!==e.dyn_ltree[18]||0!==e.dyn_ltree[20]||0!==e.dyn_ltree[26])return 1;for(t=32;t<256;t++)if(0!==e.dyn_ltree[2*t])return 1;return 0}(e)),M(e,e.l_desc),M(e,e.d_desc),n=function(e){var t;for(R(e,e.dyn_ltree,e.l_desc.max_code),R(e,e.dyn_dtree,e.d_desc.max_code),M(e,e.bl_desc),t=18;t>=3&&0===e.bl_tree[2*c[t]+1];t--);return e.opt_len+=3*(t+1)+5+5+4,t}(e),s=e.opt_len+3+7>>>3,(o=e.static_len+3+7>>>3)<=s&&(s=o)):s=o=i+5,i+4<=s&&-1!==t?L(e,t,i,r):4===e.strategy||o===s?(A(e,2+(r?1:0),3),N(e,l,h)):(A(e,4+(r?1:0),3),function(e,t,i,r){var s;for(A(e,t-257,5),A(e,i-1,5),A(e,r-4,4),s=0;s>>8&255,e.pending_buf[e.d_buf+2*e.last_lit+1]=255&t,e.pending_buf[e.l_buf+e.last_lit]=255&i,e.last_lit++,0===t?e.dyn_ltree[2*i]++:(e.matches++,t--,e.dyn_ltree[2*(u[i]+256+1)]++,e.dyn_dtree[2*v(t)]++),e.last_lit===e.lit_bufsize-1},t._tr_align=function(e){A(e,2,3),C(e,256,l),function(e){16===e.bi_valid?(y(e,e.bi_buf),e.bi_buf=0,e.bi_valid=0):e.bi_valid>=8&&(e.pending_buf[e.pending++]=255&e.bi_buf,e.bi_buf>>=8,e.bi_valid-=8)}(e)}},3939:e=>{var t,i;t="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",i={rotl:function(e,t){return e<>>32-t},rotr:function(e,t){return e<<32-t|e>>>t},endian:function(e){if(e.constructor==Number)return 16711935&i.rotl(e,8)|4278255360&i.rotl(e,24);for(var t=0;t0;e--)t.push(Math.floor(256*Math.random()));return t},bytesToWords:function(e){for(var t=[],i=0,r=0;i>>5]|=e[i]<<24-r%32;return t},wordsToBytes:function(e){for(var t=[],i=0;i<32*e.length;i+=8)t.push(e[i>>>5]>>>24-i%32&255);return t},bytesToHex:function(e){for(var t=[],i=0;i>>4).toString(16)),t.push((15&e[i]).toString(16));return t.join("")},hexToBytes:function(e){for(var t=[],i=0;i>>6*(3-o)&63)):i.push("=");return i.join("")},base64ToBytes:function(e){e=e.replace(/[^A-Z0-9+\/]/gi,"");for(var i=[],r=0,s=0;r>>6-2*s);return i}},e.exports=i},4056:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6761),n=i(6272);class a extends s.default{constructor(e,t){if(super(e,t),this.codes={},this.codeBook={},this.sortedCodes=[],this.sortedValuesByBitCode=[],this.sortedBitCodes=[],this.sortedBitLengthsByBitCode=[],this.bitCodeToValue=[],!["byte","int"].includes(this.dataType))throw new TypeError(`${this.dataType} decoding not yet implemented by HUFFMAN_INT codec`);this.buildCodeBook(),this.buildCodes(),this.buildCaches(),0===this.sortedCodes[0].bitLength&&(this._decode=this._decodeZeroLengthCode)}buildCodeBook(){let e=new Array(this.parameters.numCodes);for(let t=0;te.bitLength-t.bitLength||e.symbol-t.symbol)),this.codeBook={},e.forEach((e=>{this.codeBook[e.bitLength]||(this.codeBook[e.bitLength]=[]),this.codeBook[e.bitLength].push(e.symbol)}))}buildCodes(){this.codes={};let e=0,t=-1;Object.entries(this.codeBook).forEach((([i,r])=>{const s=Number.parseInt(i,10);r.forEach((i=>{const r={bitLength:s,value:i,bitCode:0};t+=1;const o=s-e;if(t<<=o,r.bitCode=t,e+=o,function(e){let t=e-(e>>1)&1431655765;return t=(858993459&t)+(t>>2&858993459),16843009*(t+(t>>4)&252645135)>>24}(t)>s)throw new n.CramMalformedError("Symbol out of range");this.codes[i]=r}))}))}buildCaches(){this.sortedCodes=Object.values(this.codes).sort(((e,t)=>e.bitLength-t.bitLength||e.bitCode-t.bitCode)),this.sortedValuesByBitCode=this.sortedCodes.map((e=>e.value)),this.sortedBitCodes=this.sortedCodes.map((e=>e.bitCode)),this.sortedBitLengthsByBitCode=this.sortedCodes.map((e=>e.bitLength));const e=Math.max(...this.sortedBitCodes);this.bitCodeToValue=new Array(e+1).fill(-1);for(let e=0;e-1&&this.sortedBitLengthsByBitCode[i]===t)return this.sortedValuesByBitCode[i];for(let i=e;this.sortedCodes[i+1].bitLength===t&&i{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t){this.parameters=e,this.dataType=t}}},4442:e=>{e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},4562:function(e,t,i){var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),n=0;ne.charCodeAt(0))))};const c=a(i(9505)),l=n(i(2660)),h=n(i(8594)),d=n(i(9313)),u=n(i(1739))},4652:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e){this.low=0,this.range=4294967295,this.code=0,this.FFnum=0,this.carry=0,this.cache=0}RangeStartDecode(e){for(let t=0;t<5;t++)this.code=(this.code<<8)+e.ReadByte();this.code&=4294967295,this.code>>>=0}RangeGetFrequency(e){return this.range=Math.floor(this.range/e),Math.floor(this.code/this.range)}RangeDecode(e,t,i,r){for(this.code-=t*this.range,this.range*=i;this.range<1<<24;)this.range*=256,this.code=256*this.code+e.ReadByte()}RangeShiftLow(e){if(this.low<4278190080|this.carry){for(e.WriteByte(this.cache+this.carry);this.FFnum;)e.WriteByte(this.carry-1),this.FFnum--;this.cache=this.low>>>24,this.carry=0}else this.FFnum++;this.low<<=8,this.low>>>=0}RangeEncode(e,t,i,r){const s=this.low;for(this.range=Math.floor(this.range/r),this.low+=t*this.range,this.low>>>=0,this.range*=i,this.low{e.exports={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"}},4823:e=>{var t=function(){for(var e,t=[],i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t}();e.exports=function(e,i,r,s){var o=t,n=s+r;e^=-1;for(var a=s;a>>8^o[255&(e^i[a])];return-1^e}},4997:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.default=t.CramRecord=void 0;var s=i(7480);Object.defineProperty(t,"CramRecord",{enumerable:!0,get:function(){return r(s).default}});var o=i(8751);Object.defineProperty(t,"default",{enumerable:!0,get:function(){return r(o).default}})},5011:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.parseHeaderText=function(e){const t=e.split(/\r?\n/),i=[];for(const e of t){const[t,...r]=e.split(/\t/);t&&i.push({tag:t.slice(1),data:r.map((e=>{const t=e.indexOf(":");return-1!==t?{tag:e.slice(0,t),value:e.slice(t+1)}:{tag:e,value:""}}))})}return i}},5159:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.IndexedCramFile=t.CraiIndex=t.CramFile=t.CramRecord=void 0;var s=i(4997);Object.defineProperty(t,"CramRecord",{enumerable:!0,get:function(){return s.CramRecord}}),Object.defineProperty(t,"CramFile",{enumerable:!0,get:function(){return r(s).default}});var o=i(6638);Object.defineProperty(t,"CraiIndex",{enumerable:!0,get:function(){return r(o).default}});var n=i(8223);Object.defineProperty(t,"IndexedCramFile",{enumerable:!0,get:function(){return r(n).default}})},6268:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.readStatsO0=function(e,t,i){let r=0,s=0,c=255&e.get();do{null==t.fc[c]&&(t.fc[c]=new n.default.FC),t.fc[c].F=255&e.get(),t.fc[c].F>=128&&(t.fc[c].F&=-129,t.fc[c].F=(127&t.fc[c].F)<<8|255&e.get()),t.fc[c].C=s,n.default.symbolInit(i[c],t.fc[c].C,t.fc[c].F),t.R||(t.R=new Array(o.TOTFREQ)),t.R.fill(c,s,s+t.fc[c].F),s+=t.fc[c].F,0===r&&c+1===(255&e.getByteAt(e.position()))?(c=255&e.get(),r=255&e.get()):0!==r?(r-=1,c+=1):c=255&e.get()}while(0!==c);a(s=128&&(t[s].fc[h].F&=-129,t[s].fc[h].F=(127&t[s].fc[h].F)<<8|255&e.get()),t[s].fc[h].C=l,0===t[s].fc[h].F&&(t[s].fc[h].F=o.TOTFREQ),null==i[s][h]&&(i[s][h]=new n.default.RansDecSymbol),n.default.symbolInit(i[s][h],t[s].fc[h].C,t[s].fc[h].F),null==t[s].R&&(t[s].R=new Array(o.TOTFREQ)),t[s].R.fill(h,l,l+t[s].fc[h].F),l+=t[s].fc[h].F,a(l<=o.TOTFREQ),0===c&&h+1===(255&e.getByteAt(e.position()))?(h=255&e.get(),c=255&e.get()):0!==c?(c-=1,h+=1):h=255&e.get()}while(0!==h);0===r&&s+1===(255&e.getByteAt(e.position()))?(s=255&e.get(),r=255&e.get()):0!==r?(r-=1,s+=1):s=255&e.get()}while(0!==s)};const s=i(6272),o=i(7151),n=r(i(9301));function a(e){if(!e)throw new s.CramMalformedError("assertion failed")}},6272:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CramArgumentError=t.CramSizeLimitError=t.CramMalformedError=t.CramUnimplementedError=t.CramError=void 0;class i extends Error{}t.CramError=i;class r extends Error{}t.CramUnimplementedError=r,t.CramMalformedError=class extends i{},t.CramSizeLimitError=class extends i{},t.CramArgumentError=class extends i{}},6612:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{readByte(){throw new Error("abstract method readByte() not implemented")}read(e,t,i){let r=0;for(;r{Object.defineProperty(t,"__esModule",{value:!0});const r=i(6272),s=i(6727),o=i(2169);function n(e,t){const[i,r,s,o,n,a]=t,c=i;e[c]||(e[c]=[]),e[c].push({start:r,span:s,containerStart:o,sliceStart:n,sliceBytes:a})}t.default=class{constructor(e){this.filehandle=(0,s.open)(e.url,e.path,e.filehandle)}async parseIndex(){const e={},t=31===(i=await this.filehandle.readFile())[0]&&139===i[1]?(0,o.unzip)(i):i;var i;const s=new DataView(t.buffer);if(t.length>4&&21578050===s.getUint32(0,!0))throw new r.CramMalformedError("invalid .crai index file. note: file appears to be a .bai index. this is technically legal but please open a github issue if you need support");let a=[],c="";for(const i of t)if(i>=48&&i<=57||!c&&45===i)c+=String.fromCharCode(i);else if(9===i)a.push(Number.parseInt(c,10)),c="";else if(10===i)a.push(Number.parseInt(c,10)),c="",n(e,a),a=[];else if(13!==i&&32!==i)throw new r.CramMalformedError("invalid .crai index file");return c&&a.push(Number.parseInt(c,10)),6===a.length&&n(e,a),Object.entries(e).forEach((([t,i])=>{const r=i;e[t]=r.sort(((e,t)=>e.start-t.start||e.span-t.span))})),e}getIndex(){return this.parseIndexP||(this.parseIndexP=this.parseIndex().catch((e=>{throw this.parseIndexP=void 0,e}))),this.parseIndexP}async hasDataForReferenceSequence(e){return!!(await this.getIndex())[e]}async getEntriesForRange(e,t,i){const r=(await this.getIndex())[e];if(!r)return[];const s=e=>{const r=e.start,s=e.start+e.span;return r>i?-1:s<=t?1:0},o=[];for(const e of r)0===s(e)&&o.push(e);return o}}},6727:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.RemoteFile=t.LocalFile=void 0,t.open=function(e,t,i){if(i)return i;if(e)return new r.RemoteFile(e);if(t)return new r.LocalFile(t);throw new Error("no url, path, or filehandle provided, cannot open")};const r=i(8301);var s=i(8301);Object.defineProperty(t,"LocalFile",{enumerable:!0,get:function(){return s.LocalFile}}),Object.defineProperty(t,"RemoteFile",{enumerable:!0,get:function(){return s.RemoteFile}})},6761:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.CramBufferOverrunError=void 0,t.getBits=function(e,t,r){let s=0;if(t.bytePosition+(7-t.bitPosition+r)/8>e.length)throw new i("read error during decoding. the file seems to be truncated.");for(let i=r;i;i--)s<<=1,s|=e[t.bytePosition]>>t.bitPosition&1,t.bitPosition-=1,t.bitPosition<0&&(t.bytePosition+=1),t.bitPosition&=7;return s};class i extends Error{}t.CramBufferOverrunError=i},6951:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.concatUint8Array=function(e){const t=new Uint8Array(function(e){let t=0;for(const i of e)t+=i.length;return t}(e));let i=0;for(const r of e)t.set(r,i),i+=r.length;return t}},7083:(e,t,i)=>{var r=i(1447),s=i(9805),o=i(1996),n=i(9681),a=i(4674),c=i(4442),l=i(7414),h=Object.prototype.toString;function d(e){if(!(this instanceof d))return new d(e);this.options=s.assign({chunkSize:16384,windowBits:0,to:""},e||{});var t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new c,this.strm.avail_out=0;var i=r.inflateInit2(this.strm,t.windowBits);if(i!==n.Z_OK)throw new Error(a[i]);if(this.header=new l,r.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=o.string2buf(t.dictionary):"[object ArrayBuffer]"===h.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=r.inflateSetDictionary(this.strm,t.dictionary))!==n.Z_OK))throw new Error(a[i])}function u(e,t){var i=new d(t);if(i.push(e,!0),i.err)throw i.msg||a[i.err];return i.result}d.prototype.push=function(e,t){var i,a,c,l,d,u=this.strm,f=this.options.chunkSize,p=this.options.dictionary,g=!1;if(this.ended)return!1;a=t===~~t?t:!0===t?n.Z_FINISH:n.Z_NO_FLUSH,"string"==typeof e?u.input=o.binstring2buf(e):"[object ArrayBuffer]"===h.call(e)?u.input=new Uint8Array(e):u.input=e,u.next_in=0,u.avail_in=u.input.length;do{if(0===u.avail_out&&(u.output=new s.Buf8(f),u.next_out=0,u.avail_out=f),(i=r.inflate(u,n.Z_NO_FLUSH))===n.Z_NEED_DICT&&p&&(i=r.inflateSetDictionary(this.strm,p)),i===n.Z_BUF_ERROR&&!0===g&&(i=n.Z_OK,g=!1),i!==n.Z_STREAM_END&&i!==n.Z_OK)return this.onEnd(i),this.ended=!0,!1;u.next_out&&(0!==u.avail_out&&i!==n.Z_STREAM_END&&(0!==u.avail_in||a!==n.Z_FINISH&&a!==n.Z_SYNC_FLUSH)||("string"===this.options.to?(c=o.utf8border(u.output,u.next_out),l=u.next_out-c,d=o.buf2string(u.output,c),u.next_out=l,u.avail_out=f-l,l&&s.arraySet(u.output,u.output,c,l,0),this.onData(d)):this.onData(s.shrinkBuf(u.output,u.next_out)))),0===u.avail_in&&0===u.avail_out&&(g=!0)}while((u.avail_in>0||0===u.avail_out)&&i!==n.Z_STREAM_END);return i===n.Z_STREAM_END&&(a=n.Z_FINISH),a===n.Z_FINISH?(i=r.inflateEnd(this.strm),this.onEnd(i),this.ended=!0,i===n.Z_OK):a!==n.Z_SYNC_FLUSH||(this.onEnd(n.Z_OK),u.avail_out=0,!0)},d.prototype.onData=function(e){this.chunks.push(e)},d.prototype.onEnd=function(e){e===n.Z_OK&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=s.flattenChunks(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg},t.Inflate=d,t.inflate=u,t.inflateRaw=function(e,t){return(t=t||{}).raw=!0,u(e,t)},t.ungzip=u},7151:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.TOTFREQ=t.TF_SHIFT=t.RANS_BYTE_L=void 0,t.TF_SHIFT=12,t.TOTFREQ=4096,t.RANS_BYTE_L=1<<23},7293:e=>{e.exports=function(e,t){var i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_,x,k;i=e.state,r=e.next_in,x=e.input,s=r+(e.avail_in-5),o=e.next_out,k=e.output,n=o-(t-e.avail_out),a=o+(e.avail_out-257),c=i.dmax,l=i.wsize,h=i.whave,d=i.wnext,u=i.window,f=i.hold,p=i.bits,g=i.lencode,m=i.distcode,w=(1<>>=v=F>>>24,p-=v,0==(v=F>>>16&255))k[o++]=65535&F;else{if(!(16&v)){if(64&v){if(32&v){i.mode=12;break e}e.msg="invalid literal/length code",i.mode=30;break e}F=g[(65535&F)+(f&(1<>>=v,p-=v),p<15&&(f+=x[r++]<>>=v=F>>>24,p-=v,16&(v=F>>>16&255)){if(A=65535&F,p<(v&=15)&&(f+=x[r++]<c){e.msg="invalid distance too far back",i.mode=30;break e}if(f>>>=v,p-=v,A>(v=o-n)){if((v=A-v)>h&&i.sane){e.msg="invalid distance too far back",i.mode=30;break e}if(C=0,_=u,0===d){if(C+=l-v,v2;)k[o++]=_[C++],k[o++]=_[C++],k[o++]=_[C++],y-=3;y&&(k[o++]=_[C++],y>1&&(k[o++]=_[C++]))}else{C=o-A;do{k[o++]=k[C++],k[o++]=k[C++],k[o++]=k[C++],y-=3}while(y>2);y&&(k[o++]=k[C++],y>1&&(k[o++]=k[C++]))}break}if(64&v){e.msg="invalid distance code",i.mode=30;break e}F=m[(65535&F)+(f&(1<>3,f&=(1<<(p-=y<<3))-1,e.next_in=r,e.next_out=o,e.avail_in=r{class t{constructor(e={}){if(!(e.maxSize&&e.maxSize>0))throw new TypeError("`maxSize` must be a number greater than 0");this.maxSize=e.maxSize,this.cache=new Map,this.oldCache=new Map,this._size=0}_set(e,t){this.cache.set(e,t),this._size++,this._size>=this.maxSize&&(this._size=0,this.oldCache=this.cache,this.cache=new Map)}get(e){if(this.cache.has(e))return this.cache.get(e);if(this.oldCache.has(e)){const t=this.oldCache.get(e);return this.oldCache.delete(e),this._set(e,t),t}}set(e,t){return this.cache.has(e)?this.cache.set(e,t):this._set(e,t),this}has(e){return this.cache.has(e)||this.oldCache.has(e)}peek(e){return this.cache.has(e)?this.cache.get(e):this.oldCache.has(e)?this.oldCache.get(e):void 0}delete(e){const t=this.cache.delete(e);return t&&this._size--,this.oldCache.delete(e)||t}clear(){this.cache.clear(),this.oldCache.clear(),this._size=0}*keys(){for(const[e]of this)yield e}*values(){for(const[,e]of this)yield e}*[Symbol.iterator](){for(const e of this.cache)yield e;for(const e of this.oldCache){const[t]=e;this.cache.has(t)||(yield e)}}get size(){let e=0;for(const t of this.oldCache.keys())this.cache.has(t)||e++;return this._size+e}}e.exports=t},7414:e=>{e.exports=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1}},7480:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.MateFlagsDecoder=t.CramFlagsDecoder=t.BamFlagsDecoder=t.MateFlags=t.CramFlags=t.BamFlags=void 0;const s=r(i(588)),o={a:0,A:0,c:1,C:1,g:2,G:2,t:3,T:3,n:4,N:4};function n(e){const t={};for(const[i,r]of e)t[`is${r}`]=e=>!!(e&i),t[`set${r}`]=e=>e|i;return t}t.BamFlags=[[1,"Paired"],[2,"ProperlyPaired"],[4,"SegmentUnmapped"],[8,"MateUnmapped"],[16,"ReverseComplemented"],[32,"MateReverseComplemented"],[64,"Read1"],[128,"Read2"],[256,"Secondary"],[512,"FailedQc"],[1024,"Duplicate"],[2048,"Supplementary"]],t.CramFlags=[[1,"PreservingQualityScores"],[2,"Detached"],[4,"WithMateDownstream"],[8,"DecodeSequenceAsStar"]],t.MateFlags=[[1,"OnNegativeStrand"],[2,"Unmapped"]],t.BamFlagsDecoder=n(t.BamFlags),t.CramFlagsDecoder=n(t.CramFlags),t.MateFlagsDecoder=n(t.MateFlags),t.default=class{constructor({flags:e,cramFlags:t,readLength:i,mappingQuality:r,lengthOnRef:s,qualityScores:o,mateRecordNumber:n,readBases:a,readFeatures:c,mateToUse:l,readGroupId:h,readName:d,sequenceId:u,uniqueId:f,templateSize:p,alignmentStart:g,tags:m}){this.flags=e,this.cramFlags=t,this.readLength=i,this.mappingQuality=r,this.lengthOnRef=s,this.qualityScores=o,a&&(this.readBases=a),this.readGroupId=h,this.readName=d,this.sequenceId=u,this.uniqueId=f,this.templateSize=p,this.alignmentStart=g,this.tags=m,c&&(this.readFeatures=c),l&&(this.mate={flags:l.mateFlags,readName:l.mateReadName,sequenceId:l.mateSequenceId,alignmentStart:l.mateAlignmentStart}),n&&(this.mateRecordNumber=n)}isPaired(){return!!(this.flags&s.default.BAM_FPAIRED)}isProperlyPaired(){return!!(this.flags&s.default.BAM_FPROPER_PAIR)}isSegmentUnmapped(){return!!(this.flags&s.default.BAM_FUNMAP)}isMateUnmapped(){return!!(this.flags&s.default.BAM_FMUNMAP)}isReverseComplemented(){return!!(this.flags&s.default.BAM_FREVERSE)}isMateReverseComplemented(){return!!(this.flags&s.default.BAM_FMREVERSE)}isRead1(){return!!(this.flags&s.default.BAM_FREAD1)}isRead2(){return!!(this.flags&s.default.BAM_FREAD2)}isSecondary(){return!!(this.flags&s.default.BAM_FSECONDARY)}isFailedQc(){return!!(this.flags&s.default.BAM_FQCFAIL)}isDuplicate(){return!!(this.flags&s.default.BAM_FDUP)}isSupplementary(){return!!(this.flags&s.default.BAM_FSUPPLEMENTARY)}isDetached(){return!!(this.cramFlags&s.default.CRAM_FLAG_DETACHED)}hasMateDownStream(){return!!(this.cramFlags&s.default.CRAM_FLAG_MATE_DOWNSTREAM)}isPreservingQualityScores(){return!!(this.cramFlags&s.default.CRAM_FLAG_PRESERVE_QUAL_SCORES)}isUnknownBases(){return!!(this.cramFlags&s.default.CRAM_FLAG_NO_SEQ)}getReadBases(){if(!this.readBases&&this._refRegion){const e=function(e,t){if(!e.lengthOnRef&&!e.readLength)return null;if(e.isUnknownBases())return null;const i=e.alignmentStart-t.start;if(!e.readFeatures)return t.seq.slice(i,i+(e.lengthOnRef||0)).toUpperCase();let r="",s=i,o=0;for(;r.lengththis.mate.alignmentStart&&o>0&&(o=-o),o>0?(s[0]=e,s[1]=i,s[2]=t,s[3]=r):(s[2]=e,s[3]=i,s[0]=t,s[1]=r),s.join("")}return null}addReferenceSequence(e,t){this.readFeatures&&this.readFeatures.forEach((i=>{"X"===i.code&&function(e,t,i,r){const s=r.refPos-t.start,n=t.seq.charAt(s);n&&(r.ref=n);let a=o[n];void 0===a&&(a=4);const c=i.substitutionMatrix[a][r.data];c&&(r.sub=c)}(0,e,t,i)})),!this.readBases&&e.start<=this.alignmentStart&&e.end>=this.alignmentStart+(this.lengthOnRef||this.readLength)-1&&(this._refRegion=e)}toJSON(){const e={};return Object.keys(this).forEach((t=>{t.startsWith("_")||(e[t]=this[t])})),e.readBases=this.getReadBases(),e}}},7580:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.cramFileDefinition=s,t.cramBlockHeader=o,t.cramBlockCrc32=n,t.cramTagDictionary=c,t.cramPreservationMap=l,t.isMappedSliceHeader=function(e){return"number"==typeof e.refSeqId},t.getSectionParsers=function(e){return{cramFileDefinition:s(),cramBlockHeader:o(),cramBlockCrc32:n(),cramDataSeriesEncodingMap:p(),cramTagEncodingMap:g(),cramCompressionHeader:{parser:(e,t)=>{const{value:i,offset:r}=l().parser(e,t);t=r;const{value:s,offset:o}=p().parser(e,t);t=o;const{value:n,offset:a}=g().parser(e,t);return t=a,{value:{dataSeriesEncoding:h(s),preservation:h(i),tagEncoding:h(n)},offset:t}}},cramEncoding:{parser:(e,t)=>f(e,t)},cramUnmappedSliceHeader:d(e),cramMappedSliceHeader:u(e),cramContainerHeader1:m(e),cramContainerHeader2:w(e)}};const r=i(2549);function s(){return{parser:(e,t=0)=>{const i=new DataView(e.buffer,e.byteOffset,e.length),r=new TextDecoder("utf8");let s=0;const o=r.decode(e.subarray(s,s+4));s+=4;const n=i.getUint8(s);s+=1;const a=i.getUint8(s);s+=1;const c=r.decode(e.subarray(s,s+20)).replaceAll("\0","");return s+=20,{value:{magic:o,majorVersion:n,minorVersion:a,fileId:c},offset:s}},maxLength:26}}function o(){return{parser:(e,t=0)=>{const i=e,s=new DataView(i.buffer,i.byteOffset,i.length);let o=0;const n=s.getUint8(o),a=["raw","gzip","bzip2","lzma","rans","rans4x16","arith","fqzcomp","tok3"][n];if(!a)throw new Error(`compression method number ${n} not implemented`);o+=1;const c=s.getUint8(o),l=["FILE_HEADER","COMPRESSION_HEADER","MAPPED_SLICE_HEADER","UNMAPPED_SLICE_HEADER","EXTERNAL_DATA","CORE_DATA"][c];if(!l)throw new Error(`invalid block content type id ${c}`);o+=1;const[h,d]=(0,r.parseItf8)(e,o);o+=d;const[u,f]=(0,r.parseItf8)(e,o);o+=f;const[p,g]=(0,r.parseItf8)(e,o);return o+=g,{offset:o,value:{uncompressedSize:p,compressedSize:u,contentId:h,contentType:l,compressionMethod:a}}},maxLength:17}}function n(){return{parser:(e,t)=>{const i=e,r=new DataView(i.buffer,i.byteOffset,i.length).getUint32(t,!0);return{offset:t+=4,value:{crc32:r}}},maxLength:4}}function a(e,t,i){const r=new TextDecoder("utf8").decode(e.subarray(t,i)),s=[];for(let e=0;e{const[i,s]=(0,r.parseItf8)(e,t);t+=s;const o=e.subarray(t,t+i);t+=i;const n=[];let c=0,l=0;for(;lc&&n.push(a(o,c,l)),{value:{size:i,ents:n},offset:t}}}}function l(){return{parser:(e,t)=>{const i=e,s=new DataView(i.buffer,i.byteOffset,i.length),[o,n]=(0,r.parseItf8)(e,t);t+=n;const[a,l]=(0,r.parseItf8)(e,t);t+=l;const h=[];for(let i=0;i{const[s,o]=(0,r.parseItf8)(t,i);i+=o;let n=0;if(e>=3){const[e,s]=(0,r.parseLtf8)(t,i);i+=s,n=e}else if(2===e){const[e,s]=(0,r.parseItf8)(t,i);i+=s,n=e}else console.warn("recordCounter=0");const[a,c]=(0,r.parseItf8)(t,i);i+=c;const[l,h]=(0,r.parseItf8)(t,i);i+=h;const d=[];for(let e=0;e=2&&(u=[...t.subarray(i,i+16)],i+=16),{value:{recordCounter:n,md5:u,contentIds:d,numContentIds:l,numBlocks:a,numRecords:s},offset:i}},maxLength:e=>40+5*e}}function u(e){return{parser:(t,i)=>{const[s,o]=(0,r.parseItf8)(t,i);i+=o;const[n,a]=(0,r.parseItf8)(t,i);i+=a;const[c,l]=(0,r.parseItf8)(t,i);i+=l;const[h,d]=(0,r.parseItf8)(t,i);i+=d;let u=0;if(e>=3){const[e,s]=(0,r.parseLtf8)(t,i);i+=s,u=e}else if(2===e){const[e,s]=(0,r.parseItf8)(t,i);i+=s,u=e}else console.warn("majorVersion is <2, recordCounter set to 0");const[f,p]=(0,r.parseItf8)(t,i);i+=p;const[g,m]=(0,r.parseItf8)(t,i);i+=m;const w=[];for(let e=0;e=2&&(v=[...t.subarray(i,i+16)],i+=16),{value:{md5:v,numBlocks:f,numRecords:h,numContentIds:g,refSeqSpan:c,refSeqId:s,refSeqStart:n,recordCounter:u,refBaseBlockId:b,contentIds:w},offset:i}},maxLength:e=>60+5*e}}function f(e,t){const i=e,s=new DataView(i.buffer,i.byteOffset,i.length),[o,n]=(0,r.parseItf8)(e,t);t+=n;const[a,c]=(0,r.parseItf8)(e,t);t+=c;const l={};if(0===o);else if(1===o){const[i,s]=(0,r.parseItf8)(e,t);l.blockContentId=i,t+=s}else if(2===o){const[i,s]=(0,r.parseItf8)(e,t);l.offset=i,t+=s;const[o,n]=(0,r.parseItf8)(e,t);l.M=o,t+=n}else if(3===o){const i=(0,r.parseItf8)(e,t),s=i[0];t+=i[1];const o=[];for(let i=0;i{const[i,s]=(0,r.parseItf8)(e,t);t+=s;const[o,n]=(0,r.parseItf8)(e,t);t+=n;const a=[];for(let i=0;i{const[i,s]=(0,r.parseItf8)(e,t);t+=s;const[o,n]=(0,r.parseItf8)(e,t);t+=n;const a=[];for(let i=0;i>16&255)+String.fromCharCode(i>>8&255)+String.fromCharCode(255&i),{value:n,offset:c}=f(e,t);t=c,a.push({key:o,value:n})}return{value:{mapSize:i,ents:a,mapCount:o},offset:t}}}}function m(e){return{maxLength:52,parser:(t,i)=>{const s=t,o=new DataView(s.buffer,s.byteOffset,s.length).getInt32(i,!0);i+=4;const[n,a]=(0,r.parseItf8)(t,i);i+=a;const[c,l]=(0,r.parseItf8)(t,i);i+=l;const[h,d]=(0,r.parseItf8)(t,i);i+=d;const[u,f]=(0,r.parseItf8)(t,i);i+=f;let p,g=0;if(e>=3){const[e,s]=(0,r.parseLtf8)(t,i);g=e,i+=s}else if(2===e){const[e,s]=(0,r.parseItf8)(t,i);g=e,i+=s}else console.warn("setting recordCounter=0");if(e>1){const[e,s]=(0,r.parseLtf8)(t,i);p=e,i+=s}const[m,w]=(0,r.parseItf8)(t,i);i+=w;const[b,F]=(0,r.parseItf8)(t,i);return{value:{length:o,refSeqId:n,refSeqStart:c,alignmentSpan:h,numBlocks:m,numLandmarks:b,numBases:p,recordCounter:g,numRecords:u},offset:i+=F}}}}function w(e){return{parser:(t,i)=>{const s=t,o=new DataView(s.buffer,s.byteOffset,s.length),[n,a]=(0,r.parseItf8)(t,i);i+=a;const c=[];for(let e=0;e=3&&(l=o.getUint32(i,!0),i+=4),{value:{...void 0===l?{}:{crc32:l},numLandmarks:n,landmarks:c},offset:i}},maxLength:e=>5+5*e+4}}},7593:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0})},7934:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(2549);class n extends s.default{constructor(e,t,i){super(e,t),this.instantiateCodec=i}decode(e,t,i,r){const s=this._getLengthCodec().decode(e,t,i,r)||0,o=this._getDataCodec(),n=new Uint8Array(s);for(let a=0;a{(0,o.tinyMemoize)(n,e)}))},8006:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6272),n=i(6761);class a extends s.default{decode(e,t,i,r){const{blockContentId:s}=this.parameters,n=i[s];if(!n)throw new o.CramMalformedError(`no block found with content ID ${s}`);const a=r.externalBlocks.getCursor(s);return this._decodeByteArray(n,a)}_decodeByteArray(e,t){const i=e.content,{stopByte:r}=this.parameters,s=t.bytePosition;let o=t.bytePosition;for(;i[o]!==r&&othis.getRecordsInSlice(r,(r=>r.sequenceId===e&&r.alignmentStart<=i&&void 0!==r.lengthOnRef&&r.alignmentStart+r.lengthOnRef-1>=t)))));let c=Array.prototype.concat(...a);if(r.viewAsPairs){const e={},t={};for(const i of c){const r=i.readName;if(void 0===r)throw new Error("readName undefined");const s=i.uniqueId;e[r]||(e[r]=0),e[r]+=1,t[s]=1}const i={};Object.entries(e).forEach((([e,t])=>{1===t&&(i[e]=!0)}));const o=[];for(const e of c){const t=e.readName;if(void 0===t)throw new Error("readName undefined");if(i[t]&&e.mate&&(e.mate.sequenceId===s||r.pairAcrossChr)&&Math.abs(e.alignmentStart-e.mate.alignmentStart)e.toString().localeCompare(t.toString()))).filter(((e,t,i)=>!t||e.toString()!==i[t-1].toString()));const l=[];for(const e of a){let r=this.cram.featureCache.get(e.toString());r||(r=this.getRecordsInSlice(e,(()=>!0)),this.cram.featureCache.set(e.toString(),r));const s=r.then((e=>{const r=[];for(const s of e){if(void 0===s.readName)throw new Error("readName undefined");i[s.readName]&&!t[s.uniqueId]&&r.push(s)}return r}));l.push(s)}const h=await Promise.all(l);if(h.length){const e=h.reduce(((e,t)=>e.concat(t)));c=c.concat(e)}}return c}getRecordsInSlice({containerStart:e,sliceStart:t,sliceBytes:i},r){return this.cram.getContainerAtPosition(e).getSlice(t,i).getRecords(r)}hasDataForReferenceSequence(e){return this.index.hasDataForReferenceSequence(e)}}},8301:function(e,t,i){var r=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),s=this&&this.__exportStar||function(e,t){for(var i in e)"default"===i||Object.prototype.hasOwnProperty.call(t,i)||r(t,e,i)},o=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.LocalFile=t.RemoteFile=t.BlobFile=void 0,t.fromUrl=c,t.open=function(e,t,i,r={}){if(void 0!==i)return i;if(void 0!==e)return c(e,r);if(void 0!==t)return new n.default(t,r);throw new Error("no url, path, or filehandle provided, cannot open")};const n=o(i(2616)),a=o(i(8485));function c(e,t={}){return new a.default(e,t)}s(i(7593),t);var l=i(1064);Object.defineProperty(t,"BlobFile",{enumerable:!0,get:function(){return o(l).default}});var h=i(8485);Object.defineProperty(t,"RemoteFile",{enumerable:!0,get:function(){return o(h).default}});var d=i(2616);Object.defineProperty(t,"LocalFile",{enumerable:!0,get:function(){return o(d).default}})},8411:(e,t,i)=>{var r,s=i(9805),o=i(3665),n=i(3269),a=i(4823),c=i(4674),l=-2,h=258,d=262,u=103,f=113,p=666;function g(e,t){return e.msg=c[t],t}function m(e){return(e<<1)-(e>4?9:0)}function w(e){for(var t=e.length;--t>=0;)e[t]=0}function b(e){var t=e.state,i=t.pending;i>e.avail_out&&(i=e.avail_out),0!==i&&(s.arraySet(e.output,t.pending_buf,t.pending_out,i,e.next_out),e.next_out+=i,t.pending_out+=i,e.total_out+=i,e.avail_out-=i,t.pending-=i,0===t.pending&&(t.pending_out=0))}function F(e,t){o._tr_flush_block(e,e.block_start>=0?e.block_start:-1,e.strstart-e.block_start,t),e.block_start=e.strstart,b(e.strm)}function v(e,t){e.pending_buf[e.pending++]=t}function y(e,t){e.pending_buf[e.pending++]=t>>>8&255,e.pending_buf[e.pending++]=255&t}function A(e,t,i,r){var o=e.avail_in;return o>r&&(o=r),0===o?0:(e.avail_in-=o,s.arraySet(t,e.input,e.next_in,o,i),1===e.state.wrap?e.adler=n(e.adler,t,o,i):2===e.state.wrap&&(e.adler=a(e.adler,t,o,i)),e.next_in+=o,e.total_in+=o,o)}function C(e,t){var i,r,s=e.max_chain_length,o=e.strstart,n=e.prev_length,a=e.nice_match,c=e.strstart>e.w_size-d?e.strstart-(e.w_size-d):0,l=e.window,u=e.w_mask,f=e.prev,p=e.strstart+h,g=l[o+n-1],m=l[o+n];e.prev_length>=e.good_match&&(s>>=2),a>e.lookahead&&(a=e.lookahead);do{if(l[(i=t)+n]===m&&l[i+n-1]===g&&l[i]===l[o]&&l[++i]===l[o+1]){o+=2,i++;do{}while(l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&l[++o]===l[++i]&&on){if(e.match_start=t,n=r,r>=a)break;g=l[o+n-1],m=l[o+n]}}}while((t=f[t&u])>c&&0!==--s);return n<=e.lookahead?n:e.lookahead}function _(e){var t,i,r,o,n,a=e.w_size;do{if(o=e.window_size-e.lookahead-e.strstart,e.strstart>=a+(a-d)){s.arraySet(e.window,e.window,a,a,0),e.match_start-=a,e.strstart-=a,e.block_start-=a,t=i=e.hash_size;do{r=e.head[--t],e.head[t]=r>=a?r-a:0}while(--i);t=i=a;do{r=e.prev[--t],e.prev[t]=r>=a?r-a:0}while(--i);o+=a}if(0===e.strm.avail_in)break;if(i=A(e.strm,e.window,e.strstart+e.lookahead,o),e.lookahead+=i,e.lookahead+e.insert>=3)for(n=e.strstart-e.insert,e.ins_h=e.window[n],e.ins_h=(e.ins_h<=3&&(e.ins_h=(e.ins_h<=3)if(r=o._tr_tally(e,e.strstart-e.match_start,e.match_length-3),e.lookahead-=e.match_length,e.match_length<=e.max_lazy_match&&e.lookahead>=3){e.match_length--;do{e.strstart++,e.ins_h=(e.ins_h<=3&&(e.ins_h=(e.ins_h<4096)&&(e.match_length=2)),e.prev_length>=3&&e.match_length<=e.prev_length){s=e.strstart+e.lookahead-3,r=o._tr_tally(e,e.strstart-1-e.prev_match,e.prev_length-3),e.lookahead-=e.prev_length-1,e.prev_length-=2;do{++e.strstart<=s&&(e.ins_h=(e.ins_h<15&&(a=2,r-=16),o<1||o>9||8!==i||r<8||r>15||t<0||t>9||n<0||n>4)return g(e,l);8===r&&(r=9);var c=new S;return e.state=c,c.strm=e,c.wrap=a,c.gzhead=null,c.w_bits=r,c.w_size=1<e.pending_buf_size-5&&(i=e.pending_buf_size-5);;){if(e.lookahead<=1){if(_(e),0===e.lookahead&&0===t)return 1;if(0===e.lookahead)break}e.strstart+=e.lookahead,e.lookahead=0;var r=e.block_start+i;if((0===e.strstart||e.strstart>=r)&&(e.lookahead=e.strstart-r,e.strstart=r,F(e,!1),0===e.strm.avail_out))return 1;if(e.strstart-e.block_start>=e.w_size-d&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(F(e,!0),0===e.strm.avail_out?3:4):(e.strstart>e.block_start&&(F(e,!1),e.strm.avail_out),1)})),new I(4,4,8,4,x),new I(4,5,16,8,x),new I(4,6,32,32,x),new I(4,4,16,16,k),new I(8,16,32,32,k),new I(8,16,128,128,k),new I(8,32,128,256,k),new I(32,128,258,1024,k),new I(32,258,258,4096,k)],t.deflateInit=function(e,t){return M(e,t,8,15,8,0)},t.deflateInit2=M,t.deflateReset=N,t.deflateResetKeep=E,t.deflateSetHeader=function(e,t){return e&&e.state?2!==e.state.wrap?l:(e.state.gzhead=t,0):l},t.deflate=function(e,t){var i,s,n,c;if(!e||!e.state||t>5||t<0)return e?g(e,l):l;if(s=e.state,!e.output||!e.input&&0!==e.avail_in||s.status===p&&4!==t)return g(e,0===e.avail_out?-5:l);if(s.strm=e,i=s.last_flush,s.last_flush=t,42===s.status)if(2===s.wrap)e.adler=0,v(s,31),v(s,139),v(s,8),s.gzhead?(v(s,(s.gzhead.text?1:0)+(s.gzhead.hcrc?2:0)+(s.gzhead.extra?4:0)+(s.gzhead.name?8:0)+(s.gzhead.comment?16:0)),v(s,255&s.gzhead.time),v(s,s.gzhead.time>>8&255),v(s,s.gzhead.time>>16&255),v(s,s.gzhead.time>>24&255),v(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),v(s,255&s.gzhead.os),s.gzhead.extra&&s.gzhead.extra.length&&(v(s,255&s.gzhead.extra.length),v(s,s.gzhead.extra.length>>8&255)),s.gzhead.hcrc&&(e.adler=a(e.adler,s.pending_buf,s.pending,0)),s.gzindex=0,s.status=69):(v(s,0),v(s,0),v(s,0),v(s,0),v(s,0),v(s,9===s.level?2:s.strategy>=2||s.level<2?4:0),v(s,3),s.status=f);else{var d=8+(s.w_bits-8<<4)<<8;d|=(s.strategy>=2||s.level<2?0:s.level<6?1:6===s.level?2:3)<<6,0!==s.strstart&&(d|=32),d+=31-d%31,s.status=f,y(s,d),0!==s.strstart&&(y(s,e.adler>>>16),y(s,65535&e.adler)),e.adler=1}if(69===s.status)if(s.gzhead.extra){for(n=s.pending;s.gzindex<(65535&s.gzhead.extra.length)&&(s.pending!==s.pending_buf_size||(s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),b(e),n=s.pending,s.pending!==s.pending_buf_size));)v(s,255&s.gzhead.extra[s.gzindex]),s.gzindex++;s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),s.gzindex===s.gzhead.extra.length&&(s.gzindex=0,s.status=73)}else s.status=73;if(73===s.status)if(s.gzhead.name){n=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),b(e),n=s.pending,s.pending===s.pending_buf_size)){c=1;break}c=s.gzindexn&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),0===c&&(s.gzindex=0,s.status=91)}else s.status=91;if(91===s.status)if(s.gzhead.comment){n=s.pending;do{if(s.pending===s.pending_buf_size&&(s.gzhead.hcrc&&s.pending>n&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),b(e),n=s.pending,s.pending===s.pending_buf_size)){c=1;break}c=s.gzindexn&&(e.adler=a(e.adler,s.pending_buf,s.pending-n,n)),0===c&&(s.status=u)}else s.status=u;if(s.status===u&&(s.gzhead.hcrc?(s.pending+2>s.pending_buf_size&&b(e),s.pending+2<=s.pending_buf_size&&(v(s,255&e.adler),v(s,e.adler>>8&255),e.adler=0,s.status=f)):s.status=f),0!==s.pending){if(b(e),0===e.avail_out)return s.last_flush=-1,0}else if(0===e.avail_in&&m(t)<=m(i)&&4!==t)return g(e,-5);if(s.status===p&&0!==e.avail_in)return g(e,-5);if(0!==e.avail_in||0!==s.lookahead||0!==t&&s.status!==p){var A=2===s.strategy?function(e,t){for(var i;;){if(0===e.lookahead&&(_(e),0===e.lookahead)){if(0===t)return 1;break}if(e.match_length=0,i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++,i&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(F(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?1:2}(s,t):3===s.strategy?function(e,t){for(var i,r,s,n,a=e.window;;){if(e.lookahead<=h){if(_(e),e.lookahead<=h&&0===t)return 1;if(0===e.lookahead)break}if(e.match_length=0,e.lookahead>=3&&e.strstart>0&&(r=a[s=e.strstart-1])===a[++s]&&r===a[++s]&&r===a[++s]){n=e.strstart+h;do{}while(r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&r===a[++s]&&se.lookahead&&(e.match_length=e.lookahead)}if(e.match_length>=3?(i=o._tr_tally(e,1,e.match_length-3),e.lookahead-=e.match_length,e.strstart+=e.match_length,e.match_length=0):(i=o._tr_tally(e,0,e.window[e.strstart]),e.lookahead--,e.strstart++),i&&(F(e,!1),0===e.strm.avail_out))return 1}return e.insert=0,4===t?(F(e,!0),0===e.strm.avail_out?3:4):e.last_lit&&(F(e,!1),0===e.strm.avail_out)?1:2}(s,t):r[s.level].func(s,t);if(3!==A&&4!==A||(s.status=p),1===A||3===A)return 0===e.avail_out&&(s.last_flush=-1),0;if(2===A&&(1===t?o._tr_align(s):5!==t&&(o._tr_stored_block(s,0,0,!1),3===t&&(w(s.head),0===s.lookahead&&(s.strstart=0,s.block_start=0,s.insert=0))),b(e),0===e.avail_out))return s.last_flush=-1,0}return 4!==t?0:s.wrap<=0?1:(2===s.wrap?(v(s,255&e.adler),v(s,e.adler>>8&255),v(s,e.adler>>16&255),v(s,e.adler>>24&255),v(s,255&e.total_in),v(s,e.total_in>>8&255),v(s,e.total_in>>16&255),v(s,e.total_in>>24&255)):(y(s,e.adler>>>16),y(s,65535&e.adler)),b(e),s.wrap>0&&(s.wrap=-s.wrap),0!==s.pending?0:1)},t.deflateEnd=function(e){var t;return e&&e.state?42!==(t=e.state.status)&&69!==t&&73!==t&&91!==t&&t!==u&&t!==f&&t!==p?g(e,l):(e.state=null,t===f?g(e,-3):0):l},t.deflateSetDictionary=function(e,t){var i,r,o,a,c,h,d,u,f=t.length;if(!e||!e.state)return l;if(2===(a=(i=e.state).wrap)||1===a&&42!==i.status||i.lookahead)return l;for(1===a&&(e.adler=n(e.adler,t,f,0)),i.wrap=0,f>=i.w_size&&(0===a&&(w(i.head),i.strstart=0,i.block_start=0,i.insert=0),u=new s.Buf8(i.w_size),s.arraySet(u,t,f-i.w_size,i.w_size,0),t=u,f=i.w_size),c=e.avail_in,h=e.next_in,d=e.input,e.avail_in=f,e.next_in=0,e.input=t,_(i);i.lookahead>=3;){r=i.strstart,o=i.lookahead-2;do{i.ins_h=(i.ins_h<{function i(e){return("object"==typeof e&&null!==e&&"message"in e?e.message:`${e}`).replace(/\.$/,"")}Object.defineProperty(t,"__esModule",{value:!0}),t.default=class{constructor(e,t={}){this.baseOverrides={},this.url=e;const i=t.fetch||globalThis.fetch.bind(globalThis);t.overrides&&(this.baseOverrides=t.overrides),this.fetchImplementation=i}async fetch(e,t){let r;try{r=await this.fetchImplementation(e,t)}catch(s){if(!`${s}`.includes("Failed to fetch"))throw new Error(`${i(s)} fetching ${e}`,{cause:s});console.warn(`generic-filehandle: refetching ${e} to attempt to work around chrome CORS header caching bug`);try{r=await this.fetchImplementation(e,{...t,cache:"reload"})}catch(t){throw new Error(`${i(t)} fetching ${e}`,{cause:t})}}return r}async read(e,t,i={}){const{headers:r={},signal:s,overrides:o={}}=i;e<1/0?r.range=`bytes=${t}-${t+e}`:e===1/0&&0!==t&&(r.range=`bytes=${t}-`);const n=await this.fetch(this.url,{...this.baseOverrides,...o,headers:{...r,...o.headers,...this.baseOverrides.headers},method:"GET",redirect:"follow",mode:"cors",signal:s});if(!n.ok)throw new Error(`HTTP ${n.status} fetching ${this.url}`);if(200===n.status&&0===t||206===n.status){const t=await n.arrayBuffer(),i=n.headers.get("content-range"),r=/\/(\d+)$/.exec(i||"");return r?.[1]&&(this._stat={size:parseInt(r[1],10)}),new Uint8Array(t.slice(0,e))}throw 200===n.status?new Error(`${this.url} fetch returned status 200, expected 206`):new Error(`HTTP ${n.status} fetching ${this.url}`)}async readFile(e={}){let t,i;"string"==typeof e?(t=e,i={}):(t=e.encoding,i=e,delete i.encoding);const{headers:r={},signal:s,overrides:o={}}=i,n=await this.fetch(this.url,{headers:r,method:"GET",redirect:"follow",mode:"cors",signal:s,...this.baseOverrides,...o});if(200!==n.status)throw new Error(`HTTP ${n.status} fetching ${this.url}`);if("utf8"===t)return n.text();if(t)throw new Error(`unsupported encoding: ${t}`);return new Uint8Array(await n.arrayBuffer())}async stat(){if(!this._stat&&(await this.read(10,0),!this._stat))throw new Error(`unable to determine size of file at ${this.url}`);return this._stat}async close(){}}},8594:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.decode=function(e){const t=new s.default(e),i=t.ReadByte(),r=(t.ReadUint32(),t.ReadUint32());return 0==i?function(e,t){const i=new Array(256),r=new Array(256);h(e,i,r);const s=a(r),n=new Array(4);for(var d=0;d<4;d++)n[d]=e.ReadUint32();const u=new Uint8Array(t);for(d=0;d0?(o--,r++):(r=e.ReadByte(),r==s+1&&(o=e.ReadByte())),s=r}while(0!=r)}(e,i,r);const s=new Array(256);for(var d=0;d<256;d++)s[d]=a(r[d]);const u=new Array(4),f=new Array(4);for(var p=0;p<4;p++)u[p]=e.ReadUint32(),f[p]=0;const g=new Uint8Array(t),m=Math.floor(t/4);for(d=0;d=e[i+1];)i++;return i}function a(e){const t=new Array(4096);let i=0;for(let r=0;r<4096;r++){for(;r>=e[i+1];)i++;t[r]=i}return t}function c(e,t,i){return i*(e>>12)+(4095&e)-t}function l(e,t){for(;t<1<<23;)t=(t<<8)+e.ReadByte();return t}function h(e,t,i){for(var r=0;r<256;r++)t[r]=0;let s=e.ReadByte(),o=s,n=0;do{const i=e.ReadITF8();t[s]=i,n>0?(n--,s++):(s=e.ReadByte(),s==o+1&&(n=e.ReadByte())),o=s}while(0!=s);for(i[0]=0,r=0;r<=255;r++)i[r+1]=i[r]+t[r]}},8700:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(6272),s=i(1609),o={BF:"int",CF:"int",RI:"int",RL:"int",AP:"int",RG:"int",MF:"int",NS:"int",NP:"int",TS:"int",NF:"int",TC:"byte",TN:"int",FN:"int",FC:"byte",FP:"int",BS:"byte",IN:"byteArray",SC:"byteArray",DL:"int",BA:"byte",BB:"byteArray",RS:"int",PD:"int",HC:"int",MQ:"int",RN:"byteArray",QS:"byte",QQ:"byteArray",TL:"int"};t.default=class{constructor(e){this.dataSeriesCodecCache={},this.tagCodecCache={},this.tagEncoding={},this.readNamesIncluded=e.preservation.RN,this.APdelta=e.preservation.AP,this.referenceRequired=!!e.preservation.RR,this.tagIdsDictionary=e.preservation.TD,this.substitutionMatrix=function(e){const t=new Array(5);for(let e=0;e<5;e+=1)t[e]=new Array(4);return t[0][e[0]>>6&3]="C",t[0][e[0]>>4&3]="G",t[0][e[0]>>2&3]="T",t[0][3&e[0]]="N",t[1][e[1]>>6&3]="A",t[1][e[1]>>4&3]="G",t[1][e[1]>>2&3]="T",t[1][3&e[1]]="N",t[2][e[2]>>6&3]="A",t[2][e[2]>>4&3]="C",t[2][e[2]>>2&3]="T",t[2][3&e[2]]="N",t[3][e[3]>>6&3]="A",t[3][e[3]>>4&3]="C",t[3][e[3]>>2&3]="G",t[3][3&e[3]]="N",t[4][e[4]>>6&3]="A",t[4][e[4]>>4&3]="C",t[4][e[4]>>2&3]="G",t[4][3&e[4]]="T",t}(e.preservation.SM),this.dataSeriesEncoding=e.dataSeriesEncoding,this.tagEncoding=e.tagEncoding}getCodecForTag(e){const t=this.tagCodecCache[e];if(t)return t;{const t=this.tagEncoding[e];if(!t)throw new Error("Error, no tag encoding");const i=(0,s.instantiateCodec)(t,"byteArray");return this.tagCodecCache[e]=i,i}}getTagNames(e){return this.tagIdsDictionary[e]}getCodecForDataSeries(e){let t=this.dataSeriesCodecCache[e];if(void 0===t){const i=this.dataSeriesEncoding[e];if(i){const n=o[e];if(!n)throw new r.CramMalformedError(`data series name ${e} not defined in file compression header`);t=(0,s.instantiateCodec)(i,n),this.dataSeriesCodecCache[e]=t}}return t}toJSON(){const e={};return Object.keys(this).forEach((t=>{t.endsWith("Cache")||(e[t]=this[t])})),e}}},8751:function(e,t,i){var r,s=this&&this.__createBinding||(Object.create?function(e,t,i,r){void 0===r&&(r=i);var s=Object.getOwnPropertyDescriptor(t,i);s&&!("get"in s?!t.__esModule:s.writable||s.configurable)||(s={enumerable:!0,get:function(){return t[i]}}),Object.defineProperty(e,r,s)}:function(e,t,i,r){void 0===r&&(r=i),e[r]=t[i]}),o=this&&this.__setModuleDefault||(Object.create?function(e,t){Object.defineProperty(e,"default",{enumerable:!0,value:t})}:function(e,t){e.default=t}),n=this&&this.__importStar||(r=function(e){return r=Object.getOwnPropertyNames||function(e){var t=[];for(var i in e)Object.prototype.hasOwnProperty.call(e,i)&&(t[t.length]=i);return t},r(e)},function(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var i=r(e),n=0;n0)throw new Error("Detected big-endian machine, may be unable to run")}read(e,t){return this.file.read(e,t)}async getDefinition(){const{maxLength:e,parser:t}=(0,F.cramFileDefinition)(),i=t(await this.file.read(e,0)).value;if(2!==i.majorVersion&&3!==i.majorVersion)throw new d.CramUnimplementedError(`CRAM version ${i.majorVersion} not supported`);return i}async getSamHeader(){const e=await this.getContainerById(0);if(!e)throw new d.CramMalformedError("file contains no containers");const t=(await e.getFirstBlock()).content,i=new DataView(t.buffer).getInt32(0,!0),r=new TextDecoder("utf8").decode(t.subarray(4,4+i));return this.header=r,(0,g.parseHeaderText)(r)}async getHeaderText(){return await this.getSamHeader(),this.header}async getContainerById(e){const{majorVersion:t}=await this.getDefinition();let i,r=(0,F.getSectionParsers)(t).cramFileDefinition.maxLength;for(let t=0;t<=e;t++){i=this.getContainerAtPosition(r);const e=await i.getHeader();if(0===t){r=e._endPosition;for(let t=0;t>>0;if(o!==i)throw new d.CramMalformedError(`crc mismatch in ${r}: recorded CRC32 = ${i}, but calculated CRC32 = ${o}`)}async containerCount(){const{majorVersion:e}=await this.getDefinition();let t=0,i=(0,F.getSectionParsers)(e).cramFileDefinition.maxLength;try{for(;;){const e=await this.getContainerAtPosition(i).getHeader();if(0===t){i=e._endPosition;for(let t=0;t=3){const t=await this._parseSection(i.cramBlockCrc32,s+r.compressedSize);a.crc32=t.crc32,this.validateChecksums&&await this.checkCrc32(e,r._size+r.compressedSize,t.crc32,"block data"),a._endPosition=t._endPosition,a._size=a.compressedSize+i.cramBlockCrc32.maxLength}else a._endPosition=s+a.compressedSize,a._size=a.compressedSize;return a}}t.default=y,"getDefinition getSectionParsers getSamHeader".split(" ").forEach((e=>{(0,v.tinyMemoize)(y,e)}))},8761:(e,t)=>{Object.defineProperty(t,"__esModule",{value:!0});const i=new Uint32Array([0,79764919,159529838,222504665,319059676,398814059,445009330,507990021,638119352,583659535,797628118,726387553,890018660,835552979,1015980042,944750013,1276238704,1221641927,1167319070,1095957929,1595256236,1540665371,1452775106,1381403509,1780037320,1859660671,1671105958,1733955601,2031960084,2111593891,1889500026,1952343757,2552477408,2632100695,2443283854,2506133561,2334638140,2414271883,2191915858,2254759653,3190512472,3135915759,3081330742,3009969537,2905550212,2850959411,2762807018,2691435357,3560074640,3505614887,3719321342,3648080713,3342211916,3287746299,3467911202,3396681109,4063920168,4143685023,4223187782,4286162673,3779000052,3858754371,3904687514,3967668269,881225847,809987520,1023691545,969234094,662832811,591600412,771767749,717299826,311336399,374308984,453813921,533576470,25881363,88864420,134795389,214552010,2023205639,2086057648,1897238633,1976864222,1804852699,1867694188,1645340341,1724971778,1587496639,1516133128,1461550545,1406951526,1302016099,1230646740,1142491917,1087903418,2896545431,2825181984,2770861561,2716262478,3215044683,3143675388,3055782693,3001194130,2326604591,2389456536,2200899649,2280525302,2578013683,2640855108,2418763421,2498394922,3769900519,3832873040,3912640137,3992402750,4088425275,4151408268,4197601365,4277358050,3334271071,3263032808,3476998961,3422541446,3585640067,3514407732,3694837229,3640369242,1762451694,1842216281,1619975040,1682949687,2047383090,2127137669,1938468188,2001449195,1325665622,1271206113,1183200824,1111960463,1543535498,1489069629,1434599652,1363369299,622672798,568075817,748617968,677256519,907627842,853037301,1067152940,995781531,51762726,131386257,177728840,240578815,269590778,349224269,429104020,491947555,4046411278,4126034873,4172115296,4234965207,3794477266,3874110821,3953728444,4016571915,3609705398,3555108353,3735388376,3664026991,3290680682,3236090077,3449943556,3378572211,3174993278,3120533705,3032266256,2961025959,2923101090,2868635157,2813903052,2742672763,2604032198,2683796849,2461293480,2524268063,2284983834,2364738477,2175806836,2238787779,1569362073,1498123566,1409854455,1355396672,1317987909,1246755826,1192025387,1137557660,2072149281,2135122070,1912620623,1992383480,1753615357,1816598090,1627664531,1707420964,295390185,358241886,404320391,483945776,43990325,106832002,186451547,266083308,932423249,861060070,1041341759,986742920,613929101,542559546,756411363,701822548,3316196985,3244833742,3425377559,3370778784,3601682597,3530312978,3744426955,3689838204,3819031489,3881883254,3928223919,4007849240,4037393693,4100235434,4180117107,4259748804,2310601993,2373574846,2151335527,2231098320,2596047829,2659030626,2470359227,2550115596,2947551409,2876312838,2788305887,2733848168,3165939309,3094707162,3040238851,2985771188]);t.default=class{constructor(){this.crc=4294967295}getCRC(){return~this.crc>>>0}updateCRC(e){this.crc=this.crc<<8^i[255&(this.crc>>>24^e)]}updateCRCRun(e,t){for(;t-- >0;)this.crc=this.crc<<8^i[255&(this.crc>>>24^e)]}}},8930:function(e,t,i){var r=this&&this.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0});const s=r(i(4141)),o=i(6272),n=i(2549),a=i(6761);class c extends s.default{constructor(e,t){if(super(e,t),"int"===this.dataType)this._decodeData=this._decodeInt;else{if("byte"!==this.dataType)throw new o.CramUnimplementedError(`${this.dataType} decoding not yet implemented by EXTERNAL codec`);this._decodeData=this._decodeByte}}decode(e,t,i,r){const{blockContentId:s}=this.parameters,o=i[s];return o?this._decodeData(o,r.externalBlocks.getCursor(s)):void 0}_decodeInt(e,t){const[i,r]=(0,n.parseItf8)(e.content,t.bytePosition);return t.bytePosition=t.bytePosition+r,i}_decodeByte(e,t){if(t.bytePosition>=e.content.length)throw new a.CramBufferOverrunError("attempted to read beyond end of block. this file seems truncated.");return e.content[t.bytePosition++]}}t.default=c},9301:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0});const r=i(6272),s=i(7151);class o{constructor(){this.F=void 0,this.C=void 0}}function n(e,t,i,r){return i*(e>>r)+(e&(1<>o)+(e&(1<=e[i+1];)i++;return i}function a(e,t){const i=1<=e[s+1];)s++;r[t]=s}return r}function c(e,t,i,r){return i*(e>>r)+(e&(1<o),n[o]=h(e,s[o]);const a=new Uint8Array(t);for(o=0;o>4;var h=e;if(1&p){const t=e.ReadUint7(),i=e.ReadUint7();var p=new s.default(e.ReadData(i));h=new s.default(u(p,t,4))}const g=new Array(256),m=new Array(256);!function(e,t,i,r){for(var s=0;s<256;s++){t[s]=new Array(256),i[s]=new Array(256);for(var o=0;o<256;o++)t[s][o]=0}const n=d(e);for(s=0;s<256;s++){if(!n[s])continue;let a=0;for(o=0;o<256;o++)n[o]&&(a>0?a--:(t[s][o]=e.ReadUint7(),0==t[s][o]&&(a=e.ReadByte())));for(f(t[s],r),i[s][0]=0,o=0;o<256;o++)i[s][o+1]=i[s][o]+t[s][o]}}(h,g,m,r);const w=new Array(256);for(var b=0;b<256;b++)w[b]=a(m[b],r);const F=new Array(i),v=new Array(i);for(var y=0;y>=1}else if(i<=4)for(n=0;n>=2;else if(i<=16)for(n=0;n>=4;return s}(x,v,y,F)),x}function d(e){const t=new Array(256);for(let e=0;e<256;e++)t[e]=0;let i=0,r=e.ReadByte(),s=r;do{t[r]=1,i>0?(i--,r++):(r=e.ReadByte(),r==s+1&&(i=e.ReadByte())),s=r}while(0!=r);return t}function u(e,t,i){const r=new Array(256),s=new Array(256);!function(e,t,i){for(var r=0;r<256;r++)t[r]=0;const s=d(e);for(r=0;r<256;r++)s[r]>0&&(t[r]=e.ReadUint7());for(f(t,12),i[0]=0,r=0;r<=255;r++)i[r+1]=i[r]+t[r]}(e,r,s);const n=a(s,12),h=new Array(i);for(var u=0;u>=1}}else if(this.nsym<=4)for(s=0,o=0;s>=2;else{if(!(this.nsym<=16))return e;for(s=0,o=0;s>=4}return r}packMeta(e){const t=new a.default("",0,1024),i=new Array(256);for(var r=0;ro),n[o]=this.decodeStream(e,s[o]);const a=new Uint8Array(t);for(o=0;o{e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},9685:(e,t,i)=>{Object.defineProperty(t,"__esModule",{value:!0}),t.default=function(e,t,i,c,l,h,d,u,f){let p=t("BF");const g=t("CF");if(!(0,o.isMappedSliceHeader)(c.parsedContent))throw new Error("slice header not mapped");const m=u>1&&-2===c.parsedContent.refSeqId?t("RI"):c.parsedContent.refSeqId,w=t("RL");let b=t("AP");i.APdelta&&(b+=d.lastAlignmentStart),d.lastAlignmentStart=b;const F=t("RG");let v,y,A,C;if(i.readNamesIncluded&&(v=n(t("RN"))),s.CramFlagsDecoder.isDetached(g)){const e=t("MF");let r;i.readNamesIncluded||(r=n(t("RN")),v=r);const o=t("NS"),a=t("NP");(e||o>-1)&&(y={mateFlags:e,mateSequenceId:o,mateAlignmentStart:a,mateReadName:r}),A=t("TS"),s.MateFlagsDecoder.isUnmapped(e)&&(p=s.BamFlagsDecoder.setMateUnmapped(p)),s.MateFlagsDecoder.isOnNegativeStrand(e)&&(p=s.BamFlagsDecoder.setMateReverseComplemented(p))}else s.CramFlagsDecoder.isWithMateDownstream(g)&&(C=t("NF")+f+1);const _=t("TL");if(_<0)throw new r.CramMalformedError("invalid TL index");const x={},k=i.getTagNames(_),I=k.length;for(let t=0;t1?"SC":"IN"],X:["number","BS"],D:["number","DL"],I:["string","IN"],i:["character","BA"],b:["string","BB"],q:["numArray","QQ"],Q:["number","QS"],H:["number","HC"],P:["number","PD"],N:["number","RS"]}[t];if(!h)throw new r.CramMalformedError(`invalid read feature code "${t}"`);let d=l(h);const u={B:["number","QS"]}[t];u&&(d=[d,l(u)]),n+=s;const f=n;a+=s;const p=a;"D"===t||"N"===t?a+=d:"I"===t||"S"===t?a-=d.length:"i"===t&&(a-=1),c[e]={code:t,pos:f,refPos:p,data:d}}return c}(b,e,t,0,u)),E=w,S)for(const{code:e,data:t}of S)"D"===e||"N"===e?E+=t:"I"===e||"S"===e?E-=t.length:"i"===e&&(E-=1);if(Number.isNaN(E)&&(console.warn(`${v||`${m}:${b}`} record has invalid read features`),E=w),N=t("MQ"),s.CramFlagsDecoder.isPreservingQualityScores(g)){M=new Array(w);for(let e=0;e{var i="undefined"!=typeof Uint8Array&&"undefined"!=typeof Uint16Array&&"undefined"!=typeof Int32Array;function r(e,t){return Object.prototype.hasOwnProperty.call(e,t)}t.assign=function(e){for(var t=Array.prototype.slice.call(arguments,1);t.length;){var i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(var s in i)r(i,s)&&(e[s]=i[s])}}return e},t.shrinkBuf=function(e,t){return e.length===t?e:e.subarray?e.subarray(0,t):(e.length=t,e)};var s={arraySet:function(e,t,i,r,s){if(t.subarray&&e.subarray)e.set(t.subarray(i,i+r),s);else for(var o=0;o{}},sf={},function e(t){var i=sf[t];if(void 0!==i)return i.exports;var r=sf[t]={exports:{}};return rf[t].call(r.exports,r,r.exports,e),r.exports}(5159));class nf{constructor(e,t){this.position=0,this.url=e,this.config=t,x(e)||!1===t.cacheFetches?this.useCache=!1:(this.useCache=!0,this.cache=new af({fetch:(e,t)=>this._fetch(e,t),fetchSize:t.fetchSize||1e4}))}async _fetch(e,t){const i={start:e,size:t};return await Rr.loadArrayBuffer(this.url,ts(this.config,{range:i}))}async read(e,t=0){let i;return i=this.useCache?await this.cache.get(t,e):await this._fetch(t,e),new Uint8Array(i)}async readFile(){const e=await Rr.loadArrayBuffer(this.url,ts(this.config));return new Uint8Array(e)}}class af{maxChunkCount=5;chunks=[];constructor({fetch:e,fetchSize:t=3e4}){this.fetch=e,this.fetchSize=t}async get(e,t){const i=e+t;for(let r of this.chunks)if(r.contains(e,i)){const i=e-r.start;return r.buffer.slice(i,i+t)}const r=Math.max(t,this.fetchSize),s=Math.max(0,e-1e3),o=e+r+1e3,n=await this.fetch(s,o-s),a=new cf(s,o,n);this.chunks.length>this.maxChunkCount&&this.chunks.shift(),this.chunks.push(a);const c=e-a.start,l=c+t;return n.slice(c,l)}}class cf{constructor(e,t,i){this.start=e,this.end=t,this.buffer=i}contains(e,t){return e>=this.start&&t<=this.end}}class lf{chrAliasTable=new Map;constructor(e,t,i){this.config=e,this.browser=i,this.genome=t,this.cramFile=new of.CramFile({filehandle:e.fileHandle?e.fileHandle:new nf(e.url,e),seqFetch:e.seqFetch||async function(e,t,i){const r=this.genome,s=await this.getHeader(),o=r.getChromosomeName(s.indexToChr[e]);return this.genome.getSequence(o,t-1,i)}.bind(this),checkSequenceMD5:void 0===e.checkSequenceMD5||e.checkSequenceMD5});const r=e.indexFileHandle?e.indexFileHandle:new nf(e.indexURL,e);this.indexedCramFile=new of.IndexedCramFile({cram:this.cramFile,index:new of.CraiIndex({filehandle:r}),fetchSizeLimit:e.fetchSizeLimit||1e9}),Qu.setReaderDefaults(this,e)}async getHeader(){if(!this.header){const e=await this.cramFile.getSamHeader(),t={},i=[],r=[];for(let s of e)if("SQ"===s.tag){for(let e of s.data)if("SN"===e.tag){const r=e.value;t[r]=i.length,i.push(r);break}}else"RG"===s.tag&&r.push(s.data);this.header={indexToChr:i,chrToIndex:t,chrNames:Object.keys(t),readGroups:r}}return this.header}async#_(e){if(await this.getHeader(),this.chrAliasTable.has(e)&&void 0===(e=this.chrAliasTable.get(e)))return;let t=this.header.chrToIndex[e];if(void 0===t){const i=await this.genome.getAliasRecord(e);let r;if(i){const e=Object.keys(i).filter((e=>"start"!==e&&"end"!==e)).map((e=>i[e])).filter((e=>void 0!==this.header.chrToIndex[e]));e.length>0&&(r=e[0],t=this.header.chrToIndex[e[0]])}this.chrAliasTable.set(e,r)}return t}async readAlignments(e,t,i){const r=await this.getHeader(),s=await this.#_(e),o=new fu(e,t,i,this.config);if(void 0===s)return o;try{const e=await this.indexedCramFile.getRecordsForRange(s,t,i);for(let a of e){const e=a.sequenceId,c=a.alignmentStart,l=c+a.lengthOnRef;if(e<0)continue;if(e>s||c>i)return;if(e=0&&(t="Sequence mismatch. Is this the correct genome for the loaded CRAM?"),this.browser.alert.present(new Error(t)),e}function n(e,t){const i=new Eu;if(i.chr=t[e.sequenceId],i.start=e.alignmentStart-1,i.lengthOnRef=e.lengthOnRef,i.flags=e.flags,i.strand=!(16&e.flags),i.fragmentLength=e.templateLength||e.templateSize,i.mq=e.mappingQuality,i.end=e.alignmentStart+e.lengthOnRef,i.readGroupId=e.readGroupId,e.mate&&void 0!==e.mate.sequenceId){const r=void 0!==e.mate.flags?!(1&e.mate.flags):!(32&e.flags);i.mate={chr:t[e.mate.sequenceId],position:e.mate.alignmentStart,strand:r}}return i.seq=e.getReadBases(),i.qual=e.qualityScores,i.tagDict=e.tags,i.readName=e.readName,function(e,t){const i=[];let r,s,o=0,n="";if(t.scStart=t.start,t.scLengthOnRef=t.lengthOnRef,e.readFeatures)for(let a of e.readFeatures){const e=a.code,c=a.data,l=a.pos-1,h=a.refPos-1;switch(e){case"S":case"I":case"i":case"N":case"D":if(l>o){const e=l-o;i.push(new zu({start:h-e,seqOffset:o,len:e,type:"M"})),o+=e,n+=e+"M"}if("S"===e){let r=h;t.scLengthOnRef+=c.length,0===l&&(t.scStart-=c.length,r-=c.length);const s=c.length;i.push(new zu({start:r,seqOffset:o,len:s,type:"S"})),o+=s,n+=s+e}else if("I"===e||"i"===e){void 0===r&&(r=[]);const t="i"===e?1:c.length;r.push(new zu({start:h,len:t,seqOffset:o,type:"I"})),o+=t,n+=t+e}else"D"!==e&&"N"!==e||(s||(s=[]),s.push({start:h,len:c,type:e}),n+=c+e);break;case"H":case"P":n+=c+e}}const a=e.readLength-o;a>0&&(i.push(new zu({start:e.alignmentStart+e.lengthOnRef-a-1,seqOffset:o,len:a,type:"M"})),n+=a+"M");t.blocks=i,t.insertions=r,t.gaps=s,t.cigar=n}(e,i),i.mate&&i.start>i.mate.position&&i.fragmentLength>0&&(i.fragmentLength=-i.fragmentLength),Qu.setPairOrientation(i),i}}}const hf=2291137574,df=2273964779,uf=[84,68,70,52],ff=new Uint8Array([66,65,77,1]),pf=[67,82,65,77],gf=[31,139],mf=new Set(["narrowpeak","broadpeak","regionpeak","peaks","bedgraph","wig","gff3","gff","gtf","fusionjuncspan","refflat","seg","aed","bed","bedMethyl","vcf","bb","bigbed","biginteract","biggenepred","bignarrowpeak","bw","bigwig","bam","tdf","refgene","genepred","genepredext","bedpe","bp","snp","rmsk","cram","gwas","maf","mut","hiccups","fasta","fa","fna","pytor","hic","qtl"]);function wf(e,t){const i=Math.min(e.length,t.length);if(0==i)return!1;for(let r=0;r=this.start&&e.end<=this.end}overlaps(e){return e.chr===this.chr&&!(e.endthis.end)}extend(e){e.chr===this.chr&&(this.start=Math.min(e.start,this.start),this.end=Math.max(e.end,this.end))}getLocusString(){if("all"===this.chr)return"all";{const e=F(Math.floor(this.start)+1),t=F(Math.round(this.end));return`${this.chr}:${e}-${t}`}}static fromLocusString(e){if("all"===e)return new vf({chr:"all"});const t=e.split(":"),i=t[0],r=t[1].split("-"),s=Number.parseInt(r[0].replace(/,/g,""))-1,o=Number.parseInt(r[1].replace(/,/g,""));return new vf({chr:i,start:s,end:o})}} /*! * vanilla-picker v2.12.1 * https://vanilla-picker.js.org * * Copyright 2017-2021 Andreas Borgen (https://github.com/Sphinxxxx), Adam Brooks (https://github.com/dissimulate) * Released under the ISC license. - */var yf=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Af=function(){function e(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:1;return(t>0?e.toFixed(t).replace(/0+$/,"").replace(/\.$/,""):e.toString())||"0"}var kf=function(){function e(t,i,r,s){yf(this,e);var o=this;if(void 0===t);else if(Array.isArray(t))this.rgba=t;else if(void 0===r){var n=t&&""+t;n&&function(t){if(t.startsWith("hsl")){var i=t.match(/([\-\d\.e]+)/g).map(Number),r=Cf(i,4),s=r[0],n=r[1],a=r[2],c=r[3];void 0===c&&(c=1),s/=360,n/=100,a/=100,o.hsla=[s,n,a,c]}else if(t.startsWith("rgb")){var l=t.match(/([\-\d\.e]+)/g).map(Number),h=Cf(l,4),d=h[0],u=h[1],f=h[2],p=h[3];void 0===p&&(p=1),o.rgba=[d,u,f,p]}else t.startsWith("#")?o.rgba=e.hexToRgb(t):o.rgba=e.nameToRgb(t)||e.hexToRgb(t)}(n.toLowerCase())}else this.rgba=[t,i,r,void 0===s?1:s]}return Af(e,[{key:"printRGB",value:function(e){var t=(e?this.rgba:this.rgba.slice(0,3)).map((function(e,t){return xf(e,3===t?3:0)}));return e?"rgba("+t+")":"rgb("+t+")"}},{key:"printHSL",value:function(e){var t=[360,100,100,1],i=["","%","%",""],r=(e?this.hsla:this.hsla.slice(0,3)).map((function(e,r){return xf(e*t[r],3===r?3:1)+i[r]}));return e?"hsla("+r+")":"hsl("+r+")"}},{key:"printHex",value:function(e){var t=this.hex;return e?t:t.substring(0,7)}},{key:"rgba",get:function(){if(this._rgba)return this._rgba;if(!this._hsla)throw new Error("No color is set");return this._rgba=e.hslToRgb(this._hsla)},set:function(e){3===e.length&&(e[3]=1),this._rgba=e,this._hsla=null}},{key:"rgbString",get:function(){return this.printRGB()}},{key:"rgbaString",get:function(){return this.printRGB(!0)}},{key:"hsla",get:function(){if(this._hsla)return this._hsla;if(!this._rgba)throw new Error("No color is set");return this._hsla=e.rgbToHsl(this._rgba)},set:function(e){3===e.length&&(e[3]=1),this._hsla=e,this._rgba=null}},{key:"hslString",get:function(){return this.printHSL()}},{key:"hslaString",get:function(){return this.printHSL(!0)}},{key:"hex",get:function(){return"#"+this.rgba.map((function(e,t){return t<3?e.toString(16):Math.round(255*e).toString(16)})).map((function(e){return e.padStart(2,"0")})).join("")},set:function(t){this.rgba=e.hexToRgb(t)}}],[{key:"hexToRgb",value:function(e){var t=(e.startsWith("#")?e.slice(1):e).replace(/^(\w{3})$/,"$1F").replace(/^(\w)(\w)(\w)(\w)$/,"$1$1$2$2$3$3$4$4").replace(/^(\w{6})$/,"$1FF");if(!t.match(/^([0-9a-fA-F]{8})$/))throw new Error("Unknown hex color; "+e);var i=t.match(/^(\w\w)(\w\w)(\w\w)(\w\w)$/).slice(1).map((function(e){return parseInt(e,16)}));return i[3]=i[3]/255,i}},{key:"nameToRgb",value:function(t){var i=t.toLowerCase().replace("at","T").replace(/[aeiouyldf]/g,"").replace("ght","L").replace("rk","D").slice(-5,4),r=_f[i];return void 0===r?r:e.hexToRgb(r.replace(/\-/g,"00").padStart(6,"f"))}},{key:"rgbToHsl",value:function(e){var t=Cf(e,4),i=t[0],r=t[1],s=t[2],o=t[3];i/=255,r/=255,s/=255;var n=Math.max(i,r,s),a=Math.min(i,r,s),c=void 0,l=void 0,h=(n+a)/2;if(n===a)c=l=0;else{var d=n-a;switch(l=h>.5?d/(2-n-a):d/(n+a),n){case i:c=(r-s)/d+(r1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e},h=s<.5?s*(1+r):s+r-s*r,d=2*s-h;n=l(d,h,i+1/3),a=l(d,h,i),c=l(d,h,i-1/3)}var u=[255*n,255*a,255*c].map(Math.round);return u[3]=o,u}}]),e}(),If=function(){function e(){yf(this,e),this._events=[]}return Af(e,[{key:"add",value:function(e,t,i){e.addEventListener(t,i,!1),this._events.push({target:e,type:t,handler:i})}},{key:"remove",value:function(t,i,r){this._events=this._events.filter((function(s){var o=!0;return t&&t!==s.target&&(o=!1),i&&i!==s.type&&(o=!1),r&&r!==s.handler&&(o=!1),o&&e._doRemove(s.target,s.type,s.handler),!o}))}},{key:"destroy",value:function(){this._events.forEach((function(t){return e._doRemove(t.target,t.type,t.handler)})),this._events=[]}}],[{key:"_doRemove",value:function(e,t,i){e.removeEventListener(t,i,!1)}}]),e}();function Sf(e,t,i){var r=!1;function s(e,t,i){return Math.max(t,Math.min(e,i))}function o(e,o,n){if(n&&(r=!0),r){e.preventDefault();var a=t.getBoundingClientRect(),c=a.width,l=a.height,h=o.clientX,d=o.clientY,u=s(h-a.left,0,c),f=s(d-a.top,0,l);i(u/c,f/l)}}function n(e,t){1===(void 0===e.buttons?e.which:e.buttons)?o(e,e,t):r=!1}function a(e,t){1===e.touches.length?o(e,e.touches[0],t):r=!1}e.add(t,"mousedown",(function(e){n(e,!0)})),e.add(t,"touchstart",(function(e){a(e,!0)})),e.add(window,"mousemove",n),e.add(t,"touchmove",a),e.add(window,"mouseup",(function(e){r=!1})),e.add(t,"touchend",(function(e){r=!1})),e.add(t,"touchcancel",(function(e){r=!1}))}var Ef="keydown",Nf="mousedown",Mf="focusin";function Rf(e,t){return(t||document).querySelector(e)}function Bf(e){e.preventDefault(),e.stopPropagation()}function Df(e,t,i,r,s){e.add(t,Ef,(function(e){i.indexOf(e.key)>=0&&(s&&Bf(e),r(e))}))}var Lf=function(){function e(t){yf(this,e),this.settings={popup:"right",layout:"default",alpha:!0,editor:!0,editorFormat:"hex",cancelButton:!1,defaultColor:"#0cf"},this._events=new If,this.onChange=null,this.onDone=null,this.onOpen=null,this.onClose=null,this.setOptions(t)}return Af(e,[{key:"setOptions",value:function(e){var t=this;if(e){var i=this.settings;if(e instanceof HTMLElement)i.parent=e;else{i.parent&&e.parent&&i.parent!==e.parent&&(this._events.remove(i.parent),this._popupInited=!1),function(e,t,i){for(var r in e)i&&i.indexOf(r)>=0||(t[r]=e[r])}(e,i),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var r=e.color||e.colour;r&&this._setColor(r)}var s=i.parent;if(s&&i.popup&&!this._popupInited){var o=function(e){return t.openHandler(e)};this._events.add(s,"click",o),Df(this._events,s,[" ","Spacebar","Enter"],o),this._popupInited=!0}else e.parent&&!i.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===Ef?this._domEdit:this.domElement;setTimeout((function(){return t.focus()}),100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,i=!1;if(e)if(t===Nf||t===Mf){var r=(this.__containedEvent||0)+100;e.timeStamp>r&&(i=!0)}else Bf(e),i=!0;else i=!0;i&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==Nf&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var i=void 0;try{i=new kf(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var r=i.hsla;r[3]=1,i.hsla=r}this.colour=this.color=i,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}(this.settings.template||'
');return this.domElement=t,this._domH=Rf(".picker_hue",t),this._domSL=Rf(".picker_sl",t),this._domA=Rf(".picker_alpha",t),this._domEdit=Rf(".picker_editor input",t),this._domSample=Rf(".picker_sample",t),this._domOkay=Rf(".picker_done button",t),this._domCancel=Rf(".picker_cancel button",t),t.classList.add("layout_"+this.settings.layout),this.settings.alpha||t.classList.add("no_alpha"),this.settings.editor||t.classList.add("no_editor"),this.settings.cancelButton||t.classList.add("no_cancel"),this._ifPopup((function(){return t.classList.add("popup")})),this._setPosition(),this.colour?this._updateUI():this._setColor(this.settings.defaultColor),this._bindEvents(),!0}},{key:"hide",value:function(){return this._toggleDOM(!1)}},{key:"destroy",value:function(){this._events.destroy(),this.domElement&&this.settings.parent.removeChild(this.domElement)}},{key:"_bindEvents",value:function(){var e=this,t=this,i=this.domElement,r=this._events;function s(e,t,i){r.add(e,t,i)}s(i,"click",(function(e){return e.preventDefault()})),Sf(r,this._domH,(function(e,i){return t._setHSLA(e)})),Sf(r,this._domSL,(function(e,i){return t._setHSLA(null,e,1-i)})),this.settings.alpha&&Sf(r,this._domA,(function(e,i){return t._setHSLA(null,null,null,1-i)}));var o=this._domEdit;s(o,"input",(function(e){t._setColor(this.value,{fromEditor:!0,failSilently:!0})})),s(o,"focus",(function(e){var t=this;t.selectionStart===t.selectionEnd&&t.select()})),this._ifPopup((function(){var t=function(t){return e.closeHandler(t)};s(window,Nf,t),s(window,Mf,t),Df(r,i,["Esc","Escape"],t);var o=function(t){e.__containedEvent=t.timeStamp};s(i,Nf,o),s(i,Mf,o),s(e._domCancel,"click",t)}));var n=function(t){e._ifPopup((function(){return e.closeHandler(t)})),e.onDone&&e.onDone(e.colour)};s(this._domOkay,"click",n),Df(r,i,["Enter"],n)}},{key:"_setPosition",value:function(){var e=this.settings.parent,t=this.domElement;e!==t.parentNode&&e.appendChild(t),this._ifPopup((function(i){"static"===getComputedStyle(e).position&&(e.style.position="relative");var r=!0===i?"popup_right":"popup_"+i;["popup_top","popup_bottom","popup_left","popup_right"].forEach((function(e){e===r?t.classList.add(e):t.classList.remove(e)})),t.classList.add(r)}))}},{key:"_setHSLA",value:function(e,t,i,r,s){s=s||{};var o=this.colour,n=o.hsla;[e,t,i,r].forEach((function(e,t){(e||0===e)&&(n[t]=e)})),o.hsla=n,this._updateUI(s),this.onChange&&!s.silent&&this.onChange(o)}},{key:"_updateUI",value:function(e){if(this.domElement){e=e||{};var t=this.colour,i=t.hsla,r="hsl("+360*i[0]+", 100%, 50%)",s=t.hslString,o=t.hslaString,n=this._domH,a=this._domSL,c=this._domA,l=Rf(".picker_selector",n),h=Rf(".picker_selector",a),d=Rf(".picker_selector",c);b(0,l,i[0]),this._domSL.style.backgroundColor=this._domH.style.color=r,b(0,h,i[1]),F(0,h,1-i[2]),a.style.color=s,F(0,d,1-i[3]);var u=s,f=u.replace("hsl","hsla").replace(")",", 0)"),p="linear-gradient("+[u,f]+")";if(this._domA.style.background=p+", linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0 / 2em 2em,\n linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em / 2em 2em",!e.fromEditor){var g=this.settings.editorFormat,m=this.settings.alpha,w=void 0;switch(g){case"rgb":w=t.printRGB(m);break;case"hsl":w=t.printHSL(m);break;default:w=t.printHex(m)}this._domEdit.value=w}this._domSample.style.color=o}function b(e,t,i){t.style.left=100*i+"%"}function F(e,t,i){t.style.top=100*i+"%"}}},{key:"_ifPopup",value:function(e,t){this.settings.parent&&this.settings.popup?e&&e(this.settings.popup):t&&t()}},{key:"_toggleDOM",value:function(e){var t=this.domElement;if(!t)return!1;var i=e?"":"none",r=t.style.display!==i;return r&&(t.style.display=i),r}}]),e}(),Tf=document.createElement("style");function zf(e){if(Pf[e])return Pf[e];if(Pf["chr"+e]){const t=Pf["chr"+e];return Pf[e]=t,t}{const s=(t=Math.round(255*Math.random()).toString(10),i=Math.round(255*Math.random()).toString(10),r=Math.round(255*Math.random()).toString(10),"rgb("+t+","+i+","+r+")");return Pf[e]=s,s}var t,i,r}Tf.textContent='.picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{position:absolute;z-index:-1;opacity:0}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{display:flex;flex-flow:row wrap;justify-content:space-between;align-items:stretch;font-size:10px;width:25em;padding:.5em}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper::before{content:"";display:block;width:100%;height:0;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:1 1 auto}.layout_default .picker_sl::before{content:"";display:block;padding-bottom:100%}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{order:1;flex:1 1 auto}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;background:#f2f2f2;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;box-shadow:0 0 0 1px silver;outline:none}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{padding:.4em .6em;cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(0deg, gainsboro, transparent)}.picker_wrapper button:active{background-image:linear-gradient(0deg, transparent, gainsboro)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid #fff;border-radius:100%;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);box-shadow:0 0 0 1px silver}.picker_sl{position:relative;box-shadow:0 0 0 1px silver;background-image:linear-gradient(180deg, white, rgba(255, 255, 255, 0) 50%),linear-gradient(0deg, black, rgba(0, 0, 0, 0) 50%),linear-gradient(90deg, #808080, rgba(128, 128, 128, 0))}.picker_alpha,.picker_sample{position:relative;background:linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0/2em 2em,linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em/2em 2em;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{font-family:monospace;padding:.2em .4em}.picker_sample::before{content:"";position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;box-shadow:0 0 10px 1px rgba(0,0,0,.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:"";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}',document.documentElement.firstElementChild.appendChild(Tf),Lf.StyleElement=Tf;const Pf={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};class Hf{constructor(e){this.tracks=[],this.chordSets=[]}addChordSet(e){this.chordSets=this.chordSets.filter((t=>t.name!==e.name)),this.chordSets.push(e);let t=this.tracks.find((t=>e.trackName===t.name));t&&(t.chordSets=t.chordSets.filter((t=>t.name!==e.name)),t.chordSets.push(e)),t||(t=new Of(e),this.tracks.push(t))}clearChords(){this.tracks=[],this.chordSets=[]}getTrack(e){return this.tracks.find((t=>e===t.name))}getChordSet(e){return this.chordSets.find((t=>e===t.name))}}class Of{constructor(e){this.name=e.trackName,this.color=e.trackColor,this.visible=!0,this.chordSets=[e],this.id=("0000"+(Math.random()*Math.pow(36,4)|0).toString(36)).slice(-4)}get chords(){if(1===this.chordSets.length)return this.chordSets[0].chords;const e=[];for(let t of this.chordSets)for(let i of t.chords)e.push(i);return e}}const Vf=Math.exp(5);class qf{static isInstalled(){return void 0!==window.JBrowseReactCircularGenomeView&&void 0!==window.React&&void 0!==window.ReactDOM}constructor(e,t){if(t=t||{},this.config=t,qf.isInstalled()){this.parent=e,this.groupByTrack=!0===t.groupByTrack,this.chordManager=new Hf(t);const i=document.createElement("div");i.className="igv-circview-container",e.appendChild(i),this.createControls(i),this.resetControlPanel();const r=document.createElement("div");r.className="igv-circview-circular-genome-view",i.appendChild(r),this.container=r,t.assembly&&this.setAssembly(t.assembly),this.width=t.width||500,this.height=t.height||500,this.setSize(this.width,this.height)}else console.error("JBrowse circular view is not installed")}createControls(e){const t=document.createElement("div");t.className="igv-circview-toolbar",e.appendChild(t),this.toolbar=t;const i=document.createElement("div");i.className="igv-circview-track-panel",e.appendChild(i),this.controlPanel=i,this.controlPanel.style.display="none";const r=document.createElement("div");r.className="igv-circview-toolbar-button-container",this.toolbar.appendChild(r),this.showControlsButton=document.createElement("div"),this.showControlsButton.className="igv-circview-button",r.appendChild(this.showControlsButton),this.showControlsButton.innerText="none"===this.controlPanel.style.display?"Show Controls":"Hide Controls",this.showControlsButton.addEventListener("click",(e=>{this.controlPanel.querySelectorAll("div").length>0&&("none"===this.controlPanel.style.display?(this.controlPanel.style.display="flex",e.target.innerText="Hide Controls"):(this.controlPanel.style.display="none",e.target.innerText="Show Controls"))}));let s=document.createElement("div");s.className="igv-circview-button",r.appendChild(s),s.innerText="Clear All",s.addEventListener("click",(()=>{this.clearChords()})),!1!==this.config.showCloseButton&&(s=document.createElement("div"),s.className="igv-circview-button",r.appendChild(s),s.innerText="Close",s.addEventListener("click",(()=>{this.visible=!1})))}resetControlPanel(){this.controlPanel.innerHTML="",this.controlPanel.appendChild(this.createGroupByCB());const e=this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets;for(let t of e)this.addToControlPanel(t)}createGroupByCB(){const e=document.createElement("input");e.type="checkbox",e.id="groupByCB",e.style.width="1.4em",e.style.height="1.4em",e.checked=this.groupByTrack,e.onclick=e=>{this.groupByTrack=e.target.checked,this.resetControlPanel(),this.render()};const t=document.createElement("label");t.for="groupByCB",t.innerText="Group by track",t.style.color="black",t.style.paddingLeft="10px";const i=document.createElement("div");return i.style.width="100%",i.style.paddingTop="5px",i.style.paddingBottom="5px",i.style.background="rgb(216, 230, 234)",i.appendChild(e),i.appendChild(t),i}addToControlPanel(e){const t=document.createElement("div");this.controlPanel.appendChild(t);const i=document.createElement("div");i.className="igv-circview-button",t.appendChild(i),i.innerText=!0===e.visible?"Hide":"Show",i.addEventListener("click",(t=>{!0===e.visible?(this.hideChordSet(e.name),t.target.innerText="Show"):(this.showChordSet(e.name),t.target.innerText="Hide")}));const r=document.createElement("input"),s=e=>200*Math.log(e*Vf),o=document.createElement("div");o.className="igv-circview-button",o.innerHTML="    ",t.appendChild(o),o.style.backgroundColor=Uf(e.color,1);const n={parent:o,popup:"right",editorFormat:"rgb",color:e.color,onChange:({rgbaString:t})=>{o.style.backgroundColor=Uf(t,1),this.setColor(e.name,t),r.value=s(Qf(e.color))}},a=new Lf(n);r.setAttribute("title","Adjust transparency of arcs"),r.type="range",r.style.width="100px",r.style.marginRight="10px",r.setAttribute("class","range"),r.setAttribute("min","0"),r.setAttribute("max","1000"),r.value=s(Qf(e.color)),r.oninput=()=>{const t=(i=r.value,Math.exp(i/200)/Vf);var i;this.setColor(e.name,Uf(e.color,t)),a.setColor(e.color)},t.appendChild(r);const c=document.createElement("div");c.style.color="black",t.appendChild(c),c.innerText=c.title=e.name}setAssembly(e){const t=this.genomeId||Wf();if(this.genomeId===t)return;this.chordManager.clearChords(),this.genomeId=t,this.chrNames=new Set(e.chromosomes.map((e=>Gf(e.name))));const i=[],r=[];for(let t of e.chromosomes){const e=Gf(t.name);r.push(t.color||zf(e)),i.push({refName:e,uniqueId:e,start:0,end:t.bpLength})}this.assembly={name:e.name,sequence:{trackId:t,type:"ReferenceSequenceTrack",adapter:{type:"FromConfigSequenceAdapter",features:i}},refNameColors:r},this.render()}addChords(e,t={}){const i=t.name||t.track||"*",r=i.split(" ")[0].replaceAll("%20"," "),s={name:i.replaceAll("%20"," "),trackName:r,chords:e,color:t.color||"black",trackColor:t.trackColor||t.color||"black",visible:!0,id:t.id||Wf()};this.chordManager.addChordSet(s),this.resetControlPanel(),this.render()}setSize(e,t){if(t=t||e,this.width=e,this.height=t,this.viewState){const i=this.viewState.session.view;i.setWidth(e),i.setHeight(t),i.setBpPerPx(i.minBpPerPx)}}getSize(){return Math.min(this.width,this.height)}clearChords(){this.chordManager.clearChords(),this.resetControlPanel(),this.render()}clearSelection(){this.viewState.pluginManager.rootModel.session.clearSelection()}show(){this.parent.style.display="block"}hide(){this.parent.style.display="none"}get visible(){return"none"!==this.parent.style.display}set visible(e){this.parent.style.display=e?"block":"none"}hideChordSet(e){let t=this.getChordSet(e);t?(t.visible=!1,this.render()):console.warn(`No track with name: ${name}`)}showChordSet(e){let t=this.getChordSet(e);t?(t.visible=!0,this.render()):console.warn(`No track with name: ${e}`)}deleteTrack(e){let t=this.tracks.findIndex((t=>e===t.name));t>=0&&this.tracks.splice(t,1),this.render()}getChordSet(e){return this.groupByTrack?this.chordManager.getTrack(e):this.chordManager.getChordSet(e)}setColor(e,t){const i=this.getChordSet(e);if(i){i.color=t;const e=i.id;for(let i of this.viewState.config.tracks)if(e===i.trackId){i.displays[0].renderer.strokeColor.set(t);break}}}render(){const{createViewState:e,JBrowseCircularGenomeView:t}=JBrowseReactCircularGenomeView;ReactDOM.unmountComponentAtNode(this.container);const i=(this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets).filter((e=>e.visible)),r=[],s=[];for(let e of i)r.push({trackId:e.id,name:e.name,assemblyNames:["forIGV"],type:"VariantTrack",adapter:{type:"FromConfigAdapter",features:e.chords}}),s.push(e.color);this.viewState=e({assembly:this.assembly,tracks:r});for(let e=0;e div {\n margin: 4px;\n}\n\n.igv-circview-track-panel {\n z-index: 1024;\n position: absolute;\n top: 33px;\n left: 0;\n width: 100%;\n height: fit-content;\n border-bottom-style: solid;\n border-bottom-color: dimgray;\n border-bottom-width: thin;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n}\n.igv-circview-track-panel > div {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-circview-track-panel > div > div {\n margin: 4px;\n}\n\n.igv-circview-swatch-button {\n cursor: pointer;\n padding: 5px;\n width: 8px;\n height: 8px;\n border: 1px solid #8d8b8b;\n border-radius: 16px;\n}\n\n.igv-circview-button {\n cursor: pointer;\n padding: 5px;\n color: #444;\n vertical-align: middle;\n text-align: center;\n font-family: "Open Sans", sans-serif;\n font-size: 12px;\n border: 1px solid #8d8b8b;\n border-radius: 4px;\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.2);\n}\n\n.igv-circview-button:hover {\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n.igv-circview-button:active {\n color: #007bff;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n/*# sourceMappingURL=circular-view.css.map */\n',document.head.insertBefore(e,document.head.childNodes[document.head.childNodes.length-1])}()}const $f=e=>e.startsWith("chr")?e.substring(3):e;function Kf(e){const t=[],i=[];if(e.wgChromosomeNames)for(let r of e.wgChromosomeNames){const s=e.getChromosome(r);i.push($h(s.name)),t.push({name:s.name,bpLength:s.bpLength})}return t}function Zf(e,t,i,r){const s=t.color||"rgb(0,0,255)",o=ur.addAlpha("all"===i.chr?s:$h(i.chr),r),n=ur.addAlpha(s,r),a=t.name.replaceAll(" ","%20"),c="all"===i.chr?a:`${a} ${i.chr}:${i.start}-${i.end}`;t.browser.circularView.addChords(e,{track:c,color:o,trackColor:n}),t.browser.circularViewVisible||(t.browser.circularViewVisible=!0)}class Yf{constructor(e,{minTLENPercentile:t,maxTLENPercentile:i}){this.totalCount=0,this.frCount=0,this.rfCount=0,this.ffCount=0,this.sumF=0,this.sumF2=0,this.lp=void 0===t?.1:t,this.up=void 0===i?99.5:i,this.isizes=[],this.compute(e)}compute(e){for(let r of e)if(r.isProperPair()){var t=Math.abs(r.fragmentLength);this.sumF+=t,this.sumF2+=t*t,this.isizes.push(t);var i=r.pairOrientation;if("string"==typeof i&&4===i.length)switch(""+i.charAt(0)+i.charAt(2)){case"FF":case"RR":this.ffCount++;break;case"FR":this.frCount++;break;case"RF":this.rfCount++}this.totalCount++}this.ffCount/this.totalCount>.9?this.orienation="ff":this.frCount/this.totalCount>.9?this.orienation="fr":this.rfCount/this.totalCount>.9&&(this.orienation="rf"),this.minTLEN=0===this.lp?0:Xf(this.isizes,this.lp),this.maxTLEN=Xf(this.isizes,this.up)}}function Xf(e,t){if(0!==e.length){var i=Math.floor(e.length*(t/100));return e.sort((function(e,t){return e-t})),e[i]}}const Jf="rgb(255,0,255)",ep="rgb(0,0,255)",tp="rgb(132, 178, 158)",ip=new Map;ip.set("m","rgb(255,0,0)"),ip.set("h",Jf),ip.set("o","rgb(111, 78, 129)"),ip.set("f","rgb(246, 200, 95)"),ip.set("c","rgb(157, 216, 102)"),ip.set("g","rgb(255, 160, 86)"),ip.set("e","rgb(141, 221, 208)"),ip.set("b","rgb(202, 71, 47)"),ip.set("h",Jf),ip.set("a","rgb(51,0,111)"),ip.set("NONE_A",ep),ip.set("NONE_C",ep),ip.set("NONE_T",ep),ip.set("NONE_G",ep),ip.set("NONE_N",ep);const rp=new Map;function sp(e,t,i){let r=function(e){return ip.has(e)?ip.get(e):tp}(e),s=lu(t);if(s>255)return r;const o=e+s+i;if(s<0&&(s=0),!rp.has(o)){const e="basemod2"===i?Math.max(20,Math.min(255,s*s/50-4*s+200+20)):Math.max(20,Math.min(255,.006127*s*s)),[t,n,a]=ur.rgbComponents(r);rp.set(o,`rgba(${t},${n},${a},${e/255})`)}return rp.get(o)}class op{constructor(e){this.alignmentTrack=e}updateContext(e){this.context=e}drawModifications(e,t,i,r,s,o){const{ctx:n,pixelEnd:a,bpStart:c,bpPerPixel:l}=r,h=e.getBaseModificationSets();if(h){let r;const d=s.split(":");2==d.length&&(s=d[0],r=d[1]);for(let d of e.blocks){if("S"===d.type)continue;const e=t,u=i;let f=Math.max(1,1/l);for(let t=d.seqOffset;ta)break;if(i+f<0)continue;let p,g=-1,m=255,w=0;for(let e of h)if((!r||e.modification===r)&&e.containsPosition(t)){const i=lu(e.likelihoods.get(t));m-=i,(!p||i>g)&&(p=e.modification,w=e.canonicalBase,g=i)}if(p){const t=255*o;let r;m>g&&"basemod2"===s&&m>=t?r=sp("NONE_"+w,m,s):g>=t&&(r=sp(p,g,s)),n.fillStyle=r,f<3&&(f=3,i--),n.fillRect(i,e,f,Math.max(1,u-2))}}}}}}const np=new Set(["firstOfPairStrand"]);class ap extends ma{static defaults={viewAsPairs:!1,showSoftClips:!1,showAllBases:!1,showInsertions:!0,showMismatches:!0,colorBy:void 0,groupBy:void 0,displayMode:"EXPANDED",alignmentRowHeight:14,squishedRowHeight:3,negStrandColor:"rgba(150, 150, 230, 0.75)",posStrandColor:"rgba(230, 150, 150, 0.75)",baseModPosStrandColor:"rgb(195, 195, 195)",baseModNegStrandColor:"rgb(195, 210, 195)",insertionColor:"rgb(138, 94, 161)",insertionTextColor:"white",showInsertionText:!1,deletionColor:"black",deletionTextColor:"black",showDeletionText:!1,skippedColor:"rgb(150, 170, 170)",pairConnectorColor:void 0,smallTLENColor:"rgb(0, 0, 150)",largeTLENColor:"rgb(200, 0, 0)",expectedPairOrientation:"fr",rlColor:"rgb(0, 150, 0)",rrColor:"rgb(20, 50, 200)",llColor:"rgb(0, 150, 150)",bamColorTag:"YC",hideSmallIndels:!1,indelSizeThreshold:1,highlightColor:void 0,minTLEN:void 0,maxTLEN:void 0,tagColorPallete:"Set1"};_colorTables=new Map;_baseModifications=new Set;constructor(e,t){super(e,t),(e.colorTable||e.tagColorTable)&&(this.colorTable=new $r(e.tagColorTable)),e.showTags&&e.hideTags&&console.warn("Both showTags and hideTags specified. showTags will be used."),e.showTags?(this.showTags=new Set(e.showTags),this.hiddenTags=new Set):this.hiddenTags=new Set(e.hideTags||["SA","MD"]),e.largeFragmentLengthColor&&(this.largeTLENColor=e.largeFragmentLengthColor),e.pairOrienation&&(this.expectedPairOrientation=e.pairOrientation),e.smallFragmentLengthColor&&(this.smallTLENColor=e.smallFragmentLengthColor),e.largeFragmentLengthColor&&(this.largeTLENColor=e.largeFragmentLengthColor),e.minFragmentLength&&(this.minTLEN=e.minFragmentLength),e.maxFragmentLength&&(this.maxTLEN=e.maxFragmentLength),e.displayMode&&(this.displayMode=e.displayMode.toUpperCase()),e.colorBy&&e.colorByTag&&(this.colorBy=e.colorBy+":"+e.colorByTag),this.featureSource=this.parent.featureSource,this.top=0===e.coverageTrackHeight?0:e.coverageTrackHeight+5,this.pairColors={RL:this.rlColor,RR:this.rrColor,LL:this.llColor},e.highlightedReads&&this.setHighlightedReads(e.highlightedReads),this.hasPairs=!1,this.hasSupplemental=!1,this._groupByTags=[],this._groupByPositions=[],e.groupBy&&(this.groupBy=e.groupBy,e.groupBy.startsWith("base:")&&this._groupByPositions.push(e.groupBy.substring(5)),e.groupBy.startsWith("tag:")&&this._groupByTags.push(e.groupBy.substring(4))),this._locusChange=lp.bind(this),this.browser.on("locuschange",this._locusChange)}init(e){this.parent=e.parent,delete e.parent,super.init(e)}dispose(){this.browser.off("locuschange",this._locusChange)}get baseModRenderer(){return this._baseModRenderer||(this._baseModRenderer=new op(this)),this._baseModRenderer}get baseModificationThreshold(){return this.parent.baseModificationThreshold}setTop(e,t){this.top=0===e.height||!1===t?0:5+e.height}setHighlightedReads(e,t){if(!Array.isArray(e)||!e.every((e=>"string"==typeof e)))throw new Error("AlignmentTrack.setHighlightedReads() only accept array of strings");t&&(this.highlightColor=t),this.highlightedReads=new Set(e)}computePixelHeight(e){if(e.packedGroups){let t=e.hasDownsampledIntervals()?15:0;const i="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;for(let r of e.packedGroups.values())t+=i*r.length+10;return t+5}return 0}draw(e){const t=e.features,i=e.context,r=e.bpPerPixel,s=e.bpStart,o=e.pixelWidth,n=s+o*r+1,a=this.showSoftClips,c=this.showAllBases,l=this.browser.nucleotideColors;i.save();for(let e of t.baseModificationKeys)this._baseModifications.add(e.modification);let h=t.sequence;h&&(h=h.toUpperCase());let d=0;this.colorBy||(this.colorBy=this.hasPairs?"unexpectedPair":"none");let u=e.pixelTop-up.coverageTrackHeight;this.top&&i.translate(0,this.top);const f=u+e.pixelHeight;t.hasDownsampledIntervals()?(d=15,t.downsampledIntervals.forEach((function(e){var t=(e.start-s)/r,o=(e.end-s)/r;o-t>5&&(t+=1,o-=1),Co.fillRect(i,t,2,o-t,8,{fillStyle:"black"})}))):d=0,this.alignmentsYOffset=d;const p="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight,g=t.packedGroups;if(g){let t=d;for(let r of g.keys()){const a=g.get(r),c=a.rows,l=c.length;a.pixelTop=t;for(let e=0;ef)break;if(t+rn)break;!0!==e.hidden&&(e instanceof eu?(m.call(this,e,t,r),w.call(this,e.firstAlignment,t,r),e.secondAlignment&&w.call(this,e.secondAlignment,t,r)):w.call(this,e,t,r))}t+=p}}if(a.pixelBottom=t,this.groupBy&&r){i.save(),i.font="400 12px sans-serif";const s=i.measureText(r),n=s.width+10,c=-e.pixelShift+e.viewportWidth-n-10,l=s.actualBoundingBoxAscent+s.actualBoundingBoxDescent+10,h=Math.min(a.pixelTop+l-1,a.pixelBottom);i.textAlign="center",i.fillStyle="white",i.strokeStyle="lightGray",Co.roundRect(i,c,h-s.actualBoundingBoxAscent-5,n,l,2,1,1),i.fillStyle="black",i.fillText(r,c+n/2,h),Co.dashedLine(i,0,t,o,t),i.restore(),t+=10}}}function m(e,t,o){var a=this.getConnectorColor(e.firstAlignment),c=(e.connectingStart-s)/r,l=(e.connectingEnd-s)/r,h=t+o/2;e.connectingEndn||(e.mq<=0&&(a=ur.addAlpha(a,.15)),Co.setProperties(i,{fillStyle:a,strokeStyle:a}),Co.strokeLine(i,c,h,l,h))}function w(e,d,u){if(e.start+e.lengthOnRefn)return;const f=a?e.blocks:e.blocks.filter((e=>"S"!==e.type));let g=this.getAlignmentColor(e);const m=g;e.mq<=0&&(g=ur.addAlpha(g,.15)),Co.setProperties(i,{fillStyle:g,strokeStyle:m});const w=[];for(let e=0;en))break}if(e.gaps){const t=d+u/2;for(let o of e.gaps){const e=(o.start-s)/r,n=(o.start+o.len-s)/r,a=n-e,c=o.len.toString(),l=6*c.length,h=e+a/2,u="D"===o.type?this.deletionColor:this.skippedColor;if(Co.strokeLine(i,e,t,n,t,{strokeStyle:u,lineWidth:2}),this.showDeletionText&&o.len>1&&a>=l+8){const e=h-l/2;Co.fillRect(i,e-1,d-1,l+2,12,{fillStyle:"white"}),Co.fillText(i,c,e,d+10,{font:"normal 10px monospace",fillStyle:this.deletionTextColor})}}}if(e.insertions&&this.showInsertions){let t=-1;for(let o of e.insertions){if(this.hideSmallIndels&&o.len<=this.indelSizeThreshold)continue;if(o.startn)break;const e=o.start-s,a=o.len.toString(),c=2+6*a.length,l=this.showInsertionText&&1!==o.len?Math.round(o.len/r):2,h=Math.max(Math.min(c,l),2),f=e/r-h/2;if(f-t>2){const e={fillStyle:this.insertionColor};Co.fillRect(i,f-2,d,h+4,2,e),Co.fillRect(i,f,d+2,h,u-4,e),Co.fillRect(i,f-2,d+u-2,h+4,2,e),this.showInsertionText&&o.len>1&&l>c&&Co.fillText(i,a,f+1,d+10,{font:"normal 10px monospace",fillStyle:this.insertionTextColor}),t=f}}}for(let{bbox:e,baseColor:t,readChar:s}of w){if(r<=.1&&e.height>=8){const r=Math.min(10,e.height);i.font=r+"px sans-serif";const o=e.x+e.width/2;Co.strokeText(i,s,o-i.measureText(s).width/2,r-1+e.y,{strokeStyle:t})}else Co.fillRect(i,e.x,e.y,e.width,e.height,{fillStyle:t})}if(this.colorBy&&this.colorBy.startsWith("basemod")){const t={ctx:i,bpPerPixel:r,bpStart:s,bpEnd:n,pixelEnd:o};this.baseModRenderer.drawModifications(e,d,u,t,this.colorBy,this.baseModificationThreshold)}function b(n,a){const w=[],b=n.start-t.start,F=(n.start-s)/r,v=(n.start+n.len-s)/r,y=Math.max(1,v-F),A=100/r,C=Math.min(p/2,A/6),_="S"===n.type,x=e.mq<=0||this.selectedReadName===e.readName||_||this.highlightedReads&&this.highlightedReads.has(e.readName);let k=m;this.selectedReadName===e.readName?k="red":_?k="rgb(50,50,50)":this.highlightedReads&&this.highlightedReads.has(e.readName)&&(k=this.highlightColor||"#00ff00");const I=!0===e.strand&&a===f.length-1,S=!1===e.strand&&0===a;if(I|S){let e,t;I?(e=[F,v,v+C,v,F,F],t=[d,d,d+u/2,d+u,d+u,d]):S&&(e=[v,F,F-C,F,v,v],t=[d,d,d+u/2,d+u,d+u,d]),Co.fillPolygon(i,e,t,{fillStyle:g}),x&&Co.strokePolygon(i,e,t,{strokeStyle:k})}else Co.fillRect(i,F,d,y,u,{fillStyle:g}),x&&(i.save(),i.strokeStyle=k,i.strokeRect(F,d,y,u),i.restore());if(_||c||this.showMismatches&&h&&e.seq&&"*"!==e.seq){const t=e.seq?e.seq.toUpperCase():void 0,i=e.qual,a=n.seqOffset,f=Math.max(1,1/r);for(let e=0,p=n.len;eo)break;let g=t?t.charAt(a+e):"";const m=b+e>=0?h.charAt(b+e):"";if("="===g&&(g=m),"X"===g||m!==g||_||c){let t=l[g]||"rgb(0,0,0)";if(!_&&void 0!==i&&i.length>a+e){t=cp(i[a+e],t)}w.push({bbox:{x:p,y:d,width:f,height:u},baseColor:t,readChar:g})}}}return w}}i.restore()}popupData(e){const t=this.getClickedObject(e);return t?.popupData(e.genomicLocation,this.hiddenTags,this.showTags)}menuItemList(){let t=[];t.push("
");let i=e('
');i.innerText="Color by:",t.push({name:void 0,element:i,click:void 0,init:void 0});const r=[];r.push({key:"none",label:"none"}),r.push({key:"strand",label:"read strand"}),this.hasPairs&&(r.push({key:"firstOfPairStrand",label:"first-of-pair strand"}),r.push({key:"pairOrientation",label:"pair orientation"}),r.push({key:"tlen",label:"insert size (TLEN)"}),r.push({key:"unexpectedPair",label:"pair orientation & insert size (TLEN)"})),this.colorBy&&this.colorBy.startsWith("tag:")&&r.push({key:this.colorBy,label:this.colorBy}),r.push({key:"tag",label:"tag..."});for(let e of r){const i=void 0===this.colorBy&&"none"===e.key||this.colorBy===e.key;t.push(this.colorByCB(e,i))}const s=this._baseModifications.size;if(s>0){t.push('
');let e=1===s?"base modification":"base modification (all)";if(t.push(this.basemodColorByCB({key:"basemod",label:e})),s>1)for(let e of this._baseModifications)t.push(this.basemodColorByCB({key:"basemod:"+e,label:`base modification (${au(e)})`}));if(t.push('
'),e=1===s?"base modification 2-color":"base modification 2-color (all)",t.push(this.basemodColorByCB({key:"basemod2",label:e})),s>1)for(let e of this._baseModifications)t.push(this.basemodColorByCB({key:"basemod2:"+e,label:`base modification 2-color (${au(e)})`}))}t.push("
"),i=document.createElement("div"),i.className="igv-track-menu-category",i.textContent="Group by:",t.push({name:void 0,element:i,click:void 0,init:void 0});const o=[];o.push({key:"none",label:"none"}),o.push({key:"strand",label:"read strand"}),this.hasPairs&&(o.push({key:"firstOfPairStrand",label:"first-of-pair strand"}),o.push({key:"pairOrientation",label:"pair orientation"}),o.push({key:"mateChr",label:"chromosome of mate"})),o.push({key:"chimeric",label:"chimeric"}),o.push({key:"supplementary",label:"supplementary flag"}),o.push({key:"readOrder",label:"read order"});for(let e of this._groupByTags)o.push({key:`tag:${e}`,label:`tag:${e}`});for(let e of this._groupByPositions)o.push({key:`base:${e}`,label:`base:${e}`});o.push({key:"tag",label:"tag..."});for(let e of o){const i=void 0===this.groupBy&&"none"===e.key||this.groupBy===e.key;t.push(this.groupByCB(e,i))}t.push("
"),t.push({element:ua("Show all bases",this.showAllBases),click:function(){this.alignmentTrack.showAllBases=!this.alignmentTrack.showAllBases,this.trackView.repaintViews()}}),t.push({element:ua("Show mismatches",this.showMismatches),click:function(){this.alignmentTrack.showMismatches=!this.alignmentTrack.showMismatches,this.trackView.repaintViews()}}),t.push({element:ua("Show insertions",this.showInsertions),click:function(){this.alignmentTrack.showInsertions=!this.alignmentTrack.showInsertions,this.trackView.repaintViews()}}),t.push({element:ua("Show soft clips",this.showSoftClips),click:function(){this.alignmentTrack.showSoftClips=!this.alignmentTrack.showSoftClips;const e=this.getCachedAlignmentContainers();for(let t of e)t.pack(this);this.trackView.repaintViews()}}),this.hasPairs&&(t.push("
"),t.push({element:ua("View as pairs",this.viewAsPairs),click:function(){const e=!this.alignmentTrack.viewAsPairs;if(e&&this.groupBy&&!np.has(this.groupBy))return void this.browser.alert.present(`'View as Pairs' is incompatible with 'Group By ${this.groupBy}'`);this.alignmentTrack.viewAsPairs=e;const t=this.getCachedAlignmentContainers();for(let e of t)e.pack(this);this.trackView.checkContentHeight(),this.trackView.repaintViews()}})),this.browser.circularView&&(this.hasPairs||this.hasSupplemental)&&(t.push("
"),this.hasPairs&&t.push({label:"Add discordant pairs to circular view",click:function(){for(let e of this.trackView.viewports)this.addPairedChordsForViewport(e)}}),this.hasSupplemental&&t.push({label:"Add split reads to circular view",click:function(){for(let e of this.trackView.viewports)this.addSplitChordsForViewport(e)}})),t.push("
"),i=document.createElement("div"),i.className="igv-track-menu-category",i.textContent="Display mode:",t.push({name:void 0,element:i,click:void 0,init:void 0});for(let e of["EXPANDED","SQUISHED","FULL"])t.push({element:ua(e.toLowerCase(),this.displayMode===e),click:function(){this.alignmentTrack.setDisplayMode(e)}});return t}setDisplayMode(e){const t="FULL"===this.displayMode||"FULL"===e;if(this.displayMode=e,t){const e=this.getCachedAlignmentContainers();for(let t of e)t.pack(this)}this.trackView.checkContentHeight(),this.trackView.repaintViews()}colorByCB(e,t){const i=ua(e.label,t);if("tag"!==e.key){function r(){this.alignmentTrack.colorBy=e.key,this.trackView.repaintViews()}return{name:void 0,element:i,click:r,init:void 0}}{function s(e){const t=this.alignmentTrack.colorBy.startsWith("tag:")?this.alignmentTrack.colorBy.substring(4):"";this.browser.inputDialog.present({label:"Tag Name",value:t,callback:e=>{const t=this.alignmentTrack;e?(t.colorBy="tag:"+e,t.colorTable||(t.colorTable=new Wr("Set1"))):t.colorBy=void 0,this.trackView.repaintViews()}},e)}return{name:void 0,element:i,dialog:s,init:void 0}}}basemodColorByCB(e){const t=this.colorBy===e.key;return{name:void 0,element:ua(e.label,t),click:function(){this.alignmentTrack.colorBy=e.key,this.trackView.repaintViews()},init:void 0}}groupByCB(e,t){return{name:void 0,element:ua(e.label,t),dialog:function(t){const i=()=>this.alignmentTrack.repackAlignments();if("tag"===e.key){let e="";this.alignmentTrack.groupBy&&this.alignmentTrack.groupBy.startsWith("tag:")&&(e=this.alignmentTrack.groupBy.substring(4)),this.browser.inputDialog.present({label:"Tag Name",value:e,callback:e=>{e&&(this.alignmentTrack.groupBy="tag:"+e,this.alignmentTrack._groupByTags.push(e),i())}},t)}else"none"===e.key?this.alignmentTrack.groupBy=void 0:this.alignmentTrack.groupBy=e.key,i()},init:void 0}}repackAlignments(){const e=this.getCachedAlignmentContainers();for(let t of e)"function"==typeof t.pack&&t.pack(this);this.trackView.checkContentHeight(),this.trackView.repaintViews()}contextMenuItemList(e){const t=e.viewport,i=[],r=i=>{const r=this.sortObject,s=!r||r.position!==Math.floor(e.genomicLocation)||!r.direction,o={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:i,direction:s,sortAsPairs:t.trackView.track.viewAsPairs};this.sortObject=o,t.cachedFeatures.sortRows(o),t.repaint()};i.push("Sort by..."),i.push({label:"  base",click:()=>r("BASE")}),i.push({label:"  read strand",click:()=>r("strand")}),i.push({label:"  start location",click:()=>r("START")}),i.push({label:"  insert size",click:()=>r("INSERT_SIZE")}),i.push({label:"  gap size",click:()=>r("GAP_SIZE")}),i.push({label:"  chromosome of mate",click:()=>r("MATE_CHR")}),i.push({label:"  mapping quality",click:()=>r("MQ")}),i.push({label:"  read name",click:()=>r("READ_NAME")}),i.push({label:"  aligned read length",click:()=>r("ALIGNED_READ_LENGTH")}),i.push({label:"  tag",click:()=>{const i=this.sortObject,r=!i||i.position!==Math.floor(e.genomicLocation)||!i.direction,s={label:"Tag Name",value:this.sortByTag?this.sortByTag:"",callback:i=>{if(i){const s={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:"TAG",tag:i,direction:r};this.sortByTag=i,this.sortObject=s,t.cachedFeatures.sortRows(s),t.repaint()}}};this.browser.inputDialog.present(s,e.event)}}),i.push("
");const s=`${t.referenceFrame.chr}:${F(Math.floor(e.genomicLocation)+1)}`;i.push({label:`Group by base @${s}`,click:()=>{this._groupByPositions.push(s),this.groupBy=`base:${s}`;const e=this.getCachedAlignmentContainers();for(let t of e)t.pack(this);this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),i.push("
");const o=this.getClickedObject(e);if(o){const t=this.showSoftClips,r="function"==typeof o.alignmentContaining?o.alignmentContaining(e.genomicLocation,t):o;if(r){r.isPaired()&&r.isMateMapped()&&i.push({label:"View mate in split screen",click:()=>{if(r.mate){const t=e.viewport.referenceFrame,i=this.browser.genome.getChromosome(r.mate.chr);if(i){this.selectedReadName=r.readName;const s=t.bpPerPixel*e.viewport.getWidth(),o=r.mate.position-s/2,n=r.mate.position+s/2;this.browser.addMultiLocusPanel(i.name,o,n,t)}else this.browser.alert.present(`Reference does not contain chromosome: ${r.mate.chr}`)}},init:void 0}),i.push("
");const t=r.softClippedBlocks();i.push({label:"View read sequence",click:()=>{const e=r.seq;this.browser.alert.present(e&&"*"!==e?e:"Read sequence: *")}}),t.left&&t.left.len>0&&i.push({label:"View left soft-clipped sequence",click:()=>{const e=r.seq.substring(t.left.seqOffset,t.left.seqOffset+t.left.len);this.browser.alert.present(e)}}),t.right&&t.right.len>0&&i.push({label:"View right soft-clipped sequence",click:()=>{const e=r.seq.substring(t.right.seqOffset,t.right.seqOffset+t.right.len);this.browser.alert.present(e)}}),i.push("
"),ds()&&(i.push({label:"Copy read sequence",click:async()=>{try{await navigator.clipboard.writeText(r.seq)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),t.left&&t.left.len>0&&i.push({label:"Copy left soft-clipped sequence",click:async()=>{try{const e=r.seq.substring(t.left.seqOffset,t.left.seqOffset+t.left.len);await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),t.right&&t.right.len>0&&i.push({label:"Copy right soft-clipped sequence",click:async()=>{try{const e=r.seq.substring(t.right.seqOffset,t.right.seqOffset+t.right.len);await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}));const s=r.seq;if(s&&"*"!==s){i.push("
"),s.length{const e=r.isNegativeStrand()?Eo(s):s,t=`${r.readName} - blat`,i=`${this.name} - ${t}`;Yl({sequence:e,browser:this.browser,name:t,title:i})}});const e=r.softClippedBlocks();e.left&&e.left.len>20&&e.left.len{const t=s.substring(e.left.seqOffset,e.left.seqOffset+e.left.len),i=r.isNegativeStrand()?Eo(t):t,o=`${r.readName} - blat left clip`,n=`${this.name} - ${o}`;Yl({sequence:i,browser:this.browser,name:o,title:n})}}),e.right&&e.right.len>20&&e.right.len{const t=s.substring(e.right.seqOffset,e.right.seqOffset+e.right.len),i=r.isNegativeStrand()?Eo(t):t,o=`${r.readName} - blat right clip`,n=`${this.name} - ${o}`;Yl({sequence:i,browser:this.browser,name:o,title:n})}})}i.push("
")}}return this.browser.circularView&&(this.hasPairs||this.hasSupplemental)&&(this.hasPairs&&i.push({label:"Add discordant pairs to circular view",click:()=>{this.addPairedChordsForViewport(t)}}),this.hasSupplemental&&i.push({label:"Add split reads to circular view",click:()=>{this.addSplitChordsForViewport(t)}}),i.push("
")),i}getClickedObject(e){let t=e.viewport.cachedFeatures;if(!t)return;const i=e.y-this.top,r=e.genomicLocation;if(t.packedGroups){let e=Number.MAX_VALUE;for(let s of t.packedGroups.values())if(e=Math.min(e,s.pixelTop),i>s.pixelTop&&i<=s.pixelBottom){const e="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;let t=Math.floor((i-s.pixelTop)/e);if(t>=0&&te.containsLocation(r,this.showSoftClips)));if(e.length>0)return e[0]}}if(i=r)return e}}getConnectorColor(e){if(this.pairConnectorColor)return this.pairConnectorColor;let t=this.colorBy;switch(t&&t.startsWith("tag:")&&(t.substring(4),t="tag"),t){case"strand":case"firstOfPairStrand":case"pairOrientation":case"tag":return this.color?"function"==typeof this.color?this.color(e):this.color:"rgb(200, 200, 200)";default:return this.getAlignmentColor(e)}}getAlignmentColor(e){let t;t=this.color?"function"==typeof this.color?this.color(e):this.color:"rgb(185, 185, 185)";let i,r=this.colorBy;switch(r&&r.startsWith("tag:")&&(i=r.substring(4),r="tag"),r){case"basemod":case"basemod2":t=e.strand?this.baseModPosStrandColor:this.baseModNegStrandColor;break;case"strand":t=e.strand?this.posStrandColor:this.negStrandColor;break;case"firstOfPairStrand":const s=e.firstOfPairStrand;void 0!==s&&(t=s?this.posStrandColor:this.negStrandColor);break;case"unexpectedPair":case"pairOrientation":if(e.pairOrientation){const i=uu[this.expectedPairOrientation];if(i){const r=this.pairColors[i[e.pairOrientation]];if(r){t=r;break}}}if("pairOrientation"===r)break;case"tlen":case"fragmentLength":e.mate&&e.isMateMapped()&&(e.mate.chr!==e.chr?t=$h(e.mate.chr):this.minTemplateLength&&Math.abs(e.fragmentLength)this.maxTemplateLength&&(t=this.largeTLENColor));break;case"tag":const o=e.tags()[i];void 0!==o&&("function"==typeof o.startsWith&&(t=ur.createColorStringSafe(o)),t||(this.colorTable||(this.colorTable=new Wr(this.tagColorPallete)),t=this.colorTable.getColor(o)))}return t}get nucleotideColors(){return this.browser.nucleotideColors}get minTemplateLength(){return void 0!==this.minTLEN?this.minTLEN:this.parent._pairedEndStats?this.parent._pairedEndStats.minTLEN:0}get maxTemplateLength(){return void 0!==this.maxTLEN?this.maxTLEN:this.parent._pairedEndStats?this.parent._pairedEndStats.maxTLEN:1e3}getState(){const e=super.getState();return this.highlightedReads&&(e.highlightedReads=Array.from(this.highlightedReads)),e}get name(){return this.parent.name}set name(e){this.parent.name=e}get color(){return this.parent.color}set color(e){this.parent.color=e}get trackView(){return this.parent.trackView}get getCachedAlignmentContainers(){return this.parent.getCachedAlignmentContainers}get sortObject(){return this.parent.sortObject}set sortObject(e){this.parent.sortObject=e}addPairedChordsForViewport(e){return this.parent.addPairedChordsForViewport(e)}addSplitChordsForViewport(e){return this.parent.addSplitChordsForViewport(e)}}function cp(e,t){let i;return i=e<5?.1:Math.max(.1,Math.min(1,.1+.9*(e-5)/15)),i=Math.round(10*i)/10,i<1&&(t=ur.addAlpha(t,i)),t}function lp(){"FULL"!==this.displayMode||this.browser.isTrackPanning()||this.repackAlignments()}function hp(e,t,i,r,s,o,n,a,c){const l=n.baseModCounts,h=n.coverageMap;if(l){let n;const d=a.split(":");2==d.length&&(a=d[0],n=d[1]);const u=Array.from(l.allModifications);u.sort(tu.compare);const f=h.getTotalCount(o);if(!u.filter((e=>n?n===e.modification:!e.modification.startsWith("NONE_"))).find((e=>l.getCount(o,e,0,!1)>0)))return;for(let d of u){if(d.modification.startsWith("NONE_")&&"basemod2"!==a)continue;if(n&&n!==d.modification&&!d.modification.startsWith("NONE_"))continue;const u=d.base,p=Io(u),g=h.getCount(o,u)+h.getCount(o,p),m=l.simplexModifications.has(d.modification)?h.getPosCount(o,u)+h.getNegCount(o,p):g;if(0==m)continue;const w="basemod2"===a,b=l.getCount(o,d,c,w);if(0==b)continue;const F=g/f*(b/m),v=Math.round(F*s),y=l.getLikelihoodSum(o,d,c,w)/b,A=i-v,C=sp(d.modification,y,a);e.fillStyle=C,e.fillRect(t,A,r,v),i=A}}}class dp{constructor(e,t){this.featureType="numeric",this.parent=t,this.featureSource=t.featureSource,this.paintAxis=Oc,this.top=0,this.autoscale=e.autoscale||void 0===e.max,e.coverageColor&&(this.color=e.coverageColor),this.autoscale||(this.dataRange={min:e.min||0,max:e.max})}get height(){return this.parent.coverageTrackHeight}draw(e){const t=e.pixelTop;e.pixelHeight;const i=this.parent.browser.nucleotideColors;if(t>this.height)return;const r=e.context,s=e.features,o=s.coverageMap;let n;o.refSeq&&(n=o.refSeq.toUpperCase());const a=e.bpPerPixel,c=e.bpStart,l=c+e.pixelWidth*a+1;let h;h=this.color?this.color:this.parent.color&&"function"!=typeof this.parent.color?ur.darkenLighten(this.parent.color,-35):"rgb(150, 150, 150)",Co.setProperties(r,{fillStyle:h,strokeStyle:h});const d=Math.max(1,1/a);for(let e=0,t=o.coverage.length;el)break;const i=o.coverage[e];if(!i)continue;const s=i.total/this.dataRange.max*this.height,n=this.height-s,h=(t-c)/a;Co.fillRect(r,h,n,d,s)}if(n)for(let e=0,t=o.coverage.length;el)break;const h=o.coverage[e];if(!h)continue;const u=h.total/this.dataRange.max*this.height;let f=this.height-u;const p=Math.floor((t-c)/a),g=n[e];if(this.parent.colorBy&&this.parent.colorBy.startsWith("basemod"))hp(r,p,this.height,d,u,t,s,this.parent.colorBy,this.parent.baseModificationThreshold);else if(h.isMismatch(g)){Co.setProperties(r,{fillStyle:i[g]}),Co.fillRect(r,p,f,d,u);let e=0;for(let t of["A","C","T","G"]){const s=(h["pos"+t]+h["neg"+t])/this.dataRange.max*this.height;f=this.height-s-e,e+=s,Co.setProperties(r,{fillStyle:i[t]}),Co.fillRect(r,p,f,d,s)}}}}getClickedObject(e){let t=e.viewport.cachedFeatures;if(!t||0===t.length)return;const i=Math.floor(e.genomicLocation),r=t.coverageMap,s=Math.floor(i-r.bpStart),o=r.coverage[s];return o?{coverage:o,baseModCounts:t.baseModCounts,hoverText:()=>r.coverage[s].hoverText()}:void 0}popupData(e){const t=[],{coverage:i,baseModCounts:r}=this.getClickedObject(e);if(i){const s=Math.floor(e.genomicLocation),o=e.viewport.referenceFrame;t.push(o.chr+":"+F(1+s)),t.push({name:"Total Count",value:i.total});let n=i.posA+i.negA;n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posA+"+, "+i.negA+"- )"),t.push({name:"A",value:n}),n=i.posC+i.negC,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posC+"+, "+i.negC+"- )"),t.push({name:"C",value:n}),n=i.posG+i.negG,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posG+"+, "+i.negG+"- )"),t.push({name:"G",value:n}),n=i.posT+i.negT,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posT+"+, "+i.negT+"- )"),t.push({name:"T",value:n}),n=i.posN+i.negN,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posN+"+, "+i.negN+"- )"),t.push({name:"N",value:n}),t.push("
"),t.push({name:"DEL",value:i.del.toString()}),t.push({name:"INS",value:i.ins.toString()}),r&&(t.push("
"),t.push(...r.popupData(s,this.parent.colorBy)))}return t}}class up extends ma{static defaults={alleleFreqThreshold:.2,visibilityWindow:3e4,showCoverage:!0,showAlignments:!0,height:300,coverageTrackHeight:50,baseModificationThreshold:0};constructor(e,t){super(e,t)}init(e){this.type="alignment",this.featureSource=new Ff(e,this.browser);const t=Object.assign({parent:this},e);this.coverageTrack=new dp(t,this);const i=Object.assign({parent:this},e);this.alignmentTrack=new ap(i,this.browser),super.init(e),this.showAlignments||(this._height=this.coverageTrackHeight),e.sort&&(Array.isArray(e.sort)?this.assignSort(e.sort[0]):this.assignSort(e.sort))}dispose(){this.alignmentTrack.dispose()}setHighlightedReads(e,t){this.alignmentTrack.setHighlightedReads(e,t),this.updateViews()}get expectedPairOrientation(){return this.alignmentTrack.expectedPairOrientation}get viewAsPairs(){return this.alignmentTrack.viewAsPairs}get colorBy(){return this.alignmentTrack.colorBy}set height(e){this._height=e,this.showAlignments&&(this.alignmentTrack.height=this.showCoverage?e-this.coverageTrackHeight:e)}get height(){return this._height}sort(e){e=this.assignSort(e);for(let t of this.trackView.viewports)if(t.containsPosition(e.chr,e.position)){const i=t.cachedFeatures;i&&(i.sortRows(e),t.repaint())}}assignSort(e){if(e.locus){const t=function(e){const t=e.split(":"),i=t[1].split("-"),r={chr:t[0],start:Number.parseInt(i[0].replace(/,/g,""))-1};return i.length>1?r.end=Number.parseInt(i[1].replace(/,/g,"")):r.end=r.start+1,r}(e.locus);e.chr=t.chr,e.position=t.start}else e.position--;return e.direction="ASC"===e.direction||!0===e.direction,e.chr=this.browser.genome.getChromosomeName(e.chr),this.sortObject=e,this.sortObject}async getFeatures(e,t,i,r,s){const o=await this.featureSource.getAlignments(e,t,i);if(o.viewport=s,o.hasPairs&&!this._pairedEndStats&&!this.config.maxFragmentLength){const e=new Yf(o.allAlignments(),this.config);e.totalCount>99&&(this._pairedEndStats=e)}o.pack(this.alignmentTrack);const n=this.sortObject;return n&&n.chr===e&&n.position>=t&&n.position<=i&&o.sortRows(n),this.alignmentTrack.hasPairs=this.alignmentTrack.hasPairs||o.hasPairs,o}computePixelHeight(e){return(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.computePixelHeight(e):0)}draw(e){Co.fillRect(e.context,0,e.pixelTop,e.pixelWidth,e.pixelHeight,{fillStyle:"rgb(255, 255, 255)"}),!0===this.showCoverage&&this.coverageTrackHeight>0&&!1!==this.config.showAxis?(this.trackView.axisCanvas.style.display="block",this.coverageTrack.draw(e)):this.trackView.axisCanvas.style.display="none",!0===this.showAlignments&&(this.alignmentTrack.setTop(this.coverageTrack,this.showCoverage),this.alignmentTrack.draw(e))}paintAxis(e,t,i){this.coverageTrack.paintAxis(e,t,this.coverageTrackHeight)}contextMenuItemList(e){return this.alignmentTrack.contextMenuItemList(e)}popupData(e){return!0===this.showCoverage&&e.y>=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y{if(!this.autoHeight){const e=(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.height:0);this.trackView.setTrackHeight(e)}};return e.push("
"),e.push({element:ua("Show Coverage",this.showCoverage),click:function(){this.showCoverage=!this.showCoverage,t(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push({element:ua("Show Alignments",this.showAlignments),click:function(){this.showAlignments=!this.showAlignments,t(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e}getState(){const e=super.getState();return this.sortObject&&(e.sort={chr:this.sortObject.chr,position:this.sortObject.position+1,option:this.sortObject.option,direction:this.sortObject.direction?"ASC":"DESC"}),Object.assign(e,this.alignmentTrack.getState()),e}getCachedAlignmentContainers(){return this.trackView.viewports.map((e=>e.cachedFeatures))}get dataRange(){return this.coverageTrack.dataRange}set dataRange(e){this.coverageTrack.dataRange=e}get logScale(){return this.coverageTrack.logScale}set logScale(e){this.coverageTrack.logScale=e}get autoscale(){return this.coverageTrack.autoscale}set autoscale(e){this.coverageTrack.autoscale=e}addPairedChordsForViewport(e){const t=this.maxTemplateLength,i=[],r=e.referenceFrame;for(let s of e.cachedFeatures.allAlignments())s.end>=r.start&&s.start<=r.end&&(s.paired?s.end-s.start>t&&i.push(s):s.mate&&s.mate.chr&&(s.mate.chr!==s.chr||Math.max(s.fragmentLength)>t)&&i.push(s));Zf((e=>{const t=[];for(let i of e)if(i.paired)i.firstAlignment&&i.secondAlignment&&t.push({uniqueId:i.readName,refName:$f(i.firstAlignment.chr),start:i.firstAlignment.start,end:i.firstAlignment.end,mate:{refName:$f(i.secondAlignment.chr),start:i.secondAlignment.start,end:i.secondAlignment.end}});else{const e=i.mate;e&&e.chr&&e.position&&t.push({uniqueId:i.readName,refName:$f(i.chr),start:i.start,end:i.end,mate:{refName:$f(e.chr),start:e.position-1,end:e.position}})}return t})(i),this,r,.02)}addSplitChordsForViewport(e){const t=[],i=e.referenceFrame;for(let r of e.cachedFeatures.allAlignments()){const e=r.hasTag("SA");r.end>=i.start&&r.start<=i.end&&e&&t.push(r)}Zf((e=>{const t=e=>{const t=Iu(e.tags().SA);let r=0;for(let s of t)s.start!==e.start&&i.push({uniqueId:`${e.readName}_${r++}`,refName:$f(e.chr),start:e.start,end:e.end,mate:{refName:$f(s.chr),start:s.start,end:s.start+s.lenOnRef}})},i=[];for(let i of e)i.paired?(t(i.firstAlignment),i.secondAlignment&&t(i.secondAlignment)):t(i);return i})(t),this,i,.02)}}class fp extends ma{static defaults={height:250,theta:Math.PI/4,arcOrientation:"UP",showBlocks:!0,blockHeight:3,thickness:1,alpha:.02,logScale:!0,colorBy:void 0};constructor(e,t){super(e,t)}init(e){super.init(e),!1===e.arcOrientation?this.arcOrientation="DOWN":!0===e.arcOrientation?this.arcOrientation="UP":e.arcOrientation?this.arcOrientation=e.arcOrientation.toUpperCase():this.arcOrientation="UP",this.sinTheta=Math.sin(this.theta),this.cosTheta=Math.cos(this.theta),this.arcType=function(e){if(!e.arcType)return"nested";switch(e.arcType){case"chiapet":return"inView";case"chiapetoutbound":return"partialInView";default:return e.arcType}}(e),this.painter={flipAxis:"DOWN"===this.arcOrientation,dataRange:this.dataRange,paintAxis:Oc},e.valueColumn?(this.valueColumn=e.valueColumn,this.hasValue=!0):e.useScore&&(this.hasValue=!0,this.valueColumn="score"),e.max?(this.dataRange={min:e.min||0,max:e.max},this.autoscale=!1):this.autoscale=!0,e.colorTable?this.colorTable=new $r(e.colorTable):e.colorBy&&(this.colorTable=new Wr("Set1")),e.featureSource?(this.featureSource=e.featureSource,delete e._featureSource):(e.features&&function(e){const t=[];for(let i of e)if(i.chr1===i.chr2)i.chr=i.chr1,i.start=Math.min(i.start1,i.start2),i.end=Math.max(i.end1,i.end2);else{i.chr=i.chr1,i.start=Math.min(i.start1,i.start2),i.end=Math.max(i.end1,i.end2);const e=Object.assign({},i);e.dup=!0,e.chr=e.chr2,e.start=e.start2,e.end=e.end2,t.push(e)}for(const i of t)e.push(i)}(e.features),this.featureSource=El(e,this.browser.genome),this.featureSource.getWGFeatures=bp)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow(),this.featureSource.visibilityWindow=this.visibilityWindow),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get supportsWholeGenome(){return"function"!=typeof this.featureSource.supportsWholeGenome||this.featureSource.supportsWholeGenome()}async getFeatures(e,t,i){const r=this.visibilityWindow,s=await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r});return void 0===this.hasValue&&s&&s.length>0&&(this.hasValue=void 0!==s[0].score),s}draw(e){"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?this.drawProportional(e):this.drawNested(e)}drawNested(e){const t=e.context,i=e.pixelWidth,r=e.pixelHeight,s=e.viewportWidth,o=e.bpPerPixel,n=e.bpStart,a=o;Co.fillRect(t,0,e.pixelTop,i,r,{fillStyle:"rgb(255, 255, 255)"});const c=e.features;if(c){(function(){let e=0;for(let t of c){let r=(t.start-n)/a,s=(t.end-n)/a;r>=0&&s<=i&&(e=Math.max(e,s-r))}let t=Math.min(s,e)/2;if(e>0){let e=(r-10)/t;this.theta=function(e){let t,i=[.01570925532366355,.15838444032453644,.3249196962329063,.5095254494944288,.7265425280053609,.9999999999999999],r=[.031415926535897934,.3141592653589793,.6283185307179586,.9424777960769379,1.2566370614359172,1.5707963267948966];for(t=0;te);t++);let s=0===t?0:i[t-1],o=ti)continue;let f=u-d;f<3&&(f=3,d--);const p=f/2,g=p/this.sinTheta,m=this.cosTheta*g,w=d+p;let b,F,v;if(o?(b=this.height+m,F=Math.PI+Math.PI/2-this.theta,v=Math.PI+Math.PI/2+this.theta):(b=-m,F=Math.PI/2-this.theta,v=Math.PI/2+this.theta),this.showBlocks&&"all"!==e.chr){const i=(e.start1-n)/a,r=(e.end1-n)/a,s=(e.start2-n)/a,c=(e.end2-n)/a,h=o?-this.blockHeight:this.blockHeight;t.fillRect(i,l,r-i,h),t.fillRect(s,l,c-s,h)}r&&!this.config.useScore&&f>s&&(r=wp(r,this.alpha),t.strokeStyle=r,t.fillStyle=r),t.beginPath(),t.arc(w,b,g,F,v,!1),t.stroke(),e.drawState={xc:w,yc:b,r:g}}else{let s=Math.round((e.start-n)/a),c=Math.round((e.end-n)/a);if(c<0||s>i)continue;let l=c-s;l<3&&(l=3,s--);const h=e.chr===e.chr1?e.chr2:e.chr1;t.strokeStyle=r,t.fillStyle=wp($h(h),.5),o?(t.fillRect(s,this.height/2,l,this.height/2),t.fillText(h,s+l/2,this.height/2-5),e.drawState={x:s,y:this.height/2,w:l,h:this.height/2}):(t.fillRect(s,0,l,this.height/2),t.fillText(h,s+l/2,this.height/2+13),e.drawState={x:s,y:0,w:l,h:this.height/2})}}}}drawProportional(e){const t=e.context,i=e.pixelWidth,r=e.pixelHeight,s=e.bpPerPixel,o=e.bpStart,n=s,a=e.referenceFrame.start,c=e.referenceFrame.end,l="UP"===this.arcOrientation;Co.fillRect(t,0,e.pixelTop,i,r,{fillStyle:"rgb(255, 255, 255)"});const h=e.features;if(h&&h.length>0){const r=0,s=this.getScaleFactor(r,this.dataRange.max,e.pixelHeight-1,this.logScale),d=l?e.pixelHeight:0;for(let e of h){e.drawState=void 0;const r=this.valueColumn?e[this.valueColumn]:e.score;if(void 0===r||Number.isNaN(r))continue;const h=Math.round((this.logScale?Math.log10(r+1):r)*s);if(e.chr1===e.chr2||"all"===e.chr){const{m1:i,m2:s}=pp(e,this.browser.genome);let u=Math.round((i-o)/n),f=Math.round((s-o)/n)-u;if(f<3&&(f=3,u--),rthis.dataRange.max)continue;if("proportional"!==this.arcType){const e="partialInView"===this.arcType,t=i>=a&&s<=c;let r=!1,o=!1;if(!t&&e&&(r=a<=i&&i<=c,r||(o=a<=s&&s<=c)),!(t||r||o))continue}const p=f/2,g=u+f/2;e.drawState={xc:g,yc:d,radiusX:p,radiusY:h};const m=l,w=this.getColor(e);if(t.strokeStyle=w,t.lineWidth=e.thickness||this.thickness||1,!0===t.isSVG?t.strokeEllipse(g,d,p,h,0,0,Math.PI,m):(t.beginPath(),t.ellipse(g,d,p,h,0,0,Math.PI,m),t.stroke()),this.alpha){const i=this.config.useScore&&Number.isFinite(e.score)?Math.max(.1,Math.round(10*Ic(e.score))/10):1;t.fillStyle=wp(w,i*this.alpha),!0===t.isSVG?t.fillEllipse(g,d,p,h,0,0,Math.PI,m):t.fill()}if(this.showBlocks&&"all"!==e.chr){t.fillStyle=w;const i=(e.start1-o)/n,r=(e.end1-o)/n,s=(e.start2-o)/n,a=(e.end2-o)/n,c=l?-this.blockHeight:this.blockHeight;t.fillRect(i,d,r-i,c),t.fillRect(s,d,a-s,c)}}else{let s=Math.round((e.start-o)/n),a=Math.round((e.end-o)/n);if(a<0||s>i||rthis.dataRange.max)continue;const c=Math.min(h,this.height-13);let d=a-s;d<3&&(d=3,s--);const u=e.chr===e.chr1?e.chr2:e.chr1;if(t.font="8px sans-serif",t.textAlign="center",t.fillStyle=wp($h(u),.5),l){const i=this.height-c;t.fillRect(s,i,d,c),t.fillText(u,s+d/2,i-5),e.drawState={x:s,y:i,w:d,h:c}}else t.fillRect(s,0,d,c),t.fillText(u,s+d/2,c+13),e.drawState={x:s,y:0,w:d,h:c}}}}}getColor(e){let t;if(this.colorBy){const i=e.getAttributeValue?e.getAttributeValue(this.colorBy):e[this.colorBy];t=this.colorTable.getColor(i)}else t="function"==typeof this.color?this.color(e):this.color||e.color||"rgb(180,25,137)";return this.config.useScore&&Number.isFinite(e.score)&&(t=wp(t,Ic(e.score))),t}getScaleFactor(e,t,i,r){return r?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}clearAxis(e,t,i){Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"})}paintAxis(e,t,i){const r={min:0,max:this.dataRange.max};"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?(this.painter.flipAxis="DOWN"===this.arcOrientation,this.painter.dataRange=r,this.painter.paintAxis(e,t,i)):this.clearAxis(e,t,i)}menuItemList(){let e=[];if(this.hasValue){e.push("
");const t={nested:"Nested",proportional:"Proportional - All",inView:"Proportional - Both Ends in View",partialInView:"Proportional - One End in View"};e.push("Arc Type");for(let i of["nested","proportional","inView","partialInView"])e.push({element:ua(t[i],i===this.arcType),click:function(){this.arcType=i,this.trackView.repaintViews()}})}return e.push("
"),e.push({name:"Toggle arc direction",click:function(){this.arcOrientation="UP"===this.arcOrientation?"DOWN":"UP",this.trackView.repaintViews()}}),e.push({name:this.showBlocks?"Hide Blocks":"Show Blocks",click:function(){this.showBlocks=!this.showBlocks,this.trackView.repaintViews()}}),e.push("
"),e.push({name:"Set line thickness",click:function(e){this.browser.inputDialog.present({label:"Enter line thickness",value:this.thickness||1,callback:e=>{const t=parseFloat(e);isNaN(t)?window.alert("Invalid line thickness: "+e):(this.thickness=t,this.trackView.repaintViews())}},e)}}),e.push({name:"Set alpha",click:function(e){this.browser.inputDialog.present({label:"Enter alpha transparency (0-1)",value:this.alpha,callback:e=>{const t=parseFloat(e);isNaN(t)||t<0||t>1?window.alert("Invalid alpha: "+e):(this.alpha=t,this.trackView.repaintViews())}},e)}}),this.hasValue&&e.push({element:ua("Use score",this.config.useScore),click:()=>{this.config.useScore=!this.config.useScore,this.valueColumn="score",this.trackView.repaintViews()}}),"proportional"!==this.arcType&&"inView"!==this.arcType&&"partialInView"!==this.arcType||(e=e.concat(this.numericDataMenuItems())),this.browser.circularView&&(e.push("
"),e.push({label:"Add interactions to circular view",click:function(){for(let e of this.trackView.viewports)this.addChordsForViewport(e.referenceFrame)}})),e}contextMenuItemList(e){if(this.browser.circularView){const t=e.viewport,i=[];return i.push({label:"Add interactions to circular view",click:()=>{const e=t.referenceFrame;this.addChordsForViewport(e)}}),i.push("
"),i}}addChordsForViewport(e){let t;if("all"===e.chr)t=Object.values(this.featureSource.getAllFeatures()).flat();else{t=this.featureSource.featureCache.queryFeatures(e.chr,e.start,e.end).filter((e=>e.drawState))}if(0===t.length)return;Zf(t.map((e=>{const t=e._f||e;return{uniqueId:`${t.chr1}:${t.start1}-${t.end1}_${t.chr2}:${t.start2}-${t.end2}`,refName:$f(t.chr1),start:t.start1,end:t.end1,mate:{refName:$f(t.chr2),start:t.start2,end:t.end2}}})),this,e,.5)}doAutoscale(e){let t=0;if(e)for(let i of e){const e=this.valueColumn?i[this.valueColumn]:i.score;Number.isNaN(e)||(t=Math.max(t,e))}return{min:0,max:t}}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){const t=e._||e;if(i.push({name:"Region 1",value:gp(t.chr1,t.start1,t.end1,t.strand1)}),i.push({name:"Region 2",value:gp(t.chr2,t.start2,t.end2,t.strand2)}),t.name&&i.push({name:"Name",value:t.name}),void 0!==t.value&&i.push({name:"Value",value:t.value}),void 0!==t.score&&i.push({name:"Score",value:t.score}),void 0!==t.type&&i.push({name:"Type",value:t.type}),t.extras&&this.header&&this.header.columnNames){const e=this.header.columnNames,r=this.header.hiccups?6:10;for(let s=r;s=t-a&&e.canvasX<=t+o+a&&e.canvasY>=r&&e.canvasY<=r+n){const r=-Math.abs(e.canvasX-(t+o/2));i.push({score:r,feature:s});break}}}return i.length>1&&i.sort(((e,t)=>e.score-t.score)),i.map((e=>e.feature))}}function pp(e,t){let i=(e.start1+e.end1)/2,r=(e.start2+e.end2)/2;if("all"===e.chr&&(i=t.getGenomeCoordinate(e.chr1,i),r=t.getGenomeCoordinate(e.chr2,r)),i>r){const e=i;i=r,r=e}return{m1:i,m2:r}}function gp(e,t,i,r){return r&&"."!==r?`${e}:${F(t+1)}-${F(i)} (${r})`:`${e}:${F(t+1)}-${F(i)}`}const mp=new Map;function wp(e,t){const i=`${e}_${t}`;let r=mp.get(i);return r||(r=ur.addAlpha(e,t),mp.set(i,r)),r}function bp(e){const t=e=>{const t=Object.assign({},e);return t.chr="all",t.start=i.getGenomeCoordinate(e.chr1,e.start1),t.end=i.getGenomeCoordinate(e.chr2,e.end2),t},i=this.genome;let r,s=0;for(let t of i.wgChromosomeNames){let i=e[t];if(i)for(let e of i)e.dup||(s++,e.score&&(!r||e.score>r.score)&&(r=e))}const o=this.maxWGCount,n=r&&r.score>0&&s>o?5:1,a=Math.floor(o/n),c=r&&r.score>0?Math.log(r.score)/n:Number.MAX_SAFE_INTEGER;let l,h=[],d=[];for(let e=0;e=400){const e=Error(s.statusText);throw e.code=o,e}return s.arrayBuffer()}}class yp{constructor(e){this.file=e.file,this.fetchSize=e.fetchSize||16e3,this.maxSize=e.maxSize||1e6,this.buffers=[]}async read(e,t){let i=this.buffers.filter((i=>i.overlaps(e,e+t)));for(let r of i)if(r.contains(e,e+t))return r.slice(e,e+t);if(0===i.length){let i=Math.max(t,this.fetchSize);this.buffers.sort(((e,t)=>e.start-t.start));const r=function(e,t,i){let r=i-1,s=e.length;for(;1+r>1);t(e[i])?s=i:r=i}return s}(this.buffers,(t=>t.start>e),0);re.start-t.start));const r=[];let s=e;for(let e of i){if(ss){const e=s,t=o-e,i=await this.file.read(e,t),n=new Ap(e,i);r.push(n)}const n=r[0].start,a=function(e){const t=e.reduce(((e,t)=>e+t.byteLength),0),i=new Uint8Array(t);let r=0;for(let t of e)i.set(new Uint8Array(t),r),r+=t.byteLength;return i.buffer}(r.map((e=>e.buffer))),c=new Ap(n,a),l=new Set(i);return this.buffers=this.buffers.filter((e=>!l.has(e))),this.addBuffer(c),c.slice(e,e+t)}}addBuffer(e){const t=this.buffers.reduce(((e,t)=>e+t.size),0)+e.size;if(t>this.maxSize){const e=t-this.maxSize;this.buffers.sort(((e,t)=>e.creationTime-t.creationTime));let i,r=0;for(i=0;ie));i++);this.buffers=ithis.buffer.byteLength)throw Error("buffer bounds error");return this.buffer.slice(e-this.start,t-this.start)}get end(){return this.start+this.buffer.byteLength}get size(){return this.buffer.byteLength}contains(e,t){return e>=this.start&&t<=this.end}overlaps(e,t){return e>this.start&&ethis.start&&t(((e,t,i)=>{t in e?_p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i})(e,"symbol"!=typeof t?t+"":t,i),i);async function kp(e,t,i=0){var r=new Map;for(let[s,o]of e.entries()){let e=await Bp.unpack_from_async("<"+o,t,i);i+=Bp.calcsize(o),1==e.length&&(e=e[0]),r.set(s,e)}return r}function Ip(e,t,i=0){var r=new Map;for(let[s,o]of e.entries()){let e=Bp.unpack_from("<"+o,t,i);i+=Bp.calcsize(o),1==e.length&&(e=e[0]),r.set(s,e)}return r}function Sp(e){e||e()}function Ep(e){var t="<"+Array.from(e.values()).join("");return Bp.calcsize(t)}function Np(e,t=8){return Math.ceil(e/t)*t}var Mp={u:"Uint",i:"Int",f:"Float"};function Rp(e){var t,i,r=Bp._is_big_endian(e);if(/S/.test(e))t="getString",i=0|((e.match(/S(\d*)/)||[])[1]||1);else{let[r,s,o]=e.match(/[<>=!@]?(i|u|f)(\d*)/);i=parseInt(o||4,10),t="get"+Mp[s]+(8*i).toFixed()}return[t,r,i]}var Bp=new class{constructor(){this.big_endian=function(){const e=new Uint8Array(4);return!((new Uint32Array(e.buffer)[0]=1)&e[0])}(),this.getters={s:"getUint8",b:"getInt8",B:"getUint8",h:"getInt16",H:"getUint16",i:"getInt32",I:"getUint32",l:"getInt32",L:"getUint32",q:"getInt64",Q:"getUint64",f:"getFloat32",d:"getFloat64"},this.byte_lengths={s:1,b:1,B:1,h:2,H:2,i:4,I:4,l:4,L:4,q:8,Q:8,f:4,d:8};let e=Object.keys(this.byte_lengths).join("");this.fmt_size_regex="(\\d*)(["+e+"])"}calcsize(e){for(var t,i=0,r=new RegExp(this.fmt_size_regex,"g");null!==(t=r.exec(e));){let e=parseInt(t[1]||1,10),r=t[2];i+=e*this.byte_lengths[r]}return i}_is_big_endian(e){return!/^)/.test(e)||this.big_endian)}async unpack_from_async(e,t,i){i=Number.parseInt(i||0);const r=this.calcsize(e),s=await t.slice(i,i+r);let o=0;for(var n,a=new Dp(s),c=[],l=this._is_big_endian(e),h=new RegExp(this.fmt_size_regex,"g");null!==(n=h.exec(e));){let e=parseInt(n[1]||1,10),t=n[2],i=this.getters[t],r=this.byte_lengths[t];if("s"==t)c.push((new TextDecoder).decode(s.slice(o,o+e))),o+=e;else for(var d=0;de+(t<<8*i)),0);return n}var zp=class{constructor(e,t){this.buf=e,this.offset=t,this.dtype=this.determine_dtype()}async determine_dtype(){let e=await kp(Pp,this.buf,this.offset);this.offset+=Hp;let t=15&e.get("class_and_version");if(t==Op)return this._determine_dtype_fixed_point(e);if(t==Vp)return this._determine_dtype_floating_point(e);if(t==qp)throw"Time datatype class not supported.";if(t==Up)return this._determine_dtype_string(e);if(t==Qp)throw"Bitfield datatype class not supported.";if(t==Gp)return{datatype_class:Gp,size:e.get("size")};if(t==jp)return this._determine_dtype_compound(e);if(t==Wp)return["REFERENCE",e.get("size")];if(t==$p)return this.determine_dtype();if(t==Zp)throw"Array datatype class not supported.";if(t==Kp){let t=this._determine_dtype_vlen(e);if("VLEN_SEQUENCE"==t[0]){t=["VLEN_SEQUENCE",this.determine_dtype()]}return t}throw"Invalid datatype class "+t}_determine_dtype_fixed_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;var r;return i=(8&e.get("class_bit_field_0"))>0?"i":"u",r=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=4,r+i+t.toFixed()}_determine_dtype_floating_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;return i=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=12,i+"f"+t.toFixed()}_determine_dtype_string(e){return"S"+e.get("size").toFixed()}_determine_dtype_vlen(e){return 1!=(1&e.get("class_bit_field_0"))?["VLEN_SEQUENCE",0,0]:["VLEN_STRING",e.get("class_bit_field_0")>>4,1&e.get("class_bit_field_1")]}_determine_dtype_compound(e){throw"Compound type not yet implemented!"}},Pp=new Map([["class_and_version","B"],["class_bit_field_0","B"],["class_bit_field_1","B"],["class_bit_field_2","B"],["size","I"]]),Hp=Ep(Pp);Ep(new Map([["offset","I"],["dimensionality","B"],["reserved_0","B"],["reserved_1","B"],["reserved_2","B"],["permutation","I"],["reserved_3","I"],["dim_size_1","I"],["dim_size_2","I"],["dim_size_3","I"],["dim_size_4","I"]]));var Op=0,Vp=1,qp=2,Up=3,Qp=4,Gp=5,jp=6,Wp=7,$p=8,Kp=9,Zp=10;function Yp(e){let t=e.length;for(;--t>=0;)e[t]=0}Yp(new Array(576)),Yp(new Array(60)),Yp(new Array(512)),Yp(new Array(256)),Yp(new Array(29)),Yp(new Array(30));var Xp=(e,t,i,r)=>{let s=65535&e,o=e>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+t[r++]|0,o=o+s|0}while(--n);s%=65521,o%=65521}return s|o<<16},Jp=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})()),eg=(e,t,i,r)=>{const s=Jp,o=r+i;e^=-1;for(let i=r;i>>8^s[255&(e^t[i])];return-1^e},tg={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},ig={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},rg=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),sg=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)rg(i,t)&&(e[t]=i[t])}}return e},og=e=>{let t=0;for(let i=0,r=e.length;i=252?6:Sy>=248?5:Sy>=240?4:Sy>=224?3:Sy>=192?2:1;ag[254]=ag[254]=1;var cg=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,r,s,o,n=e.length,a=0;for(s=0;s>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},lg=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let r,s;const o=new Array(2*i);for(s=0,r=0;r4)o[s++]=65533,r+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&r1?o[s++]=65533:t<65536?o[s++]=t:(t-=65536,o[s++]=55296|t>>10&1023,o[s++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&ng)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let r=0;r{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+ag[e[i]]>t?i:t};var dg=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},ug=function(e,t){let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_,x;const k=e.state;i=e.next_in,_=e.input,r=i+(e.avail_in-5),s=e.next_out,x=e.output,o=s-(t-e.avail_out),n=s+(e.avail_out-257),a=k.dmax,c=k.wsize,l=k.whave,h=k.wnext,d=k.window,u=k.hold,f=k.bits,p=k.lencode,g=k.distcode,m=(1<>>24,u>>>=F,f-=F,F=b>>>16&255,0===F)x[s++]=65535&b;else{if(!(16&F)){if(64&F){if(32&F){k.mode=12;break e}e.msg="invalid literal/length code",k.mode=30;break e}b=p[(65535&b)+(u&(1<>>=F,f-=F),f<15&&(u+=_[i++]<>>24,u>>>=F,f-=F,F=b>>>16&255,16&F){if(y=65535&b,F&=15,fa){e.msg="invalid distance too far back",k.mode=30;break e}if(u>>>=F,f-=F,F=s-o,y>F){if(F=y-F,F>l&&k.sane){e.msg="invalid distance too far back",k.mode=30;break e}if(A=0,C=d,0===h){if(A+=c-F,F2;)x[s++]=C[A++],x[s++]=C[A++],x[s++]=C[A++],v-=3;v&&(x[s++]=C[A++],v>1&&(x[s++]=C[A++]))}else{A=s-y;do{x[s++]=x[A++],x[s++]=x[A++],x[s++]=x[A++],v-=3}while(v>2);v&&(x[s++]=x[A++],v>1&&(x[s++]=x[A++]))}break}if(64&F){e.msg="invalid distance code",k.mode=30;break e}b=g[(65535&b)+(u&(1<>3,i-=v,f-=v<<3,u&=(1<{const c=a.bits;let l,h,d,u,f,p,g=0,m=0,w=0,b=0,F=0,v=0,y=0,A=0,C=0,_=0,x=null,k=0;const I=new Uint16Array(16),S=new Uint16Array(16);let E,N,M,R=null,B=0;for(g=0;g<=fg;g++)I[g]=0;for(m=0;m=1&&0===I[b];b--);if(F>b&&(F=b),0===b)return s[o++]=20971520,s[o++]=20971520,a.bits=1,0;for(w=1;w0&&(0===e||1!==b))return-1;for(S[1]=0,g=1;g852||2===e&&C>592)return 1;for(;;){E=g-y,n[m]p?(N=R[B+n[m]],M=x[k+n[m]]):(N=96,M=0),l=1<>y)+h]=E<<24|N<<16|M}while(0!==h);for(l=1<>=1;if(0!==l?(_&=l-1,_+=l):_=0,m++,0===--I[g]){if(g===b)break;g=t[i+n[m]]}if(g>F&&(_&u)!==d){for(0===y&&(y=F),f+=w,v=g-y,A=1<852||2===e&&C>592)return 1;d=_&u,s[d]=F<<24|v<<16|f-o}}return 0!==_&&(s[f+_]=g-y<<24|64<<16),a.bits=F,0},{Z_FINISH:Fg,Z_BLOCK:vg,Z_TREES:yg,Z_OK:Ag,Z_STREAM_END:Cg,Z_NEED_DICT:_g,Z_STREAM_ERROR:xg,Z_DATA_ERROR:kg,Z_MEM_ERROR:Ig,Z_BUF_ERROR:Sg,Z_DEFLATED:Eg}=ig,Ng=12,Mg=30,Rg=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Bg(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var Dg,Lg,Tg=e=>{if(!e||!e.state)return xg;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ag},zg=e=>{if(!e||!e.state)return xg;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Tg(e)},Pg=(e,t)=>{let i;if(!e||!e.state)return xg;const r=e.state;return t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?xg:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,zg(e))},Hg=(e,t)=>{if(!e)return xg;const i=new Bg;e.state=i,i.window=null;const r=Pg(e,t);return r!==Ag&&(e.state=null),r},Og=!0,Vg=e=>{if(Og){Dg=new Int32Array(512),Lg=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(bg(1,e.lens,0,288,Dg,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;bg(2,e.lens,0,32,Lg,0,e.work,{bits:5}),Og=!1}e.lencode=Dg,e.lenbits=9,e.distcode=Lg,e.distbits=5},qg=(e,t,i,r)=>{let s;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(s=o.wsize-o.wnext,s>r&&(s=r),o.window.set(t.subarray(i-r,i-r+s),o.wnext),(r-=s)?(o.window.set(t.subarray(i-r,i),0),o.wnext=r,o.whave=o.wsize):(o.wnext+=s,o.wnext===o.wsize&&(o.wnext=0),o.whaveHg(e,15),inflateInit2:Hg,inflate:(e,t)=>{let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_=0;const x=new Uint8Array(4);let k,I;const S=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return xg;i=e.state,i.mode===Ng&&(i.mode=13),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,d=a,u=c,C=Ag;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=eg(i.check,x,2,0),l=0,h=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=Mg;break}if((15&l)!==Eg){e.msg="unknown compression method",i.mode=Mg;break}if(l>>>=4,h-=4,A=8+(15&l),0===i.wbits)i.wbits=A;else if(A>i.wbits){e.msg="invalid window size",i.mode=Mg;break}i.dmax=1<>8&1),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=eg(i.check,x,2,0)),l=0,h=0,i.mode=3;case 3:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>8&255,x[2]=l>>>16&255,x[3]=l>>>24&255,i.check=eg(i.check,x,4,0)),l=0,h=0,i.mode=4;case 4:for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>8),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=eg(i.check,x,2,0)),l=0,h=0,i.mode=5;case 5:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=eg(i.check,x,2,0)),l=0,h=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(f=i.length,f>a&&(f=a),f&&(i.head&&(A=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(o,o+f),A)),512&i.flags&&(i.check=eg(i.check,r,f,o)),a-=f,o+=f,i.length-=f),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===a)break e;f=0;do{A=r[o+f++],i.head&&A&&i.length<65536&&(i.head.name+=String.fromCharCode(A))}while(A&&f>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Ng;break;case 10:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>=7&h,h-=7&h,i.mode=27;break}for(;h<3;){if(0===a)break e;a--,l+=r[o++]<>>=1,h-=1,3&l){case 0:i.mode=14;break;case 1:if(Vg(i),i.mode=20,t===yg){l>>>=2,h-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=Mg}l>>>=2,h-=2;break;case 14:for(l>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,l+=r[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Mg;break}if(i.length=65535&l,l=0,h=0,i.mode=15,t===yg)break e;case 15:i.mode=16;case 16:if(f=i.length,f){if(f>a&&(f=a),f>c&&(f=c),0===f)break e;s.set(r.subarray(o,o+f),n),a-=f,o+=f,c-=f,n+=f,i.length-=f;break}i.mode=Ng;break;case 17:for(;h<14;){if(0===a)break e;a--,l+=r[o++]<>>=5,h-=5,i.ndist=1+(31&l),l>>>=5,h-=5,i.ncode=4+(15&l),l>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Mg;break}i.have=0,i.mode=18;case 18:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[S[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,k={bits:i.lenbits},C=bg(0,i.lens,0,19,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid code lengths set",i.mode=Mg;break}i.have=0,i.mode=19;case 19:for(;i.have>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=m,h-=m,i.lens[i.have++]=b;else{if(16===b){for(I=m+2;h>>=m,h-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=Mg;break}A=i.lens[i.have-1],f=3+(3&l),l>>>=2,h-=2}else if(17===b){for(I=m+3;h>>=m,h-=m,A=0,f=3+(7&l),l>>>=3,h-=3}else{for(I=m+7;h>>=m,h-=m,A=0,f=11+(127&l),l>>>=7,h-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Mg;break}for(;f--;)i.lens[i.have++]=A}}if(i.mode===Mg)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Mg;break}if(i.lenbits=9,k={bits:i.lenbits},C=bg(1,i.lens,0,i.nlen,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid literal/lengths set",i.mode=Mg;break}if(i.distbits=6,i.distcode=i.distdyn,k={bits:i.distbits},C=bg(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,k),i.distbits=k.bits,C){e.msg="invalid distances set",i.mode=Mg;break}if(i.mode=20,t===yg)break e;case 20:i.mode=21;case 21:if(a>=6&&c>=258){e.next_out=n,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=l,i.bits=h,ug(e,u),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,i.mode===Ng&&(i.back=-1);break}for(i.back=0;_=i.lencode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,i.length=b,0===w){i.mode=26;break}if(32&w){i.back=-1,i.mode=Ng;break}if(64&w){e.msg="invalid literal/length code",i.mode=Mg;break}i.extra=15&w,i.mode=22;case 22:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;_=i.distcode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,64&w){e.msg="invalid distance code",i.mode=Mg;break}i.offset=b,i.extra=15&w,i.mode=24;case 24:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Mg;break}i.mode=25;case 25:if(0===c)break e;if(f=u-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Mg;break}f>i.wnext?(f-=i.wnext,p=i.wsize-f):p=i.wnext-f,f>i.length&&(f=i.length),g=i.window}else g=s,p=n-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do{s[n++]=g[p++]}while(--f);0===i.length&&(i.mode=21);break;case 26:if(0===c)break e;s[n++]=i.length,c--,i.mode=21;break;case 27:if(i.wrap){for(;h<32;){if(0===a)break e;a--,l|=r[o++]<{if(!e||!e.state)return xg;let t=e.state;return t.window&&(t.window=null),e.state=null,Ag},inflateGetHeader:(e,t)=>{if(!e||!e.state)return xg;const i=e.state;return 2&i.wrap?(i.head=t,t.done=!1,Ag):xg},inflateSetDictionary:(e,t)=>{const i=t.length;let r,s,o;return e&&e.state?(r=e.state,0!==r.wrap&&11!==r.mode?xg:11===r.mode&&(s=1,s=Xp(s,t,i,0),s!==r.check)?kg:(o=qg(e,t,i,i),o?(r.mode=31,Ig):(r.havedict=1,Ag))):xg},inflateInfo:"pako inflate (from Nodeca project)"};var Qg=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},Gg=Object.prototype.toString,{Z_NO_FLUSH:jg,Z_FINISH:Wg,Z_OK:$g,Z_STREAM_END:Kg,Z_NEED_DICT:Zg,Z_STREAM_ERROR:Yg,Z_DATA_ERROR:Xg,Z_MEM_ERROR:Jg}=ig;function em(e){this.options=sg({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new dg,this.strm.avail_out=0;let i=Ug.inflateInit2(this.strm,t.windowBits);if(i!==$g)throw new Error(tg[i]);if(this.header=new Qg,Ug.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=cg(t.dictionary):"[object ArrayBuffer]"===Gg.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Ug.inflateSetDictionary(this.strm,t.dictionary),i!==$g)))throw new Error(tg[i])}function tm(e,t){const i=new em(t);if(i.push(e),i.err)throw i.msg||tg[i.err];return i.result}em.prototype.push=function(e,t){const i=this.strm,r=this.options.chunkSize,s=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Wg:jg,"[object ArrayBuffer]"===Gg.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(r),i.next_out=0,i.avail_out=r),o=Ug.inflate(i,n),o===Zg&&s&&(o=Ug.inflateSetDictionary(i,s),o===$g?o=Ug.inflate(i,n):o===Xg&&(o=Zg));i.avail_in>0&&o===Kg&&i.state.wrap>0&&0!==e[i.next_in];)Ug.inflateReset(i),o=Ug.inflate(i,n);switch(o){case Yg:case Xg:case Zg:case Jg:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===Kg))if("string"===this.options.to){let e=hg(i.output,i.next_out),t=i.next_out-e,s=lg(i.output,e);i.next_out=t,i.avail_out=r-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(s)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==$g||0!==a){if(o===Kg)return o=Ug.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},em.prototype.onData=function(e){this.chunks.push(e)},em.prototype.onEnd=function(e){e===$g&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=og(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var im=function(e,t){return(t=t||{}).raw=!0,tm(e,t)},rm={Inflate:em,inflate:tm,inflateRaw:im,ungzip:tm,constants:ig},{Inflate:sm,inflate:om,inflateRaw:nm,ungzip:am}=rm,cm=om,lm=am;var hm=new Map([[1,function(e,t){let i=new Uint8Array(e);return cm(i).buffer}],[2,function(e,t){let i=e.byteLength,r=new Uint8Array(i),s=Math.floor(i/t),o=new DataView(e);for(var n=0;nHH",e,i);if(c%=65535,s!=(a%=65535)||o!=c)throw'ValueError("fletcher32 checksum invalid")'}(e),e.slice(0,-4)}]]),dm=class{constructor(e,t){this.fh=e,this.offset=t,this.depth=null}async init(){this.all_nodes=new Map,await this._read_root_node(),await this._read_children()}async _read_children(){let e=this.depth;for(;e>0;){for(var t of this.all_nodes.get(e))for(var i of t.get("addresses"))this._add_node(await this._read_node(i,e-1));e--}}async _read_root_node(){let e=await this._read_node(this.offset,null);this._add_node(e),this.depth=e.get("node_level")}_add_node(e){let t=e.get("node_level");this.all_nodes.has(t)?this.all_nodes.get(t).push(e):this.all_nodes.set(t,[e])}async _read_node(e,t){let i=await this._read_node_header(e,t);return i.set("keys",[]),i.set("addresses",[]),i}async _read_node_header(e){throw"NotImplementedError: must define _read_node_header in implementation class"}},um=class extends dm{constructor(){super(...arguments),xp(this,"B_LINK_NODE",new Map([["signature","4s"],["node_type","B"],["node_level","B"],["entries_used","H"],["left_sibling","Q"],["right_sibling","Q"]]))}async _read_node_header(e,t){let i=await kp(this.B_LINK_NODE,this.fh,e);if(null!=t&&i.get("node_level")!=t)throw"node level does not match";return i}},fm=class extends um{constructor(e,t){super(e,t),xp(this,"NODE_TYPE",0),this.ready=this.init()}async _read_node(e,t){let i=await this._read_node_header(e,t);e+=Ep(this.B_LINK_NODE);let r=[],s=[],o=i.get("entries_used");for(var n=0;n=0&&F[A]>=e[A];A--)F[A]=0,b[A]=w[A],A>0&&(F[A-1]+=1,b[A-1]+=1);if(b.slice(0,-1).every((function(e,i){return e=0;n--){if(t&1<0?s*=r:s=r}}return o}_nrecords_max(e,t,i){return Math.floor((e-10-i)/(t+i))}_required_bytes(e){return Math.ceil(Lp(e)/8)}_int_format(e){return["0&&(h=(await Bp.unpack_from_async(a,this.fh,i))[0],i+=s),c.push([r,l,h])}}return o.set("keys",a),o.set("addresses",c),o}async _read_node_header(e,t){let i=await kp(this.B_LINK_NODE,this.fh,e);return i.set("node_level",t),i}*iter_records(){for(let e of this.all_nodes.values())for(let t of e)for(let e of t.get("keys"))yield e}_parse_record(e){throw"NotImplementedError"}},mm=class extends gm{constructor(){super(...arguments),xp(this,"NODE_TYPE",5)}async _parse_record(e,t,i){let r=(await Bp.unpack_from_async("0)throw"Filter info size not supported on FractalHeap";if(t.get("btree_address_huge_objects")!=_m)throw"Huge objects not implemented in FractalHeap";t.set("btree_address_huge_objects",null),t.get("root_block_address")==_m&&t.set("root_block_address",null);let i=t.get("log2_maximum_heap_size"),r=this._min_size_nbits(i),s=new Map([["signature","4s"],["version","B"],["heap_header_adddress","Q"],["block_offset",`${r}B`]]);this.indirect_block_header=new Map(s),this.indirect_block_header_size=Ep(s),2&~t.get("flags")||s.set("checksum","I"),this.direct_block_header=s,this.direct_block_header_size=Ep(s);let o=t.get("maximum_direct_block_size");this._managed_object_offset_size=this._min_size_nbits(i);let n=Math.min(o,t.get("max_managed_object_size"));this._managed_object_length_size=this._min_size_integer(n);let a=t.get("starting_block_size"),c=t.get("table_width");if(!(a>0))throw"Starting block size == 0 not implemented";let l=Number(Math.floor(Math.log2(o)));Sp(1n<0)for await(let e of this._iter_indirect_block(this.fh,f,p))u.push(e);else{let e=await this._read_direct_block(this.fh,f,a);u.push(e)}let g=u.reduce(((e,t)=>e+t.byteLength),0),m=new Uint8Array(g),w=0;u.forEach((e=>{m.set(new Uint8Array(e),w),w+=e.byteLength})),this.managed=m.buffer}async _read_direct_block(e,t,i){let r=await e.slice(t,t+i);return Sp("FHDB"==Ip(this.direct_block_header,r).get("signature")),r}get_data(e){let t=Bp.unpack_from(">4&3,r=1;if(0==i){Sp(0==t>>6);let i=this._managed_object_offset_size,s=Tp(i,e,r);r+=i,i=this._managed_object_length_size;let o=Tp(i,e,r);return this.managed.slice(s,s+o)}throw 1==i?"tiny objectID not supported in FractalHeap":2==i?"huge objectID not supported in FractalHeap":"unknown objectID type in FractalHeap"}_min_size_integer(e){return this._min_size_nbits(Lp(e))}_min_size_nbits(e){return Math.ceil(e/8)}async*_iter_indirect_block(e,t,i){let r=await kp(this.indirect_block_header,e,t);t+=this.indirect_block_header_size,Sp("FHIB"==r.get("signature"));let s=r.get("block_offset").reduce(((e,t,i)=>e+(t<<8*i)),0);r.set("block_offset",s);let[o,n]=this._indirect_info(i),a=[];for(let i=0;ithis._chunks))}get shape(){let e=this.find_msg_type(dw)[0].get("offset_to_message");return async function(e,t){let i=(await Bp.unpack_from_async("255&&(o=(await Bp.unpack_from_async("0;e.set("optional",a);let c,l=(await Bp.unpack_from_async("0&&(c=(await Bp.unpack_from_async(`${o}s`,i,t))[0],t+=o),e.set("name",c);let h=await Bp.unpack_from_async(`<${l}i`,i,t);t+=4*l,e.set("client_data_values",h),s.push(e)}}return this._filter_pipeline=s,this._filter_pipeline}find_msg_type(e){return this.msgs.filter((function(t){return t.get("type")==e}))}async get_attributes(){let e={},t=this.find_msg_type(bw);for(let i of t){let t=i.get("offset_to_message"),[r,s]=await this.unpack_attribute(t);e[r]=s}return e}async get_fillvalue(){var e,t=this.find_msg_type(pw)[0].get("offset_to_message");let i=(await Bp.unpack_from_async("=s&&([o,s]=a[++c],l=0);let t=await kp(Xm,e,o+l),i=o+l+Jm;if(t.set("offset_to_message",i),t.get("type")==Fw){var[u,f]=await Bp.unpack_from_async("=n-tw){let e=c[++l];if(null==e)break;[s,n]=e,h=0}let t=await kp(ew,e,s+h),i=s+h+tw+r;if(t.set("offset_to_message",i),t.get("type")==Fw){var[d,u]=await Bp.unpack_from_async("0,c=(4&r)>0;(8&r)>0?(s=(await Bp.unpack_from_async("0&&(t+=8);let s=(2&r)>0?sw:rw,o=await kp(s,e,t),n=new Map;for(let[e,t]of o.entries())n.set(e,t==Om?null:t);return n}get is_dataset(){return this.find_msg_type(dw).length>0}async get_data(){let e=this.find_msg_type(mw)[0].get("offset_to_message");var[t,i,r,s]=await this._get_data_message_properties(e);if(0==r)throw"Compact storage of DataObject not implemented";return 1==r?this._get_contiguous_data(s):2==r?this._get_chunked_data(e):void 0}async _get_data_message_properties(e){let t,i,r,[s,o,n]=await Bp.unpack_from_async("=1&&s<=4),[s,t,i,r]}async _get_contiguous_data(e){let[t]=await Bp.unpack_from_async("=!@\|]?(i|u|f|S)(\d*)/.test(r)){let[e,i,o]=Rp(r),a=new Array(s);const c=await this.fh.slice(t,t+o*s);let l=new Dp(c);for(var n=0;n=1&&t<=3);var a="<"+(i-1).toFixed()+"I",c=await Bp.unpack_from_async(a,this.fh,o);this._chunks=c,this._chunk_dims=i,this._chunk_address=n}}}};var Om=Bp.unpack_from("this.get(e)))}length(){return this.keys.length}_dereference(e){if(!e)throw"cannot deference null reference";let t=this.file._get_object_by_address(e);if(null==t)throw"reference not found in file";return t}async get(e){if("number"==typeof e)return this._dereference(e);var t=_w(e);if("/"==t)return this.file;if("."==t)return this;if(/^\//.test(t))return this.file.get(t.slice(1));if(""!=function(e){let t="/",i=e.lastIndexOf(t)+1,r=e.slice(0,i),s=new RegExp("^"+t+"+$"),o=new RegExp(t+"$");r&&!s.test(r)&&(r=r.replace(o,""));return r}(t))var[i,r]=t.split(/\/(.*)/);else var i=t,r=".";if(!(i in this._links))throw i+" not found in group";var s=_w(this.name+"/"+i);let o=this._links[i];if("string"==typeof o)try{return this.get(o)}catch(e){return null}var n=new Hm(this.file._fh,o);if(await n.ready,n.is_dataset){if("."!=r)throw s+" is a dataset, not a group";return new Cw(s,n,this)}var a=new yw(s,this);return await a.init(n),a.get(r)}visit(e){return this.visititems(((t,i)=>e(t)))}visititems(e){var t=this.name.length;/\/$/.test(this.name)||(t+=1);for(var i=this.values.slice();i;){let r=i.shift();1==i.length&&console.log(r);let s=e(r.name.slice(t),r);if(null!=s)return s;r instanceof yw&&(i=i.concat(r.values))}return null}get attrs(){return null==this._attrs&&(this._attrs=this._dataobjects.get_attributes()),this._attrs}},Aw=class extends yw{constructor(e,t,i){super("/",null),this.ready=this.init(e,t,i)}async init(e,t,i){var r=new bm(e,0);await r.ready;var s=await r.get_offset_to_dataobjects(),o=new Hm(e,s);if(await o.ready,this.parent=this,this.file=this,this.name="/",this._dataobjects=o,this._attrs=null,this._keys=null,this._fh=e,this.filename=t||"",this.mode="r",this.userblock_size=0,i&&i.index)this.index=i.index;else{let t;if(i&&i.indexOffset)t=i.indexOffset;else{const e=await this.attrs;if(e.hasOwnProperty("_index_offset"))t=e._index_offset;else{const e=this.indexName||"_index",i=await o.find_link(e);i&&(t=i[1])}}if(t)try{const i=new Hm(e,t);await i.ready;const r=await i.get_data(),s=lm(r),o=(new TextDecoder).decode(s);this.index=JSON.parse(o)}catch(e){console.error(`Error loading index by offset ${e}`)}}this.index&&this.name in this.index?this._links=this.index[this.name]:this._links=await o.get_links()}_get_object_by_address(e){return this._dataobjects.offset==e?this:this.visititems((e=>{e._dataobjects.offset}))}},Cw=class extends Array{constructor(e,t,i){super(),this.parent=i,this.file=i.file,this.name=e,this._dataobjects=t,this._attrs=null,this._astype=null}get value(){var e=this._dataobjects.get_data();return null==this._astype?this.getValue(e):e.astype(this._astype)}get shape(){return this._dataobjects.shape}get attrs(){return this._dataobjects.get_attributes()}get dtype(){return this._dataobjects.dtype}get fillvalue(){return this._dataobjects.get_fillvalue()}async to_array(){return function(e,t){const i=e.length,r=t.reduce(((e,t)=>e*t),1);i!==r&&console.warn(`shape product: ${r} does not match length of flattened array: ${i}`);let s=e;const o=t.slice(1).reverse();for(let e of o){const t=[],{length:i}=s;let r=0;for(;r{let t=e.indexOf("\0");return t>=0?e.substring(0,t):e})):e}};function _w(e){return e.replace(/\/(\/)+/g,"/")}async function xw(e){var t;e.url&&("function"==typeof(t=e.url).slice&&"function"==typeof t.arrayBuffer)&&(e.file=e.url,e.url=void 0);const i=void 0!==e.url;let r=e.reader?e.reader:kw(e);const s=e.fetchSize||2e3,o=e.maxSize||2e5;i&&(r=new yp({file:r,fetchSize:s,maxSize:o}));const n=new Iw(r),a=await async function(e){if(e.index)return e.index;{let t;if(e.indexReader)t=e.indexReader;else{let i;if(e.indexURL)i=Object.assign({url:e.indexURL},e);else if(e.indexPath)i=Object.assign({path:e.indexPath},e);else{if(!e.indexFile)return;i=Object.assign({file:e.indexFile},e)}t=kw(i)}const i=await t.read(),r=(new TextDecoder).decode(i);return JSON.parse(r)}}(e),c=e.indexOffset,l=function(e){if(e.url)return Sw(e.url);if(e.path)return Sw(e.path);if(e.file)return e.file.name}(e),h=new Aw(n,l,{index:a,indexOffset:c});return await h.ready,h}function kw(e){if(e.url)return new vp(e);if(e.path)return new NodeLocalFile(e);if(e.file)return new Cp(e.file);throw Error("One of 'url', 'path (node only)', or 'file (browser only)' must be specified")}class Iw{constructor(e){this.fileReader=e}async slice(e,t){return this.fileReader.read(e,t-e)}}function Sw(e){const t=e.lastIndexOf("/");return t>0?e.substring(t+1):e}class Ew{constructor(e,t){this.chrom=e,this.signal_bin_size=t;this.signals={raw_RD:`his_rd_p_${this.chrom}_${this.signal_bin_size}`,gc_RD:`his_rd_p_${this.chrom}_${this.signal_bin_size}_GC`,gc_partition:`his_rd_p_${this.chrom}_${this.signal_bin_size}_partition_GC_merge`,baf:`snp_likelihood_${this.chrom}_${this.signal_bin_size}_mask`,baf_i1:`snp_i1_${this.chrom}_${this.signal_bin_size}_mask`,Mosaic_segments:`his_rd_p_${this.chrom}_${this.signal_bin_size}_partition_GC_mosaic_segments_2d`,Mosaic_calls:`his_rd_p_${this.chrom}_${this.signal_bin_size}_partition_GC_mosaic_call_2d`}}}class Nw{constructor(e,t=1e5){this.config=e,this.bin_size=t,this.h5_obj=void 0,this.pytorKeys=[],this.availableBins=[]}async fetch(){if(!this.h5_obj){const e=Object.assign(this.config,{fetchSize:1e6,maxSize:2e8});this.h5_obj=await xw(e)}return this.h5_obj}async get_keys(){return(await this.fetch()).keys}async get_rd_signal(e=this.bin_size,t=void 0){const i=await this.fetch();this.pytorKeys=i.keys;const r=new Mw(this.pytorKeys);this.availableBins=r.getAllBins(),this.availableBins.includes(e)||(e=this.availableBins.at(-1));const s=await this.getChromosomes(t);let o=await this.rd_stat(e);const n=await this.getWigFeatures(s,e,o);return this.setCallers(n),{[e]:n}}async getWigFeatures(e,t,i){const r={RD_Raw:[],RD_Raw_gc_coor:[],ReadDepth:[],"2D":[],BAF1:[],BAF2:[]};for(const s of e){const e=new Ew(s,t);r.RD_Raw.push(...await this.get_chr_signal(s,t,e.signals.raw_RD,i)),r.RD_Raw_gc_coor.push(...await this.get_chr_signal(s,t,e.signals.gc_RD,i)),r.ReadDepth.push(...await this.get_chr_signal(s,t,e.signals.gc_partition,i)),r["2D"].push(...await this.rd_call_combined(s,t,i,e));const[o,n]=await this.getBafSignals(s,t,e.signals.baf_i1);r.BAF1.push(...o),r.BAF2.push(...n)}return r}async getChromosomes(e){const t=await this.h5_obj.get("rd_chromosomes"),i=await t.value;if(e){let t=new Set(e);return i.filter((e=>t.has(e)))}return i}setCallers(e){this.callers=[],e.ReadDepth.length&&this.callers.push("ReadDepth"),e["2D"].length&&this.callers.push("2D")}decode_segments(e){let t=[],i=[];for(let r of e)4294967295==r?(t.push(i),i=[]):i.push(r);return t}async rd_call_combined(e,t,i,r){let s,o=[],n=r.signals.Mosaic_segments;if(this.pytorKeys.includes(n)){const e=await this.h5_obj.get(n);let t=await e.value;s=this.decode_segments(t)}let a=r.signals.Mosaic_calls;if(this.pytorKeys.includes(a)){const r=await this.h5_obj.get(a);let n=await r.to_array();s.forEach(((r,s)=>{r.forEach(((r,a)=>{o.push({chr:e,start:r*t,end:(r+1)*t,value:n[0][s]/i[4]*2})}))}))}return o}async rd_stat(e){let t,i=`rd_stat_${e}_auto`;if(this.pytorKeys.includes(i)){const e=await this.h5_obj.get(i);t=await e.value}return t}async get_chr_signal(e,t,i,r){let s=[];if(this.pytorKeys.includes(i)){const o=await this.h5_obj.get(i);(await o.value).forEach(((i,o)=>{s.push({chr:e,start:o*t,end:(o+1)*t,value:i/r[4]*2})}))}return s}async getBafSignals(e,t,i,r=-1){const s=[],o=[];if(this.pytorKeys.includes(i)){const n=await this.h5_obj.get(i);(await n.to_array()).forEach(((i,n)=>{isNaN(i)||(s.push({chr:e,start:n*t,end:(n+1)*t,value:r*(.5-i)}),.5!==i&&o.push({chr:e,start:n*t,end:(n+1)*t,value:r*(.5+i)}))}))}return[s,o]}}class Mw{constructor(e){this.signals=e}getAllBins(){const e=this.getRdBins(),t=this.getSnpBins();return[...new Set([...e,...t])].sort(((e,t)=>e-t))}getRdBins(){return this.extractBins(/^his_rd_p_(.*)_(\d+)$/)}getSnpBins(){return this.extractBins(/^snp_likelihood_(.*)_(\d+)_mask$/)}extractBins(e){return[...new Set(this.signals.map((t=>t.match(e))).filter((e=>null!==e)).map((e=>Number(e[2]))))]}}function Rw(e){if(e.length<4)return e;let t,i,r,s,o,n;return t=e.slice().sort(((e,t)=>e-t)),t.length/4%1==0?(i=.5*(t[t.length/4]+t[t.length/4+1]),r=.5*(t[t.length*(3/4)]+t[t.length*(3/4)+1])):(i=t[Math.floor(t.length/4+1)],r=t[Math.ceil(t.length*(3/4)+1)]),s=r-i,o=r+1.5*s,n=i-1.5*s,t.filter((e=>e>=n&&e<=o))}function Bw(e){let t=Rw(e);const i=t.length,r=t.reduce(((e,t)=>e+t))/i,s=Math.sqrt(t.map((e=>Math.pow(e-r,2))).reduce(((e,t)=>e+t))/i);return[r,s]}var Dw={range_function:function(e,t,i){return Array(Math.ceil((t-e)/i)).fill(e).map(((e,t)=>e+t*i))},getDistParams:Bw,linspace:function(e,t,i){if(void 0===i&&(i=Math.max(Math.round(t-e)+1,1)),i<2)return 1===i?[e]:[];var r=Array(i);for(let s=--i;s>=0;s--)r[s]=(s*t+(i-s)*e)/i;return r},GetFit:class{constructor(e){this.allBins=e}getValues(){return Object.values(this.allBins).reduce(((e,t)=>e.concat(t.filter((e=>e.binScore>0)).map((e=>e.binScore)))),[])}getMean(e){return e.reduce((function(e,t){return e+t}))/e.length}fit_data(){return Bw(this.getValues())}histogram(e,t){const i=t[1]-t[0],r=[];e.forEach(((e,s)=>{t.forEach(((t,s)=>{if(r[t]||(r[t]={count:0}),t<=e&&e{s.push(e.count)})),s}},filterOutliers:Rw};function Lw(e,t){return isNaN(e)||isNaN(t)||t<=0?NaN:0===e?.5:.5+.5*(Tw(.5*t,.5,1)-Tw(.5*t,.5,t/(t+e*e)))*Math.sign(e)}function Tw(e,t,i){if(0==i)return 0;if(1==i)return 1;{let r=Ow(e+t)-Ow(e)-Ow(t)+e*Math.log(i)+t*Math.log(1-i);return i<(e+1)/(e+t+2)?Math.exp(r)*zw(e,t,i)/e:1-Math.exp(r)*zw(t,e,1-i)/t}}function zw(e,t,i,r=1e3){let s=1,o=1,n=1,a=e+t,c=e+1,l=e-1,h=1-a*i/c;for(let d=0;d<=r;d++){let r=parseFloat(d+1),u=r+r,f=r*(t-r)*i/((l+u)*(e+u)),p=s+f*o,g=h+f*n;f=-(e+r)*(a+r)*i/((c+u)*(e+u));let m=g+f*h,w=s;if(o=p/m,n=g/m,s=(p+f*s)/m,h=1,Math.abs(s-w)<3e-7*Math.abs(s))return s}}function Pw(e){if(0==e||1==e)return 1;return e*Pw(e-1)}function Hw(e){let t;var i=[75122.633153,80916.6278952,36308.2951477,8687.24529705,1168.92649479,83.8676043424,2.50662827511],r=0,s=1;if(0==e)t=1e99;else if(e%1==0)t=Pw(e-1);else{for(let t=0;t1&&void 0!==arguments[1]?arguments[1]:{};if(!function(e){const t=Yw.call(e);return t.endsWith("Array]")&&!t.includes("Big")}(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");var i=t.fromIndex,r=void 0===i?0:i,s=t.toIndex,o=void 0===s?e.length:s;if(r<0||r>=e.length||!Number.isInteger(r))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=r||o>e.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var n=e[r],a=r+1;an&&(n=e[a]);return n}const Jw=Object.prototype.toString;function eb(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!function(e){const t=Jw.call(e);return t.endsWith("Array]")&&!t.includes("Big")}(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");var i=t.fromIndex,r=void 0===i?0:i,s=t.toIndex,o=void 0===s?e.length:s;if(r<0||r>=e.length||!Number.isInteger(r))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=r||o>e.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var n=e[r],a=r+1;a1&&void 0!==arguments[1]?arguments[1]:{};if(!Zw(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");if(void 0!==i.output){if(!Zw(i.output))throw new TypeError("output option must be an array if specified");t=i.output}else t=new Array(e.length);var r=eb(e),s=Xw(e);if(r===s)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var o=i.min,n=void 0===o?i.autoMinMax?r:0:o,a=i.max,c=void 0===a?i.autoMinMax?s:1:a;if(n>=c)throw new RangeError("min option must be smaller than max option");for(var l=(c-n)/(s-r),h=0;h=0&&i?` ${lb(e,t-1)}`:lb(e,t)).padEnd(t)}function lb(e,t){let i=e.toString();if(i.length<=t)return i;let r=e.toFixed(t);if(r.length>t&&(r=e.toFixed(Math.max(0,t-(r.length-t)))),r.length<=t&&!r.startsWith("0.000")&&!r.startsWith("-0.000"))return r;let s=e.toExponential(t);return s.length>t&&(s=e.toExponential(Math.max(0,t-(s.length-t)))),s.slice(0)}function hb(e,t,i){let r=i?e.rows:e.rows-1;if(t<0||t>r)throw new RangeError("Row index out of range")}function db(e,t,i){let r=i?e.columns:e.columns-1;if(t<0||t>r)throw new RangeError("Column index out of range")}function ub(e,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==e.columns)throw new RangeError("vector size must be the same as the number of columns");return t}function fb(e,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==e.rows)throw new RangeError("vector size must be the same as the number of rows");return t}function pb(e,t){if(!rb.isAnyArray(t))throw new TypeError("row indices must be an array");for(let i=0;i=e.rows)throw new RangeError("row indices are out of range")}function gb(e,t){if(!rb.isAnyArray(t))throw new TypeError("column indices must be an array");for(let i=0;i=e.columns)throw new RangeError("column indices are out of range")}function mb(e,t,i,r,s){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(bb("startRow",t),bb("endRow",i),bb("startColumn",r),bb("endColumn",s),t>i||r>s||t<0||t>=e.rows||i<0||i>=e.rows||r<0||r>=e.columns||s<0||s>=e.columns)throw new RangeError("Submatrix indices are out of range")}function wb(e,t=0){let i=[];for(let r=0;r=s)throw new RangeError("min must be smaller than max");let n=s-r,a=new Ab(e,t);for(let i=0;ii?(s=!0,i=t):(r=!1,s=!0);e++}return r}isReducedEchelonForm(){let e=0,t=0,i=-1,r=!0,s=!1;for(;ei?(s=!0,i=t):(r=!1,s=!0);for(let i=t+1;ie.get(r,i)&&(r=s);if(0===e.get(r,i))i++;else{e.swapRows(t,r);let s=e.get(t,i);for(let r=i;r=0;)if(0===e.maxRow(r))r--;else{let s=0,o=!1;for(;se[t]&&(e[t]=this.get(t,i));return e}case"column":{const e=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let t=0;te[i]&&(e[i]=this.get(t,i));return e}case void 0:{let e=this.get(0,0);for(let t=0;te&&(e=this.get(t,i));return e}default:throw new Error(`invalid option: ${e}`)}}maxIndex(){Fb(this);let e=this.get(0,0),t=[0,0];for(let i=0;ie&&(e=this.get(i,r),t[0]=i,t[1]=r);return t}min(e){if(this.isEmpty())return NaN;switch(e){case"row":{const e=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let t=0;tt&&(t=this.get(e,i));return t}maxRowIndex(e){hb(this,e),Fb(this);let t=this.get(e,0),i=[e,0];for(let r=1;rt&&(t=this.get(e,r),i[1]=r);return i}minRow(e){if(hb(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let i=1;it&&(t=this.get(i,e));return t}maxColumnIndex(e){db(this,e),Fb(this);let t=this.get(0,e),i=[0,e];for(let r=1;rt&&(t=this.get(r,e),i[0]=r);return i}minColumn(e){if(db(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let i=1;i1;r/=2)1&r&&(t=t.mmul(i)),i=i.mmul(i);return t}strassen2x2(e){e=Ab.checkMatrix(e);let t=new Ab(2,2);const i=this.get(0,0),r=e.get(0,0),s=this.get(0,1),o=e.get(0,1),n=this.get(1,0),a=e.get(1,0),c=this.get(1,1),l=e.get(1,1),h=(i+c)*(r+l),d=(n+c)*r,u=i*(o-l),f=c*(a-r),p=(i+s)*l,g=h+f-p+(s-c)*(a+l),m=u+p,w=d+f,b=h-d+u+(n-i)*(r+o);return t.set(0,0,g),t.set(0,1,m),t.set(1,0,w),t.set(1,1,b),t}strassen3x3(e){e=Ab.checkMatrix(e);let t=new Ab(3,3);const i=this.get(0,0),r=this.get(0,1),s=this.get(0,2),o=this.get(1,0),n=this.get(1,1),a=this.get(1,2),c=this.get(2,0),l=this.get(2,1),h=this.get(2,2),d=e.get(0,0),u=e.get(0,1),f=e.get(0,2),p=e.get(1,0),g=e.get(1,1),m=e.get(1,2),w=e.get(2,0),b=e.get(2,1),F=e.get(2,2),v=(i-o)*(-u+g),y=(-i+o+n)*(d-u+g),A=(o+n)*(-d+u),C=i*d,_=(-i+c+l)*(d-f+m),x=(-i+c)*(f-m),k=(c+l)*(-d+f),I=(-s+l+h)*(g+w-b),S=(s-h)*(g-b),E=s*w,N=(l+h)*(-w+b),M=(-s+n+a)*(m+w-F),R=(s-a)*(m-F),B=(n+a)*(-w+F),D=C+E+r*p,L=(i+r+s-o-n-l-h)*g+y+A+C+I+E+N,T=C+_+k+(i+r+s-n-a-c-l)*m+E+M+B,z=v+n*(-d+u+p-g-m-w+F)+y+C+E+M+R,P=v+y+A+C+a*b,H=E+M+R+B+o*f,O=C+_+x+l*(-d+f+p-g-m-w+b)+I+S+E,V=I+S+E+N+c*u,q=C+_+x+k+h*F;return t.set(0,0,D),t.set(0,1,L),t.set(0,2,T),t.set(1,0,z),t.set(1,1,P),t.set(1,2,H),t.set(2,0,O),t.set(2,1,V),t.set(2,2,q),t}mmulStrassen(e){e=Ab.checkMatrix(e);let t=this.clone(),i=t.rows,r=t.columns,s=e.rows,o=e.columns;function n(e,t,i){let r=e.rows,s=e.columns;if(r===t&&s===i)return e;{let r=vb.zeros(t,i);return r=r.setSubMatrix(e,0,0),r}}r!==s&&console.warn(`Multiplying ${i} x ${r} and ${s} x ${o} matrix: dimensions do not match.`);let a=Math.max(i,s),c=Math.max(r,o);return t=n(t,a,c),function e(t,i,r,s){if(r<=512||s<=512)return t.mmul(i);r%2==1&&s%2==1?(t=n(t,r+1,s+1),i=n(i,r+1,s+1)):r%2==1?(t=n(t,r+1,s),i=n(i,r+1,s)):s%2==1&&(t=n(t,r,s+1),i=n(i,r,s+1));let o=parseInt(t.rows/2,10),a=parseInt(t.columns/2,10),c=t.subMatrix(0,o-1,0,a-1),l=i.subMatrix(0,o-1,0,a-1),h=t.subMatrix(0,o-1,a,t.columns-1),d=i.subMatrix(0,o-1,a,i.columns-1),u=t.subMatrix(o,t.rows-1,0,a-1),f=i.subMatrix(o,i.rows-1,0,a-1),p=t.subMatrix(o,t.rows-1,a,t.columns-1),g=i.subMatrix(o,i.rows-1,a,i.columns-1),m=e(vb.add(c,p),vb.add(l,g),o,a),w=e(vb.add(u,p),l,o,a),b=e(c,vb.sub(d,g),o,a),F=e(p,vb.sub(f,l),o,a),v=e(vb.add(c,h),g,o,a),y=e(vb.sub(u,c),vb.add(l,d),o,a),A=e(vb.sub(h,p),vb.add(f,g),o,a),C=vb.add(m,F);C.sub(v),C.add(A);let _=vb.add(b,v),x=vb.add(w,F),k=vb.sub(m,w);k.add(b),k.add(y);let I=vb.zeros(2*C.rows,2*C.columns);return I=I.setSubMatrix(C,0,0),I=I.setSubMatrix(_,C.rows,0),I=I.setSubMatrix(x,0,C.columns),I=I.setSubMatrix(k,C.rows,C.columns),I.subMatrix(0,r-1,0,s-1)}(t,e=n(e,a,c),a,c)}scaleRows(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{min:t=0,max:i=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(i))throw new TypeError("max must be a number");if(t>=i)throw new RangeError("min must be smaller than max");let r=new Ab(this.rows,this.columns);for(let e=0;e0&&sb(s,{min:t,max:i,output:s}),r.setRow(e,s)}return r}scaleColumns(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{min:t=0,max:i=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(i))throw new TypeError("max must be a number");if(t>=i)throw new RangeError("min must be smaller than max");let r=new Ab(this.rows,this.columns);for(let e=0;ei||t<0||t>=this.columns||i<0||i>=this.columns)throw new RangeError("Argument out of range");let r=new Ab(e.length,i-t+1);for(let s=0;s=this.rows)throw new RangeError(`Row index out of range: ${e[s]}`);r.set(s,o-t,this.get(e[s],o))}return r}subMatrixColumn(e,t,i){if(void 0===t&&(t=0),void 0===i&&(i=this.rows-1),t>i||t<0||t>=this.rows||i<0||i>=this.rows)throw new RangeError("Argument out of range");let r=new Ab(i-t+1,e.length);for(let s=0;s=this.columns)throw new RangeError(`Column index out of range: ${e[s]}`);r.set(o-t,s,this.get(o,e[s]))}return r}setSubMatrix(e,t,i){if((e=Ab.checkMatrix(e)).isEmpty())return this;mb(this,t,t+e.rows-1,i,i+e.columns-1);for(let r=0;r=0))throw new TypeError("nColumns must be a positive integer");for(let i=0;i=0)this.#x(e,t);else{if(!rb.isAnyArray(e))throw new TypeError("First argument must be a positive number or an array");{const i=e;if("number"!=typeof(t=(e=i.length)?i[0].length:0))throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let r=0;r"number"==typeof e)))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(i[r]))}this.rows=e,this.columns=t}}}set(e,t,i){return this.data[e][t]=i,this}get(e,t){return this.data[e][t]}removeRow(e){return hb(this,e),this.data.splice(e,1),this.rows-=1,this}addRow(e,t){return void 0===t&&(t=e,e=this.rows),hb(this,e,!0),t=Float64Array.from(ub(this,t)),this.data.splice(e,0,t),this.rows+=1,this}removeColumn(e){db(this,e);for(let t=0;t>e);return this},e.prototype.signPropagatingRightShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t>e.get(t,i));return this},e.signPropagatingRightShift=function(e,i){return new t(e).signPropagatingRightShift(i)},e.prototype.rightShift=function(e){return"number"==typeof e?this.rightShiftS(e):this.rightShiftM(e)},e.prototype.rightShiftS=function(e){for(let t=0;t>>e);return this},e.prototype.rightShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t>>e.get(t,i));return this},e.rightShift=function(e,i){return new t(e).rightShift(i)},e.prototype.zeroFillRightShift=e.prototype.rightShift,e.prototype.zeroFillRightShiftS=e.prototype.rightShiftS,e.prototype.zeroFillRightShiftM=e.prototype.rightShiftM,e.zeroFillRightShift=e.rightShift,e.prototype.not=function(){for(let e=0;e=0)this.#k=new Ab(e,e);else if(this.#k=new Ab(e),!this.isSymmetric())throw new TypeError("not symmetric data")}clone(){const e=new Cb(this.diagonalSize);for(const[t,i,r]of this.upperRightEntries())e.set(t,i,r);return e}toMatrix(){return new Ab(this)}get(e,t){return this.#k.get(e,t)}set(e,t,i){return this.#k.set(e,t,i),this.#k.set(t,e,i),this}removeCross(e){return this.#k.removeRow(e),this.#k.removeColumn(e),this}addCross(e,t){void 0===t&&(t=e,e=this.diagonalSize);const i=t.slice();return i.splice(e,1),this.#k.addRow(e,i),this.#k.addColumn(e,t),this}applyMask(e){if(e.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const t=[];for(const[i,r]of e.entries())r||t.push(i);t.reverse();for(const e of t)this.removeCross(e);return this}toCompact(){const{diagonalSize:e}=this,t=new Array(e*(e+1)/2);for(let i=0,r=0,s=0;s=e&&(i=++r);return t}static fromCompact(e){const t=e.length,i=(Math.sqrt(8*t+1)-1)/2;if(!Number.isInteger(i))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(e)}`);const r=new Cb(i);for(let s=0,o=0,n=0;n=i&&(s=++o);return r}*upperRightEntries(){for(let e=0,t=0;e=this.diagonalSize&&(t=++e)}}*upperRightValues(){for(let e=0,t=0;e=this.diagonalSize&&(t=++e)}}}Cb.prototype.klassType="SymmetricMatrix";class _b extends Cb{static isDistanceMatrix(e){return Cb.isSymmetricMatrix(e)&&"DistanceMatrix"===e.klassSubType}constructor(e){if(super(e),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(e,t,i){return e===t&&(i=0),super.set(e,t,i)}addCross(e,t){return void 0===t&&(t=e,e=this.diagonalSize),(t=t.slice())[e]=0,super.addCross(e,t)}toSymmetricMatrix(){return new Cb(this)}clone(){const e=new _b(this.diagonalSize);for(const[t,i,r]of this.upperRightEntries())t!==i&&e.set(t,i,r);return e}toCompact(){const{diagonalSize:e}=this,t=new Array((e-1)*e/2);for(let i=1,r=0,s=0;s=e&&(i=1+ ++r);return t}static fromCompact(e){const t=e.length;if(0===t)return new this(0);const i=(Math.sqrt(8*t+1)+1)/2;if(!Number.isInteger(i))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(e)}`);const r=new this(i);for(let s=1,o=0,n=0;n=i&&(s=1+ ++o);return r}}_b.prototype.klassSubType="DistanceMatrix";class xb extends vb{constructor(e,t,i){super(),this.matrix=e,this.rows=t,this.columns=i}}class kb extends xb{constructor(e,t,i){pb(e,t),gb(e,i),super(e,t.length,i.length),this.rowIndices=t,this.columnIndices=i}set(e,t,i){return this.matrix.set(this.rowIndices[e],this.columnIndices[t],i),this}get(e,t){return this.matrix.get(this.rowIndices[e],this.columnIndices[t])}}class Ib extends vb{constructor(e,t={}){const{rows:i=1}=t;if(e.length%i!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=i,this.columns=e.length/i,this.data=e}set(e,t,i){let r=this._calculateIndex(e,t);return this.data[r]=i,this}get(e,t){let i=this._calculateIndex(e,t);return this.data[i]}_calculateIndex(e,t){return e*this.columns+t}}class Sb extends vb{constructor(e){super(),this.data=e,this.rows=e.length,this.columns=e[0].length}set(e,t,i){return this.data[e][t]=i,this}get(e,t){return this.data[e][t]}}class Eb{constructor(e){let t,i,r,s,o,n,a,c,l,h=(e=Sb.checkMatrix(e)).clone(),d=h.rows,u=h.columns,f=new Float64Array(d),p=1;for(t=0;tMath.abs(c[s])&&(s=t);if(s!==i){for(r=0;r=0;s--){for(r=0;rt?r.set(s,t,e.get(s,t)):s===t?r.set(s,t,1):r.set(s,t,0);return r}get upperTriangularMatrix(){let e=this.LU,t=e.rows,i=e.columns,r=new Ab(t,i);for(let s=0;sMath.abs(t)?(i=t/e,Math.abs(e)*Math.sqrt(1+i*i)):0!==t?(i=e/t,Math.abs(t)*Math.sqrt(1+i*i)):0}class Mb{constructor(e){let t,i,r,s,o=(e=Sb.checkMatrix(e)).clone(),n=e.rows,a=e.columns,c=new Float64Array(a);for(r=0;r=0;o--){for(s=0;s=0;i--){for(e=0;e=0;e--)if(0!==f[e]){for(let t=e+1;t=0;e--){if(e0;){let e,t;for(e=A-2;e>=-1&&-1!==e;e--){const t=Number.MIN_VALUE+_*Math.abs(f[e]+Math.abs(f[e+1]));if(Math.abs(m[e])<=t||Number.isNaN(m[e])){m[e]=0;break}}if(e===A-2)t=4;else{let i;for(i=A-1;i>=e&&i!==e;i--){let t=(i!==A?Math.abs(m[i]):0)+(i!==e+1?Math.abs(m[i-1]):0);if(Math.abs(f[i])<=_*t){f[i]=0;break}}i===e?t=3:i===A-1?t=1:(t=2,e=i)}switch(e++,t){case 1:{let t=m[A-2];m[A-2]=0;for(let i=A-2;i>=e;i--){let s=Nb(f[i],t),o=f[i]/s,n=t/s;if(f[i]=s,i!==e&&(t=-n*m[i-1],m[i-1]=o*m[i-1]),l)for(let e=0;e=f[e+1]);){let t=f[e];if(f[e]=f[e+1],f[e+1]=t,l&&et&&s.set(o,i,e.get(o,i)/this.s[i]);let o=this.U,n=o.rows,a=o.columns,c=new Ab(i,n);for(let e=0;ee&&t++;return t}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return Ab.diag(this.s)}}function Bb(e,t,i=!1){return e=Sb.checkMatrix(e),t=Sb.checkMatrix(t),i?new Rb(e).solve(t):e.isSquare()?new Eb(e).solve(t):new Mb(e).solve(t)}function Db(e,t){let i=[];for(let r=0;rs)return new Array(t.rows+1).fill(0);{let e=t.addRow(i,[0]);for(let t=0;t0;a--){for(d=0,n=0,l=0;l0&&(o=-o),t[a]=d*o,n-=s*o,i[a-1]=s-o,c=0;cl)do{for(s=i[l],d=(i[l+1]-s)/(2*t[l]),u=Nb(d,1),d<0&&(u=-u),i[l]=t[l]/(d+u),i[l+1]=t[l]*(d+u),f=i[l+1],o=s-i[l],n=l+2;n=l;n--)for(m=g,g=p,F=b,s=p*t[n],o=p*d,u=Nb(d,t[n]),t[n+1]=b*u,b=t[n]/u,p=d/u,d=p*i[n]-b*s,i[n+1]=o+b*(p*s+b*i[n]),c=0;cA*y);i[l]=i[l]+v,t[l]=0}for(n=0;n=l;a--)i[a]=t.get(a,l-1)/h,n+=i[a]*i[a];for(o=Math.sqrt(n),i[l]>0&&(o=-o),n-=i[l]*o,i[l]=i[l]-o,c=l;c=l;a--)s+=i[a]*t.get(a,c);for(s/=n,a=l;a<=u;a++)t.set(a,c,t.get(a,c)-s*i[a])}for(a=0;a<=u;a++){for(s=0,c=u;c>=l;c--)s+=i[c]*t.get(a,c);for(s/=n,c=l;c<=u;c++)t.set(a,c,t.get(a,c)-s*i[c])}i[l]=h*i[l],t.set(l,l-1,h*o)}}for(a=0;a=d+1;l--)if(0!==t.get(l,l-1)){for(a=l+1;a<=u;a++)i[a]=t.get(a,l-1);for(c=l;c<=u;c++){for(o=0,a=l;a<=u;a++)o+=i[a]*r.get(a,c);for(o=o/i[l]/t.get(l,l-1),a=l;a<=u;a++)r.set(a,c,r.get(a,c)+o*i[a])}}}(o,e,t,n),function(e,t,i,r,s){let o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v=e-1,y=0,A=e-1,C=Number.EPSILON,_=0,x=0,k=0,I=0,S=0,E=0,N=0,M=0;for(o=0;oA)&&(i[o]=s.get(o,o),t[o]=0),n=Math.max(o-1,0);n=y;){for(c=v;c>y&&(E=Math.abs(s.get(c-1,c-1))+Math.abs(s.get(c,c)),0===E&&(E=x),!(Math.abs(s.get(c,c-1))=0){for(N=k>=0?k+N:k-N,i[v-1]=u+N,i[v]=i[v-1],0!==N&&(i[v]=u-d/N),t[v-1]=0,t[v]=0,u=s.get(v,v-1),E=Math.abs(u)+Math.abs(N),k=u/E,I=N/E,S=Math.sqrt(k*k+I*I),k/=S,I/=S,n=v-1;n0)){for(E=Math.sqrt(E),f=c&&(N=s.get(l,l),S=u-N,E=f-N,k=(S*E-d)/s.get(l+1,l)+s.get(l,l+1),I=s.get(l+1,l+1)-N-S-E,S=s.get(l+2,l+1),E=Math.abs(k)+Math.abs(I)+Math.abs(S),k/=E,I/=E,S/=E,l!==c)&&!(Math.abs(s.get(l,l-1))*(Math.abs(I)+Math.abs(S))l+2&&s.set(o,o-3,0);for(a=l;a<=v-1&&(b=a!==v-1,a!==l&&(k=s.get(a,a-1),I=s.get(a+1,a-1),S=b?s.get(a+2,a-1):0,u=Math.abs(k)+Math.abs(I)+Math.abs(S),0!==u&&(k/=u,I/=u,S/=u)),0!==u);a++)if(E=Math.sqrt(k*k+I*I+S*S),k<0&&(E=-E),0!==E){for(a!==l?s.set(a,a-1,-E*u):c!==l&&s.set(a,a-1,-s.get(a,a-1)),k+=E,u=k/E,f=I/E,N=S/E,I/=k,S/=k,n=a;n=0;v--)if(k=i[v],I=t[v],0===I)for(c=v,s.set(v,v,1),o=v-1;o>=0;o--){for(d=s.get(o,o)-k,S=0,n=c;n<=v;n++)S+=s.get(o,n)*s.get(n,v);if(t[o]<0)N=d,E=S;else if(c=o,0===t[o]?s.set(o,v,0!==d?-S/d:-S/(C*x)):(u=s.get(o,o+1),f=s.get(o+1,o),I=(i[o]-k)*(i[o]-k)+t[o]*t[o],h=(u*E-N*S)/I,s.set(o,v,h),s.set(o+1,v,Math.abs(u)>Math.abs(N)?(-S-d*h)/u:(-E-f*h)/N)),h=Math.abs(s.get(o,v)),C*h*h>1)for(n=o;n<=v;n++)s.set(n,v,s.get(n,v)/h)}else if(I<0)for(c=v-1,Math.abs(s.get(v,v-1))>Math.abs(s.get(v-1,v))?(s.set(v-1,v-1,I/s.get(v,v-1)),s.set(v-1,v,-(s.get(v,v)-k)/s.get(v,v-1))):(F=zb(0,-s.get(v-1,v),s.get(v-1,v-1)-k,I),s.set(v-1,v-1,F[0]),s.set(v-1,v,F[1])),s.set(v,v-1,0),s.set(v,v,1),o=v-2;o>=0;o--){for(p=0,g=0,n=c;n<=v;n++)p+=s.get(o,n)*s.get(n,v-1),g+=s.get(o,n)*s.get(n,v);if(d=s.get(o,o)-k,t[o]<0)N=d,S=p,E=g;else if(c=o,0===t[o]?(F=zb(-p,-g,d,I),s.set(o,v-1,F[0]),s.set(o,v,F[1])):(u=s.get(o,o+1),f=s.get(o+1,o),m=(i[o]-k)*(i[o]-k)+t[o]*t[o]-I*I,w=2*(i[o]-k)*I,0===m&&0===w&&(m=C*x*(Math.abs(d)+Math.abs(I)+Math.abs(u)+Math.abs(f)+Math.abs(N))),F=zb(u*S-N*p+I*g,u*E-N*g-I*p,m,w),s.set(o,v-1,F[0]),s.set(o,v,F[1]),Math.abs(u)>Math.abs(N)+Math.abs(I)?(s.set(o+1,v-1,(-p-d*s.get(o,v-1)+I*s.get(o,v))/u),s.set(o+1,v,(-g-d*s.get(o,v)-I*s.get(o,v-1))/u)):(F=zb(-S-f*s.get(o,v-1),-E-f*s.get(o,v),N,I),s.set(o+1,v-1,F[0]),s.set(o+1,v,F[1]))),h=Math.max(Math.abs(s.get(o,v-1)),Math.abs(s.get(o,v))),C*h*h>1)for(n=o;n<=v;n++)s.set(n,v-1,s.get(n,v-1)/h),s.set(n,v,s.get(n,v)/h)}for(o=0;oA)for(n=o;n=y;n--)for(o=y;o<=A;o++){for(N=0,a=y;a<=Math.min(n,A);a++)N+=r.get(o,a)*s.get(a,n);r.set(o,n,N)}}(o,c,a,n,e)}this.n=o,this.e=c,this.d=a,this.V=n}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let e,t,i=this.n,r=this.e,s=this.d,o=new Ab(i,i);for(e=0;e0?o.set(e,e+1,r[e]):r[e]<0&&o.set(e,e-1,r[e])}return o}}function zb(e,t,i,r){let s,o;return Math.abs(i)>Math.abs(r)?(s=r/i,o=i+s*r,[(e+s*t)/o,(t-s*e)/o]):(s=i/r,o=r+s*i,[(s*e+t)/o,(s*t-e)/o])}class Pb{constructor(e){if(!(e=Sb.checkMatrix(e)).isSymmetric())throw new Error("Matrix is not symmetric");let t,i,r,s=e,o=s.rows,n=new Ab(o,o),a=!0;for(i=0;i0,n.set(i,i,Math.sqrt(Math.max(e,0))),r=i+1;r=0;o--)for(s=0;so;t++)l=e.transpose().mmul(n).div(n.transpose().mmul(n).get(0,0)),l=l.div(l.norm()),a=e.mmul(l).div(l.transpose().mmul(l).get(0,0)),t>0&&(d=a.clone().sub(h).pow(2).sum()),h=a.clone(),i?(c=i.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),c=c.div(c.norm()),n=i.mmul(c).div(c.transpose().mmul(c).get(0,0))):n=a;if(i){let t=e.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0));t=t.div(t.norm());let r=e.clone().sub(a.clone().mmul(t.transpose())),s=n.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),o=i.clone().sub(a.clone().mulS(s.get(0,0)).mmul(c.transpose()));this.t=a,this.p=t.transpose(),this.w=l.transpose(),this.q=c,this.u=n,this.s=a.transpose().mmul(a),this.xResidual=r,this.yResidual=o,this.betas=s}else this.w=l.transpose(),this.s=a.transpose().mmul(a).sqrt(),this.t=r?a.clone().div(this.s.get(0,0)):a,this.xResidual=e.sub(a.mmul(l.transpose()))}}jw.AbstractMatrix=vb,jw.CHO=Pb,jw.CholeskyDecomposition=Pb,jw.DistanceMatrix=_b,jw.EVD=Tb,jw.EigenvalueDecomposition=Tb,jw.LU=Eb,jw.LuDecomposition=Eb;var Ob=jw.Matrix=Ab;jw.MatrixColumnSelectionView=class extends xb{constructor(e,t){gb(e,t),super(e,e.rows,t.length),this.columnIndices=t}set(e,t,i){return this.matrix.set(e,this.columnIndices[t],i),this}get(e,t){return this.matrix.get(e,this.columnIndices[t])}},jw.MatrixColumnView=class extends xb{constructor(e,t){db(e,t),super(e,e.rows,1),this.column=t}set(e,t,i){return this.matrix.set(e,this.column,i),this}get(e){return this.matrix.get(e,this.column)}},jw.MatrixFlipColumnView=class extends xb{constructor(e){super(e,e.rows,e.columns)}set(e,t,i){return this.matrix.set(e,this.columns-t-1,i),this}get(e,t){return this.matrix.get(e,this.columns-t-1)}},jw.MatrixFlipRowView=class extends xb{constructor(e){super(e,e.rows,e.columns)}set(e,t,i){return this.matrix.set(this.rows-e-1,t,i),this}get(e,t){return this.matrix.get(this.rows-e-1,t)}},jw.MatrixRowSelectionView=class extends xb{constructor(e,t){pb(e,t),super(e,t.length,e.columns),this.rowIndices=t}set(e,t,i){return this.matrix.set(this.rowIndices[e],t,i),this}get(e,t){return this.matrix.get(this.rowIndices[e],t)}},jw.MatrixRowView=class extends xb{constructor(e,t){hb(e,t),super(e,1,e.columns),this.row=t}set(e,t,i){return this.matrix.set(this.row,t,i),this}get(e,t){return this.matrix.get(this.row,t)}},jw.MatrixSelectionView=kb,jw.MatrixSubView=class extends xb{constructor(e,t,i,r,s){mb(e,t,i,r,s),super(e,i-t+1,s-r+1),this.startRow=t,this.startColumn=r}set(e,t,i){return this.matrix.set(this.startRow+e,this.startColumn+t,i),this}get(e,t){return this.matrix.get(this.startRow+e,this.startColumn+t)}},jw.MatrixTransposeView=class extends xb{constructor(e){super(e,e.columns,e.rows)}set(e,t,i){return this.matrix.set(t,e,i),this}get(e,t){return this.matrix.get(t,e)}},jw.NIPALS=Hb,jw.Nipals=Hb,jw.QR=Mb,jw.QrDecomposition=Mb,jw.SVD=Rb,jw.SingularValueDecomposition=Rb,jw.SymmetricMatrix=Cb,jw.WrapperMatrix1D=Ib,jw.WrapperMatrix2D=Sb,jw.correlation=function(e,t=e,i={}){e=new Ab(e);let r=!1;if("object"!=typeof t||Ab.isMatrix(t)||rb.isAnyArray(t)?t=new Ab(t):(i=t,t=e,r=!0),e.rows!==t.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:s=!0,scale:o=!0}=i;s&&(e.center("column"),r||t.center("column")),o&&(e.scale("column"),r||t.scale("column"));const n=e.standardDeviation("column",{unbiased:!0}),a=r?n:t.standardDeviation("column",{unbiased:!0}),c=e.transpose().mmul(t);for(let t=0;tt?o[e]=1/o[e]:o[e]=0;return s.mmul(Ab.diag(o).mmul(r.transpose()))},jw.solve=Bb,jw.wrap=function(e,t){if(rb.isAnyArray(e))return e[0]&&rb.isAnyArray(e[0])?new Sb(e):new Ib(e,t);throw new Error("the argument is not an array")};const Ub=Ob;Vb.Matrix&&Vb.Matrix;const Qb=qb;function Gb(e,t,i,r,s,o,n){let a=i,c=Ub.eye(t.length,t.length,a);const l=s(t);let h=new Float64Array(e.x.length);for(let t=0;te}else{if(!Uw(a))throw new Error("weights should be a number or array with length equal to the number of data points");if(a.lengthe}else m=e=>1/a[e]**2}if(void 0!==r){if("number"!=typeof r)throw new Error("timeout should be a number");let e=Date.now()+1e3*r;w=()=>Date.now()>e}else w=()=>!1;let y=new Array(e.x.length);for(let e=0;eg?c=Math.max(c/h,1e-7):(m=d,c=Math.min(c*l,1e7)),r())throw new Error(`The execution time is over to ${i.timeout} seconds`);w=m<=u}return{parameterValues:n,parameterError:m,iterations:b}}class Wb{constructor(e){this.binScores=e}get_histogram(){let e=Math.max(...this.binScores),t=Math.floor(e/1e3),i=this.range(0,Math.floor(e/t)*t+t,t);const{counts:r,bins:s}=this.histogram(this.binScores,i);return{counts:r,bins:s}}range(e,t,i){const r=[];for(let s=e;s{for(let r=0;r=t[r]&&ee*Math.exp(-Math.pow(r-t,2)/(2*Math.pow(i,2)))/(Math.sqrt(2*Math.PI)*i)}get_initial_model_values(e,t){const i=t.slice(1,-1).reduce(((e,t)=>e+t),0);if(0===i)return console.debug("Problem with fit: all data points have zero value. Return zeros instead fit parameters!"),null;const r=(e[1]-e[0])*i,s=e.reduce(((e,i,r)=>e+i*t[r]),0)/i,o=e.reduce(((e,i,r)=>e+t[r]*Math.pow(i-s,2)),0),n=Math.sqrt(o/i);return[r,s,n]}normal_fit(e,t){const i={initialValues:this.get_initial_model_values(e,t),maxIterations:100};return jb({x:e,y:t},this.normal_distribution,i)}}class $b{constructor(e,t){this.binSize=e,this.refGenome=t,this.gcBin=this.getGCbinSize()}getGCbinSize(){for(let e of[1e5,1e4])if(this.binSize%e==0)return e;return!1}async getBinGC(){const e={};if(!this.gcBin)return e;const t="https://storage.googleapis.com/cnvpytor_data/gcInfoData/GCinfo.json";try{const i=(await Rr.loadJson(t,{timeout:5e3})).find((e=>e.id===this.refGenome));if(!i)return console.warn("GC data not found for ",this.refGenome),e;const r=i.Bins.find((e=>e.BinSize===this.gcBin));if(!r)return console.warn("GC data not found for ",this.refGenome," Bin : ",this.gcBin),e;let s=`${t.split("/").slice(0,-1).join("/")}${r.fileURL}`;(await Rr.load(s,{})).split("\n").forEach((t=>{if(""!==t.trim()){const[i,r,s,o,n]=t.split("\t");e[i]||(e[i]=[]),e[i].push({start:+r,gcContent:+s,gcCount:+o,atCount:+n})}}))}catch(e){console.error(e),console.warn("Errors loading GC correction data.")}return e}}class Kb extends $b{constructor(e,t,i){super(t,i),this.wigFeatures=e,this.binSize=t,this.refGenome=i}async apply_gcCorrection(){if(!this.wigFeatures)return console.error("BinScore data is not available."),null;const e=Object.values(this.wigFeatures).reduce(((e,t)=>e.concat(t.filter((e=>e.binScore>0)).map((e=>e.binScore)))),[]);let t=new Wb(e);const{counts:i,bins:r}=t.get_histogram();let s=t.normal_fit(r,i);this.globalMean=s.parameterValues[1],this.globalStd=s.parameterValues[2],this.gcData=await this.getBinGC(),this.gcFlag=Object.keys(this.gcData).length>0,this.binScoreField=this.gcFlag?"gcCorrectedBinScore":"binScore",this.getGcCorrectionSignal(this.globalMean)}getGcCorrectionSignal(e){let t=this.getGcCorrection(e);Object.keys(this.wigFeatures).forEach((e=>{this.wigFeatures[e].forEach((e=>{e.binScore?e.gcCorrectedBinScore=Math.round(t[e.gc]*e.binScore):e.gcCorrectedBinScore=null}))}))}getGcCorrection(e){const t={};if(this.gcFlag){let i=this.getGCbinSize();const r={};let s=parseInt(this.binSize/i);for(let e in this.wigFeatures)for(let t=0;t{let s,o=r[i];if(o.length<4)s=o.reduce(((e,t)=>e+t),0)/o.length;else{let e=new Wb(r[i]);const{counts:t,bins:o}=e.get_histogram();s=e.normal_fit(o,t).parameterValues[1]}t[i]=e/s}))}return t}formatDataStructure(e,t=1){const i=[];for(const[s,o]of Object.entries(this.wigFeatures))for(let s of o){var r={...s};1!=t&&(r.value=s[e]/t*2),i.push(r)}return i}formatDataStructure_BAF(e,t=-1){const i=[],r=[];for(const[s,o]of Object.entries(this.wigFeatures))o.forEach((s=>{var o={...s},n={...s};let a=s[e];.5!=a&&(n.value=t*(1-a),r.push(n)),o.value=t*a,i.push(o)}));return[i,r]}}function Zb(e){return e.reduce((function(e,t){return e>t?e:t}))}function Yb(e,t,i,r){return t*Math.exp(-1*(e-i)**2/(2*r**2))/Math.sqrt(2*Math.PI)/r}function Xb(e,t,i,r){return Math.exp(-1*(e-i)**2/(t**2+r**2))}function Jb(e,t){let i;try{i=e.reduce(((e,i,r)=>e+Math.min(i,t[r])))}catch{return console.log("Failed to find likelihood overlap: ",e,t),0}return i}function eF(e,t,i,r){return 0==t&&0==r?{nl:.5*(e+i),ne:0}:{nl:(e*r*r+i*t*t)/(t*t+r*r),ne:Math.sqrt(t*t*r*r/(t*t+r*r))}}function tF(e,t){let i=parseInt(t*(e.length-1)),r=t*(e.length-1)-i;return iMath.floor(t/2)&&(r=t-1-r);const s=(t/2-r)/(t+1),o=Math.floor((t/2+r)/2),n=t-1-o;let a=e.slice(o,n+1).reduce(((e,t)=>e+t),0)/e.reduce(((e,t)=>e+t),0);return r===Math.floor(t/2)&&(a=1),{mean:s,p:a}}var rF={CombinedCaller:class extends Kb{constructor(e,t,i){super(e,t,i)}async call_2d(e=null,t=null,i="both",r=.1,s=0,o=10,n=0){await this.apply_gcCorrection();let a=this.gcFlag?"gcCorrectedBinScore":"binScore",c=null==e?.05*this.binSize/3e9:e,l=null==t?parseInt(this.binSize/1e4):t,h=[],d=[],u=[],f=[],p=[],g=[];for(const[e,t]of Object.entries(this.wigFeatures)){let e=[],i=[],o=[];t.forEach(((t,r)=>{t.hets_count>4&&t.dp_count>l&&t[a]&&(e.push([r]),i.push(t[a]),o.push(t.likelihood_score),delete t.likelihood_score)}));let n=[];for(let e=1;eMath.sqrt(Math.sqrt(e)**2+this.globalStd**2+Math.pow(g[t]/2,2)))),w=[];for(let t=0;t0;){w=w.filter((e=>"number"==typeof e));let t=Zb(w);if(isNaN(t)&&console.log("NaN value",w),te*o[n+1][t])),s=r.reduce(((e,t)=>e+t))}catch{console.log(o),console.log("max_overlap:",t,n,w.length),console.log("likelihood: ",n,o[n],o[n+1]),console.log("nlh: ",s)}if(i[n]=a.nl,m[n]=a.ne,o[n]=r.map((function(e){return e/s})),e[n].push(...e[n+1]),i.splice(n+1,1),m.splice(n+1,1),e.splice(n+1,1),o.splice(n+1,1),w.splice(n,1),n0){let e=Xb(i[n-1],m[n-1],i[n],m[n])*Jb(o[n-1],o[n]);w[n-1]=e}}let b=-1;for(;;){w=[];for(let t=0;te*o[s+1][t])),a=r.reduce(((e,t)=>e+t));o[s]=r.map((function(e){return e/a})),e[s].push(...e[s+1]),e[s]=e[s].sort(((e,t)=>e-t)),i.splice(n,1),m.splice(n,1),e.splice(n,1),o.splice(n,1),n>=e.length&&(s+=1,n=s+1)}else n+=1,n>=e.length&&(s+=1,n=s+1)}if(b==e.length)break;b=e.length}e.forEach(((e,r)=>{let n=iF(o[r]);e.length>1&&(e.forEach(((e,o)=>{d.push(t[e]),n.mean<=s&&h.push(t[e]),t[e].segment_score=i[r]})),u.push(i[r]),f.push(m[r]),p.push(o[r]))}))}let m=parseInt(1e3*(1-n));0==m&&(m=1);let w=Dw.linspace(n,1,m),b={},F={};for(let e=10;e>-1;e--)for(let t=0;t1-t+t*e/2)),a=e/2;e>0?(r=.5-t/(t+o),s=w.map(((e,i)=>.5-(1-e+e*t)/(2-2*e+(t+o)*e)))):(r=0,s=w.map(((e,t)=>0*e)));for(let i=0;i{if(!isNaN(s[t])){let r=Yb(e*this.globalMean,1,u[i],f[i])*tF(p[i],.5+s[t]);l+=r,r>h&&(h=r,d=w[t])}})),i in b?b[i].push([e,t,o,l/w.length,d]):b[i]=[e,t,o,l/w.length,d]}for(let e=0;ee[3]-t[3]));else if(b[e].sort(((e,t)=>e[3]-t[3])),"both"==i&&(F[e].sort(((e,t)=>e[3]-t[3])),F[e][0][3]>b[e][0][3])){let t=b[e].filter((t=>t[0]!=F[e][0][0]&&t[1]<=F[e][0][1]));b[e]=[F[e][0]].push(...t)}for(let e=0;e{var s={...e};1!=i&&(s.value=e[t]/i*2),r.push(s)}));return r}}};const sF=2871e6;function oF(e){for(var t=1,i=1,r=1*e,s=1;s<50;s++)t*=s,r+=(i*=-1)*Math.pow(e,2*s+1)/(t*(2*s+1));return 2*r/Math.sqrt(3.14159265358979)}function nF(e,t,i,r,s){var o=new lF(i.slice(r,s));return 0==o.std&&(o.std=t>0?t*o.mean/e:1),hF(e,o.mean,o.std,s-r)/(s-r)}function aF(e,t,i,r,s){var o=new lF(i.slice(r,s));if(o.meano&!l&c0&&(h=nF(e,t,i,r-1,s)),s-r>2)var d=nF(e,t,i,r+1,s),u=nF(e,t,i,r,s-1);if(se+t))/e.length,this.std=Math.sqrt(e.reduce(((e,t)=>(t-this.mean)**2))/e.length)}}function hF(e,t,i,r){0==i&&(i=1);var s=(e-t)/i*Math.sqrt(r);return 1-Vw.TdistributionCDF(Math.abs(s),r-1)}function dF(e,t,i,r,s,o){0==t&&(t=1),0==s&&(s=1);var n=(e-r)/Math.sqrt(t**2/i+s**2/o),a=(t**2/i+s**2/o)**2*(i-1)*(o-1)/(t**4*(o-1)/i**2+s**4*(i-1)/o**2);return 1-Vw.TdistributionCDF(Math.abs(n),parseInt(a+.5))}var uF={Partition:class{constructor(e,t,i){this.rd=e,this.mean=t,this.std=i,this.bin_bands=[2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128]}get_rd_signal_bandwidth(e){var t=[];return e.forEach(((e,i)=>{var r=0;r=e>this.mean/4?this.mean/(this.std**2*e):4/this.std**2,t.push(r)})),t}meanShiftCaller(e,t=3){var i={};return Object.entries(this.rd).forEach((([e,r])=>{var s=new Array(r.length).fill(!1),o=new Array(r.length);for(let e=0;e{var n=s.map(((e,t)=>!e)),a=[];Object.entries(r).forEach((([e,t])=>{a.push(t.binScore)}));var c=[0],l=0;for(let e=0;e0&&(c.push(c[c.length-1]+l-1),l=0):l+=1;c.shift();for(let i=0;i=a.length||Math.abs(t-i)>=a.length)){var u=(i-t)*Math.exp(-.5*(i-t)**2/e**2)*Math.exp(-.5*(a[t]-a[i])**2*h[t]);d[t]+=u}for(var f=new Array,p=0;p=0&&f.push(p);f.push(d.length-1),f=f.concat(c).sort(((e,t)=>e-t)),f=Array.from(new Set(f));var g=0;for(p=0;pe+t))/m.length;a.fill(w,g,f[p]+1),g=f[p]+1}}p=0;for(var b=0;p.01&&f.push(p+1)}f.unshift(0),f.push(o.length),s=new Array(this.rd.length).fill(!1);for(p=1;p1))continue;v[0]=f[p-2];var y=[f[p],f[p]];if(!(p.01/sF*bin_size*(A+C))continue;if(dF(x.mean,x.std,x.data.length,N.mean,N.std,N.data.length)>.01/sF*bin_size*(A+_))continue}if(hF(this.mean,x.mean,x.std,x.data.length)>.05)continue;let e=a.slice(F[0],F[1]);var M=new lF(e);s.fill(!0,F[0],F[1]),o.fill(M.mean,F[0],F[1])}})),i[e]=o})),i}call_mean_shift(e=3){for(var t=new Array(this.rd.length).fill(!1),i=new Array(this.rd.length),r=0;r{var o=t.map(((e,t)=>!e)),n=[];o.forEach(((e,t)=>{e&&n.push(this.rd[t])}));for(var a=[0],c=0,l=0;l0&&(a.push(a[a.length-1]+c-1),c=0):c+=1;a.shift();for(var h=0;h=n.length||Math.abs(l-f)>=n.length)){var p=(f-l)*Math.exp(-.5*(f-l)**2/r**2)*Math.exp(-.5*(n[l]-n[f])**2*d[l]);u[l]+=p}var g=new Array;for(l=0;l=0&&g.push(l);g.push(u.length-1),g=g.concat(a).sort(((e,t)=>e-t)),g=Array.from(new Set(g));var m=0;for(l=0;le+t))/w.length;n.fill(b,m,g[l]+1),m=g[l]+1}}for(l=0,f=0;l.01&&g.push(l+1)}g.unshift(0),g.push(i.length),t=new Array(this.rd.length).fill(!1);for(l=1;l1){v[0]=g[l-2];var y=[g[l],g[l]];if(l3.483106931382794e-9*(A+C))continue;if(dF(x.mean,x.std,x.data.length,N.mean,N.std,N.data.length)>3.483106931382794e-9*(A+_))continue}if(!(hF(this.mean,x.mean,x.std,x.data.length)>.05)){var M=new lF(this.rd.slice(F[0],F[1]));t.fill(!0,F[0],F[1]),i.fill(M.mean,F[0],F[1])}}}}}})),i}cnv_calling(e=1e5){var t=.25*this.mean,i=this.mean-t,r=this.mean+t,s=2971e6,o=this.meanShiftCaller(e),n={},a=[];return Object.entries(o).forEach((([c,l])=>{for(var h=!1;!h;){h=!0;var d=new Array(1).fill(0);for(let e=0;e.01&&d.push(e+1)}d.push(l.length);for(let e=0;e0&&(f=Math.abs(l[d[e]]-l[d[e-1]])),e{m.push(t.binScore)}));for(var w,b=new Array(l.length).fill(""),F=0,v=.05*e/s;FA+1){var C=cF(this.mean,this.std,m,A,_,v);if(C){var _=C;b.fill("D",A,_)}}for(A=F;Fr;)F+=1;(_=F)>A+1&&(C=cF(this.mean,this.std,m,A,_,v))&&(_=C,b.fill("A",A,_)),F==y&&(F+=1)}for(F=0;FA+1&&(aF(this.mean,this.std,m,A,_)<1682935038707506e-26&&b.fill(["d"]*(_-A),A,_),F-=1),F+=1}(F=0)=b.length););if(F>A){var k=new lF(x.slice(A,F));x.fill(k.mean,A,F)}F{i.forEach(((i,r)=>{t[e]&&(i.partitionLevel=parseInt(t[e][r]))}))}));return{binScore:this.formatDataStructure("binScore",this.globalMean),gcCorrectedBinScore:this.formatDataStructure("gcCorrectedBinScore",this.globalMean),segmentsCNV:this.formatDataStructure("partitionLevel",this.globalMean)}}getRDSignalBandWidth(e){const t=this.globalMean/4,i=4/this.globalStd**2;return e.map((e=>e>t?this.globalMean/(this.globalStd**2*e):i))}partition(e=3){let t={};Object.keys(this.wigFeatures).sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0}))).forEach((e=>{t[e]=this.wigFeatures[e]}));let i=this.gcFlag?"gcCorrectedBinScore":"binScore";var r={};for(const[n,a]of Object.entries(t)){var s=new Array(a.length).fill(!1),o=a.map(((e,t)=>s[t]?void 0:e[i]));this.binBands.forEach(((t,i)=>{var r=s.map(((e,t)=>!e)),n=o.filter(((e,t)=>!s[t])),a=[0],c=0;s.forEach((e=>{e?c>0&&(a.push(a[a.length-1]+c-1),c=0):e||c++})),a.shift();for(let i=0;i=0&&u.push(f);u.push(h.length-1),u=u.concat(a).sort(((e,t)=>e-t)),u=Array.from(new Set(u));var p=0;for(f=0;fe+t))/g.length;n.fill(m,p,u[f]+1),p=u[f]+1}}f=0;for(var w=0;f.01&&u.push(f+1)}u.unshift(0),u.push(o.length),s=new Array(this.wigFeatures.length).fill(!1);for(f=1;f1))continue;F[0]=u[f-2];var v=[u[f],u[f]];if(!(f.01/sF*this.binSize*(y+A))continue;if(dF(_.mean,_.std,_.data.length,E.mean,E.std,E.data.length)>.01/sF*this.binSize*(y+C))continue}if(hF(this.globalMean,_.mean,_.std,_.data.length)>.05)continue;let e=n.slice(b[0],b[1]);var N=new lF(e);s.fill(!0,b[0],b[1]),o.fill(N.mean,b[0],b[1])}})),r[n]=o}return r}cnvCalling(e){var t=.25*this.globalMean,i=this.globalMean-t,r=this.globalMean+t,s=2971e6,o={},n=[];return Object.entries(e).forEach((([a,c])=>{for(var l=!1;!l;){l=!0;var h=new Array(1).fill(0);for(let e=0;e.01&&h.push(e+1)}h.push(c.length);for(let i=0;i0&&(u=Math.abs(c[h[i]]-c[h[i-1]])),i{g.push(t.binScore)}));for(var m,w=new Array(c.length).fill(""),b=0,F=.05*this.binSize/s;by+1){var A=cF(this.globalMean,this.std,g,y,C,F);if(A){var C=A;w.fill("D",y,C)}}for(y=b;br;)b+=1;(C=b)>y+1&&(A=cF(this.globalMean,this.std,g,y,C,F))&&(C=A,w.fill("A",y,C)),b==v&&(b+=1)}for(b=0;by+1&&(aF(this.globalMean,this.std,g,y,C)<1682935038707506e-26&&w.fill(["d"]*(C-y),y,C),b-=1),b+=1}(b=0)=w.length););if(b>y){var x=new lF(_.slice(y,b));_.fill(x.mean,y,b)}b=0;e--){var i;let r=this.allVariants[e];this.allVariants.splice(e,1);let s=r.chr;i=Math.max(Math.floor(r.start/this.rowBinSize),0),t[s]||(t[s]=[]),t[s][i]||(t[s][i]={chr:s,start:i*this.rowBinSize,end:(i+1)*this.rowBinSize,dp_sum_score:0,dp_count:0,hets_count:0,hets:[]});const o=Object.values(r.calls);if(1!==o.length)throw Error(`Unexpected number of genotypes: ${o.length}. CNVPytor expects 1 and only 1 genotype`);const n=o[0],a=n.info.DP;a&&(t[s][i].dp_sum_score+=Number.parseInt(a),t[s][i].dp_count++);let c=n.info.AD.split(","),l=n.genotype;if(0==l[0]&&1==l[1]||1==l[0]&&0==l[1]){t[s][i].hets_count++;let e=parseInt(c[0]),r=parseInt(c[1]);t[s][i].hets.push({ref:e,alt:r})}}this.chromosomes=Object.keys(t);let r="ReadDepth"==e;var s,o=this.adjust_bin_size(t,r);if("ReadDepth"==e){let e=new uF.MeanShiftCaller(o,this.binSize,this.refGenome),t=await e.callMeanshift();s=[t.binScore,t.gcCorrectedBinScore,t.segmentsCNV];var n=e.formatDataStructure_BAF("max_likelihood",-1)}else if("2D"==e){let e=new rF.CombinedCaller(o,this.binSize,this.refGenome),t=await e.call_2d();s=[t.binScore,t.gcCorrectedBinScore,t.segmentScore];n=e.formatDataStructure_BAF("max_likelihood",-1)}return[s,n]}format_BAF_likelihood(e){const t=[];for(const[r,s]of Object.entries(e))for(let e of s){var i={...e};.5!=e.value&&(i.value=1-e.value,t.push(i))}return t}get_max_min_score(e){if(e.likelihood_score.length>0){const t=Math.max(...e.likelihood_score),i=e.likelihood_score.indexOf(t);e.value=Math.max(i/100,1-i/100),e.min_score=Math.min(i/100,1-i/100)}else e.score=0;return e}adjust_bin_size(e,t=!1){var i={};const r=this.binSize/150;for(let n of this.chromosomes){i[n]||(i[n]=[]);for(let a=0;apF(t.ref,t.alt,e)));else{var o=0;i[n][a].likelihood_score=Dw.linspace(0,1,100).map(((e,r)=>{var s=i[n][a].likelihood_score[r]*pF(t.ref,t.alt,e);return o+=s,s})),i[n][a].likelihood_score=Dw.linspace(0,1,100).map(((e,t)=>i[n][a].likelihood_score[t]/o))}i[n][a].dp_count>0&&(i[n][a].binScore=i[n][a].dp_sum_score/i[n][a].dp_count*r);const l=this.get_max_min_score(i[n][a]);i[n][a].max_likelihood=l.value,t&&delete i[n][a].likelihood_score}}return i}}function pF(e,t,i,r=!0){return Math.pow(i,e)*Math.pow(1-i,t)+Math.pow(i,t)*Math.pow(1-i,e)}class gF extends ma{static DEFAULT_TRACK_HEIGHT=250;constructor(e,t){super(e,t)}init(e){this.featureType="numeric",this.type="cnvpytor",e.max||(this.defaultScale=!0,this.autoscale=!1),e.height||(e.height=gF.DEFAULT_TRACK_HEIGHT),this.type="cnvpytor",this.graphType=e.graphType||"points",this.bin_size=e.bin_size||1e5,this.signal_name=e.signal_name||"rd_snp",this.cnv_caller=e.cnv_caller||"2D",this.colors=e.colors||["gray","black","green","blue"],this.hasChroms={},super.init(e)}get supportsWholeGenome(){return!0}get_signals(){let e=[];return"rd_snp"==this.signal_name?e=["RD_Raw","RD_Raw_gc_coor",this.cnv_caller,"BAF1","BAF2"]:"rd"==this.signal_name?e=["RD_Raw","RD_Raw_gc_coor",this.cnv_caller]:"snp"==this.signal_name?e=["BAF1","BAF2"]:"cnh"==this.signal_name&&(e=[this.cnv_caller]),e}get_signal_colors(){return[{singal_name:"RD_Raw",color:this.colors[0]},{singal_name:"RD_Raw_gc_coor",color:this.colors[1]},{singal_name:"ReadDepth",color:this.colors[2]},{singal_name:"2D",color:this.colors[2]},{singal_name:"BAF1",color:this.colors[3]},{singal_name:"BAF2",color:this.colors[3]}]}async postInit(){if("vcf"==this.config.format){let e;this.featureSource?e=Object.values(this.featureSource.getAllFeatures()).flat():(this.featureSource=this.featureSource||El(this.config,this.browser.genome),this.header=await this.getHeader(),e=this.featureSource.reader.features);const t=this.browser.config.genome,i=new fF(e,this.bin_size,t);let r,s,o;this.wigFeatures_obj={},this.wigFeatures_obj[this.bin_size]={},"2D"==this.cnv_caller?(o=await i.read_rd_baf("2D"),r=o[0],s=o[1],this.wigFeatures_obj[this.bin_size]["2D"]=r[2],this.available_callers=["2D"]):(o=await i.read_rd_baf(),r=o[0],s=o[1],this.wigFeatures_obj[this.bin_size].ReadDepth=r[2],this.available_callers=["ReadDepth"]),this.wigFeatures_obj[this.bin_size].RD_Raw=r[0],this.wigFeatures_obj[this.bin_size].RD_Raw_gc_coor=r[1],this.wigFeatures_obj[this.bin_size].BAF1=s[0],this.wigFeatures_obj[this.bin_size].BAF2=s[1],this.available_bins=[this.bin_size],this.set_available_callers()}else{this.cnvpytor_obj=new Nw(this.config,this.bin_size);let e=[...new Set(this.browser.referenceFrameList.map((e=>e.chr)))],t=this.getAliasChromsList(e);this.wigFeatures_obj=await this.cnvpytor_obj.get_rd_signal(this.bin_size,t),this.update_hasChroms(this.wigFeatures_obj,e),this.available_bins=this.cnvpytor_obj.availableBins,this.available_bins.includes(this.bin_size)||(this.bin_size=this.available_bins.at(-1)),this.available_callers=this.cnvpytor_obj.callers,this.set_available_callers()}this.tracks=[];const e=[];this.signals=this.get_signals(),this.signal_colors=this.get_signal_colors();for(let t in this.wigFeatures_obj)for(const[i,r]of Object.entries(this.wigFeatures_obj[t]))if(this.signals.includes(i)){let t={type:"wig",isMergedTrack:!0};t.features=r,t.name=i,t.color=this.signal_colors.filter((e=>e.singal_name===i)).map((e=>e.color));const s=await this.browser.createTrack(t);s?(s.autoscale=!1,this.tracks.push(s)):console.warn("Could not create track "+t),"function"==typeof s.postInit&&e.push(s.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return Promise.all(e)}getAliasChromsList(e){let t=e.map((e=>{let t=this.browser.genome.chromAlias.aliasRecordCache.get(e);return Object.values(t)}));return t=t.flat(),t}set_available_callers(){this.available_callers.includes(this.cnv_caller)||(this.available_callers.length>0?this.cnv_caller=this.available_callers[0]:this.cnv_caller=null)}async getHeader(){if(!this.header){if("function"==typeof this.featureSource.getHeader){const e=await this.featureSource.getHeader();e&&(this.callSets=e.callSets||[]),this.header=e}this.sampleKeys=this.callSets?this.callSets.map((e=>e.sample)):[],this.sampleNames=this.sampleKeys}return this.header}get height(){return this._height}set height(e){if(this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}menuItemList(){let e=[];void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:function(){this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e=e.concat(this.numericDataMenuItems()),e.push("
"),e.push("Bin Sizes");for(let t of this.available_bins)e.push({element:ua(t,t===this.bin_size),click:async function(){this.bin_size=t,this.trackView.startSpinner(),await this.recreate_tracks(t),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}});e.push("
"),e.push("Signal Type");let t={rd_snp:"RD and BAF Likelihood",rd:"RD Signal",snp:"BAF Likelihood"};for(let i in t)e.push({element:ua(t[i],i===this.signal_name),click:async function(){this.signal_name=i,await this.recreate_tracks(this.bin_size),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}});e.push("
"),e.push("CNV caller");for(let t of this.available_callers)e.push({element:ua(t,t===this.cnv_caller),click:async function(){this.cnv_caller=t,this.trackView.startSpinner(),await this.recreate_tracks(this.bin_size),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}});if(this.variantState){e.push("
");for(let t of this.available_callers)e.push({label:"Convert to variant track",click:()=>{this.convertToVariant()}})}return e}async recreate_tracks(e){this.tracks=[];const t=[];if(!(e in this.wigFeatures_obj))if(Object.keys(this.hasChroms).length>0){let t=[...new Set(this.browser.referenceFrameList.map((e=>e.chr)))];"all"==t[0]&&(t=this.browser.genome.chromosomeNames),this.wigFeatures_obj={...this.wigFeatures_obj,...await this.cnvpytor_obj.get_rd_signal(e,t)},this.update_hasChroms(this.wigFeatures_obj,t)}else this.wigFeatures_obj={...this.wigFeatures_obj,...await this.cnvpytor_obj.get_rd_signal(e)};this.signals=this.get_signals(),this.signal_colors=this.get_signal_colors();for(const[i,r]of Object.entries(this.wigFeatures_obj[e]))if(this.signals.includes(i)){let e={type:"wig",isMergedTrack:!0};e.features=r,e.name=i,e.color=this.signal_colors.filter((e=>e.singal_name===i)).map((e=>e.color));const s=await this.browser.createTrack(e);s?(s.autoscale=!1,this.tracks.push(s)):console.warn("Could not create track "+e),"function"==typeof s.postInit&&t.push(s.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return Promise.all(t)}update_hasChroms(e,t){for(let i in e)this.hasChroms[i]||(this.hasChroms[i]=new Set),t.forEach((e=>this.hasChroms[i].add(e)));return this.hasChroms}async getFeatures(e,t,i,r){if(Object.keys(this.hasChroms).length>0&&0!=this.hasChroms[this.bin_size].size){let e=[...new Set(this.browser.referenceFrameList.map((e=>e.chr)))];"all"==e[0]&&(e=this.browser.genome.chromosomeNames);let t=e.filter((e=>!this.hasChroms[this.bin_size].has(e)));if(0!=t.length){let e=this.getAliasChromsList(t),i=await this.cnvpytor_obj.get_rd_signal(this.bin_size,e);this.update_hasChroms(i,t);for(let e in i)for(const[t,r]of Object.entries(i[e]))await this.wigFeatures_obj[e][t].push(...r);for(let e of this.tracks)await e.featureSource.updateFeatures(this.wigFeatures_obj[this.bin_size][e.name])}}if(this.tracks){const s=this.tracks.map((s=>s.getFeatures(e,t,i,r)));return Promise.all(s)}}getScaleFactor(e,t,i,r){return r?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,r=this.dataRange.min;return i<=0?0:(r<=-1&&(r=0),r=r<=0?0:Math.log10(r+1),i=Math.log10(i+1),e=Math.log10(e+1),(this.flipAxis?e-r:i-e)*t)}draw(e){const t=e.features;if(!t)return;if(this.defaultScale&&("rd_snp"==this.signal_name?this.dataRange={min:this.config.min||this.dataRange.min||-1,max:this.config.max||this.dataRange.max||5}:"rd"==this.signal_name?this.dataRange={min:this.config.min||this.dataRange.min||0,max:this.config.max||this.dataRange.max||5}:"snp"==this.signal_name&&(this.dataRange={min:this.config.min||this.dataRange.min||-1,max:this.config.max||this.dataRange.max||0})),this.autoscale&&(this.dataRange=function(e,t){let i=0,r=-Number.MAX_VALUE;for(let e of t)for(let t of e)void 0===t.value||Number.isNaN(t.value)||(i=Math.min(i,t.value),r=Math.max(r,t.value));return{min:i,max:r}}(e.referenceFrame.chr,t)),this.tracks)for(let i=0,r=this.tracks.length;ithis.logScale?this.computeYPixelValueInLogScale(e,i):this.computeYPixelValue(e,i);if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=r(t.y),s={strokeStyle:t.color,strokeWidth:1};t.dotted?Co.dashedLine(e.context,0,i,e.pixelWidth,i,5,s):Co.strokeLine(e.context,0,i,e.pixelWidth,i,s)}let s=r(2);Co.dashedLine(e.context,0,s,e.pixelWidth,s,5,{strokeStyle:"lightgray",strokeWidth:.5})}paintAxis(e,t,i){var r,s,o,n,a,c,l,h={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};if(void 0===this.dataRange||void 0===this.dataRange.max||void 0===this.dataRange.min)return;let d=void 0!==this.flipAxis&&this.flipAxis;function u(e){return e<0?Math.abs(e):0===e?"0":Math.abs(e)>=10||e%1==0?e.toFixed():Math.abs(e)>=1?e.toFixed(1):e.toFixed(2)}Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"}),r=(l=.95*t)-8,a={x:s=l,y:o=n=.01*i},Co.strokeLine(e,r,o,s,n,h),Co.fillText(e,u(d?this.dataRange.min:this.dataRange.max),r+4,o+12,h),c={x:s,y:o=n=.99*i},Co.strokeLine(e,r,o,s,n,h),Co.fillText(e,u(d?this.dataRange.max:this.dataRange.min),r+4,o-4,h),Co.strokeLine(e,a.x,a.y,c.x,c.y,h);const f=this.getScaleFactor(this.dataRange.min,this.dataRange.max,i,this.logScale),p=e=>this.logScale?this.computeYPixelValueInLogScale(e,f):this.computeYPixelValue(e,f),g=Math.ceil((this.dataRange.max-this.dataRange.min)/10);for(let t=Math.ceil(this.dataRange.min+1);t0&&t.push("
"),t.push(`
${this.tracks[r].name}
`);const s=this.tracks[r].popupData(e,i[r]);t.push(...s)}return t}}async convertToVariant(){this.variantState&&(Object.setPrototypeOf(this,bF.prototype),this.init(this.variantState),await this.postInit(),this.trackView.clearCachedFeatures(),this.variantState.trackHeight&&this.trackView.setTrackHeight(this.variantState.trackHeight),this.trackView.checkContentHeight(),this.trackView.updateViews(),delete this.variantState)}}const mF=b,wF=10;class bF extends ma{static defaultColor="rgb(0,0,150)";static defaults={displayMode:"EXPANDED",sortDirection:"ASC",showGenotypes:!0,expandedVariantHeight:10,squishedVariantHeight:2,squishedCallHeight:1,expandedCallHeight:10,expandedVGap:2,squishedVGap:1,expandedGroupGap:10,squishedGroupGap:5,featureHeight:14,noGenotypeColor:"rgb(200,180,180)",noCallColor:"rgb(225, 225, 225)",nonRefColor:"rgb(200, 200, 215)",mixedColor:"rgb(200, 220, 200)",homrefColor:"rgb(200, 200, 200)",homvarColor:"rgb(17,248,254)",hetvarColor:"rgb(34,12,253)",refColor:"rgb(0,0,220)",altColor:"rgb(255,0,0)",visibilityWindow:void 0,labelDisplayMode:void 0,type:"variant"};_sortDirections=new Map;constructor(e,t){super(e,t)}init(e){if(super.init(e),e.variantHeight&&(this.expandedVariantHeight=e.variantHeight),this.featureSource=El(e,this.browser.genome),this.colorTables=new Map,e.colorTable){const t=e.colorBy||"*";this.colorTables.set(t,new $r(e.colorTable))}if(this.strokecolor=e.strokecolor,this._context_hook=e.context_hook,e.color&&(this.colorBy=void 0),this.nVariantRows=1,e.samples)for(let t of e.samples)this.sampleKeys=e.samples;e.sort&&(this.initialSort=e.sort),this._colorByItems=new Map([["none","None"]])}async postInit(){if(this.header=await this.getHeader(),this.header.INFO){const e=new Set(Object.keys(this.header.INFO));this.config.colorBy?this.colorBy=this.config.colorBy:!this.config.color&&e.has("AF")&&(this.colorBy="AF"),e.has("AF")&&this._colorByItems.set("AF","Allele frequency"),e.has("VT")&&this._colorByItems.set("VT","Variant Type"),e.has("SVTYPE")&&this._colorByItems.set("SVTYPE","SV Type")}if(this.config.colorBy&&!this._colorByItems.has(this.config.colorBy)&&this._colorByItems.set(this.config.colorBy,this.config.colorBy),!this.disposed){if(this.header&&!this.sampleKeys&&(this.sampleKeys=this.header.sampleNameMap?Array.from(this.header.sampleNameMap.keys()):[]),void 0===this.visibilityWindow&&!1!==this.config.indexed){const e=x(this.config.url)?this.config.url.name:this.config.url;mF(e)&&e.toLowerCase().includes("gnomad")?this.visibilityWindow=1e3:"function"==typeof this.featureSource.defaultVisibilityWindow?this.visibilityWindow=await this.featureSource.defaultVisibilityWindow():this.visibilityWindow=1e6}return this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}}get supportsWholeGenome(){return!this.config.indexURL||!0===this.config.supportsWholeGenome}get color(){return this._color||bF.defaultColor}set color(e){this._color=e,e&&(this.colorBy=void 0)}async getHeader(){return this.header||"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader()),this.header}getSampleCount(){return this.sampleKeys?this.sampleKeys.length:0}async getFeatures(e,t,i,r){void 0===this.header&&(this.header=await this.getHeader());const s=await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:this.visibilityWindow});if(this.initialSort){const e=this.initialSort;if(void 0===e.option||"GENOTYPE"===e.option.toUpperCase())this.sortSamplesByGenotype(e,s);else if("ATTRIBUTE"===e.option.toUpperCase()&&e.attribute){const t="ASC"===e.direction?1:-1;this.sortByAttribute(e.attribute,t)}this.initialSort=void 0}return s}hasSamples(){return this.getSampleCount()>0}getSamples(){const e="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,t="COLLAPSED"===this.displayMode?1:this.nVariantRows,i="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,r=t*(("SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight)+e),s=wF+t*(i+e);return{names:this.sampleKeys,yOffset:s,height:r}}computePixelHeight(e){if(!e||0===e.length)return wF;const t="COLLAPSED"===this.displayMode?1:this.nVariantRows,i="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,r="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,s="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight,o=!1===this.showGenotypes?0:this.getSampleCount()*t;return wF+t*(r+i)+i+(o+1)*(s+i)}variantRowCount(e){this.nVariantRows=e}draw({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:r,bpStart:s,pixelTop:o,features:n}){Co.fillRect(e,0,o,t,i,{fillStyle:"rgb(255, 255, 255)"});const a="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,c="COLLAPSED"===this.displayMode?1:this.nVariantRows,l="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight;this.variantBandHeight=wF+c*(l+a);let h=this.sampleColumns;const d=this.hasSamples();if(h&&d&&!1!==this.showGenotypes&&Co.strokeLine(e,0,this.variantBandHeight,t,this.variantBandHeight,{strokeStyle:"rgb(224,224,224) "}),n){const i="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight,o="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,a=s+t*r+1;for(let t of n){if(this._filter&&!this._filter(t))continue;if(t.enda)break;const n="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,c=wF+("COLLAPSED"===this.displayMode?0:t.row*(n+o)),l=n;let h=(t.start-s)/r,u=(t.end-s)/r,f=Math.max(1,u-h);f<3?(f=3,h-=1):f>5&&(h+=1,f-=2);const p=t._f||t;let g;try{g=p.alleleFreq()}catch(e){console.log(e)}if("AF"===this.colorBy&&g){const t=Math.min(1,g)*l,i=l-t;e.fillStyle=p.isFiltered()?this.refColorFiltered:this.refColor,e.fillRect(h,c,f,i),e.fillStyle=p.isFiltered()?this.altColorFiltered:this.altColor,e.fillRect(h,c+i,f,t)}else e.fillStyle=this.getColorForFeature(p),e.fillRect(h,c,f,l);let m=this.getVariantStrokecolor(p);if(m&&(e.strokeStyle=m,e.strokeRect(h,c,f,l)),this.callContextHook(p,e,h,c,f,l),d&&!1!==this.showGenotypes){const t="COLLAPSED"===this.displayMode?1:this.nVariantRows;this.sampleYOffset=this.variantBandHeight+o,this.sampleHeight=t*(i+o);let r=0;for(let t of this.sampleKeys){const s=this.header.sampleNameMap.get(t),n=p.calls[s];if(n){const t="COLLAPSED"===this.displayMode?0:p.row,s=this.sampleYOffset+r*this.sampleHeight+t*(i+o);let a=!0,c=!0,l=!1;if(n.genotype)for(let e of n.genotype){if("."===e){l=!0;break}0!==e&&(c=!1),0===e&&(a=!1)}n.genotype?e.fillStyle=l?this.noCallColor:c?this.homrefColor:a?this.homvarColor:this.hetvarColor:e.fillStyle=this.noGenotypeColor,e.fillRect(h,s,f,i)}r++}}}}else console.log("No feature list")}get refColorFiltered(){return this._refColorFiltered||(this._refColorFiltered=ur.addAlpha(this.refColor,.2)),this._refColorFiltered}get altColorFiltered(){return this._altColorFiltered||(this._altColorFiltered=ur.addAlpha(this.altColor,.2)),this._altColorFiltered}getColorForFeature(e){const t=e._f||e;let i;if(this.colorBy&&"none"!==this.colorBy){const e=t.getAttributeValue(this.colorBy);i=void 0!==e?this.getVariantColorTable(this.colorBy).getColor(e):"gray"}else i=this.color?"function"==typeof this.color?this.color(e):this.color:"NONVARIANT"===t.type?this.nonRefColor:"MIXED"===t.type?this.mixedColor:this.color;return t.isFiltered()&&(i=ur.addAlpha(i,.2)),i}getVariantStrokecolor(e){const t=e._f||e;let i;return i=this.strokecolor?"function"==typeof this.strokecolor?this.strokecolor(t):this.strokecolor:void 0,i}callContextHook(e,t,i,r,s,o){if(this._context_hook&&"function"==typeof this._context_hook){const n=e._f||e;t.save(),this._context_hook(n,t,i,r,s,o),t.restore()}}clickedFeatures(e){let t=super.clickedFeatures(e);const i="EXPANDED"===this.displayMode?this.expandedVGap:this.squishedVGap,r=i+("SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight),s=e.y;if(s<=this.variantBandHeight){const e="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,r=Math.floor((s-wF)/(e+i));"COLLAPSED"!==this.displayMode&&(t=t.filter((e=>e.row===r)))}else if(this.sampleKeys){const e=s-this.variantBandHeight,i=Math.floor(e/this.sampleHeight);if(i>=0&&ie.row===s)),n=this.sampleKeys[i],a=this.header.sampleNameMap.get(n);t=o.map((e=>{const t=e.calls[a];return t.genotypeString=function(e,t){if(e.genotype){let i="";if("."===t.alternateBases)i="No Call";else{const r=t.alternateBases.split(",");for(let s of e.genotype)if(i.length>0&&(i+=" | "),"."===s)i+=".";else if(0===s)i+=t.referenceBases;else{i+=r[s-1].replace("<","<")}}return i}}(t,e),t}))}}return t}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,r=this.browser.genome.id;let s=[];for(let e of t){const t=e._f||e;if(s.length>0&&s.push({html:'
'}),"function"==typeof t.popupData){const e=t.popupData(i,r);Array.prototype.push.apply(s,e)}}return s}menuItemList(){const t=[];if(this.header.INFO&&this.header.INFO){const i=this._colorByItems;t.push("
");const r=e('
');r.textContent="Color by:",t.push({name:void 0,element:r,click:void 0,init:void 0});for(let e of i.keys()){const r=this.colorBy===e;t.push(this.colorByCB({key:e,label:i.get(e)},r))}t.push(this.colorByCB({key:"info",label:"Info field..."}))}if(!0===dd(this.browser.sampleInfo,this.sampleKeys)){t.push("
"),t.push("Sort by attribute:");for(const e of this.browser.sampleInfo.attributeNames)if(this.sampleKeys.some((t=>{const i=this.browser.sampleInfo.getAttributes(t);return i&&i[e]}))){const i=document.createElement("div");i.innerHTML=`  ${e.split(sd.emptySpaceReplacement).join(" ")}`;const r=()=>{const t=this._sortDirections.get(e)||1;this.sortByAttribute(e,t),this.config.sort={option:"ATTRIBUTE",attribute:e,direction:t>0?"ASC":"DESC"},this._sortDirections.set(e,-1*t)};t.push({element:i,click:r})}}t.push("
"),this.getSampleCount()>0&&(t.push({element:e('
')}),t.push({element:ua("Show Genotypes",this.showGenotypes),click:function(){this.showGenotypes=!this.showGenotypes,this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.browser.sampleNameControl.performClickWithState(this.browser,this.showGenotypes),this.browser.sampleInfoControl.performClickWithState(this.browser,this.showGenotypes)}})),t.push({element:e('
')});for(let e of["COLLAPSED","SQUISHED","EXPANDED"]){t.push({element:ua({COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"}[e],e===this.displayMode),click:function(){this.displayMode=e,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})}return this.browser.circularView&&(t.push("
"),t.push({label:"Add SVs to circular view",click:function(){for(let e of this.trackView.viewports)this.sendChordsForViewport(e)}})),this.canCovertToPytor()&&(t.push("
"),t.push({label:"Convert to CNVpytor track",click:function(){this.convertToPytor()}})),t}contextMenuItemList(e){const t=[];if(this.hasSamples()&&this.showGenotypes){const i=e.viewport.referenceFrame,r=e.genomicLocation,s=i.toBP(2.5),o=this._sortDirections.get("genotype")||1;this._sortDirections.set("genotype",-1*o),t.push({label:"Sort by genotype",click:t=>{const i={direction:o,option:"genotype",chr:e.viewport.referenceFrame.chr,start:Math.floor(r-s),end:Math.ceil(r+s)},n=e.viewport.cachedFeatures;this.sortSamplesByGenotype(i,n),this.config.sort=i}}),t.push("
")}if(this.browser.circularView){const i=e.viewport;t.push({label:"Add SVs to Circular View",click:()=>{this.sendChordsForViewport(i)}}),t.push("
")}return t}async sortSamplesByGenotype({chr:e,position:t,start:i,end:r,direction:s},o){if(void 0===i&&(i=t-1),void 0===r&&(r=t),o||(o=await this.featureSource.getFeatures({chr:e,start:i,end:r})),!o)return;const n=new Map,a="ASC"===s?1:-1;for(let e of o)if(!(e.endr)break;for(let t of e.calls){const e=t.sample,i=t.zygosityScore();n.set(e,n.has(e)?n.get(e)+i:i)}}this.sampleKeys.sort((function(e,t){let i=n.get(e)||0,r=n.get(t)||0;return a*(i-r)})),this.trackView.repaintViews()}sortByAttribute(e,t){this.config.sort={option:"ATTRIBUTE",attribute:e,direction:1===t?"ASC":"DESC"},this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,e,t),this.trackView.repaintViews()}sendChordsForViewport(e){const t=e.referenceFrame;let i;if("all"===t.chr){const e=this.featureSource.getAllFeatures(),t=Object.keys(e).map((t=>e[t]));i=[].concat(...t)}else i=this.featureSource.featureCache.queryFeatures(t.chr,t.start,t.end);Zf(i.filter((e=>{const t=e._f||e;return t.info&&t.info.CHR2&&t.info.END&&(t.info.CHR2!==t.chr||Math.abs(Number.parseInt(t.info.END)-t.pos)>1e6)})).map((e=>{const t=e._f||e,i=Number.parseInt(t.info.END),r=i-100,s=i+100;return{uniqueId:`${t.chr}:${t.start}-${t.end}_${t.info.CHR2}:${t.info.END}`,refName:$f(t.chr),start:t.start,end:t.end,mate:{refName:$f(t.info.CHR2),start:r,end:s}}})),this,t,.5)}colorByCB(e,t){const i=ua(e.label,t);if("info"!==e.key){function r(){const t="none"===e.key?void 0:e.key;this.colorBy=t,this.config.colorBy=t,this.trackView.repaintViews()}return{name:void 0,element:i,click:r,init:void 0}}{function s(e){this.browser.inputDialog.present({label:"Info field",value:"",callback:e=>{e?(this.colorBy=e,this._colorByItems.set(e,e)):this.colorBy=void 0,this.trackView.repaintViews()}},e)}return{name:void 0,element:i,dialog:s,init:void 0}}}getState(){const e=super.getState();return this.color&&"function"!=typeof this.color&&(e.color=this.color),e}getVariantColorTable(e){if(this.colorTables.has(e))return this.colorTables.get(e);if(this.colorTables.has("*"))return this.colorTables.get("*");{let t;if("SVTYPE"===e)t=FF;else t=new Wr("Set1");return this.colorTables.set(e,t),t}}paintAxis(){}canCovertToPytor(){return!this.config.indexURL&&(!!this.header&&(1===Object.keys(this.sampleKeys).length&&this.header.FORMAT&&this.header.FORMAT.AD&&this.header.FORMAT.DP))}async convertToPytor(){this.variantState={...this.config,...this.getState()},this.variantState.trackHeight=this.height,this.trackView.startSpinner(),setTimeout((async()=>{try{const e=Object.assign({},this.config);Object.setPrototypeOf(this,gF.prototype),this.init(e),await this.postInit(),this.trackView.clearCachedFeatures(),this.trackView.setTrackHeight(this.config.height||gF.DEFAULT_TRACK_HEIGHT),this.trackView.checkContentHeight(),this.trackView.updateViews()}finally{this.trackView.stopSpinner()}}),100)}getFilterableAttributes(){return this.header.INFO}_repackCachedFeatures(){for(let e of this.trackView.viewports)if(e.cachedFeatures){const t=this.config.maxRows||Number.MAX_SAFE_INTEGER;ga(e.cachedFeatures,t,this._filter)}}}const FF=new $r({DEL:"#ff2101",INS:"#001888",DUP:"#028401",INV:"#008688",CNV:"#8931ff",BND:"#891100","*":"#002eff"}),vF={timeout:5e3,type:"plain",url:"https://igv.org/genomes/locus.php?genome=$GENOME$&name=$FEATURE$",coords:0};async function yF(e,t){const i=e.searchConfig||vF;let r;t=t.toUpperCase();const s=e.tracks.filter((e=>e.searchable));for(let e of s){const i=await e.search(t);if(i)return i}if(e.config&&!1!==e.config.search)try{return r=await async function(e,t,i){let r=i.url.replace("$FEATURE$",t.toUpperCase());r.indexOf("$GENOME$")>-1&&(r=r.replace("$GENOME$",e.genome.id?e.genome.id:"hg19"));const s=i.timeout?{timeout:i.timeout}:void 0,o=await Rr.loadString(r,s);return function(e,t,i){let r;r="plain"===i.type?function(e,t){const i=[],r=v(t);for(let t of r){const r=t.split("\t");if(r.length>=3){const t=r[1].split(":"),s=t[1].split("-");i.push({chromosome:e.genome.getChromosomeName(t[0].trim()),start:parseInt(s[0].replace(/,/g,"")),end:parseInt(s[1].replace(/,/g,"")),name:r[0].toUpperCase()})}}return i}(e,t):JSON.parse(t);i.resultsField&&(r=r[i.resultsField]);if(r&&0!==r.length){const e=i.chromosomeField||"chromosome",t=i.startField||"start",s=i.endField||"end",o=i.coords||1;let n;n=Array.isArray(r)?r[0]:r,n.hasOwnProperty(e)&&n.hasOwnProperty(t)||console.error("Search service results must include chromosome and start fields: "+n);const a=n[e];let c=n[t]-o,l=n[s];void 0===l&&(l=c+1);const h={chr:a,start:c,end:l};if(!n.type||n.type,i.geneField&&i.snpField){const e=n[i.geneField]||n[i.snpField];e&&(h.name=e.toUpperCase())}return h}return}(e,o,i)}(e,t,i),r}catch(e){console.log("Search service not available "+e)}}function AF(e,t=!1){const i=e.split("\t");if(i.length>2)try{const e=i[0],t=parseInt(i[1].replace(/,/g,""),10)-1,r=parseInt(i[2].replace(/,/g,""),10);if(!isNaN(t)&&!isNaN(r))return{chr:e,start:t,end:r}}catch(e){}const r=e.split(":"),s={chr:r[0]};if(r.length>1){let e,i=r[1].split("-");if(i.length>2){if(!r[1].startsWith("-"))return;{const e=r[1].indexOf("-",1);if(e>0){i=[r[1].substring(0,e),r[1].substring(e+1)]}}}if(e=i[0].replace(/,/g,""),isNaN(e))return;if(s.start=parseInt(e,10)-1,s.end=s.start+1,1===i.length&&(s.start-=20,s.end+=20),2===i.length){if(e=i[1].replace(/,/g,""),isNaN(e))return;if(s.end=parseInt(e,10),s.start<0&&!t){const e=-extent.start;s.start+=e,s.end+=e}}}return s}class CF extends ma{constructor(e,t){super(e,t)}init(e){super.init(e),this.type="qtl",this.name=e.name;const t=e.minLogP||e.min,i=e.maxLogP||e.max;this.dataRange={min:void 0!==t?t:3.5,max:i||25},this.autoscale=!i||e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||2,this.height=e.height||100,this.disableButtons=e.disableButtons,this.featureSource=El(e,this.browser.genome)}paintAxis(e,t,i){const r=(this.dataRange.max-this.dataRange.min)/i,s={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});const o=Math.ceil(10*(this.dataRange.max-this.dataRange.min)/i);for(let n=4;n<=this.dataRange.max;n+=o){const o=.85*t,a=o-5,c=o,l=i-(n-this.dataRange.min)/r;Co.strokeLine(e,a,l,c,l,s),l>8&&Co.fillText(e,n,a-1,l+2,s)}s.textAlign="center",Co.fillText(e,"-log10(pvalue)",t/4,i/2,s,{rotate:{angle:-90}})}async getFeatures(e,t,i){const r=this.visibilityWindow;return await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r})}draw(e){const{context:t,referenceFrame:i,pixelWidth:r,pixelHeight:s}=e;this.background&&Co.fillRect(t,0,0,r,s,{fillStyle:this.background}),Co.strokeLine(t,0,s-1,r,s-1,{strokeStyle:this.divider}),i.feature&&i.feature.match(/RS[0-9]+/);const o=i=>{const o=i?2*this.dotSize:this.dotSize,n=e.bpStart,a=(this.dataRange.max-this.dataRange.min)/s;for(let d of e.features){const u=(d.start-n+.5)/e.bpPerPixel;if(u<0)continue;if(u>r)break;const f=d.phenotype;let p;if(this.browser.qtlSelections.qtl?(l=this.browser.qtlSelections.qtl,h=d,p=l.chr===h.chr&&l.start===h.start&&l.pValue===h.pValue):p=this.browser.qtlSelections.snps.size>0?this.browser.qtlSelections.hasSnp(d.snp)&&this.browser.qtlSelections.hasPhenotype(f):this.browser.qtlSelections.hasPhenotype(f),!i||p){var c=-Math.log(d.pValue)/Math.LN10;if(c>=this.dataRange.min){let e;c>this.dataRange.max?(c=this.dataRange.max,e=!0):e=!1;const r=Math.max(0+o,s-Math.round((c-this.dataRange.min)/a));let n;d.px=u,d.py=r,d.radius=o,i&&p?(n=this.browser.qtlSelections.colorForGene(f),Co.setProperties(t,{fillStyle:n,strokeStyle:"black"})):(n=e?"rgb(150, 150, 150)":"rgb(180, 180, 180)",Co.setProperties(t,{fillStyle:n,strokeStyle:n})),Co.fillCircle(t,u,r,o),Co.strokeCircle(t,u,r,o)}}}var l,h};o(!1),o(!0)}popupData(e,t){if(void 0===t&&(t=e.viewport.cachedFeatures),!t||0===t.length)return[];const i=this.name,r=[];for(let s of this._clickedFeatures(e,t))r.length>0&&r.push("
"),"function"==typeof s.popupData?r.push(...s.popupData(e)):r.push({name:"snp id",value:s.snp},{name:"gene id",value:s.gencodeId},{name:"gene name",value:s.geneSymbol},{name:"p value",value:s.pValue},{name:"tissue",value:i});return r}_clickedFeatures(e,t){const i=(e,t)=>Math.sqrt((e.px-t.canvasX)*(e.px-t.canvasX)+(e.py-t.canvasY)*(e.py-t.canvasY)),r=t.filter((t=>i(t,e)<6));if(r.length>1){r.sort(((t,r)=>i(t,e)-i(r,e)));const t=i(r[0],e);return r.filter((r=>i(r,e)<=t))}return r}contextMenuItemList(e){const t=[],i=e.viewport.cachedFeatures;if(i){const r=this._clickedFeatures(e,i);r.length>0&&(t.push({label:"Highlight associated features",click:async()=>{this.browser.qtlSelections.clear();for(let e of r)this.browser.qtlSelections.qtl=e,this.browser.qtlSelections.addPhenotype(e.phenotype);this.browser.repaintViews()}}),t.push("
"))}return t}menuItemList(){const e=[];return e.push(...this.numericDataMenuItems()),e.push("
"),e.push({label:"Search for...",dialog:function(e){this.browser.inputDialog.present({label:"Search for snp or phenotype",value:"",callback:async e=>{if(e){e=e.trim().toUpperCase();const t=t=>((t.phenotype&&t.phenotype.toUpperCase())===e||t.snp&&t.snp.toUpperCase()===e)&&-Math.log(t.pValue)/Math.LN10>this.dataRange.min;let i,r,s,o=await this.featureSource.findFeatures(t);if(0==o.length){await this.browser.search(e)&&(o=await this.featureSource.findFeatures(t))}if(o.length>0){this.browser.qtlSelections.clear();const t=new Set;i=o[0].chr,r=o[0].start,s=o[0].end;for(let n of o)n.snp&&n.snp.toUpperCase()===e&&this.browser.qtlSelections.addSnp(n.snp),this.browser.qtlSelections.addPhenotype(n.phenotype),t.add(n.phenotype),n.chr===i&&(r=Math.min(r,n.start),s=Math.max(s,n.end));const n=this.browser.genome.getChromosomeName(i);for(let e of t){const t=await yF(this.browser,e);t&&n===this.browser.genome.getChromosomeName(t.chr)&&(r=Math.min(r,t.start),s=Math.max(s,t.end))}const a=Math.floor(.1*(s-r));r=Math.max(0,r-a),s+=a,await this.browser.search(`${i}:${r}-${s}`)}}}},e)}}),e}doAutoscale(e){let t=this.config.max||25;if(e.length>0){const i=e.map((e=>-Math.log(e.pValue)/Math.LN10));i.sort(((e,t)=>e-t));t=i[Math.floor(i.length*(this.autoscalePercentile/100))]}return this.dataRange.max=Math.max(t,10),this.dataRange}}const _F={X:"rgb(204, 153, 0)",Y:"rgb(153, 204, 0)",Un:"darkGray)",1:"rgb(80, 80, 255)",2:"rgb(206, 61, 50)","2a":"rgb(210, 65, 55)","2b":"rgb(215, 70, 60)",3:"rgb(116, 155, 88)",4:"rgb(240, 230, 133)",5:"rgb(70, 105, 131)",6:"rgb(186, 99, 56)",7:"rgb(93, 177, 221)",8:"rgb(128, 34, 104)",9:"rgb(107, 215, 107)",10:"rgb(213, 149, 167)",11:"rgb(146, 72, 34)",12:"rgb(131, 123, 141)",13:"rgb(199, 81, 39)",14:"rgb(213, 143, 92)",15:"rgb(122, 101, 165)",16:"rgb(228, 175, 105)",17:"rgb(59, 27, 83)",18:"rgb(205, 222, 183)",19:"rgb(97, 42, 121)",20:"rgb(174, 31, 99)",21:"rgb(231, 199, 111)",22:"rgb(90, 101, 94)",23:"rgb(204, 153, 0)",24:"rgb(153, 204, 0)",25:"rgb(51, 204, 0)",26:"rgb(0, 204, 51)",27:"rgb(0, 204, 153)",28:"rgb(0, 153, 204)",29:"rgb(10, 71, 255)",30:"rgb(71, 117, 255)",31:"rgb(255, 194, 10)",32:"rgb(255, 209, 71)",33:"rgb(153, 0, 51)",34:"rgb(153, 26, 0)",35:"rgb(153, 102, 0)",36:"rgb(128, 153, 0)",37:"rgb(51, 153, 0)",38:"rgb(0, 153, 26)",39:"rgb(0, 153, 102)",40:"rgb(0, 128, 153)",41:"rgb(0, 51, 153)",42:"rgb(26, 0, 153)",43:"rgb(102, 0, 153)",44:"rgb(153, 0, 128)",45:"rgb(214, 0, 71)",46:"rgb(255, 20, 99)",47:"rgb(0, 214, 143)",48:"rgb(20, 255, 177)"};for(let Ey of Object.keys(_F)){_F["chr"+Ey]=_F[Ey]}for(let Ny=1;Ny<=48;Ny++){if(10===Ny)continue;const My=xF(Ny);_F[My]=_F[Ny.toString()]}function xF(e){if(!+e)return!1;for(var t=String(+e).split(""),i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"],r="",s=3;s--;)r=(i[+t.pop()+10*s]||"")+r;return Array(+t.join("")+1).join("M")+r}class kF extends ma{constructor(e,t){super(e,t)}init(e){super.init(e),this.useChrColors=void 0===e.useChrColors||e.useChrColors,this.trait=e.trait,this.posteriorProbability=e.posteriorProbability,this.valueProperty="bed"===e.format?"score":"value",this.height=e.height||100,this.autoscale=e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||3,this.popoverWindow=void 0===e.popoverWindow?1e8:e.popoverWindow,this.useChrColors?this.colorScale=new $r(e.colorTable||_F):e.color?this.colorScale=new Wc(e.color):this.colorScale=new Qc(e.colorScale||{thresholds:[5e-8,5e-4,.5],colors:["rgb(255,50,50)","rgb(251,100,100)","rgb(251,170,170)","rgb(227,238,249)"]}),this.featureSource=El(e,this.browser.genome)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),this.autoscale||(this.posteriorProbability?this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?1:this.config.max}:this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?25:this.config.max}),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get supportsWholeGenome(){return!0}async getFeatures(e,t,i){const r=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r})}draw(e){const t=e.features,i=e.context,r=e.pixelWidth,s=e.pixelHeight;if(this.background&&Co.fillRect(i,0,0,r,s,{fillStyle:this.background}),Co.strokeLine(i,0,s-1,r,s-1,{strokeStyle:this.divider}),t){const o=e.bpPerPixel,n=e.bpStart,a=n+r*o+1;for(let e of t){const t=e.start;if(ta)break;let r;if(this.posteriorProbability)r=e[this.valueProperty];else{const t=e[this.valueProperty];if(!t)continue;r=-Math.log10(t)}const c=this.useChrColors?e._f?e._f.chr:e.chr:r,l=this.colorScale.getColor(c),h=(this.dataRange.max-this.dataRange.min)/s,d=Math.round((t-n)/o),u=Math.max(this.dotSize,s-Math.round((r-this.dataRange.min)/h));l&&Co.setProperties(i,{fillStyle:l,strokeStyle:"black"}),Co.fillCircle(i,d,u,this.dotSize),e.px=d,e.py=u}}}paintAxis(e,t,i){Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});var r={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};const s=(this.dataRange.max-this.dataRange.min)/i;if(this.posteriorProbability){const t=.1;for(let o=this.dataRange.min;o0&&i.push("
"),5==s){i.push("...");break}if(o=o._f||o,"function"==typeof o.popupData)i=i.concat(o.popupData());else{const e=o[this.valueProperty],t=o.chr,s=F(o.start+1);i.push({name:"chromosome",value:t}),i.push({name:"position",value:s}),i.push({name:"name",value:o.name}),r.posteriorProbability?i.push({name:"posterior probability",value:e}):i.push({name:"pValue",value:e})}s++}}}return i}menuItemList(){return this.numericDataMenuItems()}doAutoscale(e){if(e.length>0){const t=this.valueProperty,i=this.posteriorProbability,r=e.map((function(e){const r=e[t];return{value:i?r:-Math.log(r)/Math.LN10}}));this.dataRange=is(r)}else this.posteriorProbability?this.dataRange={min:this.config.min||0,max:this.config.max||1}:this.dataRange={min:this.config.max||25,max:this.config.min||0};return this.dataRange}}class IF extends ma{constructor(e,t){super(e,t)}init(e){super.init(e),this.autoscale=e.autoscale||void 0===e.max,this.dataRange={min:e.min||0,max:e.max},this.windowFunction=e.windowFunction||"mean",this.paintAxis=Oc,this.graphType=e.graphType||"bar",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=El(this.config,this.browser.genome),this.visibilityWindow=-1,this.featureSource.visibilityWindow=this.visibilityWindow}async postInit(){if("function"==typeof this.featureSource.getHeader){if(this.header=await this.featureSource.getHeader(),this.disposed)return;if(this.sampleKeys=this.header.columnNames.slice(3),this.setTrackProperties(this.header),this.header.hasOwnProperty("clickToHighlight")){let e=this.header.clickToHighlight;this.config.clickToHighlight=e,this.config.samplesClickedToHighlight={}}if(this.header.hasOwnProperty("onlyHandleClicksForHighlightedSamples")&&(this.config.onlyHandleClicksForHighlightedSamples=!0),this.header.hasOwnProperty("highlight")){this.config.highlightSamples={};let e=this.header.highlight;Array.isArray(e)||(e=[e]);for(let t of e){const e=t.split(";");2===e.length&&(this.config.highlightSamples[e[0]]=e[1])}}}this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor}menuItemList(){return this.numericDataMenuItems()}async getFeatures(e,t,i){const r=await this.featureSource.getFeatures({chr:e,start:0,end:Number.MAX_SAFE_INTEGER,visibilityWindow:this.visibilityWindow});let s,o;for(let e=1;et&&(s=e-1),void 0===o&&r[e].start>i){o=e+1;break}return void 0===s&&(s=0),void 0===o&&(o=r.length),r.slice(s,o)}draw(e){const{features:t,context:i,bpPerPixel:r,bpStart:s,pixelWidth:o,pixelHeight:n}=e,a=e=>(this.dataRange.max-e)/(this.dataRange.max-this.dataRange.min)*n,c=function(e){let t=Math.floor((e-s)/r);return isNaN(t)&&console.warn("isNaN(x). feature start "+F(e)+" bp start "+F(s)),t};if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){const e=this.config.highlightSamples,r=this.config.onlyHandleClicksForHighlightedSamples,s=this.config.clickToHighlight;let o=-1,n={},l=[],h=[];this.clickDetectorCache={};for(let d of t){const t=c(d.start),u=c(d.end),f=o>=0?c(o):t;if(!isNaN(t)&&!isNaN(u)){this.clickDetectorCache[t]=[],this.clickDetectorCache[u]=[];for(let o=0;o=1){const o=n[c],h=a(o),d=e&&e[c];d?l.push([f,h,t,g,d]):s&&c in this.config.samplesClickedToHighlight?l.push([f,h,t,g,this.config.samplesClickedToHighlight[c]]):Co.strokeLine(i,f,h,t,g,{strokeStyle:"#D9D9D9"}),r&&!(c in e)||this.clickDetectorCache[t].push([f,h,t,g,c,d||"gray"])}if(u-t>=1){const o=e&&e[c];o?h.push([t,g,u,g,o]):s&&c in this.config.samplesClickedToHighlight?h.push([t,g,u,g,this.config.samplesClickedToHighlight[c]]):Co.strokeLine(i,t,g,u,g,{strokeStyle:"gray"}),r&&!(c in e)||this.clickDetectorCache[u].push([t,g,u,g,c,o||"gray"])}n[c]=p}o=d.end}}for(let e of l)Co.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:1.3});for(let e of h)Co.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:2})}(e=>{if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=a(t.y),r={strokeStyle:t.color,strokeWidth:2};t.dotted?Co.dashedLine(e.context,0,i,e.pixelWidth,i,5,r):Co.strokeLine(e.context,0,i,e.pixelWidth,i,r)}})(e)}doAutoscale(e){let t,i;return e.length>0?(t=Number.MAX_VALUE,i=-Number.MAX_VALUE,e.forEach((function(e){t=Math.min(t,...e.values),i=Math.max(i,...e.values)})),t-=.01,i+=.01):(t=0,i=100),{min:t,max:i}}clickedFeatures(e){const t=e.canvasX,i=e.canvasY;let r=null;for(r of Object.keys(this.clickDetectorCache))if(r=parseInt(r),r>=t)break;if(r){let e=Number.MAX_VALUE,n=[];const a=this.clickDetectorCache[r];for(let r of a){const s=r[0],o=r[2];if(to)return[];const a=r[1],c=r[3];if(iMath.max(a,c)+10)continue;const l=SF(t,i,s,a,o,c);l0?c/l:0}class EF extends ma{static defaults={height:300,theta:Math.PI/2,arcOrientation:"UP"};constructor(e,t){super(e,t),!1===e.arcOrientation?this.arcOrientation="DOWN":!0===e.arcOrientation?this.arcOrientation="UP":e.arcOrientation?this.arcOrientation=e.arcOrientation.toUpperCase():this.arcOrientation="UP","bp"===e.format?this.featureSource=new MF(e,t.genome):this.featureSource=new Fl(e,t.genome)}async getFeatures(e,t,i){const r=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r})}draw(e){const t=e.context,i=Math.PI/2,r=e.pixelWidth,s=e.pixelHeight;e.viewportWidth;const o=e.bpPerPixel,n=e.bpStart,a=o,c="UP"===this.arcOrientation;Co.fillRect(t,0,e.pixelTop,r,s,{fillStyle:"rgb(255, 255, 255)"});const l=e.features;if(l){NF(l,1);for(let e of l)if(e.startLeft){let r=Math.round((e.startLeft-n)/a),s=Math.round((e.startRight-n)/a),o=Math.round((e.endLeft-n)/a),l=Math.round((e.endRight-n)/a);t.fillStyle=e.color,t.strokeStyle=e.color,t.beginPath();let h=(r+l)/2,d=(l-r)/2,u=this.height,f=Math.PI+(Math.PI/2-i),p=2*Math.PI-(Math.PI/2-i);c?(t.arc(h,u,d,f,p),t.lineTo(o,u)):(u=0,t.arc(h,u,d,p,f),t.lineTo(l,u));const g=(s+o)/2,m=(o-s)/2,w=u;c?(t.arc(g,w,m,p,f,!0),t.lineTo(r,w)):(t.arc(g,w,m,f,p,!0),t.lineTo(o,w)),t.stroke(),t.fill(),e.drawState={x1:h,y1:u,r1:d,x2:g,y2:w,r2:m,sa:f,ea:p}}else{let r=Math.round((e.start-n)/a),s=Math.round((e.end-n)/a);t.strokeStyle=e.color,t.beginPath();let o=(r+s)/2,l=(s-r)/2,h=this.height,d=Math.PI+(Math.PI/2-i),u=2*Math.PI-(Math.PI/2-i);c?t.arc(o,h,l,d,u):(h=0,t.arc(o,h,l,u,d)),t.stroke(),e.drawState={x1:o,y1:h,r1:l,sa:d,ea:u}}}}clickedFeatures(e){const t=super.clickedFeatures(e),i=[];NF(t,-1);for(let r of t){const t=r.drawState,s=e.canvasX-t.x1,o=e.canvasY-t.y1,n=Math.sqrt(s*s+o*o),a=t.r1+3;let c,l;if(void 0===t.x2)c=n,l=t.r1-3;else{const i=e.canvasX-t.x2,r=e.canvasY-t.y2;c=Math.sqrt(i*i+r*r),l=t.r2-3}if(nl){i.push(r);break}}return i}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0)return this.extractPopupData(t[0],this.getGenomeId())}menuItemList(){return[{name:"Toggle arc direction",click:function(){this.arcOrientation="UP"===this.arcOrientation?"DOWN":"UP",this.trackView.repaintViews()}}]}}function NF(e,t){e.sort((function(e,i){const r=void 0===e.score?-Number.MAX_VALUE:e.score,s=void 0===i.score?-Number.MAX_VALUE:i.score;return(void 0===t?1:t)*(r-s)}))}class MF{constructor(e,t){this.config=e,this.genome=t}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s}){const o=this.genome;if(!this.featureCache){const e=ts(this.config),t=await Rr.loadByteArray(this.config.url,e);if(!t)return null;const i=Wa(t);let r,s=!0;const a=[],c=[],l=[],h=new Set;for(;void 0!==(r=i.nextLine());){const e=r.split("\t");if(s&&r.startsWith("color:")){const t="rgb("+e[1]+","+e[2]+","+e[3]+")";a.push(t),e.length>4&&c.push(e[4])}else{s=!1;const t=e[0],i=Number.parseInt(e[1])-1,r=Number.parseInt(e[2])-1,o=Number.parseInt(e[3]),d=Number.parseInt(e[4]);var n=Number.parseInt(e[5]);const u=a[n];let f;f=i<=d?{chr:t,startLeft:Math.min(i,r),startRight:Math.max(i,r),endLeft:Math.min(o,d),endRight:Math.max(o,d),color:u,score:n}:{chr:t,startLeft:Math.min(o,d),startRight:Math.max(o,d),endLeft:Math.min(i,r),endRight:Math.max(i,r),color:u,score:n},f.start=f.startLeft,f.end=f.endRight,c.length>n&&(f.description=c[n]),h.add(t),l.push(f)}}this.chromAliasManager=new fc(h,o),this.featureCache=new cn(l)}const a=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e;return this.featureCache.queryFeatures(a,t,i)}}class RF{constructor(e){this.browser=e,this.type="ideogram",this.id="ideogram",this.height=e.config.showCytobandNames?20:16,this.order=Number.MIN_SAFE_INTEGER,this.disableButtons=!0,this.ignoreTrackMenu=!0,this.showCytobandNames=e.config.showCytobandNames}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,features:s}){const o=t.chr,n=t.genome.getChromosome(o);if(void 0===n||i<=0||r<=0||"all"===o.toLowerCase())return;!function({ctx:e,chr:t,referenceFrame:i,genome:r,width:s,height:o,stainColors:n,features:a,showCytobandNames:c}){const l=1,h=.5*l,d=0;if(void 0===r)return;Co.fillRect(e,0,0,s,o,{fillStyle:ur.greyScale(255)});const u=a;if(u){const t=d+o/2,i=[],r=[];if(0===u.length)return;const a=s/u[u.length-1].end;e.beginPath(),Co.roundRect(e,h,h+d,s-2*h,o-2*h,(o-2*h)/2,0,1),e.clip();for(let s=0;s0&&h[h.length-1].end&&(l=Math.max(l,h[h.length-1].end),n.bpLength=l),a4);e.save(),e.beginPath(),e.rect(i,2+s,c,a),e.clip();const h=i+c/2,d=2+s+a/2+1;let u;u=null!==n?.2126*n+.7152*n+.0722*n:39.764;const f=u<128?"white":"black";Co.fillText(e,t,h,d,{fillStyle:f,textAlign:"center",textBaseline:"middle",font:`${l}px sans-serif`}),e.restore()}function DF(e,t){if("c"===t.type)return{color:"rgb(150, 10, 10)",shade:null};{let r=t.stain,s=230;"p"===t.type&&(s=Math.floor(230-r/100*230));var i=e[s];return i||(i="rgb("+s+","+s+","+s+")",e[s]=i),{color:i,shade:s}}}let LF=new Wr("Dark2");["GT/AG","CT/AC","GC/AG","CT/GC","AT/AC","GT/AT","non-canonical"].forEach((e=>{LF.getColor(e)}));class TF extends ma{static defaults={margin:10,colorByNumReadsThreshold:5,height:100};constructor(e,t){super(e,t)}init(e){super.init(e),this.type=e.type||"junctions",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=e.featureSource?e.featureSource:El(e,this.browser.genome)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow()),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get supportsWholeGenome(){return!1}async getFeatures(e,t,i,r){const s=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s})}computePixelHeight(e){return this.height}draw(e){const t=e.features,i=e.context,r=e.bpPerPixel,s=e.bpStart,o=e.pixelWidth,n=e.pixelHeight,a=s+o*r+1;if(this.isMergedTrack||Co.fillRect(i,0,e.pixelTop,o,n,{fillStyle:"rgb(255, 255, 255)"}),t){const o={};o.referenceFrame=e.viewport.referenceFrame,o.referenceFrameStart=o.referenceFrame.start,o.referenceFrameEnd=o.referenceFrameStart+o.referenceFrame.toBP(e.viewport.getWidth()),o.featureZoomOutTracker={};for(let e of t)if(!(e.enda)break;this.renderJunction(e,s,r,n,i,o)}}else console.log("No feature list")}renderJunction(e,t,i,r,s,o){e.isVisible=!1;const n=Math.round((e.start-t)/i),a=Math.round((e.end-t)/i),c=(n+a)/2;if(a-n<=3){if(c in o.featureZoomOutTracker)return;o.featureZoomOutTracker[c]=!0}if(this.config.hideAnnotatedJunctions&&"true"===e.attributes.annotated_junction)return;if(this.config.hideUnannotatedJunctions&&"false"===e.attributes.annotated_junction)return;if(this.config.hideMotifs&&this.config.hideMotifs.includes(e.attributes.motif))return;if(this.config.hideStrand===e.strand)return;if(this.config.minJunctionEndsVisible){let t=0;if(e.start>=o.referenceFrameStart&&e.start<=o.referenceFrameEnd&&(t+=1),e.end>=o.referenceFrameStart&&e.end<=o.referenceFrameEnd&&(t+=1),t0&&h/d>this.config.maxFractionMultiMappedReads)return;if(e.attributes.maximum_spliced_alignment_overhang&&parseInt(e.attributes.maximum_spliced_alignment_overhang)this.config.maxSamplesWithThisJunction)return;if(e.attributes.num_samples_total&&(e.attributes.percent_samples_with_this_junction=100*u/Number(e.attributes.num_samples_total),this.config.minPercentSamplesWithThisJunction&&(e.attributes.percent_samples_with_this_junctionthis.config.maxPercentSamplesWithThisJunction)))return}const f=this.margin,p=r,g=f+.5*p;let m=f;const w=f+p-10,b=(n+c)/2,F=(c+a)/2;let v,y,A=1;e.attributes.line_width?A=Number(e.attributes.line_width):(void 0===this.config.thicknessBasedOn||"numUniqueReads"===this.config.thicknessBasedOn?A=l:"numReads"===this.config.thicknessBasedOn?A=d:"numSamplesWithThisJunction"===this.config.thicknessBasedOn&&void 0!==u&&(A=u),A=1+Math.log(A+1)/Math.log(12)),void 0===this.config.bounceHeightBasedOn||"random"===this.config.bounceHeightBasedOn?v=(e.start+e.end)%7:"distance"===this.config.bounceHeightBasedOn?v=6*(e.end-e.start)/(o.referenceFrameEnd-o.referenceFrameStart):"thickness"===this.config.bounceHeightBasedOn&&(v=2*A),m+=p*Math.max(7-v,0)/10,y=e.attributes.color?e.attributes.color:void 0===this.config.colorBy||"numUniqueReads"===this.config.colorBy?l>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"numReads"===this.config.colorBy?d>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"isAnnotatedJunction"===this.config.colorBy?"true"===e.attributes.annotated_junction?"#b0b0ec":"orange":"strand"===this.config.colorBy?"+"===e.strand?"#b0b0ec":"#ecb0b0":"motif"===this.config.colorBy?LF.getColor(e.attributes.motif):"#AAAAAA";let C="";e.attributes.label?C=e.attributes.label.replace(/_/g," "):void 0===this.config.labelWith||"uniqueReadCount"===this.config.labelWith?C=l:"totalReadCount"===this.config.labelWith?C=d:"numSamplesWithThisJunction"===this.config.labelWith?void 0!==u&&(C=u):"percentSamplesWithThisJunction"===this.config.labelWith?void 0!==e.attributes.percent_samples_with_this_junction&&(C=e.attributes.percent_samples_with_this_junction.toFixed(0)+"%"):"motif"===this.config.labelWith&&void 0!==e.attributes.motif&&(C+=e.attributes.motif),"uniqueReadCount"===this.config.labelWithInParen?C+=" ("+l+")":"totalReadCount"===this.config.labelWithInParen?C+=" ("+d+")":"multiMappedReadCount"===this.config.labelWithInParen?h>0&&(C+=" (+"+h+")"):"numSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==u&&(C+=" ("+u+")"):"percentSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==e.attributes.percent_samples_with_this_junction&&(C+=" ("+e.attributes.percent_samples_with_this_junction.toFixed(0)+"%)"):"motif"===this.config.labelWithInParen&&void 0!==e.attributes.motif&&(C+=` ${e.attributes.motif}`),e.isVisible=!0,s.beginPath(),s.moveTo(n,w),s.bezierCurveTo(b,m,F,m,a,w),s.lineWidth=A,s.strokeStyle=y,s.stroke();const _=(e,t,i,r)=>{e.beginPath(),e.moveTo(t,i),e.lineTo(t-r/2,i-r),e.lineTo(t+r/2,i-r),e.lineTo(t,i),e.closePath(),e.fill()};if(e.attributes.left_shape||e.attributes.right_shape){s.fillStyle=y;const t=s.lineWidth>2?10:7;e.attributes.left_shape&&_(s,n,w,t),e.attributes.right_shape&&_(s,a,w,t)}s.fillText(C,c-s.measureText(C).width/2,(7*m+g)/8)}clickedFeatures(e){return super.clickedFeatures(e).filter((function(e){return e.isVisible&&e.attributes}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,r=[];for(let e of t){const t="function"==typeof e.popupData?e.popupData(i):this.extractPopupData(e._f||e,this.getGenomeId());t&&(r.length>0&&r.push("

"),Array.prototype.push.apply(r,t))}return r}dispose(){this.trackView=void 0}}const zF={min:0,max:3e3,color:"rgb(0,0,255)"};class PF{constructor(e){e=e||zF,this.max=e.max,this.min=e.min||0,this.cache=[],this.nbins=1e3,this.binsize=(this.max-this.min)/this.nbins,this.updateColor(e.color||"rgb(0,0,255)"),this.br=255,this.bg=255,this.bb=255}updateColor(e){const t=e.substring(4).replace(")","").split(",");3===t.length&&(this.r=Number.parseInt(t[0].trim()),this.g=Number.parseInt(t[1].trim()),this.b=Number.parseInt(t[2].trim())),this.cache=[]}setMinMax(e,t){this.min=e,this.max=t,this.cache=[],this.binsize=(this.max-this.min)/this.nbins}getColor(e){if(e<=this.min)return"white";if(e>=this.max)return`rgb(${this.r},${this.g},${this.b})`;const t=Math.floor((Math.min(this.max,e)-this.min)/this.binsize);if(void 0===this.cache[t]){const i=(e-this.min)/(this.max-this.min),r=1-i;this.cache[t]=`rgb(${Math.floor(i*this.r+r*this.br)},${Math.floor(i*this.g+r*this.bg)},${Math.floor(i*this.b+r*this.bb)})`}return this.cache[t]}toJson(){return{min:this.min,max:this.max,color:`rgb(${this.r},${this.g},${this.b})`}}static parse(e){const t=e.split(","),i={min:Number.parseFloat(t[0]),max:Number.parseFloat(t[1]),color:`${t[2]},${t[3]},${t[4]}`};return new PF(i)}}class HF extends ma{static defaults={height:300,rowHeight:3,min:.5,max:3,scale:1,visibilityWindow:1e4,supportHiDPI:!1,startSize:4,stepSize:2};constructor(e,t){super(e,t)}init(e){super.init(e),this.type="shoebox",e.max&&(this.dataRange={min:e.min||0,max:e.max});const t=Object.assign({},this.config);t.format="shoebox",this.featureSource=El(t,this.browser.genome)}async postInit(){if("function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader(),this.disposed))return;this.header&&(this.header.scale&&(this.header.scale=Number.parseFloat(this.header.scale)),this.setTrackProperties(this.header),this.rowCount=this.header.firstFeature?this.header.firstFeature.values.length:100);const e=this.dataRange.min,t=this.dataRange.max;this.colorScale=new PF({min:e,max:t,color:this.color}),this.scale||(this.scale=1),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor}get color(){return this._color||"rgb(0,0,255)"}set color(e){this._color=e,this.colorScale&&this.colorScale.updateColor(e)}menuItemList(){const e=[];e.push("
");let t=document.createElement("div");t.textContent="Set row height";const i=this.browser;return e.push({element:t,dialog:function(e){const t={label:"Row Height",value:this.rowHeight,callback:()=>{const e=parseInt(this.browser.inputDialog.value,10);if(void 0!==e){i.sampleNameViewportWidth=void 0;const t=[];this.trackView.track.selected?t.push(...this.trackView.browser.getSelectedTrackViews().map((({track:e})=>e))):t.push(this);for(const i of t)i.rowHeight=e,i.rowHeight*i.rowCount"),t=document.createElement("div"),t.textContent="Set data range",e.push({element:t,dialog:function(e){this.trackView.track.selected?this.browser.dataRangeDialog.configure(this.trackView.browser.getSelectedTrackViews()):this.browser.dataRangeDialog.configure(this.trackView),this.browser.dataRangeDialog.present(e)}}),e}setDataRange({min:e,max:t}){this.dataRange.min=e,this.dataRange.max=t,this.colorScale.setMinMax(e,t),this.trackView.repaintViews()}async getFeatures(e,t,i,r){const s=this.visibilityWindow;return await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s})}draw({context:e,pixelTop:t,pixelWidth:i,pixelHeight:r,features:s,bpPerPixel:o,bpStart:n}){if(Co.fillRect(e,0,t,i,r,{fillStyle:"rgb(255, 255, 255)"}),s&&s.length>0){const a=this.rowHeight,c=t+r,l=n+i*o+1,h=a;for(let i of s){if(i.endl)continue;const r=Math.floor((i.start-n)/o),s=Math.floor((i.end-n)/o),d=Math.max(1,s-r);for(let s=i.values.length-1;s>=0;s--){const o=i.values[s];if(o>=this.dataRange.min){const n=(i.values.length-1-s)*a;if(n+ac)continue;const l=this.colorScale.getColor(o);e.fillStyle=l,e.fillRect(r,n,d,h)}}}}}paintAxis(e,t,i){var r={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};const s=this.startSize+this.rowCount*this.stepSize,o=this.startSize,n=(s-o)/i;for(let t=50;t<=s;t+=50){const s=Math.max(10,i-Math.round((t-o)/n));Co.strokeLine(e,35,s,40,s,r),t>o&&Co.fillText(e,OF(t),30,s+4,r)}r.textAlign="center",r.font="normal 10px Arial",Co.fillText(e,"Footprint size (bp)",10,i/2,r,{rotate:{angle:-90}})}computePixelHeight(e){return e&&0!==e.length?e[0].values.length*this.rowHeight:0}clickedFeatures(e){const t=super.clickedFeatures(e),i=e.y;return t.filter((function(e){const t=e.pixelRect;return t&&i>=t.y&&i<=t.y+t.h}))}hoverText(e){const t=this.clickedFeatures(e);if(t&&t.length>0)return`${t[0].sample}: ${t[0].value}`}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){i.length>0&&(i.push("
"),i.push("
"));const t=e._f||e,r="function"==typeof t.popupData?t.popupData(this.type,this.browser.genome.id):this.extractPopupData(t);Array.prototype.push.apply(i,r)}return i}get supportsWholeGenome(){return!1}getState(){const e=super.getState();return e.colorScale=this.colorScale.toJson(),e}}function OF(e){return Number.isInteger(e)||e%1==0?e:Math.abs(e)>=10?e.toFixed():Math.abs(e)>=1?e.toFixed(1):Math.abs(e)>=.1?e.toFixed(2):e.toExponential(1)}class VF extends ma{static defaults={};constructor(e,t){super(e,t)}init(e){if(super.init(e),!e.images)throw Error("images are required");this.locus=e.locus,this.type="image",this.resolutionAware=!0}async postInit(){this._images=[];for(let e of this.config.images){const t=new Image;t.onload=()=>{e.img=t,e.bpPerPixel=(e.end-e.start)/t.width,this._images.push(e)},t.onerror=e=>{console.error(e)},t.src=e.src}}computePixelHeight(e){return e?e.height:0}menuItemList(){return[]}async getFeatures(e,t,i,r){return this.selectImage(e,t,i,r)}selectImage(e,t,i,r){if(0==this._images.length)return null;this._images.sort(((e,t)=>e.bpPerPixelr)return e;const s=this._images[this._images.length-1];return s.chr===e?s:null}draw({context:e,pixelTop:t,pixelWidth:i,pixelHeight:r,features:s,bpPerPixel:o,bpStart:n}){const a=s.img;if(a){const t=a.width,i=a.height,r=(s.end-s.start)/t/o,c=(s.start-n)/o;e.drawImage(a,c,0,r*t,i)}}get supportsWholeGenome(){return!1}}const qF=new Map([["ideogram",(e,t)=>new RF(e,t)],["sequence",(e,t)=>new sh(e,t)],["feature",(e,t)=>new Gl(e,t)],["seg",(e,t)=>new Zd(e,t)],["mut",(e,t)=>new Zd(e,t)],["maf",(e,t)=>new Zd(e,t)],["shoebox",(e,t)=>new HF(e,t)],["wig",(e,t)=>new ml(e,t)],["merged",(e,t)=>new vd(e,t)],["alignment",(e,t)=>new up(e,t)],["interaction",(e,t)=>new fp(e,t)],["interact",(e,t)=>new fp(e,t)],["variant",(e,t)=>new bF(e,t)],["qtl",(e,t)=>new CF(e,t)],["eqtl",(e,t)=>new CF(e,t)],["gwas",(e,t)=>new kF(e,t)],["arc",(e,t)=>new EF(e,t)],["gcnv",(e,t)=>new IF(e,t)],["junction",(e,t)=>new TF(e,t)],["blat",(e,t)=>new Zl(e,t)],["cnvpytor",(e,t)=>new gF(e,t)],["image",(e,t)=>new VF(e,t)]]);class UF{constructor(e,t){const i=(new DOMParser).parseFromString(e,"text/xml");this.processRootNode(i,t);const r=i.getElementsByTagName("Resource"),s=i.getElementsByTagName("Track"),o=s&&s.length>0,n=[];this.tracks=n;const a=new Map;Array.from(r).forEach((function(e,t){var i={url:e.getAttribute("path"),indexURL:e.getAttribute("index"),order:t};a.set(i.url,i),o||n.push(i)})),o&&Array.from(s).forEach((function(e){const t=e.getElementsByTagName("Track");if(t&&t.length>0){const i={type:"merged",tracks:[]};QF(e,i),n.push(i),Array.from(t).forEach((function(e){e.processed=!0;const t=e.getAttribute("id"),r=a.get(t);r&&(i.tracks.push(r),QF(e,r),r.autoscale=!1,i.height=r.height)}))}else if(!e.processed){const t=e.getAttribute("id"),i=a.get(t);i&&(n.push(i),QF(e,i))}}))}processRootNode(e,t){const i=e.getElementsByTagName("Session");!i||i.length;const r=i.item(0),s=r.getAttribute("genome"),o=r.getAttribute("locus"),n=r.getAttribute("ucscID");t&&t.hasOwnProperty(s)?this.genome=s:(this.reference={fastaURL:s},n&&(this.reference.id=n)),o&&(this.locus=o)}}function QF(e,t){t.name=e.getAttribute("name");const i=e.getAttribute("color");i&&(t.color="rgb("+i+")");const r=e.getAttribute("altColor");i&&(t.altColor="rgb("+r+")");const s=e.getAttribute("height");s&&(t.height=parseInt(s));const o=e.getAttribute("autoScale");o&&(t.autoscale="true"===o);const n=e.getAttribute("autoscaleGroup");n&&(t.autoscaleGroup=n);const a=e.getAttribute("windowFunction");a&&(t.windowFunction=a);const c=e.getAttribute("visibilityWindow")||e.getAttribute("featureVisibilityWindow");c&&(t.visibilityWindow=c);const l=e.getAttribute("indexed");l&&(t.indexed="true"===l);const h=e.getAttribute("normalize");h&&(t.normalize="true"===h);const d=e.getElementsByTagName("DataRange");if(d.length>0){const e=d.item(0);t.min=Number(e.getAttribute("minimum")),t.max=Number(e.getAttribute("maximum")),t.logScale="LOG"===e.getAttribute("type")}}class GF{constructor(e,t,i,r,s){this.genome=e,this.chr=t,this.start=i,this.end=r,this.bpPerPixel=s,this.id=n()}get center(){return(this.start+this.end)/2}get locusSearchString(){return`${this.chr}:${this.start+1}-${this.end}`}extend(e){const t=Math.min(e.start,this.start),i=Math.max(e.end,this.end),r=(i-t)/(this.end-this.start);this.start=t,this.end=i,this.bpPerPixel*=r}calculateEnd(e){return this.start+this.bpPerPixel*e}calculateCenter(e){return this.start+this.bpPerPixel*e/2}calculateBPP(e,t){return(e-this.start)/t}set(e){this.chr=e.chr,this.start=e.start,this.bpPerPixel=e.bpPerPixel}toPixels(e){return e/this.bpPerPixel}toBP(e){return this.bpPerPixel*e}shift(e){this.start+=e,this.end+=e}shiftPixels(e,t,i){const r=this.start,s=e*this.bpPerPixel;return this.start+=s,i&&this.clampStart(t),this.end=this.start+t*this.bpPerPixel,r!==this.start}clampStart(e){const t=this.genome.getChromosome(this.chr).bpStart||0;if(this.start=Math.max(t,this.start),e){const{bpLength:t}=this.genome.getChromosome(this.chr),i=t-e*this.bpPerPixel;this.start>i&&(this.start=i)}}async zoomWithScaleFactor(e,t,i,r){const s=void 0===r?this.start+this.toBP(i/2):r,o=this.start,n=this.bpPerPixel,a=this.getChromosome().bpLength,c=t<1?e.minimumBases()/i:a/i;this.bpPerPixel=t<1?Math.max(this.bpPerPixel*t,c):Math.min(this.bpPerPixel*t,c);const l=this.bpPerPixel*i;this.start=s-.5*l,this.clampStart(i),this.end=this.start+l;(o!==this.start||n!==this.bpPerPixel)&&await e.updateViews(!0)}getChromosome(){return this.genome.getChromosome(this.chr)}updateForViewportWidth(e){const{chr:t}=this,{bpLength:i}=this.getChromosome(),r=this.toBP(e);Dh.isWholeGenomeView(t)||r>i?this.bpPerPixel=i/e:this.end=this.start+this.toBP(e)}getMultiLocusLabelBPLengthOnly(e){const t=" ",i=Math.floor(this.start)+1,r=Math.round(this.start+this.bpPerPixel*e);return`${t}${this.chr}${t}${ns(r-i)}${t}`}getMultiLocusLabelLocusOnly(e){const t=" ",{chr:i,start:r,end:s}=this.getPresentationLocusComponents(e);return`${t}${i}:${r}-${s}${t}`}getMultiLocusLabel(e){const t=" ",{chr:i,start:r,end:s}=this.getPresentationLocusComponents(e),o=Math.floor(this.start)+1;return`${t}${i}:${r}-${s}${t}${t}(${ns(Math.round(this.start+this.bpPerPixel*e)-o)})${t}`}getPresentationLocusComponents(e){if("all"===this.chr)return{chr:this.chr};{const t=F(Math.floor(this.start)+1),i=F(Math.round(this.start+this.bpPerPixel*e));return{chr:this.chr,start:t,end:i}}}getLocusString(){if("all"===this.chr)return"all";return`${this.genome.getChromosomeDisplayName(this.chr)}:${F(Math.floor(this.start)+1)}-${F(Math.round(this.end))}`}description(e){console.log(` ${e||""} referenceFrame - ${this.chr} bpp ${this.bpPerPixel.toFixed(3)} start ${F(Math.round(this.start))} end ${F(Math.round(this.end))} `)}overlaps(e){return this.chr===e.chr&&this.end>=e.start&&e.end>=this.start}}function jF(){return"3.5.0"}const WF="Maximum sequence count exceeded";class $F{constructor(e,i){this.container=t({class:"igv-chromosome-select-widget-container"}),i.appendChild(this.container),this.select=document.createElement("select"),this.select.setAttribute("name","chromosome-select-widget"),this.container.appendChild(this.select),this.select.addEventListener("change",(async()=>{if(this.select.blur(),""!==this.select.value&&WF!==this.select.value)if("all"===this.select.value.trim().toLowerCase()||"*"===this.select.value){if(e.genome.wholeGenomeView){const t=e.genome.getChromosome("all");e.updateLoci([{chr:"all",start:0,end:t.bpLength}])}}else{const t=await e.genome.loadChromosome(this.select.value),i={chr:t.name};void 0===i.start&&void 0===i.end&&(i.start=0,i.end=t.bpLength),e.updateLoci([i])}})),this.showAllChromosomes=!1!==e.config.showAllChromosomes,this.genome=e.genome}show(){this.container.style.display="flex"}hide(){this.container.style.display="none"}setValue(e){this.select.value=this.genome.getChromosomeDisplayName(e)}update(e){this.genome=e;const t=e.wgChromosomeNames?e.wgChromosomeNames.map((t=>e.getChromosomeDisplayName(t))):[];if(this.showAllChromosomes&&e.chromosomeNames.length>1){const i=new Set(t);let r=0;for(let s of e.chromosomeNames){if(1e3===++r){t.push(WF);break}i.has(s)||(s=e.getChromosomeDisplayName(s),t.push(s))}}this.select.innerHTML="",e.showWholeGenomeView()&&t.unshift("all");for(let i of t){const t=document.createElement("option");t.setAttribute("value",i),t.innerText=e.getChromosomeDisplayName(i),this.select.appendChild(t)}}}class KF{constructor(e,i){this.container=t({class:"igv-windowsize-panel-container"}),e.appendChild(this.container),i.on("locuschange",(e=>{this.updatePanel(e)})),this.browser=i}show(){this.container.style.display="block"}hide(){this.container.style.display="none"}updatePanel(e){const t=this.browser.calculateViewportWidth(this.browser.referenceFrameList.length);this.container.innerText=1===e.length?ns(Math.round(t*e[0].bpPerPixel)):""}}class ZF extends bd{constructor(e,t,i,r){super(e,t,"Select Tracks",Fd,'\n multi select\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n','\n multi select hover\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n',!1),this.navbar=i,this.enableMultiTrackSelection=!1,this.button.addEventListener("mouseenter",(e=>{!1===r&&this.setState(!0)})),this.button.addEventListener("mouseleave",(e=>{!1===r&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{this.setMultiTrackSelection(!this.enableMultiTrackSelection)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler)}setMultiTrackSelection(e){this.enableMultiTrackSelection=e,this.setState(this.enableMultiTrackSelection),!1===this.enableMultiTrackSelection&&this.navbar.overlayTrackButton.setVisibility(!1);for(const t of this.browser.trackViews)t.enableTrackSelection(e)}}class YF extends bd{constructor(e,t){super(e,t,"Crosshairs",Fd,'\n cursor\n \n \n \n \n \n \n \n \n \n \n','\n cursor hover\n \n \n \n \n \n \n \n \n \n \n',t.doShowCursorGuide),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowCursorGuide&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowCursorGuide&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{t.doShowCursorGuide=!t.doShowCursorGuide,t.setCursorGuideVisibility(t.doShowCursorGuide),this.setState(t.doShowCursorGuide)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(t.config.showCursorTrackingGuideButton)}}class XF extends bd{constructor(e,t){super(e,t,"Center Line",Fd,'\n centerline\n \n \n \n \n \n \n','\n centerline hover\n \n \n \n \n \n \n',t.config.showCenterGuide),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowCenterLine&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowCenterLine&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{t.doShowCenterLine=!t.doShowCenterLine,t.setCenterLineVisibility(t.doShowCenterLine),this.setState(t.doShowCenterLine)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(t.config.showCenterGuideButton)}}class JF extends bd{constructor(e,t){super(e,t,"Track Labels",Fd,'\n track labels\n \n \n \n \n \n \n \n \n \n','\n track labels hover\n \n \n \n \n \n \n \n \n \n',t.config.showTrackLabels),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowTrackLabels&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowTrackLabels&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{t.doShowTrackLabels=!t.doShowTrackLabels,t.setTrackLabelVisibility(t.doShowTrackLabels),this.setState(t.doShowTrackLabels)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(t.config.showTrackLabelButton)}}class ev extends bd{constructor(e,t){super(e,t,["ROI","Regions of Interest Table"],Fd,'\n roi\n \n \n \n \n ROI\n \n \n \n','\n roi hover\n \n \n \n \n ROI\n \n \n \n',!1),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowROITable&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowROITable&&this.setState(!1)})),this.button.addEventListener("click",(()=>this.buttonHandler(!t.doShowROITable))),this.setVisibility(!1)}buttonHandler(e){this.setState(e),this.browser.setROITableVisibility(e)}}class tv extends bd{constructor(e,t){super(e,t,"Sample Info",Fd,'\n sample info\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 sample info hover\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',!1),this.showSampleInfo=!1,this.button.addEventListener("mouseenter",(()=>{!1===this.showSampleInfo&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===this.showSampleInfo&&this.setState(!1)})),this.button.addEventListener("click",(()=>{this.performClickWithState(t,void 0)}))}performClickWithState(e,t){this.showSampleInfo=void 0===t?!this.showSampleInfo:t;e.columnContainer.querySelector(".igv-sample-info-column").style.display=!1===this.showSampleInfo?"none":"flex",this.setState(this.showSampleInfo),e.layoutChange()}setButtonVisibility(e){this.showSampleInfo=e,this.setState(this.showSampleInfo),!0===this.showSampleInfo?this.show():this.hide()}}class iv extends bd{constructor(e,t){super(e,t,"Sample Names",'\n \n \n \n \n \n \n \n \n','\n sample names\n \n \n \n \n \n \n \n \n','\n sample names hover\n \n \n \n \n \n \n \n \n',t.config.showSampleNames),this.button.addEventListener("mouseenter",(()=>{!1===t.showSampleNames&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.showSampleNames&&this.setState(!1)})),this.button.addEventListener("click",(()=>{this.performClickWithState(t,void 0)})),!0===t.config.showSampleNameButton?this.show():this.hide()}performClickWithState(e,t){e.showSampleNames=void 0===t?!e.showSampleNames:t;e.columnContainer.querySelector(".igv-sample-name-column").style.display=!1===e.showSampleNames?"none":"flex",this.setState(e.showSampleNames),e.layoutChange()}}class rv{constructor(e,i){this.parent=e,this.popover=t({class:"igv-ui-dropdown"}),e.appendChild(this.popover),this.popoverContent=t(),this.popover.appendChild(this.popoverContent),this.popover.style.display="none",this.shim=i}configure(e){if(0===e.length)return;const t=ps(e,this.popover);for(const{element:e}of t)this.popoverContent.appendChild(e)}present(e){this.popover.style.display="block";let{x:t,y:i}=a(e,this.parent);this.popover.style.left=`${t+this.shim.left}px`,this.popover.style.top=`${i+this.shim.top}px`}_present(e){this.popover.style.display="block";let{x:t,y:i,width:r}=a(e,this.parent);t+=this.shim.left,i+=this.shim.top,this.popover.style.top=`${i}px`;const{width:s}=this.popover.getBoundingClientRect(),o=t+s,n=o-r;this.popover.style.left=`${o>r?t-n:t}px`}dismiss(){this.popover.style.display="none"}}class sv extends bd{constructor(e,t){super(e,t,"Save Image",Fd,'\n save image\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n','\n save image\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n',!1),this.button.addEventListener("mouseenter",(()=>this.setState(!0))),this.button.addEventListener("mouseleave",(()=>{for(const e of this.button.querySelectorAll("div"))if("block"===e.style.display)return;this.setState(!1)})),this.dropdown=new rv(this.button.parentNode,{top:24,left:-88});const i=[{label:"Save as SVG",click:e=>{this.browser.saveSVGtoFile("igvjs.svg"),this.dropdown.dismiss()}},{label:"Save as PNG",click:e=>{this.browser.savePNGtoFile("igvjs.png"),this.dropdown.dismiss()}}];this.dropdown.configure(i),this.button.addEventListener("click",(e=>{let t;if(e.target===this.button)t=!0;else if(e.target.closest("svg")){e.target.closest("div")===this.button&&(t=!0)}!0===t&&("none"===this.dropdown.popover.style.display?this.dropdown.present(e):this.dropdown.dismiss())})),this.setVisibility(t.config.showSVGButton)}navbarResizeHandler(e){this.dropdown.dismiss(),super.navbarResizeHandler(e)}}const ov=function(e,i,r){const s=t({class:"igv-navbar-button"});e.appendChild(s),s.textContent=r.label,s.addEventListener("click",(()=>r.callback(i)))};let nv=23,av=0;class cv{constructor(e,i,r){this.browser=i,this.zoomContainer=t({class:"igv-zoom-widget"}),r.appendChild(this.zoomContainer),this.zoomOutButton=t(),this.zoomContainer.appendChild(this.zoomOutButton),this.zoomOutButton.appendChild(l("minus-circle")),this.zoomOutButton.addEventListener("click",(()=>{i.zoomOut()}));const s=t();this.zoomContainer.appendChild(s),this.slider=document.createElement("input"),this.slider.type="range",this.slider.min="0",this.slider.max=`${nv}`,s.appendChild(this.slider),this.slider.addEventListener("change",(e=>{e.preventDefault(),e.stopPropagation();const t=i.referenceFrameList[0],{bpLength:r}=t.genome.getChromosome(t.chr),{end:s,start:o}=t,n=s-o,a=r/Math.pow(2,e.target.valueAsNumber);i.zoomWithScaleFactor(a/n)})),this.zoomInButton=t(),this.zoomContainer.appendChild(this.zoomInButton),this.zoomInButton.appendChild(l("plus-circle")),this.zoomInButton.addEventListener("click",(()=>{i.zoomIn()})),i.on("locuschange",(e=>{this.browser.isMultiLocusMode()?this.disable():(this.enable(),this.update(e))}))}update(e){if(this.slider){const t=e[0],{bpLength:i}=t.genome.getChromosome(t.chr),{start:r,end:s}=t;nv=Math.ceil(Math.log2(i/this.browser.minimumBases())),this.slider.max=`${nv}`;const o=i/(s-r);av=Math.log2(o),this.slider.value=`${Math.round(av)}`}}enable(){this.slider&&(this.slider.disabled=!1)}disable(){this.slider&&(this.slider.disabled=!0)}hide(){this.zoomContainer.style.display="none"}show(){this.zoomContainer.style.display="block"}hideSlider(){this.slider&&(this.slider.style.display="none")}showSlider(){this.slider&&(this.slider.style.display="block")}}class lv{constructor(e,t){this.browser=t,this.config=e,this.currentClass="igv-navbar-text-button";const i=document.createElement("div");i.className="igv-navbar",this.navigation=i;const r=document.createElement("div");r.className="igv-navbar-left-container",i.appendChild(r),this.navbarLeftContainer=r;const s=document.createElement("div");s.className="igv-logo",r.appendChild(s);const o=function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","690px"),e.setAttribute("height","324px"),e.setAttribute("viewBox","0 0 690 324"),e.setAttribute("version","1.1"),e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");const t=document.createElementNS("http://www.w3.org/2000/svg","title");t.textContent="IGV",e.appendChild(t);const i=document.createElementNS("http://www.w3.org/2000/svg","g");i.setAttribute("id","Page-1"),i.setAttribute("stroke","none"),i.setAttribute("stroke-width","1"),i.setAttribute("fill","none"),i.setAttribute("fill-rule","evenodd"),e.appendChild(i);const r=document.createElementNS("http://www.w3.org/2000/svg","g");r.setAttribute("id","IGV"),r.setAttribute("fill","#666666"),i.appendChild(r);const s=document.createElementNS("http://www.w3.org/2000/svg","polygon");s.setAttribute("id","Path"),s.setAttribute("points","379.54574 8.00169252 455.581247 8.00169252 515.564813 188.87244 532.884012 253.529506 537.108207 253.529506 554.849825 188.87244 614.833392 8.00169252 689.60164 8.00169252 582.729511 320.722144 486.840288 320.722144"),r.appendChild(s);const o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d","M261.482414,323.793286 C207.975678,323.793286 168.339046,310.552102 142.571329,284.069337 C116.803612,257.586572 103.919946,217.158702 103.919946,162.784513 C103.919946,108.410325 117.437235,67.8415913 144.472217,41.0770945 C171.507199,14.3125977 212.903894,0.930550071 268.663545,0.930550071 C283.025879,0.930550071 298.232828,1.84616386 314.284849,3.6774189 C330.33687,5.50867394 344.839793,7.97378798 357.794056,11.072835 L357.794056,68.968378 C339.48912,65.869331 323.578145,63.5450806 310.060654,61.9955571 C296.543163,60.4460336 284.574731,59.6712835 274.154998,59.6712835 C255.850062,59.6712835 240.502308,61.4320792 228.111274,64.9537236 C215.720241,68.4753679 205.793482,74.2507779 198.330701,82.2801269 C190.867919,90.309476 185.587729,100.87425 182.48997,113.974767 C179.392212,127.075284 177.843356,143.345037 177.843356,162.784513 C177.843356,181.942258 179.251407,198.000716 182.067551,210.960367 C184.883695,223.920018 189.671068,234.41436 196.429813,242.443709 C203.188559,250.473058 212.059279,256.178037 223.042241,259.558815 C234.025202,262.939594 247.683295,264.629958 264.01693,264.629958 C268.241146,264.629958 273.098922,264.489094 278.590403,264.207362 C284.081883,263.925631 289.643684,263.50304 295.275972,262.939577 L295.275972,159.826347 L361.595831,159.826347 L361.595831,308.579859 C344.698967,313.087564 327.239137,316.750019 309.215815,319.567334 C291.192494,322.38465 275.281519,323.793286 261.482414,323.793286 L261.482414,323.793286 L261.482414,323.793286 Z"),o.setAttribute("id","Path"),r.appendChild(o);const n=document.createElementNS("http://www.w3.org/2000/svg","polygon");return n.setAttribute("id","Path"),n.setAttribute("points","0.81355666 5.00169252 73.0472883 5.00169252 73.0472883 317.722144 0.81355666 317.722144"),r.appendChild(n),e}();o.style.width="34px",o.style.height="32px",s.appendChild(o),this.currentGenome=document.createElement("div"),this.currentGenome.className="igv-current-genome",r.appendChild(this.currentGenome),this.currentGenome.textContent="";const n=document.createElement("div");n.className="igv-navbar-genomic-location",r.appendChild(n),this.chromosomeSelectWidget=new $F(t,n),!1!==e.showChromosomeWidget?this.chromosomeSelectWidget.show():this.chromosomeSelectWidget.hide();const a=document.createElement("div");a.className="igv-locus-size-group",n.appendChild(a);const c=document.createElement("div");c.className="igv-search-container",a.appendChild(c),this.searchInput=document.createElement("input"),this.searchInput.className="igv-search-input",this.searchInput.type="text",this.searchInput.placeholder="Locus Search",c.appendChild(this.searchInput),this.searchInput.addEventListener("keyup",(e=>{e.stopImmediatePropagation()})),this.searchInput.addEventListener("change",(()=>{this.doSearch(this.searchInput.value)}));const h=document.createElement("div");h.className="igv-search-icon-container",c.appendChild(h);const d=l("search");h.appendChild(d),h.addEventListener("click",(()=>{this.doSearch(this.searchInput.value)})),this.windowSizePanel=new KF(a,t);const u=document.createElement("div");u.className="igv-navbar-right-container",i.appendChild(u),this.navbarRightContainer=u;const f=document.createElement("div");f.className="igv-navbar-toggle-button-container",u.appendChild(f),this.toggleButtonContainer=f,this.overlayTrackButton=new Cd(f,t),this.overlayTrackButton.setVisibility(!1);const p=!1!==e.showMultiSelectButton;if(this.multiTrackSelectButton=new ZF(f,t,this,p),this.cursorGuideButton=new YF(f,t),this.centerLineButton=new XF(f,t),this.trackLabelControl=new JF(f,t),this.roiTableControl=new ev(f,t),this.sampleInfoControl=new tv(f,t),this.sampleNameControl=new iv(f,t),!0===e.showSVGButton&&(this.saveImageControl=new sv(f,t)),e.customButtons)for(let i of e.customButtons)new ov(f,t,i);this.zoomWidget=new cv(e,t,u),!1===e.showNavigation&&(this.navigation.style.display="none")}navbarDidResize(){const e=this.currentNavbarButtonClass();"igv-navbar-text-button"===e&&(this.textButtonContainerWidth=this.navbarRightContainer.getBoundingClientRect().width);const t=this.browser,i=t.isMultiLocusWholeGenomeView()||t.referenceFrameList&&Dh.isWholeGenomeView(t.referenceFrameList[0].chr);i?this.windowSizePanel.hide():this.windowSizePanel.show();const{x:r,width:s}=this.navbarLeftContainer.getBoundingClientRect(),o=r+s,{x:n}=this.navbarRightContainer.getBoundingClientRect();let a;if("igv-navbar-text-button"===e&&n-o<8)a="igv-navbar-icon-button";else if(this.textButtonContainerWidth&&"igv-navbar-icon-button"===e){this.navigation.offsetWidth-o-this.textButtonContainerWidth>8&&(a="igv-navbar-text-button")}let c;a&&e!==a&&(this.currentClass=a,this.browser.fireEvent("navbar-resize",[a])),c=i?"igv-zoom-widget-hidden":this.navigation.offsetWidth>860?"igv-zoom-widget":"igv-zoom-widget-900",this.zoomWidget.zoomContainer.className="",this.zoomWidget.zoomContainer.classList.add(c)}updateGenome(e){let t=e.id&&e.id.length<20?e.id:`${e.id.substring(0,8)}...${e.id.substring(e.id.length-8)}`;this.currentGenome.textContent=t,this.currentGenome.setAttribute("title",e.description);!1!==this.config.showChromosomeWidget&&!1!==e.showChromosomeWidget&&e.chromosomeNames&&e.chromosomeNames.length>1?(this.chromosomeSelectWidget.update(e),this.chromosomeSelectWidget.show()):this.chromosomeSelectWidget.hide()}updateLocus(e,t){this.searchInput&&(this.searchInput.value=e),this.chromosomeSelectWidget&&(this.chromosomeSelectWidget.select.value=t)}currentNavbarButtonClass(){return this.currentClass}setEnableTrackSelection(e){this.multiTrackSelectButton.setMultiTrackSelection(e)}getEnableTrackSelection(){return this.multiTrackSelectButton.enableMultiTrackSelection}hide(){this.navigation.style.display="none"}show(){this.navigation.style.display="flex"}async doSearch(e){await this.browser.search(e)||this.browser.alert.present(new Error(`Unrecognized locus: ${e} `))}}const hv=(e,t)=>{const i=0===e?t.nextElementSibling:t.previousElementSibling;t.remove(),i.remove()},dv=e=>{const i=t({class:"igv-column-shim"});hs(i,e);const r=t({class:"igv-column"});return hs(r,i),r},uv=(e,i)=>{for(let r=0;r1&&r>0){ls(t({class:"igv-column-shim"}),s)}}};class fv{constructor(e,i,r){this.browser=e,this.referenceFrame=i,this.column=r,this.container=t({class:"igv-center-line"}),r.appendChild(this.container),e.doShowCenterLine?this.show():this.hide()}repaint(){if(this.referenceFrame){if(1/this.referenceFrame.bpPerPixel>1){const e=Math.floor(this.referenceFrame.toPixels(1));this.container.style.width=`${e}px`,this.container.classList.remove("igv-center-line-thin"),this.container.classList.add("igv-center-line-wide")}else this.container.style.width="1px",this.container.classList.remove("igv-center-line-wide"),this.container.classList.add("igv-center-line-thin")}}show(){this.isVisible=!0,this.container.style.display="block",this.repaint()}hide(){this.isVisible=!1,this.container.style.display="none"}resize(){this.repaint()}}const pv=function(e,i){this.button=t({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.textContent="circular view",this.button.addEventListener("click",(()=>{i.circularViewVisible=!i.circularViewVisible})),this.browser=i,this.setVisibility(i.config.showCircularViewButton),this.setState(i.circularViewVisible)};pv.prototype.setVisibility=function(e){!0===e?this.show():this.hide()},pv.prototype.setState=function(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")},pv.prototype.show=function(){this.button.style.display="block",this.setState(this.browser.circularViewVisible)},pv.prototype.hide=function(){this.button.style.display="none"};class gv{constructor(e,i){this.browser=e,this.container=t({class:"igv-roi-menu"}),i.appendChild(this.container);const r=t();this.container.appendChild(r),u(r,(()=>this.container.style.display="none")),this.body=t(),this.container.appendChild(this.body),this.container.style.display="none"}async present(e,t,i,r,s,o){const n=this.menuItems(e,t,i,r,s,o);this.browser.menuPopup.presentTrackContextMenu(i,n)}menuItems(e,t,i,r,s,o){const n=e.name?[`${e.name}
`]:[];return"name"in t&&n.push(`ROI Set: ${t.name}`),n.length>0&&n.push("
"),t.isUserDefined&&this.#I(n,e,i),ds()&&e.end-e.start<1e6&&this.#S(n,e),e.end-e.start<=25e3&&this.#E(n,e),this.#N(n,e),t.isUserDefined&&this.#M(n,e,t,r,s,o),n}#M(e,t,i,r,s,o){e.push("
"),e.push({label:"Delete",click:async()=>{i.removeFeature(t);const e=await i.getAllFeatures();0===Object.keys(e).length&&r.deleteUserDefinedROISet(),r.deleteRegionWithKey(o.dataset.region,s),r.repaintTable()}})}#S(e,t){e.push({label:"Copy reference sequence",click:async()=>{this.container.style.display="none";let e=await this.browser.genome.getSequence(t.chr,t.start,t.end);e||(e="Unknown sequence");try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(void 0,`Failed to copy the sequence to the clipboard. (${e.message})`)}}})}#I(e,t,i){e.push({label:"Set description ...",click:()=>{const e={label:"Description",value:t.name||"",callback:()=>{const e=this.browser.inputDialog.value||"";t.name=e.trim(),this.browser.roiManager.repaintTable()}};this.browser.inputDialog.present(e,i)}})}#N(e,t){const i=this.browser.findTracks((e=>"function"==typeof e.sortByValue));if(i.length>0){e.push("
");const{chr:r,start:s,end:o}=t;e.push({label:"Sort by value (ascending)",click:()=>Promise.all(i.map((e=>e.sortByValue({option:"VALUE",direction:"ASC",chr:r,start:s,end:o}))))}),e.push('
'),e.push({label:"Sort by value (descending)",click:()=>Promise.all(i.map((e=>e.sortByValue({option:"VALUE",direction:"DESC",chr:r,start:s,end:o}))))})}}#E(e,t){e.push({label:"BLAT reference sequence",click:async()=>{this.container.style.display="none";const{chr:e,start:i,end:r}=t;let s=await this.browser.genome.getSequence(e,i,r);if(s){const t=`blat: ${e}:${i+1}-${r}`,o=`blat: ${e}:${i+1}-${r}`;Yl({sequence:s,browser:this.browser,name:t,title:o})}}})}dispose(){this.container.innerHTML=""}}class mv extends jl{constructor(e){const t={browser:e,parent:e.columnContainer,headerTitle:"Regions of Interest",dismissHandler:()=>e.roiTableControl.buttonHandler(!1),gotoButtonHandler:mv.gotoButtonHandler};t.columnFormat=mv.getColumnFormatConfiguration(!0),super(Object.assign({width:"640px"},t))}tableRowDOM(e){const i=t({class:"igv-roi-table-row"}),{setName:r,feature:s}=e;i.dataset.region=vv(s.chr,s.start,s.end);let o=[s.chr,F(s.start),F(s.end),s.name||"",r];4===this.columnFormat.length&&(o=o.slice(0,4));for(let e=0;ee.remove())),e.length>0){const t=e.sort(((e,t)=>e.feature.chr.localeCompare(t.feature.chr)||e.feature.start-t.feature.start||e.feature.end-t.feature.end));for(let e of t){const t=this.tableRowDOM(e);this.tableRowContainer.appendChild(t)}}}set footerDOM(e){super.footerDOM=e,this.gotoButton.textContent="Go to selected region(s)";const i=t({class:"igv-roi-table-button"});this._footerDOM.appendChild(i),i.id="igv-roi-hide-show-button",i.textContent="Copy Sequence",i.title="One region only of max size 1 mb",this.copySequenceButton=i,wv(this.copySequenceButton,!1),this.boundCopySequenceButtonHandler=async function(e){e.preventDefault(),e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected");if(t.length>0){const e=[];for(let i of t){const{locus:t}=Av(i.dataset.region);e.push(t)}for(let e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");if(this.setTableRowSelectionState(!1),e.length>0){const{chr:t,start:i,end:r}=AF(e[0],this.browser.isSoftclipped()),s=await this.browser.genome.getSequence(t,i,r);await navigator.clipboard.writeText(s)}}}.bind(this),this.copySequenceButton.addEventListener("click",this.boundCopySequenceButtonHandler);const r=t({class:"igv-roi-table-button"});this._footerDOM.appendChild(r),r.id="igv-roi-hide-show-button",r.textContent="Hide Overlays",this.toggleROIButton=r,this.boundToggleDisplayButtonHandler=function(e){e.preventDefault(),e.stopPropagation(),this.roiManager.toggleROIs()}.bind(this),this.toggleROIButton.addEventListener("click",this.boundToggleDisplayButtonHandler)}get roiManager(){return this.browser.roiManager}setTableRowSelectionState(e){super.setTableRowSelectionState(e);const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected");if(t.length>0&&t.length<2){const{locus:e}=Av(t[0].dataset.region),{chr:i,start:r,end:s}=AF(e,this.browser.isSoftclipped());wv(this.copySequenceButton,s-r<1e6)}else wv(this.copySequenceButton,!1)}dispose(){document.removeEventListener("click",this.boundGotoButtonHandler),document.removeEventListener("click",this.boundCopySequenceButtonHandler),document.removeEventListener("click",this.boundToggleDisplayButtonHandler),this.browser.roiTableControl.buttonHandler(!1),super.dispose()}static getColumnFormatConfiguration(e){return!0===e?[{label:"Chr",width:"20%"},{label:"Start",width:"15%"},{label:"End",width:"15%"},{label:"Description",width:"30%"},{label:"ROI Set",width:"20%"}]:[{label:"Chr",width:"25%"},{label:"Start",width:"20%"},{label:"End",width:"20%"},{label:"Description",width:"35%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(let e of t){const{locus:t}=Av(e.dataset.region);i.push(t)}for(let e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),i.length>0&&this.browser.search(i.join(" "))}}function wv(e,t){e.style.pointerEvents=t?"auto":"none",e.style.color=Gr(t?"licorice":"silver"),e.style.borderColor=Gr(t?"licorice":"silver")}class bv{constructor(e){this.browser=e,this.roiMenu=new gv(e,e.columnContainer),this.roiTable=new mv(e,e.columnContainer),this.top=0,this.roiSets=[],this.showOverlays=!0,this.boundLocusChangeHandler=Fv.bind(this),e.on("locuschange",this.boundLocusChangeHandler)}async reset(){this.roiSets.length>0&&this.browser.roiTableControl.setVisibility(!0);const e=this.roiSets.map((e=>this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:e})));e.length>0&&await Promise.all(e);const t=await this.getTableRecords();this.roiTable.renderTable(t),this.roiSets.length>0&&this.setOverlayVisibility(this.showOverlays)}setOverlayVisibility(e){const t=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let i=0;i0&&!1===i[0].isVisible&&(this.showOverlays=!1);for(let e of i)!e.name&&e.url&&(e.name=await os(e.url)),e.url&&!e.format&&(e.format=await bf(e)),this.roiSets.push(new Qh(e,t));await this.reset()}clearROIs(){this.roiTable.clearTable();const e=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let t of e)t.remove();for(let e of this.roiSets)e.dispose();this.roiSets=[]}async getTableRecords(){const e=[];for(let t of this.roiSets){const i=t.name||"",r=await t.getAllFeatures();for(let t of Object.keys(r))for(let s of r[t])e.push({setName:i,feature:s})}return e}presentTable(){this.roiTable.present()}async repaintTable(){const e=await this.getTableRecords();this.roiTable.renderTable(e)}dismissTable(){this.roiTable.dismiss()}roiTableIsVisible(){return this.roiTable.isVisible()}async updateUserDefinedROISet(e){let t=await this.getUserDefinedROISet();void 0===t&&(t=this.initializeUserDefinedROISet()),t.addFeature(e),this.setROITableButtonVisibility(!0),await this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:t});const i=await this.getTableRecords();this.roiTable.renderTable(i)}setROITableButtonVisibility(e){this.browser.roiTableControl.setVisibility(e)}toggleROIs(){this.showOverlays=!this.showOverlays,this.setOverlayVisibility(this.showOverlays)}async renderAllROISets(){for(let e of this.roiSets)await this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:e})}async renderROISet({browser:e,pixelTop:t,roiSet:i}){const r=e.columnContainer.querySelectorAll(".igv-column");for(let s=0;sa)&&e.remove()}const h=await i.getFeatures(o,n,a);if(h)for(let l of h){const h=vv(o,l.start,l.end),{x:d,width:u}=Gh(Math.max(n,l.start),Math.min(a,l.end),n,c),f=r[s].querySelector(yv(h));if(f)f.style.left=`${d}px`,f.style.width=`${u}px`;else{const o=this.createRegionElement(e.columnContainer,t,d,u,i,h,l);r[s].appendChild(o)}}}}createRegionElement(e,i,r,s,o,n,c){const l=t({class:"igv-roi-region"});l.style.top=`${i}px`,l.style.left=`${r}px`,l.style.width=`${s}px`;const h=`${this.getROIRegionTopMargin()}px`;l.style.marginTop=h,l.dataset.color=o.color,l.dataset.region=n,this.showOverlays?l.style.backgroundColor=o.color:l.style.backgroundColor="rgba(0, 0, 0, 0)";const d=t();return l.appendChild(d),d.style.backgroundColor=o.headerColor,d.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation(),a(t,e),this.roiMenu.present(c,o,t,this,e,l)})),l}updateROIRegionPositions(){const e=`${this.getROIRegionTopMargin()}px`,t=this.browser.columnContainer.querySelectorAll(".igv-column");for(let i=0;inew Set(["ideogram","ruler"]).has(e.type))),[t,i]=e.map((e=>e.trackView.viewports[0].viewportElement)).map((e=>function(e){const t=window.getComputedStyle(e),i=parseInt(t.marginTop),r=parseInt(t.marginBottom),{top:s,bottom:o,height:n}=e.getBoundingClientRect();return{top:Math.floor(s)-i,bottom:Math.floor(o)+r,height:Math.floor(n)+i+r}}(e)));return(t?t.height:0)+(i?i.height:0)+-.5}renderSVGContext(e,t,{deltaX:i,deltaY:r}){for(const s of e.querySelectorAll(".igv-roi-region")){const{x:e,y:o,width:n,height:a}=s.getBoundingClientRect();t.fillStyle=s.style.backgroundColor,t.fillRect(e-i,o+r,n,a);const c=s.querySelector("div"),{x:l,y:h,width:d,height:u}=c.getBoundingClientRect();t.fillStyle=c.style.backgroundColor,t.fillRect(l-i,h+r,d,u)}}getUserDefinedROISet(){return this.roiSets.find((e=>!0===e.isUserDefined))}deleteUserDefinedROISet(){this.roiSets=this.roiSets.filter((e=>!0!==e.isUserDefined))}initializeUserDefinedROISet(){const e=new Qh({name:"user defined",isUserDefined:!0,features:[]},this.browser.genome);return this.roiSets.push(e),e}async deleteRegionWithKey(e,t){t.querySelectorAll(yv(e)).forEach((e=>e.remove()));0===(await this.getTableRecords()).length&&(this.browser.roiTableControl.buttonHandler(!1),this.setROITableButtonVisibility(!1))}toJSON(){return this.roiSets.map((e=>e.toJSON()))}dispose(){this.browser.off("locuschange",this.boundLocusChangeHandler);const e=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let t of e)t.remove();this.roiMenu&&this.roiMenu.dispose(),this.roiTable&&this.roiTable.dispose();for(let e of this.roiSets)e.dispose();for(let e of Object.keys(this))this[e]=void 0}}function Fv(){this.renderAllROISets()}function vv(e,t,i){return`${e}-${t}-${i}`}function yv(e){return`[data-region="${e}"]`}function Av(e){let t=e.split("-"),i=parseInt(t.pop()),r=parseInt(t.pop()),s=t.join("-");return{chr:s,start:r,end:i,locus:`${s}:${r}-${i}`,bedRecord:`${s}\t${r}\t${i}`}}class Cv{constructor(e,t){this.name=e.name,this.featureSource=e.featureSource||El(e,t),this.color=e.color||qh}async getFeatures(e,t,i){return this.featureSource.getFeatures({chr:e,start:t,end:i})}draw(e){const{context:t,bpPerPixel:i,bpStart:r,pixelTop:s,pixelHeight:o,pixelWidth:n,features:a}=e;if(!a)return;const c=r+n*i+1;for(let{start:e,end:n}of a){if(nc)break;const{x:a,width:l}=Gh(e,n,r,i);Co.fillRect(t,a,s,l,o,{fillStyle:this.color})}}}class _v{constructor(e){this.config=e,this.url=e.path||e.url}async read(e,t){const i={start:e,size:t};return Rr.loadArrayBuffer(this.url,{range:i})}}class xv{constructor(e){this.file=e}async read(e,t){const i=this.file;return void 0!==e?i.slice(e,e+t).arrayBuffer():i.arrayBuffer()}}class kv{constructor(e,t){this.file=e,this.rateLimiter=t}async read(e,t){const i=this.file,r=this.rateLimiter;return new Promise((function(s,o){r.limiter((async function(i){try{const r=await i.read(e,t);s(r)}catch(e){o(e)}}))(i)}))}}class Iv{constructor(e){this.file=e.file,this.size=e.size||64e3,this.position=0,this.bufferStart=0,this.bufferLength=0,this.buffer=void 0}async read(e,t){const i=e,r=e+t,s=this.bufferStart,o=this.bufferStart+this.bufferLength;if(t>this.size)return this.buffer=void 0,this.bufferStart=0,this.bufferLength=0,this.file.read(e,t);if(i>=s&&r<=o){const e=i-s,r=e+t;return this.buffer.slice(e,r)}if(is){const r=s-i,o=await this.file.read(e,r),n=t-r;if(n>0){const e=this.buffer.slice(0,n);return Sv(o,e)}return o}if(!(io))return this.buffer=await this.file.read(e,this.size),this.bufferStart=e,this.bufferLength=this.buffer.byteLength,this.buffer.slice(0,t);{const e=o-i,r=this.bufferLength-e,s=this.buffer.slice(r,this.bufferLength),n=t-e;if(!(n>0))return s;try{this.buffer=await this.file.read(o,this.size),this.bufferStart=o,this.bufferLength=this.buffer.byteLength;const e=this.buffer.slice(0,n);return Sv(s,e)}catch(e){if(e.code&&416===e.code)return s;throw e}}}}var Sv=function(e,t){var i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer};const Ev=function(e,t){this.littleEndian=void 0===t||t,this.position=0,this.view=e,this.length=e.byteLength};function Nv(e,t){this.block=e,this.offset=t}Ev.prototype.available=function(){return this.length-this.position},Ev.prototype.remLength=function(){return this.length-this.position},Ev.prototype.hasNext=function(){return this.position=0;i--)t=256*t+e[i];else for(i=0;i0&&(r+=String.fromCharCode(i));return r},Ev.prototype.getFixedLengthTrimmedString=function(e){var t,i,r="";for(t=0;t32&&(r+=String.fromCharCode(i));return r},Ev.prototype.getFloat=function(){var e=this.view.getFloat32(this.position,this.littleEndian);return this.position+=4,e},Ev.prototype.getDouble=function(){var e=this.view.getFloat64(this.position,this.littleEndian);return this.position+=8,e},Ev.prototype.skip=function(e){return this.position+=e,this.position},Ev.prototype.getVPointer=function(){var e=this.position,t=this.view.getUint8(e+1)<<8|this.view.getUint8(e),i=4294967296*(255&this.view.getUint8(e+6))+16777216*(255&this.view.getUint8(e+5))+65536*(255&this.view.getUint8(e+4))+256*(255&this.view.getUint8(e+3))+(255&this.view.getUint8(e+2));return this.position+=8,new Nv(i,t)},Nv.prototype.isLessThan=function(e){return this.blocke.block||this.block===e.block&&this.offset>e.offset},Nv.prototype.print=function(){return this.block+":"+this.offset};class Mv{constructor(e,t){this.chr1=e,this.chr2=t}getKey(){return this.chr1.name+"_"+this.chr2.name+"_"+this.zoom.unit+"_"+this.zoom.binSize}getBlockNumbers(e,t,i){if(e.chr==this.chr2&&t.chr===this.chr1){const i=e;e=t,t=i}const r=this.chr1===this.chr2,s=this.zoom.binSize,o=this.blockBinCount,n=this.blockColumnCount;return i<9||!r?function(){const i=e.start/s,a=e.end/s,c=t.start/s,l=t.end/s,h=Math.floor(i/o),d=Math.floor((a-1)/o),u=Math.floor(c/o),f=Math.floor((l-1)/o),p=[];for(let e=u;e<=f;e++)for(let t=h;t<=d;t++){let i;i=r&&e0;){const e=t.getInt(),i=t.getLong(),r=t.getInt();this.blockIndex[e]={filePosition:i,size:r}}}getBlockIndexEntry(e){return this.blockIndex[e]}}class Bv{constructor(e,t,i){this.chr1=e,this.chr2=t,this.bpZoomData=[],this.fragZoomData=[];for(let e of i)"BP"===e.zoom.unit?this.bpZoomData.push(e):this.fragZoomData.push(e)}findZoomForResolution(e,t){const i="FRAG"===t?this.fragZoomData:this.bpZoomData;for(let t=1;tt){const i=e;e=t,t=i}return`${e}_${t}`}static parseMatrix(e,t){const i=new Ev(new DataView(e)),r=i.getInt(),s=i.getInt(),o=t[r],n=t[s];let a=i.getInt();const c=[];for(;a-- >0;){const e=Mv.parseMatrixZoomData(o,n,i);c.push(e)}return new Bv(r,s,c)}}class Dv{constructor(e,t,i){this.bin1=e,this.bin2=t,this.counts=i}getKey(){return this.bin1+"_"+this.bin2}}class Lv{constructor(e=10){this.max=e,this.map=new Map}get(e){let t=this.map.get(e);return t&&(this.map.delete(e),this.map.set(e,t)),t}set(e,t){this.map.has(e)?this.map.delete(e):this.map.size===this.max&&this.map.delete(this.first()),this.map.set(e,t)}has(e){return this.map.has(e)}clear(){this.map.clear()}first(){return this.map.keys().next().value}}class Tv{constructor(e,t,i,r){this.file=e,this.filePosition=t,this.nValues=i,this.dataType=r,this.cache=void 0}async getValues(e,t){if(!this.cache||ethis.cache.end){const i=Math.max(0,e-1e3),r=Math.min(this.nValues,t+1e3),s=this.filePosition+i*this.dataType,o=r-i,n=o*this.dataType,a=await this.file.read(s,n);if(!a)return;const c=new Ev(new DataView(a)),l=[];for(let e=0;e=0||t.indexOf("www.googleapis.com/drive")>0?this.file=new kv(i,Hv):this.file=i}}var t}async init(){this.initialized||(await this.readHeaderAndFooter(),this.initialized=!0)}async getVersion(){if(void 0===this.version){const e=await this.file.read(0,128);if(!e)return;const t=new Ev(new DataView(e));return this.magic=t.getString(),this.version=t.getInt(),this.version}return this.version}async getMetaData(){return await this.init(),this.meta}async readHeaderAndFooter(){let e=await this.file.read(0,16);if(!e||0===e.byteLength)throw Error("File content is empty");let t=new Ev(new DataView(e));if(this.magic=t.getString(),this.version=t.getInt(),this.version<5)throw Error("Unsupported hic version: "+this.version);this.footerPosition=t.getLong(),await this.readFooter();const i=Object.values(this.masterIndex).reduce(((e,t)=>Math.min(e,t.start)),Number.MAX_VALUE),r=i-16;e=await this.file.read(16,r),t=new Ev(new DataView(e)),this.genomeId=t.getString(),this.version>=9&&(this.normVectorIndexPosition=t.getLong(),this.normVectorIndexSize=t.getLong()),this.attributes={};let s=t.getInt();for(;s-- >0;)this.attributes[t.getString()]=t.getString();this.chromosomes=[],this.chromosomeIndexMap={};let o=t.getInt(),n=0;for(;o-- >0;){const e={index:n,name:t.getString(),size:this.version<9?t.getInt():t.getLong()};"all"===e.name.toLowerCase()&&(this.wholeGenomeChromosome=e,this.wholeGenomeResolution=Math.round(2*e.size)),this.chromosomes.push(e),this.chromosomeIndexMap[e.name]=e.index,n++}this.bpResolutions=[];let a=t.getInt();for(;a-- >0;)this.bpResolutions.push(t.getInt());if(this.loadFragData){this.fragResolutions=[];let e=t.getInt();if(e>0)for(;e-- >0;)this.fragResolutions.push(t.getInt())}this.chrAliasTable={};for(let e of Object.keys(this.chromosomeIndexMap))e.startsWith("chr")?this.chrAliasTable[e.substr(3)]=e:"MT"===e?this.chrAliasTable.chrM=e:this.chrAliasTable["chr"+e]=e;this.meta={version:this.version,genome:this.genomeId,chromosomes:this.chromosomes,resolutions:this.bpResolutions}}async readFooter(){const e=this.version<9?8:12;let t=await this.file.read(this.footerPosition,e);if(!t)return null;let i=new Ev(new DataView(t));const r=this.version<9?i.getInt():i.getLong();let s=i.getInt();const o=196*s;for(t=await this.file.read(this.footerPosition+e,Math.min(o,r)),i=new Ev(new DataView(t)),this.masterIndex={};s-- >0;){const e=i.getString(),t=i.getLong(),r=i.getInt();this.masterIndex[e]={start:t,size:r}}if(this.expectedValueVectors={},this.version>5){const e=this.version<9?4:8;this.normExpectedValueVectorsPosition=this.footerPosition+e+r}return this}async printIndexStats(){let e,t=0,i=0;await await this.init();for(let r of Object.keys(this.masterIndex)){const s=this.masterIndex[r];t+=s.size,s.size>i&&(i=s.size,e=r)}console.log(`${i} ${e} ${this.config.url}`)}async getMatrix(e,t){const i=Bv.getKey(e,t);if(this.matrixCache.has(i))return this.matrixCache.get(i);{const r=await this.readMatrix(e,t);return this.matrixCache.set(i,r),r}}async readMatrix(e,t){if(await this.init(),e>t){const i=e;e=t,t=i}const i=Bv.getKey(e,t),r=this.masterIndex[i];if(!r)return;const s=await this.file.read(r.start,r.size);return s?Bv.parseMatrix(s,this.chromosomes):void 0}async getContactRecords(e,t,i,r,s,o=!1){await this.init();const n=this.chromosomeIndexMap[this.getFileChrName(t.chr)],a=this.chromosomeIndexMap[this.getFileChrName(i.chr)];if(n>a||n===a&&t.start>=i.end){const e=t;t=i,i=e}const c=await this.getBlocks(t,i,r,s);if(!c||0===c.length)return[];const l=[],h=t.start/s,d=t.end/s,u=i.start/s,f=i.end/s,p=Math.floor(h),g=Math.ceil(d),m=Math.floor(u),w=Math.ceil(f);for(let n of c)if(n){let a,c,b=e&&"NONE"!==e;const F=this.getFileChrName(t.chr),v=this.getFileChrName(i.chr);if(b){const t=await this.getNormalizationVector(e,F,r,s),i=F===v?t:await this.getNormalizationVector(e,v,r,s);t&&i?(a=await t.getValues(p,g),c=await i.getValues(m,w)):b=!1}for(let e of n.records)if(o||e.bin1>=h&&e.bin1=u&&e.bin210&&(this.percentile95=Qv(n.records,95))}return l}async getBlocks(e,t,i,r){const s=(e,t)=>`${t.getKey()}_${e}`;await this.init();const o=this.getFileChrName(e.chr),n=this.getFileChrName(t.chr),a=this.chromosomeIndexMap[o],c=this.chromosomeIndexMap[n];if(void 0===a)return console.log("No chromosome named: "+e.chr),[];if(void 0===c)return console.log("No chromosome named: "+t.chr),[];const l=await this.getMatrix(a,c);if(!l)return console.log("No matrix for "+e.chr+"-"+t.chr),[];const h=l.getZoomData(r,i);if(!h){let i=`No data avalailble for resolution: ${r} for map ${e.chr}-${t.chr}`;throw new Error(i)}const d=h.getBlockNumbers(e,t,this.version),u=[],f=[];for(let e of d){const t=s(e,h);this.blockCache.has(r,t)?u.push(this.blockCache.get(r,t)):f.push(e)}const p=f.map((e=>this.readBlock(e,h))),g=await Promise.all(p);for(let e of g)e&&this.blockCache.set(r,s(e.blockNumber,h),e);return u.concat(g)}async readBlock(e,t){const i=await t.blockIndex.getBlockIndexEntry(e);if(i){let r=await this.file.read(i.filePosition,i.size);if(!r)return;r=new Zi(new Uint8Array(r)).buffer;const s=new Ev(new DataView(r)),o=s.getInt(),n=[];if(this.version<7)for(let e=0;e0;)this.parseNormVectorEntry(i);return this.normVectorIndex}async readNormExpectedValuesAndNormVectorIndex(){if(await this.init(),void 0===this.normExpectedValueVectorsPosition)return;const e=await this.skipExpectedValues(this.normExpectedValueVectorsPosition);let t=4,i=await this.file.read(e,4);if(0===i.byteLength)return;const r=new Ev(new DataView(i)).getInt(),s={start:e+t,size:30*r};i=await this.file.read(s.start,s.size),this.normalizedExpectedValueVectors={},this.normVectorIndex={},await async function i(r,s){const o=new Ev(new DataView(s));for(;r-- >0;){if(o.available()<100){r++,t+=o.position;const s=Math.max(1e3,30*r),n={start:e+t,size:s},a=await this.file.read(n.start,n.size);return i.call(this,r,a)}this.parseNormVectorEntry(o)}t+=o.position}.call(this,r,i),this.config.nvi=e.toString()+","+t}async skipExpectedValues(e){const t=this.version,i=new Iv({file:this.file,size:256e3}),r={start:e,size:4},s=await i.read(r.start,r.size),o=new Ev(new DataView(s)).getInt();return 0===o?e+4:async function e(r,s){let o={start:r,size:500},n=0,a=r,c=await i.read(o.start,o.size),l=new Ev(new DataView(c));l.getString(),l.getString(),l.getInt();const h=t<9?l.getInt():l.getLong();n+=l.position+h*(t<9?8:4),o={start:r+n,size:4},c=await i.read(o.start,o.size),l=new Ev(new DataView(c));const d=l.getInt();return n+=4+d*(4+(t<9?8:4)),s--,0===s?a+n:e(a+n,s)}(e+4,o)}getZoomIndexForBinSize(e,t){let i;if("BP"===(t=t||"BP"))i=this.bpResolutions;else{if("FRAG"!==t)throw new Error("Invalid unit: "+t);i=this.fragResolutions}for(let t=0;te.counts));i.sort((function(e,t){return e-t}));return i[Math.floor(t/100*e.length)]}class Gv{aliasRecordCache=new Map;constructor(e,t){this.genomeID=e,this.update(e,t)}async preload(){}getChromosomeName(e){return this.aliasRecordCache.has(e)?this.aliasRecordCache.get(e).chr:e}getChromosomeAlias(e,t){const i=this.aliasRecordCache.get(e);return i&&i[t]||e}update(e,t){if(t){const i=[];for(let r of t){if(this.aliasRecordCache.has(r))continue;const t={chr:r};if(i.push(t),r.startsWith("gi|")){const e=Gv.getNCBIName(r);t["ncbi-gi-versioned"]=e;const i=e.lastIndexOf(".");if(i>0){const e=e.substring(0,i);t["ncbi-gi"]=e}}else if("chrM"===r?t.ncbi="MT":"MT"===r?t.ucsc="chrM":r.toLowerCase().startsWith("chr")&&Number.isInteger(Number(r.substring(3)))?t.ncbi=r.substring(3):Number.isInteger(Number(r))&&(t.ucsc="chr"+r),e.startsWith("hg")||e.startsWith("GRCh")||"1kg_ref"===e||"b37"===e)switch(r){case"23":t.ucsc="chrX",t.assembly="X";break;case"24":t.ucsc="chrY",t.assembly="Y";break;case"chrX":t.ncbi="23",t.assembly="X";break;case"chrY":t.ncbi="24",t.assembly="Y";break;case"X":t.ucsc="chrX",t.ncbi="23";break;case"Y":t.ucsc="chrY",t.ncbi="24"}else if(e.startsWith("mm")||e.startsWith("GRCm")||e.startsWith("rheMac"))switch(r){case"21":t.ucsc="chrX",t.assembly="X";break;case"22":t.ucsc="chrY",t.assembly="Y";break;case"chrX":t.ncbi="21",t.assembly="X";break;case"chrY":t.ncbi="22",t.assembly="Y";break;case"X":t.ucsc="chrX",t.ncbi="21";break;case"Y":t.ucsc="chrY",t.ncbi="22"}}for(let e of i){Gv.addCaseAliases(e);for(let t of Object.values(e))this.aliasRecordCache.set(t,e)}}}search(e){return this.aliasRecordCache.get(e)}static getNCBIName(e){const t=e.split("\\|");return t[t.length-1]}static addCaseAliases(e){const t=e.chr.toUpperCase(),i=e.chr.toLowerCase(),r=e.chr.charAt(0).toUpperCase()+e.chr.slice(1);e.chr!==t&&(e._uppercase=t),e.chr!==i&&(e._lowercase=i),e.chr!==r&&(e._cap=r);const s=e.chr.startsWith("chr")?e.chr.substring(3):"chr"+e.chr;e._chrprefix_=s}}class jv{aliasRecordCache=new Map;constructor(e,t,i){(t=t||{}).url=e,this.reader=new Nc(t,i)}async preload(e){await this.reader.preload();for(let t of e)await this.search(t)}getChromosomeName(e){return this.aliasRecordCache.has(e)?this.aliasRecordCache.get(e).chr:e}getChromosomeAlias(e,t){const i=this.aliasRecordCache.get(e);return i&&i[t]||e}async search(e){if(!this.aliasRecordCache.has(e)){const t=await this.reader.search(e);if(t){Gv.addCaseAliases(t);for(let e of Object.keys(t))"start"!==e&&"end"!==e&&this.aliasRecordCache.set(t[e],t)}}return this.aliasRecordCache.get(e)}}class Wv{aliasRecordCache=new Map;constructor(e,t,i){this.aliasURL=e,this.config=t,this.genome=i}async preload(e){}getChromosomeName(e){return this.aliasRecordCache.has(e)?this.aliasRecordCache.get(e).chr:e}getChromosomeAlias(e,t){const i=this.aliasRecordCache.get(e);return i&&i[t]||e}async loadAliases(){const e=await Rr.loadString(this.aliasURL,ts(this.config)),t=v(e),i=t[0];i.startsWith("#")&&(this.headings=i.substring(1).split("\t").map((e=>e.trim())),this.altNameSets=this.headings.slice(1));const r=this.genome.chromosomeNames?new Set(this.genome.chromosomeNames):new Set;for(let e of t)if(!e.startsWith("#")&&e.length>0){const t=e.split("\t");let i=t.find((e=>r.has(e)));i||(i=t[0]);const s={chr:i};Gv.addCaseAliases(s);for(let e=0;enew $v(e.start,e.end,e.name,e.gieStain)))}}class Zv{cytobands=new Map;constructor(e,t){this.url=e,this.config=t}async getCytobands(e){return 0===this.cytobands.size&&await this.#B(),this.cytobands.get(e)}async#B(){let e,t;if(as(this.url)){const t=nr(this.url);e="";const i=t.length;for(let r=0;r0&&this.cytobands.set(t,i)}}function Yv(e){if(!function(e){return t=e.fastaURL,(t&&"string"==typeof t||t instanceof String)&&(e.fastaURL.startsWith("https://igv.org")||["igv.org.genomes","igv.broadinstitute.org","igv.genepattern.org","igvdata.broadinstitute.org","igv-genepattern-org"].some((t=>e.fastaURL.includes(t))));var t}(e)||!Xv[e.id])return;const t=Xv[e.id];t&&(delete e.fastaURL,e.indexURL&&delete e.indexURL,e.twoBitURL=t.twoBitURL,t.twoBitBptURL&&(e.twoBitBptURL=t.twoBitBptURL),t.chromSizesURL&&(e.chromSizesURL=t.chromSizesURL))}const Xv={hs1:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.chrom.sizes.txt"},hg38:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.chrom.sizes"},hg19:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.chrom.sizes"},hg18:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg18/bigZips/hg18.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg18/bigZips/hg18.chrom.sizes"},mm39:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm39/bigZips/mm39.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm39/bigZips/mm39.chrom.sizes"},mm10:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm10/bigZips/mm10.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm10/bigZips/mm10.chrom.sizes"},mm9:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm9/bigZips/mm9.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm9/bigZips/mm9.chrom.sizes"},rn7:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/015/227/675/GCF_015227675.2/GCF_015227675.2.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/015/227/675/GCF_015227675.2/GCF_015227675.2.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/015/227/675/GCF_015227675.2/GCF_015227675.2.chrom.sizes.txt"},rn6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/895/GCF_000001895.5/GCF_000001895.5.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/895/GCF_000001895.5/GCF_000001895.5.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/895/GCF_000001895.5/GCF_000001895.5.chrom.sizes.txt"},gorGor6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor6/bigZips/gorGor6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor6/bigZips/gorGor6.chrom.sizes"},gorGor4:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor4/bigZips/gorGor4.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor4/bigZips/gorGor4.chrom.sizes"},panTro6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro6/bigZips/panTro6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro6/bigZips/panTro6.chrom.sizes"},panTro5:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro5/bigZips/panTro5.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro5/bigZips/panTro5.chrom.sizes"},panTro4:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro4/bigZips/panTro4.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro4/bigZips/panTro4.chrom.sizes"},macFas5:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/macFas5/bigZips/macFas5.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/macFas5/bigZips/macFas5.chrom.sizes"},panPan2:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panPan2/bigZips/panPan2.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panPan2/bigZips/panPan2.chrom.sizes"},canFam6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam6/bigZips/canFam6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam6/bigZips/canFam6.chrom.sizes"},canFam5:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam5/bigZips/canFam5.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam5/bigZips/canFam5.chrom.sizes"},canFam4:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam4/bigZips/canFam4.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam4/bigZips/canFam4.chrom.sizes"},canFam3:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam3/bigZips/canFam3.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam3/bigZips/canFam3.chrom.sizes"},bosTau9:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau9/bigZips/bosTau9.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau9/bigZips/bosTau9.chrom.sizes"},bosTau8:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau8/bigZips/bosTau8.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau8/bigZips/bosTau8.chrom.sizes"},susScr11:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/susScr11/bigZips/susScr11.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/susScr11/bigZips/susScr11.chrom.sizes"},galGal6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/galGal6/bigZips/galGal6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/galGal6/bigZips/galGal6.chrom.sizes"},danRer11:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer11/bigZips/danRer11.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer11/bigZips/danRer11.chrom.sizes"},danRer10:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer10/bigZips/danRer10.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer10/bigZips/danRer10.chrom.sizes"},ce11:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/ce11/bigZips/ce11.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/ce11/bigZips/ce11.chrom.sizes"},dm6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm6/bigZips/dm6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm6/bigZips/dm6.chrom.sizes"},dm3:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm3/bigZips/dm3.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm3/bigZips/dm3.chrom.sizes"},sacCer3:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/146/045/GCF_000146045.2/GCF_000146045.2.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/146/045/GCF_000146045.2/GCF_000146045.2.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/146/045/GCF_000146045.2/GCF_000146045.2.chrom.sizes.txt"},"GCF_000002945.1":{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/002/945/GCF_000002945.1/GCF_000002945.1.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/002/945/GCF_000002945.1/GCF_000002945.1.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/002/945/GCF_000002945.1/GCF_000002945.1.chrom.sizes.txt"},"GCF_009858895.2":{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/009/858/895/GCF_009858895.2/GCF_009858895.2.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/009/858/895/GCF_009858895.2/GCF_009858895.2.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/009/858/895/GCF_009858895.2/GCF_009858895.2.chrom.sizes.txt"},tair10:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/735/GCF_000001735.3/GCF_000001735.3.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/735/GCF_000001735.3/GCF_000001735.3.chrom.sizes.txt"},"GCA_000022165.1":{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCA/000/022/165/GCA_000022165.1/GCA_000022165.1.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCA/000/022/165/GCA_000022165.1/GCA_000022165.1.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCA/000/022/165/GCA_000022165.1/GCA_000022165.1.chrom.sizes.txt"}},Jv=new Map([["1kg_ref","hg18"],["1kg_v37","hg19"],["b37","hg19"]]);class ey{#D;#L=new Map;static async createGenome(e,t){Yv(e);const i=new ey(e,t);return await i.init(),i}constructor(e,t){this.config=e,this.browser=t,this.id=e.id||function(e){return void 0!==e.id?e.id:e.fastaURL&&b(e.fastaURL)&&!e.fastaURL.startsWith("data:")?e.fastaURL:e.fastaURL&&e.fastaURL.name?e.fastaURL.name:""}(e),this.ucscID=e.ucscID||Jv.get(this.id)||this.id,this.blatDB=e.blatDB||this.ucscID,this.name=e.name,this.nameSet=e.nameSet||"ucsc"}async init(){const e=this.config;if(this.sequence=await Yo(e,this.browser),!1!==e.showIdeogram&&!1!==e.wholeGenomeView&&(e.cytobandURL?this.cytobandSource=new Zv(e.cytobandURL,Object.assign({},e)):e.cytobandBbURL&&(this.cytobandSource=new Kv(e.cytobandBbURL,Object.assign({},e),this))),this.sequence.chromosomes?this.chromosomes=this.sequence.chromosomes:e.chromSizesURL?this.chromosomes=await async function(e){const t=new Map;let i;if(as(e)){let t=nr(e);i="";for(let e of t)i+=String.fromCharCode(e)}else i=await Rr.load(e,{});const r=Oo(i);let s=0;for(let e of r){const i=e.split("\t");if(i.length>1){const e=Number.parseInt(i[1]);t.set(i[0],new No(i[0],s++,e))}}return t}(e.chromSizesURL):this.chromosomes=new Map,this.sequence.chromosomeNames?this.chromosomeNames=this.sequence.chromosomeNames:this.chromosomes.size>0&&(this.chromosomeNames=Array.from(this.chromosomes.keys())),e.chromAliasBbURL?this.chromAlias=new jv(e.chromAliasBbURL,Object.assign({},e),this):e.aliasURL?this.chromAlias=new Wv(e.aliasURL,Object.assign({},e),this):this.chromosomeNames&&(this.chromAlias=new Gv(this.id,this.chromosomeNames)),!1!==e.wholeGenomeView&&this.chromosomes.size>0&&(e.chromosomeOrder?(Array.isArray(e.chromosomeOrder)?this.#D=e.chromosomeOrder:this.#D=e.chromosomeOrder.split(",").map((e=>e.trim())),await this.chromAlias.preload(this.#D),this.#D=this.#D.map((e=>this.getChromosomeName(e))).filter((e=>this.chromosomes.has(e)))):(this.#D=function(e){const t=[];let i,r=1;for(let s of e.values()){if(i){if(s.bpLength1,this.wholeGenomeView){const e=this.#D.reduce(((e,t)=>e+this.chromosomes.get(t).bpLength),0);this.chromosomes.set("all",new No("all",0,e))}}get description(){return this.config.description||`${this.id}\n${this.name}`}get infoURL(){return this.config.infoURL}showWholeGenomeView(){return this.wholeGenomeView}toJSON(){return Object.assign({},this.config,{tracks:void 0})}get initialLocus(){return this.config.locus?this.config.locus:this.getHomeChromosomeName()}getHomeChromosomeName(){return this.showWholeGenomeView()&&this.chromosomes.has("all")?"all":this.chromosomeNames?this.chromosomeNames[0]:void 0}getChromosomeName(e){return this.chromAlias?this.chromAlias.getChromosomeName(e,this.chromosomes.keys()):e}getChromosomeDisplayName(e){return this.nameSet&&this.chromAlias&&this.chromAlias.getChromosomeAlias(e,this.nameSet)||e}getChromosome(e){return this.chromAlias&&(e=this.chromAlias.getChromosomeName(e)),this.chromosomes.get(e)}async loadChromosome(e){const t=await this.getAliasRecord(e);if(t&&(e=t.chr),!this.chromosomes.has(e)){let t;const i=await this.sequence.getSequenceRecord(e);i&&(t=new No(e,0,i.bpLength)),this.chromosomes.set(e,t)}return this.chromosomes.get(e)}async getAliasRecord(e){if(this.#L.has(e))return this.#L.get(e);if(this.chromAlias){let t=await this.chromAlias.search(e);if(t||e===e.toLowerCase()||(t=await this.chromAlias.search(e.toLowerCase())),t){const e=t.chr.toUpperCase(),i=t.chr.toLowerCase(),r=t.chr.charAt(0).toUpperCase()+t.chr.slice(1);t.chr!==e&&(t._uppercase=e),t.chr!==i&&(t._lowercase=i),t.chr!==r&&(t._cap=r)}return this.#L.set(e,t),t}}async getCytobands(e){if(this.cytobandSource){const t=this.getChromosomeName(e);return await this.cytobandSource.getCytobands(t)}}getChromosomes(){return this.chromosomes}get wgChromosomeNames(){return this.#D?this.#D.slice():void 0}get showChromosomeWidget(){return this.config.showChromosomeWidget}getGenomeCoordinate(e,t){var i=this.getCumulativeOffset(e);if(void 0!==i)return i+t}getChromosomeCoordinate(e){let t;void 0===this.cumulativeOffsets&&(this.cumulativeOffsets=computeCumulativeOffsets.call(this));let i=0;for(let r of this.#D){const s=this.cumulativeOffsets[r];if(s>e){return{chr:t,position:e-i}}t=r,i=s}return{chr:this.#D[this.#D.length-1],position:0}}getCumulativeOffset(e){void 0===this.cumulativeOffsets&&(this.cumulativeOffsets=function(){let e={},t=0;for(let i of this.#D){e[i]=Math.floor(t);t+=this.getChromosome(i).bpLength}return e}.call(this));const t=this.getChromosomeName(e);return this.cumulativeOffsets[t]}getGenomeLength(){if(!this.bpLength){let e=0;for(let t of this.#D){e+=this.chromosomes.get(t).bpLength}this.bpLength=e}return this.bpLength}async getSequence(e,t,i){return e=this.getChromosomeName(e),this.sequence.getSequence(e,t,i)}getSequenceInterval(e,t,i){return"function"==typeof this.sequence.getSequenceInterval?this.sequence.getSequenceInterval(e,t,i):void 0}getHubURLs(){return this.config.hubs}}class ty{constructor(){this.clear()}clear(){this.phenotypeColors=new Map,this.snps=new Set,this.qtl=null}isEmpty(){return 0===this.phenotypeColors.size&&0===this.snps.size&&null===this.qtl}addSnp(e){e=e.toUpperCase(),this.snps.add(e)}addPhenotype(e){e=e.toUpperCase();const t=this.phenotypeColors.size;if(!this.phenotypeColors.has(e.toUpperCase())){const i=t0&&(e.phenotypes=Array.from(this.phenotypeColors.keys())),this.snps.size>0&&(e.snps=Array.from(this.snps)),this.qtl&&(e.qtl=this.qtl),e}static fromJSON(e){const t=new ty;if(e.phenotypes)for(let i of e.phenotypes)t.addPhenotype(i);if(e.snps)for(let i of e.snps)t.addSnp(i);return e.qtl&&(t.qtl=e.qtl),t}}const iy=[];iy.push("rgb(228,26,28)"),iy.push("rgb(55,126,184)"),iy.push("rgb(77,175,74)"),iy.push("rgb(166,86,40)"),iy.push("rgb(152,78,163)"),iy.push("rgb(255,127,0)"),iy.push("rgb(247,129,191)"),iy.push("rgb(255,255,51)"),iy.push("rgb(102,194,165)"),iy.push("rgb(252,141,98)"),iy.push("rgb(141, 160, 203)"),iy.push("rgb(231, 138, 195)"),iy.push("rgb(166, 216, 84)"),iy.push("rgb(255, 217, 47)"),iy.push("rgb(229, 196, 148)"),iy.push("rgb( 141, 211, 199)"),iy.push("rgb(255, 255, 179)"),iy.push("rgb(190, 186, 218)"),iy.push("rgb(251, 128, 114)"),iy.push("rgb(128, 177, 211)"),iy.push("rgb(253, 180, 98)"),iy.push("rgb(179, 222, 105)"),iy.push("rgb(252, 205, 229)"),iy.push("rgb(188, 128, 189)"),iy.push("rgb(204, 235, 197)"),iy.push("rgb(255, 237, 111)");class ry{constructor(e,i){this.browser=i,this.columnContainer=e,this.horizontalGuide=t({class:"igv-cursor-guide-horizontal"}),e.appendChild(this.horizontalGuide),this.verticalGuide=t({class:"igv-cursor-guide-vertical"}),e.appendChild(this.verticalGuide),this.addMouseHandler(i),this.setVisibility(i.config.showCursorGuide)}addMouseHandler(e){this.boundMouseMoveHandler=function(t){t.target.tagName;const{x:i,y:r}=a(t,this.columnContainer);if(this.horizontalGuide.style.top=`${r}px`,"CANVAS"===t.target.tagName){const r=function(e,t){for(;e.parentElement;){if(e.parentElement.classList.contains(t))return e.parentElement;e=e.parentElement}return}(t.target,"igv-viewport");if(r&&e.getRulerTrackView()){this.verticalGuide.style.left=`${i}px`;const s=e.root.querySelectorAll(".igv-column");let o;const n=r.parentElement;for(let e=0;e',this._output=document.createRange().createContextualFragment(s).firstChild,this.input_container.appendChild(this._output);const o=t({class:"igv-ui-generic-dialog-ok-cancel"});this.container.appendChild(o),this.ok=t(),o.appendChild(this.ok),this.ok.textContent="OK",this.cancel=t(),o.appendChild(this.cancel),this.cancel.textContent="Cancel",r(this.container),this._input.addEventListener("input",(()=>{const e=parseFloat(this._input.value)/this._scaleFactor;this.callback(e),this._output.value=`${e.toFixed(this._precision)}`}),!1),this.ok.addEventListener("click",(()=>{if("function"==typeof this.callback){const e=parseFloat(this._input.value)/this._scaleFactor;this.callback(e),this.callback=void 0}this._input.value=void 0,r(this.container)}));const n=()=>{this._input.value=void 0,r(this.container)};this.cancel.addEventListener("click",n),u(i,n),p(this.container,i)}get value(){return vo.sanitize(this._input.value)}present(e,t){this.label.textContent=e.label,this._scaleFactor=e.scaleFactor,this._precision=e.precision||2;const[i,r,o]=[e.min,e.max,e.value].map((e=>Math.floor(this._scaleFactor*e).toString()));this._input.min=i,this._input.max=r,this._input.value=o;const n=parseFloat(o)/this._scaleFactor;this._output.value=`${n.toFixed(this._precision)}`,this.callback=e.callback||e.click,s(this.container),this.clampLocation(t.clientX,t.clientY)}clampLocation(e,t){const{width:i,height:r}=this.container.getBoundingClientRect(),s=window.innerHeight,o=window.innerWidth,n=Math.min(s-r,t),a=Math.min(o-i,e);this.container.style.left=`${a}px`,this.container.style.top=`${n}px`}}class oy{qtlSelections=new ty;constructor(e,i){this.config=e,this.guid=n(),this.namespace=".browser_"+this.guid,this.parent=i;let r=i.shadowRoot;if(!r){r=i.attachShadow({mode:"open"});const e=new CSSStyleSheet;e.replaceSync('.igv-ui-dropdown{cursor:default;position:absolute;top:0;left:0;z-index:2048;border-color:#7f7f7f;border-style:solid;border-width:1px;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;background-color:#fff}.igv-ui-dropdown>div{overflow-y:auto;overflow-x:hidden;background-color:#fff}.igv-ui-dropdown>div>div{padding:4px;width:100%;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:1px;background-color:#fff}.igv-ui-dropdown>div>div:last-child{border-bottom-color:rgba(0,0,0,0);border-bottom-width:0}.igv-ui-dropdown>div>div:hover{cursor:pointer;background-color:rgba(0,0,0,.04)}.igv-ui-popover{cursor:default;position:absolute;z-index:2048;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:1px;font-family:"Open Sans",sans-serif;font-size:small;background-color:#fff}.igv-ui-popover>div:first-child{display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;width:100%;height:24px;cursor:move;border-top-width:0;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-popover>div:first-child>div:first-child{margin-left:4px}.igv-ui-popover>div:first-child>div:last-child{margin-right:4px;height:12px;width:12px;color:#7f7f7f}.igv-ui-popover>div:first-child>div:last-child:hover{cursor:pointer;color:#444}.igv-ui-popover>div:last-child{user-select:text;overflow-y:auto;overflow-x:hidden;max-height:400px;max-width:800px;background-color:#fff;border-bottom-width:0;border-bottom-left-radius:5px;border-bottom-right-radius:5px}.igv-ui-popover>div:last-child>div{margin-left:4px;margin-right:4px;min-width:220px;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.igv-ui-popover>div:last-child>div>span{font-weight:bolder}.igv-ui-popover>div:last-child hr{width:100%}.igv-track-label-popover{position:absolute;z-index:2048;border:1px solid #7f7f7f;border-radius:5px;background:#fff;font-family:"Open Sans",sans-serif;font-size:small;min-width:260px;max-width:800px;box-shadow:0 2px 8px rgba(0,0,0,.12);user-select:text}.igv-track-label-popover__header{display:flex;align-items:center;justify-content:space-between;height:24px;background:#eee;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom:1px solid #7f7f7f;padding:0 8px;cursor:move}.igv-track-label-popover__title{font-weight:bold;font-size:1em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.igv-track-label-popover__close{width:14px;height:14px;color:#7f7f7f;display:flex;align-items:center;justify-content:center;border-radius:2px;cursor:pointer;transition:background .2s,color .2s;margin-left:8px}.igv-track-label-popover__close svg{width:14px;height:14px}.igv-track-label-popover__close:hover,.igv-track-label-popover__close:focus{background:#ddd;color:#444;outline:none}.igv-track-label-popover__body{max-height:400px;overflow-y:auto;padding:8px 0;background:#fff;border-bottom-left-radius:5px;border-bottom-right-radius:5px}.igv-track-label-popover__row{display:flex;align-items:baseline;margin:0 12px 4px 12px;min-width:220px;white-space:nowrap;overflow-x:hidden;text-overflow:ellipsis}.igv-track-label-popover__key{font-weight:bold;margin-right:.5em}.igv-track-label-popover__value{font-weight:normal;flex:1 1 auto;overflow-x:hidden;text-overflow:ellipsis}.igv-track-label-popover hr{width:100%;border:none;border-top:1px solid #7f7f7f;margin:8px 0}.igv-ui-alert-dialog-container{position:fixed;top:20%;left:50%;transform:translateX(-50%);z-index:2048;box-sizing:content-box;width:400px;height:200px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;outline:none;font-family:"Open Sans",sans-serif;font-size:15px;font-weight:400;background-color:#fff;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:space-between;align-items:center}.igv-ui-alert-dialog-container>div:first-child{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-alert-dialog-container>div:first-child div:first-child{padding-left:8px}.igv-ui-alert-dialog-container .igv-ui-alert-dialog-body{-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text;color:#373737;width:100%;height:calc(100% - 24px - 64px);overflow-y:scroll}.igv-ui-alert-dialog-container .igv-ui-alert-dialog-body .igv-ui-alert-dialog-body-copy{margin:16px;width:auto;height:auto;overflow-wrap:break-word;word-break:break-word;background-color:#fff;border:unset}.igv-ui-alert-dialog-container>div:last-child{width:100%;margin-bottom:10px;background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-ui-alert-dialog-container>div:last-child div{margin:unset;width:40px;height:30px;line-height:30px;text-align:center;color:#fff;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;border-color:#2b81af;border-style:solid;border-width:thin;border-radius:4px;background-color:#2b81af}.igv-ui-alert-dialog-container>div:last-child div:hover{cursor:pointer;border-color:#25597f;background-color:#25597f}.igv-ui-generic-dialog-container{box-sizing:content-box;position:fixed;top:20%;left:75%;transform:translateX(-50%);z-index:2048;background-color:#fff;cursor:pointer;width:300px;height:fit-content;padding-bottom:16px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-header div:hover{cursor:pointer;color:#444}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-one-liner{color:#373737;width:95%;line-height:24px;text-align:left;margin-top:8px;padding-left:8px;overflow-wrap:break-word;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input{margin-top:8px;width:95%;height:24px;color:#373737;line-height:24px;padding-left:8px;background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input>div{width:fit-content;height:100%;font-size:16px;text-align:right;padding-right:8px;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input input{width:50%;font-size:16px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input{margin-top:8px;width:calc(100% - 16px);height:24px;color:#373737;line-height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input input{font-size:16px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input input[type=range]{width:70%;-webkit-appearance:none;background:linear-gradient(90deg, white, black);outline:none;margin:0}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input output{display:block;height:100%;width:20%;font-size:16px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel{width:100%;height:28px;padding-top:16px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div{color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:first-child{margin-left:32px;margin-right:0;background-color:#5ea4e0}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:last-child{margin-left:0;margin-right:32px;background-color:#c4c4c4}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-ui-generic-container{position:fixed;cursor:pointer;background-color:#fff;z-index:2048;box-sizing:content-box;width:300px;height:200px;top:20%;left:75%;transform:translateX(-50%);display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-ui-generic-container>div:nth-child(1){cursor:move;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;height:24px;width:100%;background-color:#ddd}.igv-ui-generic-container>div:nth-child(1)>div{display:block;color:#5f5f5f;cursor:pointer;width:14px;height:14px;margin-right:8px;margin-bottom:4px}.igv-ui-colorpicker-container{background-color:#eee;height:fit-content;flex-direction:column;flex-wrap:nowrap}.igv-ui-colorpicker-container>div:nth-child(2){display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-ui-colorpicker-container>div:nth-child(3){box-sizing:border-box;position:relative;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;padding:.5rem;font-family:"Open Sans",sans-serif;font-size:1rem;font-weight:400;width:100%;border-top-style:solid;border-top-width:thin;border-top-color:#373737}.igv-ui-colorpicker-container>div:nth-child(4){width:100%;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-ui-color-swatch{position:relative;box-sizing:content-box;display:flex;flex-flow:row;flex-wrap:wrap;justify-content:center;align-items:center;margin:2px;width:32px;height:32px;border-style:solid;border-width:0;border-color:#fff;border-radius:3px}.igv-ui-color-swatch-shim{cursor:pointer;position:relative;box-sizing:content-box;display:flex;flex-flow:row;flex-wrap:wrap;justify-content:center;align-items:center;width:32px;height:32px;background-color:#fff;border-style:solid;border-width:thin;border-color:#fff;border-radius:4px}.igv-ui-dialog{z-index:2048;position:fixed;width:fit-content;height:fit-content;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;background-color:#fff;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400}.igv-ui-dialog .igv-ui-dialog-header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-dialog .igv-ui-dialog-header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-ui-dialog .igv-ui-dialog-header div:hover{cursor:pointer;color:#444}.igv-ui-dialog .igv-ui-dialog-one-liner{width:95%;height:24px;line-height:24px;text-align:left;margin:8px;overflow-wrap:break-word;background-color:#fff;font-weight:bold}.igv-ui-dialog .igv-ui-dialog-ok-cancel{width:100%;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-dialog .igv-ui-dialog-ok-cancel div{margin:16px;margin-top:32px;color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:first-child{background-color:#5ea4e0}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:last-child{background-color:#c4c4c4}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-ui-dialog .igv-ui-dialog-ok{width:100%;height:36px;margin-top:32px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-dialog .igv-ui-dialog-ok div{width:98px;height:36px;line-height:36px;text-align:center;color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;border-color:#fff;border-style:solid;border-width:thin;border-radius:4px;background-color:#2b81af}.igv-ui-dialog .igv-ui-dialog-ok div:hover{cursor:pointer;background-color:#25597f}.igv-ui-panel,.igv-ui-panel-row,.igv-ui-panel-column{z-index:2048;background-color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;justify-content:flex-start;align-items:flex-start}.igv-ui-panel-column{display:flex;flex-direction:column}.igv-ui-panel-row{display:flex;flex-direction:row}.igv-ui-textbox{background-color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;justify-content:flex-start;align-items:flex-start}.igv-ui-table{background-color:#fff}.igv-ui-table thead{position:sticky;top:0}.igv-ui-table th{text-align:left}.igv-ui-table td{padding-right:20px}.igv-ui-table tr:hover{background-color:#add8e6}.igv-roi-seg-filter-dialog{box-sizing:content-box;position:fixed;top:20%;left:75%;transform:translateX(-50%);z-index:2048;background-color:#fff;cursor:pointer;width:350px;height:fit-content;padding-bottom:16px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-roi-seg-filter-dialog__header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-roi-seg-filter-dialog__header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-roi-seg-filter-dialog__header div:hover{cursor:pointer;color:#444}.igv-roi-seg-filter-dialog__radio-group{margin-top:8px;display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}.igv-roi-seg-filter-dialog__radio-group label{display:flex;align-items:center;gap:4px;cursor:pointer}.igv-roi-seg-filter-dialog__radio-group input[type=radio]{cursor:pointer}.igv-roi-seg-filter-dialog__radio-group .op{display:flex;flex-direction:row;justify-content:flex-start;align-items:center;margin-left:16px;margin-bottom:8px;gap:2px}.igv-roi-seg-filter-dialog__radio-group .op input[type=radio]{display:block;margin:0}.igv-roi-seg-filter-dialog__radio-group .op label{display:block;margin-left:4px}.igv-roi-seg-filter-dialog__one-liner{color:#373737;width:95%;line-height:24px;text-align:left;margin-top:8px;padding-left:8px;overflow-wrap:break-word;background-color:#fff}.igv-roi-seg-filter-dialog__input{margin-top:8px;width:80%;height:24px;color:#373737;line-height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-roi-seg-filter-dialog__input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-roi-seg-filter-dialog__input input{font-size:16px}.igv-roi-seg-filter-dialog__ok-cancel{width:100%;height:28px;padding-top:16px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-roi-seg-filter-dialog__ok-cancel>div{color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child{margin-left:32px;margin-right:0;background-color:#5ea4e0}.igv-roi-seg-filter-dialog__ok-cancel>div:last-child{margin-left:0;margin-right:32px;background-color:#c4c4c4}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child.disabled{cursor:not-allowed;background-color:#ccc;opacity:.6}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child.disabled:hover{cursor:not-allowed;background-color:#ccc}.igv-roi-seg-filter-dialog__ok-cancel>div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-clear-filters__container{font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;flex-direction:column;max-width:300px;background-color:#fff;padding:12px;gap:8px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin}.igv-clear-filters__row{display:flex;align-items:flex-start;padding:12px;gap:12px;cursor:pointer}.igv-clear-filters__row:last-of-type{border-bottom:none}.igv-clear-filters__track-container{border-bottom:1px solid #7f7f7f;padding-bottom:8px;margin-bottom:8px}.igv-clear-filters__track-container:last-of-type{border-bottom:none;margin-bottom:0}.igv-clear-filters__track-header{display:flex;align-items:center;padding:8px 12px;gap:12px;background-color:#f5f5f5;border-radius:4px;margin-bottom:4px;font-weight:500;font-size:14px}.igv-clear-filters__track-name{color:#333;font-weight:600}.igv-clear-filters__filter-checkbox{flex:0 0 16px;width:16px;height:16px;margin-top:2px;cursor:pointer}.igv-clear-filters__checkbox{flex:0 0 16px;width:16px;height:16px;margin-top:2px;cursor:pointer}.igv-clear-filters__content{display:flex;flex-direction:row;flex:1;gap:4px}.igv-clear-filters__description{color:#333;font-size:14px;line-height:1.4}.igv-clear-filters__region{color:#666;font-family:monospace;font-size:12px;line-height:1.4}.igv-clear-filters__button-container{display:flex;gap:8px;margin-top:8px}.igv-clear-filters__button{display:flex;align-items:center;justify-content:center;flex:1;padding:10px;background-color:#5ea4e0;color:#fff;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px;cursor:pointer;font-size:14px;font-weight:400;transition:background-color .2s ease}.igv-clear-filters__button:hover{background-color:#3b5c7f}.igv-clear-filters__button--cancel{background-color:#c4c4c4}.igv-clear-filters__button--cancel:hover{background-color:#7f7f7f}.igv-navbar{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;box-sizing:border-box;width:100%;color:#444;font-size:12px;font-family:"Open Sans",sans-serif;font-weight:400;line-height:32px;padding-left:8px;padding-right:8px;margin-top:2px;margin-bottom:6px;height:32px;border-style:solid;border-radius:3px;border-width:thin;border-color:#bfbfbf;background-color:#f3f3f3}.igv-navbar .igv-navbar-left-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;height:32px;line-height:32px}.igv-navbar .igv-navbar-left-container .igv-logo{width:34px;height:32px;margin-right:8px}.igv-navbar .igv-navbar-left-container .igv-current-genome{height:32px;margin-left:4px;margin-right:4px;user-select:none;line-height:32px;vertical-align:middle;text-align:center}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;height:100%}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-chromosome-select-widget-container{display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:space-around;align-items:center;height:100%;width:125px;margin-right:4px}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-chromosome-select-widget-container select{display:block;cursor:pointer;width:100px;height:75%;outline:none;font-size:12px;font-family:"Open Sans",sans-serif;font-weight:400}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;margin-left:8px;height:22px}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;width:240px;height:22px;line-height:22px}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container input.igv-search-input{cursor:text;width:85%;height:22px;line-height:22px;font-size:12px;font-family:"Open Sans",sans-serif;font-weight:400;text-align:left;padding-left:8px;margin-right:8px;outline:none;border-style:solid;border-radius:3px;border-width:thin;border-color:#bfbfbf;background-color:#fff}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container .igv-search-icon-container{cursor:pointer;height:16px;width:16px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-windowsize-panel-container{margin-left:4px;user-select:none}.igv-navbar .igv-navbar-right-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center}.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container{position:relative;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container-hidden{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;height:100%}.igv-navbar .igv-navbar-right-container .igv-zoom-widget{color:#737373;font-size:18px;margin-left:8px;user-select:none;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div{cursor:pointer;margin-left:unset;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:first-child{height:20px;width:20px;margin-left:unset;margin-right:4px}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:last-child{height:20px;width:20px;margin-left:4px;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:nth-child(even){display:block;height:fit-content}.igv-navbar .igv-navbar-right-container .igv-zoom-widget input{display:block;width:125px}.igv-navbar .igv-navbar-right-container .igv-zoom-widget svg{display:block}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900{color:#737373;font-size:18px;height:32px;line-height:32px;margin-left:8px;user-select:none;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div{cursor:pointer;margin-left:unset;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:first-child{height:20px;width:20px;margin-left:unset;margin-right:4px}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:last-child{height:20px;width:20px;margin-left:4px;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:nth-child(even){width:0;height:0;display:none}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 input{width:0;height:0;display:none}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 svg{display:block}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-hidden{display:none}.igv-navbar-button{display:block;box-sizing:unset;padding-left:6px;padding-right:6px;height:18px;text-transform:capitalize;user-select:none;line-height:18px;text-align:center;vertical-align:middle;font-family:"Open Sans",sans-serif;font-size:11px;font-weight:200;color:#737373;background-color:#f3f3f3;border-color:#737373;border-style:solid;border-width:thin;border-radius:6px}.igv-navbar-button:hover{cursor:pointer}.igv-navbar-button-clicked{color:#fff;background-color:#737373}.igv-navbar-icon-button{cursor:pointer;position:relative;width:24px;height:24px;margin-left:4px;margin-right:4px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-icon-button>div:first-child{z-index:512;position:absolute;top:36px;left:-18px;width:24px;height:24px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-icon-button>div:last-child{z-index:512;position:absolute;top:36px;left:18px;width:24px;height:24px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-text-button{cursor:pointer;position:relative;margin-left:2px;margin-right:2px;border:none;display:flex;justify-content:center;align-items:center}.igv-navbar-text-button>div:nth-child(2){z-index:512;position:absolute;top:36px;left:0;width:38px;height:18px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-text-button>div:nth-child(3){z-index:512;position:absolute;top:36px;left:42px;width:38px;height:18px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}#igv-text-button-label{text-anchor:middle;dominant-baseline:middle}.igv-navbar-text-button-svg-inactive rect{stroke:#737373;fill:#fff}.igv-navbar-text-button-svg-inactive text{fill:#737373}.igv-navbar-text-button-svg-inactive tspan{dominant-baseline:middle}.igv-navbar-text-button-svg-hover rect{stroke:#737373;fill:#737373}.igv-navbar-text-button-svg-hover text{fill:#fff}.igv-navbar-text-button-svg-hover tspan{dominant-baseline:middle}#igv-save-svg-group rect{stroke:#737373;fill:#fff}#igv-save-svg-group text{fill:#737373}#igv-save-svg-group:hover rect{stroke:#737373;fill:#737373}#igv-save-svg-group:hover text{fill:#fff}#igv-save-png-group rect{stroke:#737373;fill:#fff}#igv-save-png-group text{fill:#737373}#igv-save-png-group:hover rect{stroke:#737373;fill:#737373}#igv-save-png-group:hover text{fill:#fff}.igv-zoom-in-notice-container{z-index:256;position:absolute;top:8px;left:50%;transform:translate(-50%, 0%);display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:center;align-items:center;background-color:#fff}.igv-zoom-in-notice-container>div{padding-left:4px;padding-right:4px;padding-top:2px;padding-bottom:2px;width:100%;height:100%;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;color:#3f3f3f}.igv-zoom-in-notice{position:absolute;top:10px;left:50%}.igv-zoom-in-notice div{position:relative;left:-50%;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;color:#3f3f3f;background-color:hsla(0,0%,100%,.51);z-index:64}.igv-container-spinner{position:absolute;top:90%;left:50%;transform:translate(-50%, -50%);z-index:1024;width:24px;height:24px;pointer-events:none;color:#737373}.igv-multi-locus-close-button{position:absolute;top:2px;right:0;padding-left:2px;padding-right:2px;width:12px;height:12px;color:#666;background-color:#fff;z-index:1000}.igv-multi-locus-close-button>svg{vertical-align:top}.igv-multi-locus-close-button:hover{cursor:pointer;color:#434343}.igv-multi-locus-ruler-label{z-index:64;position:absolute;top:2px;left:0;width:100%;height:12px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-multi-locus-ruler-label>div{font-family:"Open Sans",sans-serif;font-size:12px;color:#101010;background-color:#fff}.igv-multi-locus-ruler-label>div{cursor:pointer}.igv-multi-locus-ruler-label-square-dot{z-index:64;position:absolute;left:50%;top:5%;transform:translate(-50%, 0%);background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-multi-locus-ruler-label-square-dot>div:first-child{width:14px;height:14px}.igv-multi-locus-ruler-label-square-dot>div:last-child{margin-left:16px;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;color:#101010}.igv-ruler-sweeper{display:none;pointer-events:none;position:absolute;top:26px;bottom:0;left:0;width:0;z-index:99999;background-color:rgba(68,134,247,.25)}.igv-ruler-tooltip{pointer-events:none;z-index:128;position:absolute;top:0;left:0;width:1px;height:32px;background-color:rgba(0,0,0,0);display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-ruler-tooltip>div{pointer-events:none;width:128px;height:auto;padding:1px;color:#373737;font-size:10px;font-family:"Open Sans",sans-serif;font-weight:400;background-color:#fff;border-style:solid;border-width:thin;border-color:#373737}.igv-track-label{position:absolute;left:8px;top:8px;width:auto;height:auto;max-width:50%;padding-left:4px;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;text-align:center;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-color:#444;border-radius:2px;border-style:solid;border-width:thin;background-color:#fff;z-index:128;cursor:pointer}.igv-track-label:hover,.igv-track-label:focus,.igv-track-label:active{background-color:#e8e8e8}.igv-track-label-popup-shim{position:absolute;right:8px;top:8px;width:auto;height:auto;max-width:50%;padding-left:4px;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;text-align:center;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-color:#444;border-radius:2px;border-style:solid;border-width:thin;background-color:#fff;z-index:128}.igv-attribute-group-label{position:absolute;right:5px;z-index:128;width:auto;height:auto;max-width:50%;padding-left:4px;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;text-align:center;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-color:#444;border-radius:2px;border-style:solid;border-width:thin;background-color:#fff}.igv-attribute-group-line{position:absolute;left:0px;width:100%;height:1px;background-color:rgba(0,0,0,0);border-top:1px dotted #666;pointer-events:none;z-index:127}.igv-center-line{display:none;pointer-events:none;position:absolute;top:0;bottom:0;left:50%;transform:translateX(-50%);z-index:8;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-left-style:dashed;border-left-width:thin;border-right-style:dashed;border-right-width:thin}.igv-center-line-wide{background-color:rgba(0,0,0,0);border-left-color:rgba(127,127,127,.51);border-right-color:rgba(127,127,127,.51)}.igv-center-line-thin{background-color:rgba(0,0,0,0);border-left-color:rgba(127,127,127,.51);border-right-color:rgba(0,0,0,0)}.igv-cursor-guide-horizontal{display:none;pointer-events:none;user-select:none;-moz-user-select:none;-webkit-user-select:none;position:absolute;left:0;right:0;top:50%;height:1px;z-index:32;margin-left:50px;margin-right:54px;border-top-style:dotted;border-top-width:thin;border-top-color:rgba(127,127,127,.76)}.igv-cursor-guide-vertical{pointer-events:none;user-select:none;-moz-user-select:none;-webkit-user-select:none;position:absolute;top:0;bottom:0;left:50%;width:1px;z-index:32;border-left-style:dotted;border-left-width:thin;border-left-color:rgba(127,127,127,.76);display:none}.igv-user-feedback{position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);width:512px;height:360px;z-index:2048;background-color:#fff;border-color:#a2a2a2;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;color:#444;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-user-feedback div:first-child{position:relative;height:24px;width:100%;background-color:#fff;border-bottom-color:#a2a2a2;border-bottom-style:solid;border-bottom-width:thin}.igv-user-feedback div:first-child div{position:absolute;top:2px;width:16px;height:16px;background-color:rgba(0,0,0,0)}.igv-user-feedback div:first-child div:first-child{left:8px}.igv-user-feedback div:first-child div:last-child{cursor:pointer;right:8px}.igv-user-feedback div:last-child{width:100%;height:calc(100% - 24px);border-width:0}.igv-user-feedback div:last-child div{width:auto;height:auto;margin:8px}.igv-generic-dialog-container{position:fixed;top:20%;left:75%;transform:translateX(-50%);width:300px;height:200px;border-color:#7f7f7f;border-radius:4px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;z-index:2048;background-color:#fff;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-generic-dialog-container .igv-generic-dialog-header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-generic-dialog-container .igv-generic-dialog-header div:hover{cursor:pointer;color:#444}.igv-generic-dialog-container .igv-generic-dialog-one-liner{color:#373737;width:95%;height:24px;line-height:24px;text-align:left;margin-top:8px;padding-left:8px;overflow-wrap:break-word;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-label-input{margin-top:8px;width:95%;height:24px;color:#373737;line-height:24px;padding-left:8px;background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-label-input div{width:30%;height:100%;font-size:16px;text-align:right;padding-right:8px;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-label-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-label-input input{width:50%;font-size:16px}.igv-generic-dialog-container .igv-generic-dialog-input{margin-top:8px;width:calc(100% - 16px);height:24px;color:#373737;line-height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-input input{font-size:16px}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel{width:100%;height:28px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div{margin-top:32px;color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:first-child{margin-left:32px;margin-right:0;background-color:#5ea4e0}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:last-child{margin-left:0;margin-right:32px;background-color:#c4c4c4}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-generic-dialog-container .igv-generic-dialog-ok{width:100%;height:36px;margin-top:32px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-ok div{width:98px;height:36px;line-height:36px;text-align:center;color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;border-color:#fff;border-style:solid;border-width:thin;border-radius:4px;background-color:#2b81af}.igv-generic-dialog-container .igv-generic-dialog-ok div:hover{cursor:pointer;background-color:#25597f}.igv-generic-container{position:fixed;top:20%;left:75%;transform:translateX(-50%);z-index:2048;background-color:#fff;cursor:pointer;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-generic-container>div:nth-child(1){cursor:move;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;height:24px;width:100%;background-color:#ddd}.igv-generic-container>div:nth-child(1) i{display:block;color:#5f5f5f;cursor:pointer;width:14px;height:14px;margin-right:8px;margin-bottom:4px}.igv-menu-popup{position:absolute;top:0;left:0;width:max-content;max-width:400px;z-index:2048;cursor:pointer;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;color:#4b4b4b;background:#fff;border-radius:4px;border-color:#7f7f7f;border-style:solid;border-width:thin;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-end;text-align:left}.igv-menu-popup>div:not(:first-child){width:100%}.igv-menu-popup>div:not(:first-child)>div{background:#fff}.igv-menu-popup>div:not(:first-child)>div.context-menu{padding-left:4px;padding-right:4px}.igv-menu-popup>div:not(:first-child)>div:last-child{border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom-color:rgba(0,0,0,0);border-bottom-style:solid;border-bottom-width:thin}.igv-menu-popup>div:not(:first-child)>div:hover{background:#efefef}.igv-menu-popup-shim{padding-left:8px;padding-right:8px;padding-bottom:1px;padding-top:1px}.igv-menu-popup-header{position:relative;width:100%;height:24px;cursor:move;border-top-color:rgba(0,0,0,0);border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-menu-popup-header div{margin-right:4px;height:12px;width:12px;color:#7f7f7f}.igv-menu-popup-header div:hover{cursor:pointer;color:#444}.igv-menu-popup-check-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;width:100%;height:20px;margin-right:4px;background-color:rgba(0,0,0,0)}.igv-menu-popup-check-container div{padding-top:2px;padding-left:8px}.igv-menu-popup-check-container div:first-child{position:relative;width:12px;height:12px}.igv-menu-popup-check-container div:first-child svg{position:absolute;width:12px;height:12px}.igv-loading-spinner-container{z-index:1024;position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);width:32px;height:32px;display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-loading-spinner-container>div{box-sizing:border-box;width:100%;height:100%;border-radius:50%;border:4px solid rgba(128,128,128,.5);border-top-color:#fff;animation:spin 1s ease-in-out infinite;-webkit-animation:spin 1s ease-in-out infinite}@keyframes spin{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes spin{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.igv-roi-menu{position:absolute;z-index:512;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;color:#4b4b4b;background-color:#fff;width:192px;border-radius:4px;border-color:#7f7f7f;border-style:solid;border-width:thin;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch}.igv-roi-menu>div:first-child{height:24px;border-top-color:rgba(0,0,0,0);border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-roi-menu>div:first-child>div{margin-right:4px;height:12px;width:12px;color:#7f7f7f}.igv-roi-menu>div:first-child>div:hover{cursor:pointer;color:#444}.igv-roi-menu>div:last-child{background-color:#fff;border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom-color:rgba(0,0,0,0);border-bottom-style:solid;border-bottom-width:0;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;text-align:start;vertical-align:middle}.igv-roi-menu>div:last-child>div{height:24px;padding-left:4px;border-bottom-style:solid;border-bottom-width:thin;border-bottom-color:#7f7f7f}.igv-roi-menu>div:last-child>div:not(:first-child):hover{cursor:pointer;background-color:rgba(127,127,127,.1)}.igv-roi-menu>div:last-child div:first-child{font-style:italic;text-align:center;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.igv-roi-menu>div:last-child>div:last-child{border-bottom-width:0;border-bottom-color:rgba(0,0,0,0)}.igv-roi-placeholder{font-style:normal;color:rgba(75,75,75,.6)}.igv-roi-table{position:absolute;z-index:1024;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;resize:both;overflow:hidden;width:min-content;max-width:1600px;border-color:#7f7f7f;border-radius:4px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:12px;font-weight:400;background-color:#fff;cursor:default}.igv-roi-table>div{height:24px;font-size:14px;text-align:start;vertical-align:middle;line-height:24px}.igv-roi-table>div:first-child{border-color:rgba(0,0,0,0);border-top-left-radius:4px;border-top-right-radius:4px;border-top-width:0;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee;cursor:move;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center}.igv-roi-table>div:first-child>div:first-child{text-align:center;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;margin-left:4px;margin-right:4px;width:calc(100% - 4px - 12px)}.igv-roi-table>div:first-child>div:last-child{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-roi-table>div:first-child>div:last-child>svg{display:block}.igv-roi-table>div:first-child>div:last-child:hover{cursor:pointer;color:#444}.igv-roi-table>.igv-roi-table-description{padding:4px;margin-left:4px;word-break:break-all;overflow-y:auto;display:flex;flex-flow:row;flex-wrap:nowrap;background-color:rgba(0,0,0,0)}.igv-roi-table>.igv-roi-table-goto-explainer{margin-top:5px;margin-left:4px;color:#7f7f7f;font-style:italic;height:24px;border-top:solid #d3d3d3;background-color:rgba(0,0,0,0)}.igv-roi-table>.igv-roi-table-column-titles{height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:stretch;align-items:stretch;padding-right:16px;background-color:#fff;border-top-color:#7f7f7f;border-top-style:solid;border-top-width:thin;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin}.igv-roi-table>.igv-roi-table-column-titles>div{font-size:14px;vertical-align:middle;line-height:24px;text-align:left;margin-left:4px;height:24px;overflow:hidden;text-overflow:ellipsis;border-right-color:#7f7f7f;border-right-style:solid;border-right-width:thin}.igv-roi-table>.igv-roi-table-column-titles>div:last-child{border-right:unset}.igv-roi-table>.igv-roi-table-row-container{display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;overflow:auto;height:360px;flex:1 1 auto;background-color:rgba(0,0,0,0)}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row{height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:stretch;align-items:stretch}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row>div{font-size:14px;vertical-align:middle;line-height:24px;text-align:left;margin-left:4px;height:24px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;border-right-color:rgba(0,0,0,0);border-right-style:solid;border-right-width:thin}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row>div:last-child{border-right:unset}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row-hover{background-color:rgba(0,0,0,.04)}.igv-roi-table>div:last-child{min-height:32px;height:32px;line-height:32px;border-top-color:#7f7f7f;border-top-style:solid;border-top-width:thin;border-bottom-color:rgba(0,0,0,0);border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom-width:0;background-color:#eee;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-roi-table-row-selected{background-color:rgba(0,0,0,.125)}.igv-roi-table-button{cursor:pointer;height:20px;user-select:none;line-height:20px;text-align:center;vertical-align:middle;font-family:"Open Sans",sans-serif;font-size:13px;font-weight:400;color:#000;padding-left:6px;padding-right:6px;background-color:#efefef;border-color:#000;border-style:solid;border-width:thin;border-radius:3px}.igv-roi-table-button:hover{font-weight:400;background-color:rgba(0,0,0,.13)}.igv-roi-region{z-index:64;position:absolute;top:0;bottom:0;pointer-events:none;overflow:visible;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch}.igv-roi-region>div{position:relative;width:100%;height:8px;pointer-events:auto}.igv-roi-menu-row{height:24px;padding-left:8px;font-size:small;text-align:start;vertical-align:middle;line-height:24px;background-color:#fff}.igv-roi-menu-row-edit-description{width:-webkit-fill-available;font-size:small;text-align:start;vertical-align:middle;background-color:#fff;padding-left:4px;padding-right:4px;padding-bottom:4px;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:stretch;align-items:stretch}.igv-roi-menu-row-edit-description>label{margin-left:2px;margin-bottom:0;display:block;width:-webkit-fill-available}.igv-roi-menu-row-edit-description>input{display:block;margin-left:2px;margin-right:2px;margin-bottom:1px;width:-webkit-fill-available}.picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{position:absolute;z-index:-1;opacity:0}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{display:flex;flex-flow:row wrap;justify-content:space-between;align-items:stretch;font-size:10px;width:25em;padding:.5em}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper::before{content:"";display:block;width:100%;height:0;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:1 1 auto}.layout_default .picker_sl::before{content:"";display:block;padding-bottom:100%}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{order:1;flex:1 1 auto}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;background:#f2f2f2;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;box-shadow:0 0 0 1px silver;outline:none}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{padding:.4em .6em;cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(0deg, gainsboro, transparent)}.picker_wrapper button:active{background-image:linear-gradient(0deg, transparent, gainsboro)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid #fff;border-radius:100%;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);box-shadow:0 0 0 1px silver}.picker_sl{position:relative;box-shadow:0 0 0 1px silver;background-image:linear-gradient(180deg, white, rgba(255, 255, 255, 0) 50%),linear-gradient(0deg, black, rgba(0, 0, 0, 0) 50%),linear-gradient(90deg, #808080, rgba(128, 128, 128, 0))}.picker_alpha,.picker_sample{position:relative;background:linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0/2em 2em,linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em/2em 2em;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{font-family:monospace;padding:.2em .4em}.picker_sample::before{content:"";position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;box-shadow:0 0 10px 1px rgba(0,0,0,.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:"";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}.igv-ui-center-fixed{left:50%;top:50%;transform:translate(-50%, -50%)}.igv-container{all:initial;position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;padding-top:4px;user-select:none;-webkit-user-select:none;-ms-user-select:none;min-height:160px}.igv-viewport{position:relative;margin-top:5px;line-height:1;overflow-x:hidden;overflow-y:hidden}.igv-viewport-content{position:relative;width:100%}.igv-viewport-content>canvas{position:relative;display:block}.igv-column-container{position:relative;display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;width:100%}.igv-column-shim{width:1px;margin-left:2px;margin-right:2px;background-color:#545453}.igv-axis-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:50px}.igv-axis-column>div{position:relative;margin-top:5px;width:100%}.igv-axis-column>div>div{z-index:512;position:absolute;top:8px;left:8px;width:fit-content;height:fit-content;background-color:rgba(0,0,0,0);display:grid;align-items:start;justify-items:center}.igv-axis-column>div>div>input{display:block;margin:unset;cursor:pointer}.igv-column{position:relative;flex:auto;position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%}.igv-sample-info-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%}.igv-sample-name-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%}.igv-scrollbar-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:14px}.igv-scrollbar-column>div{position:relative;margin-top:5px;width:14px}.igv-scrollbar-column>div>div{cursor:pointer;position:absolute;top:0;left:2px;width:8px;border-width:1px;border-style:solid;border-color:#c4c4c4;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-left-radius:4px;border-bottom-right-radius:4px}.igv-scrollbar-column>div>div:hover{background-color:#c4c4c4}.igv-track-drag-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:12px;background-color:#fff}.igv-track-drag-column>.igv-track-drag-handle{z-index:512;position:relative;cursor:pointer;margin-top:5px;width:100%;border-style:solid;border-width:0;border-top-right-radius:6px;border-bottom-right-radius:6px}.igv-track-drag-column .igv-track-drag-handle-color{background-color:#c4c4c4}.igv-track-drag-column .igv-track-drag-handle-hover-color{background-color:#787878}.igv-track-drag-column .igv-track-drag-handle-selected-color{background-color:#0963fa}.igv-track-drag-column>.igv-track-drag-shim{position:relative;margin-top:5px;width:100%;border-style:solid;border-width:0}.igv-gear-menu-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:28px}.igv-gear-menu-column>div{display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center;margin-top:5px;width:100%;background:#fff}.igv-gear-menu-column>div>div{position:relative;margin-top:4px;width:16px;height:16px;color:#7f7f7f}.igv-gear-menu-column>div>div:hover{cursor:pointer;color:#444}.igv-vertical-center{margin:0 !important;top:50% !important;-ms-transform:translateY(-50%) !important;transform:translateY(-50%) !important}'),r.adoptedStyleSheets=[e]}if(this.root=t({class:"igv-container"}),r.appendChild(this.root),this.alert=new Ud(this.root),this.columnContainer=t({class:"igv-column-container"}),this.root.appendChild(this.columnContainer),this.menuPopup=new md(this.columnContainer),this.menuUtils=new Bd(this),this.initialize(e),this.trackViews=[],this.constants={dragThreshold:3,scrollThreshold:5,defaultColor:"rgb(0,0,150)",doubleClickDelay:e.doubleClickDelay||500},this.eventHandlers={},e.listeners)for(let t of Object.keys(e.listeners))this.on(t,e.listeners[t]);this.on("trackremoved",(()=>{0===this.findTracks((e=>"function"==typeof e.getSamples)).length&&(this.sampleInfoControl.setButtonVisibility(!1),this.sampleNameViewportWidth=void 0,this.showSampleNames=!1,this.sampleNameControl.setState(this.showSampleNames),this.sampleNameControl.hide(),this.layoutChange())})),this.on("didchangecolumnlayout",(()=>{if(Ph.length>0){const e=Ph.length;for(let t=0;t1}isMultiLocusWholeGenomeView(){if(void 0===this.referenceFrameList||1===this.referenceFrameList.length)return!1;for(let e of this.referenceFrameList)if("all"===e.chr.toLowerCase())return!0;return!1}currentLoci(){const e=e=>`${e.chr}:${e.start+1}-${e.end}`;return void 0===this.referenceFrameList||0===this.referenceFrameList.length?"":1===this.referenceFrameList.length?e(this.referenceFrameList[0]):this.referenceFrameList.map((t=>e(t)))}toSVG(){const{x:e,y:t,width:i,height:r}=this.columnContainer.getBoundingClientRect(),s=Number.MAX_SAFE_INTEGER,o=new gh({width:i,height:s,backdropColor:"white",multiLocusGap:0,viewbox:{x:0,y:0,width:i,height:s}}),n={deltaX:0,deltaY:-t};for(let e of this.trackViews)e.renderSVGContext(o,n);return n.deltaX=e,o.setHeight(r),o.getSerializedSvg(!0)}saveSVGtoFile(e,t){let i=this.toSVG();if(t){const e=document.createElement("svg");e.innerHTML=i,t.appendChild(e)}const r=e||"igvjs.svg",s=URL.createObjectURL(new Blob([i],{type:"application/octet-stream"}));k(r,s),URL.revokeObjectURL(s)}savePNGtoFile(e){const t=this.toSVG(),i=new Blob([t],{type:"image/svg+xml"}),r=URL.createObjectURL(i),s=document.createElement("img");s.addEventListener("load",(()=>{const t=this.columnContainer.getBoundingClientRect(),i=window.devicePixelRatio,o=t.width*i,n=t.height*i,a=document.createElement("canvas");a.width=o,a.height=n;const c=a.getContext("2d");c.scale(i,i),c.drawImage(s,0,0);const l=a.toDataURL("image/png");k(e=e||"igvjs.png",l),URL.revokeObjectURL(r)})),s.src=r}async loadSession(e){let t;this.sampleInfo.initialize(),this.roiSets=[],t=e.url||e.file?await oy.loadSessionFile(e,this.config):e,await this.loadSessionObject(t)}static async loadSessionFile(e,t){const i=e.url||e.file;let r;if(e.url&&b(e.url)&&(e.url.startsWith("blob:")||e.url.startsWith("data:"))){const t=oy.uncompressSession(e.url);r=JSON.parse(t)}else{let t=e.filename;if(t||(t=e.url?await os(e.url):e.file.name),t.endsWith(".xml")){const e=Dh.KNOWN_GENOMES,t=await Rr.loadString(i);r=new UF(t,e)}else if(t.endsWith("hub.txt")){r={reference:(await Nh(i)).getGenomeConfig()}}else{if(!t.endsWith(".json"))throw Error("Unrecognized session file format:"+t);r=await Rr.loadJson(i)}}return uy(r,t),r}async loadSessionObject(e){if(this.cleanHouseForSession(),this.config=e,e.browsers&&(e=await async function(e){const t=e.browsers[0],i={},r=new Ov({url:t.url});await r.readHeaderAndFooter(),i.sampleNameViewportWidth=20,i.genome="hg38";const s=t.state.split(","),o=r.bpResolutions[Number.parseInt(s[2])],n=Number.parseInt(s[0]),a=Math.floor(Number.parseFloat(s[3])*o),c=a+Math.floor(1700*o);return i.locus=`${r.chromosomes[n].name}:${a}-${c}`,i.tracks=(t.tracks||[]).filter((e=>!("refgene"===e.format||"cellType"===e.name))),i.tracks.push({type:"shoebox",url:t.url,name:t.name,colorScale:t.colorScale,_hicFile:r}),i}(e)),this.navbar.sampleInfoControl.setButtonVisibility(!1),this.showSampleNames=e.showSampleNames||!1,this.navbar.sampleNameControl.setState(!0===this.showSampleNames),e.sampleNameViewportWidth&&(this.sampleNameViewportWidth=e.sampleNameViewportWidth),"left"===this.config.gearColumnPosition){const e=cs(this.columnContainer,"igv-gear-menu-column");!1===this.config.showGearColumn&&(e.style.width="0px")}const t=cs(this.columnContainer,"igv-axis-column");!1===this.config.showAxis&&(t.style.display="none"),void 0!==this.config.axisWidth&&(t.style.width=this.config.axisWidth+"px"),cs(this.columnContainer,"igv-sample-info-column"),cs(this.columnContainer,"igv-sample-name-column"),cs(this.columnContainer,"igv-scrollbar-column");const i=cs(this.columnContainer,"igv-track-drag-column");if(!1===this.config.showTrackDragHandles&&(i.style.display="none"),"left"!==this.config.gearColumnPosition){const e=cs(this.columnContainer,"igv-gear-menu-column");!1===this.config.showGearColumn&&(e.style.width="0px")}const r=e.reference||e.genome;if(!r)return void console.warn("No genome or reference object specified");const s=b(r)?await Dh.expandReference(this.alert,r):r,o=await this.loadReference(s,s.locus||e.locus);if(this.centerLineList=this.createCenterLineList(this.columnContainer),!1!==e.showIdeogram){const e=new RF(this),t=new Sd(this,this.columnContainer,e);this.trackViews.push(t)}if(!1!==e.showRuler){const e=new cd(this),t=new Sd(this,this.columnContainer,e);this.trackViews.push(t)}e.qtlSelections&&(this.qtlSelections=ty.fromJSON(e.qtlSelections)),void 0!==e.showROIOverlays&&(this.roiManager.showOverlays=e.showROIOverlays),this.roiManager.clearROIs(),e.roi?this.roiManager.loadROI(e.roi,o):await this.roiManager.reset();const n=[];if(e.sampleinfo){const t=Array.isArray(e.sampleinfo)?e.sampleinfo:[e.sampleinfo];for(const e of t)e.file?n.push(e.file):await this.sampleInfo.loadSampleInfo(e)}const a=s.tracks||[],c=e.tracks?a.concat(e.tracks):a;0===c.filter((e=>"sequence"===e.type&&!e.url&&!e.fastaURL)).length&&!1!==this.config.showSequence&&c.push({type:"sequence",order:Xl,removable:!1});const l=c.filter((e=>void 0!==e.file)).map((({file:e})=>e)),h=c.filter((e=>void 0!==e.indexFile)).map((({indexFile:e})=>e));h.length>0&&l.push(...h),n.length>0&&l.push(...n),l.length>0&&alert(`Local files cannot be loaded automatically.\nThis session contains references to these local files:\n${l.map((e=>` ${e}`)).join("\n")}`);const d=c.filter((e=>void 0===e.file));let u=1;for(let e of d)void 0===e.order&&(e.order=u++);const f=d.filter((e=>!0===e.hidden));for(const e of f){const t=El(e,this.genome);await t.getFeatures({chr:"1",start:0,end:Number.MAX_SAFE_INTEGER})}await this.loadTrackList(d)}cleanHouseForSession(){for(let e of this.trackViews)e.removeDOMFromColumnContainer();this.columnContainer.querySelectorAll(".igv-axis-column, .igv-column-shim, .igv-column, .igv-sample-info-column, .igv-sample-name-column, .igv-scrollbar-column, .igv-track-drag-column, .igv-gear-menu-column").forEach((e=>e.remove())),this.trackViews=[],this.circularView&&this.circularView.clearChords()}async loadReference(e,t){let i;this.removeAllTracks(),this.roiManager.clearROIs(),this.navbar.setEnableTrackSelection(!1),i=e.gbkURL?await _l(e.gbkURL):await ey.createGenome(e,this);const r=void 0===this.genome||this.genome.id!==i.id;this.genome=i,this.navbar.updateGenome(i);let s=t||i.initialLocus;if(void 0!==s.chr&&void 0!==s.start)await this.genome.loadChromosome(s.chr),await this.updateLoci([s],!0);else{Array.isArray(s)&&(s=s.join(" "));await this.search(s,!0)||(console.error(`Cannot set initial locus ${s}`),s!==i.initialLocus&&await this.search(i.initialLocus))}return r&&(this.fireEvent("genomechange",[{genome:i}]),this.circularView&&this.circularView.setAssembly({name:this.genome.id,id:this.genome.id,chromosomes:Kf(this.genome)})),i}async loadGenome(e){let t;e.genarkAccession&&(e.url=mh(e.genarkAccession)),e.url&&(b(e.url)&&e.url.endsWith("/hub.txt")?(e.hubURL=e.url,delete e.url):"gbk"===function(e){let t;if(e instanceof File)t=e.name;else{if("string"!=typeof e)throw new Error("Input must be a File object or a URL string");t=e}const i=t.split(".").pop();return i.split("?")[0]}(e.url)&&(e.gbkURL=e.url,delete e.url));if(e.hubURL||e.url&&b(e.url)&&e.url.endsWith("/hub.txt")){t=(await Nh(e.hubURL||e.url)).getGenomeConfig()}else t=b(e)||!(e.url||e.fastaURL||e.twoBitURL||e.gbkURL)?await Dh.expandReference(this.alert,e):e;let i;await this.loadReference(t),i=t.gbkURL||"gbk"===t.format?[{name:"Annotations",format:"gbk",url:t.gbkURL}]:t.tracks||[];return 0===i.filter((e=>"sequence"===e.type)).length&&i.push({type:"sequence",order:Xl}),await this.loadTrackList(i),this.genome}updateUIWithReferenceFrameList(){const e=this.referenceFrameList;this.isMultiLocusWholeGenomeView()||Dh.isWholeGenomeView(e[0].chr),this.navbar.navbarDidResize(),hy(this.trackViews,this.doShowTrackLabels),this.doShowCenterLine&&Dh.isWholeGenomeView(e[0].chr)&&this.navbar.centerLineButton.boundMouseClickHandler(),this.doShowCursorGuide&&Dh.isWholeGenomeView(e[0].chr)&&this.navbar.cursorGuideButton.boundMouseClickHandler(),this.setCenterLineAndCenterLineButtonVisibility(Dh.isWholeGenomeView(e[0].chr))}setCenterLineAndCenterLineButtonVisibility(e){e?this.navbar.centerLineButton.setVisibility(!1):this.navbar.centerLineButton.setVisibility(this.config.showCenterGuideButton);for(let t of this.centerLineList)e?this.setCenterLineVisibility(!e):this.setCenterLineVisibility(this.doShowCenterLine)}setTrackLabelVisibility(e){hy(this.trackViews,e)}setROITableVisibility(e){!0===e?this.roiManager.presentTable():this.roiManager.dismissTable()}setCursorGuideVisibility(e){e?this.cursorGuide.show():this.cursorGuide.hide()}setCustomCursorGuideMouseHandler(e){this.cursorGuide.customMouseHandler=e}setCenterLineVisibility(e){for(let t of this.centerLineList)!0===e?(t.show(),t.repaint()):t.hide()}async loadTrackList(e){let t=this.trackViews.length+1;for(let i of e)void 0===i.order&&(i.order=t++);const i=[];for(const t of e)i.push(this.#T(t));const r=await Promise.all(i);return this.trackViews.some((({track:e})=>e.selected))&&this.navbar.setEnableTrackSelection(!0),this.reorderTracks(),await ny.call(this),this.fireEvent("trackorderchanged",[this.getTrackOrder()]),r}async loadTrack(e){const t=await this.loadTrackList([e]);return e.autoscaleGroup&&this.updateViews(),t[0]}async#T(e){let t;b(e)&&(e=JSON.parse(e));try{t=await this.createTrack(e)}catch(t){let i=t.message||t.error||t.toString();const r={401:"Access unauthorized",403:"Access forbidden",404:"Not found"};r.hasOwnProperty(i)&&(i=r[i]),i=`${i} : ${x(e.url)?e.url.name:e.url}`;const s=new Error(i);throw console.error(s),s}return t?await this.addTrack(t):void 0}async addTrack(e){void 0===e.order&&(e.order=this.trackViews.length);const t=new Sd(this,this.columnContainer,e);if(this.trackViews.push(t),hy(this.trackViews,this.doShowTrackLabels),"function"==typeof e.postInit)try{t.startSpinner(),await e.postInit()}finally{t.stopSpinner()}return"function"==typeof e.hasSamples&&e.hasSamples()&&(this.sampleInfo.hasAttributes()&&this.sampleInfoControl.setButtonVisibility(!0),!1!==this.config.showSampleNameButton&&this.sampleNameControl.show()),e.trackView.enableTrackSelection(this.navbar.getEnableTrackSelection()),e}async loadROI(e){return this.roiManager.loadROI(e,this.genome)}clearROIs(){this.roiManager.clearROIs()}async getUserDefinedROIs(){if(this.roiManager){const e=this.roiManager.getUserDefinedROISet();if(void 0===e)return[];const t=await e.getAllFeatures(),i=[];for(let e of Object.values(t))i.push(...e);return i}return[]}getRulerTrackView(){const e=this.trackViews.filter((({track:e})=>"ruler"===e.id));return e.length>0?e[0]:void 0}async createTrack(e){let t=await async function(e){return"function"==typeof e?e():e} -/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */(e.url||e.fastaURL);if(b(t)&&(t=t.trim()),t)if(e.format)e.format=e.format.toLowerCase();else if(e.fastaURL)e.format="fasta";else if(e.sourceType)"htsget"===e.sourceType&&await hc.inferFormat(e);else{const t=await bf(e);t&&(e.format=t)}e.type&&Gd(e);let i=e.type?e.type.toLowerCase():void 0;if(!i){if(!e.format)throw Error(`Unrecognized track: ${JSON.stringify(e)}`);if("hic"===e.format){const t=new Ov(e);if(await t.readHeaderAndFooter(),!t.chromosomeIndexMap.celltype)throw Error("'.hic' files not supported");i="shoebox",e._hicFile=t}else if(i=Qd(e.format),"bedtype"===i){const t=El(e,this.genome);e._featureSource=t;const r=await t.trackType();i=r&&new Set(qF.keys()).has(r)?r:"annotation"}e.type=i}if(this.trackDefaults&&i){const t=this.trackDefaults[i];if(t)for(let i in t)t.hasOwnProperty(i)&&void 0===e[i]&&(e[i]=t[i])}const r=function(e,t,i){let r;switch(e){case"annotation":case"genes":case"fusionjuncspan":case"snp":r="feature";break;case"seg":case"maf":case"mut":r="seg";break;case"junctions":case"splicejunctions":r="junction";break;default:r=e}return qF.has(r)?qF.get(r)(t,i):void 0}(i,e,this);if(void 0!==r)return e.roi&&e.roi.length>0&&(r.roiSets=e.roi.map((e=>new Cv(e,this.genome)))),r;this.alert.present(new Error(`Error creating track. Could not determine track type for file: ${e.url||e}`),void 0)}reorderTracks(){this.trackViews.sort((function(e,t){const i=e=>"ideogram"===e.track.id?1:"ruler"===e.track.id?2:3,r=i(e),s=i(t);if(r===s){return(e.track.order||0)-(t.track.order||0)}return r-s}));for(let{axis:e,viewports:t,sampleInfoViewport:i,sampleNameViewport:r,outerScroll:s,dragHandle:o,gearContainer:n}of this.trackViews){e.remove();for(let{viewportElement:e}of t)e.parentNode.removeChild(e);i.viewport.remove(),r.viewport.remove(),s.remove(),o.remove(),n.remove()}const e=this.columnContainer.querySelectorAll(".igv-column");for(let{axis:t,viewports:i,sampleInfoViewport:r,sampleNameViewport:s,outerScroll:o,dragHandle:n,gearContainer:a}of this.trackViews){this.columnContainer.querySelector(".igv-axis-column").appendChild(t);for(let t=0;te.track&&e.track.name)).map((e=>e.track.name))}getSelectedTrackViews(){return this.trackViews.filter((e=>!0===e.track.selected))}removeTrackByName(e){const t=this.trackViews.slice();for(let i of t)e===i.track.name&&this.removeTrack(i.track)}removeTrack(e){for(let t of this.trackViews)if(e===t.track){this._removeTrack(t.track);break}}_removeTrack(e){e.disposed||(this.trackViews.splice(this.trackViews.indexOf(e.trackView),1),this.fireEvent("trackremoved",[e]),this.fireEvent("trackorderchanged",[this.getTrackOrder()]),e.trackView&&e.trackView.dispose())}removeAllTracks(){const e=this.trackViews;this.trackViews=[];for(let t of e)"ruler"!==t.track.id&&"ideogram"!==t.track.id?(this.fireEvent("trackremoved",[t.track]),t.dispose()):this.trackViews.push(t)}get ideogramTrackView(){return this.trackViews[0]}get rulerTrackView(){return this.trackViews[1]}findTracks(e,t){let i="function"==typeof e?t=>e(t.track):i=>t===i.track[e];return this.trackViews.filter(i).map((e=>e.track))}get tracks(){return this.trackViews.map((e=>e.track)).filter((e=>void 0!==e))}setTrackHeight(e){this.trackHeight=e,this.trackViews.forEach((function(t){t.setTrackHeight(e)}))}async visibilityChange(){this.layoutChange()}async layoutChange(){if(this.referenceFrameList.find((e=>e.bpPerPixel<0))){const e=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList)t.bpPerPixel=(t.end-t.start)/e}this.referenceFrameList&&this.navbar.navbarDidResize(),ny.call(this),this.roiManager.updateROIRegionPositions(),await this.updateViews()}async updateViews(){const e=this.trackViews;this.updateLocusSearchWidget();for(const{bpPerPixel:e,chr:t,start:i}of this.referenceFrameList)e<=10&&await this.genome.getSequence(t,i,i+1);for(const e of this.centerLineList)e.repaint();if(this.dragObject)for(const t of e)await t.updateViews();else{const t={},i=[];for(const r of e)if(r.track.autoscaleGroup){const e=r.track.autoscaleGroup;t[e]||(t[e]=[]),t[e].push(r)}else i.push(r);if(Object.entries(t).length>0)for(const[e,i]of Object.entries(t)){const e=await Promise.all(i.map((e=>e.getInViewFeatures()))),t=is(e.flat());for(const e of i)e.track.dataRange=Object.assign({},t),e.track.autoscale=!1;await Promise.all(i.map((e=>e.updateViews())))}await Promise.all(i.map((e=>e.updateViews())))}}repaintViews(){for(let e of this.trackViews)e.repaintViews()}updateLocusSearchWidget(){if(!this.referenceFrameList)return;const e=this.referenceFrameList,t=this.calculateViewportWidth(this.referenceFrameList.length);for(let i of e)i.end=i.start+i.bpPerPixel*t;const i=this.referenceFrameList.map((e=>e.getLocusString())).join(" "),r=1===e.length?this.genome.getChromosomeDisplayName(this.referenceFrameList[0].chr):"";this.navbar.updateLocus(i,r),this.fireEvent("locuschange",[this.referenceFrameList])}calculateViewportWidth(e){let{width:t}=this.columnContainer.getBoundingClientRect();const i=this.getSampleInfoViewportWidth(),r=this.getSampleNameViewportWidth();return t-=(!1===this.config.showAxis?0:50)+i+r+14+(!1===this.config.showTrackDragHandles?0:12)+(!1===this.config.showGearColumn?0:28),t-=5*(e-1),Math.floor(t/e)}updateReferenceFrames(e){for(const t of this.referenceFrameList)t.updateForViewportWidth(e)}updateViewportElements(e){for(let t=0;t{i===t||e.remove()})),this.columnContainer.querySelectorAll(".igv-column-shim").forEach((e=>e.remove()));for(let e of this.trackViews){const i=e.viewports[t];e.viewports.filter(((e,i)=>i!==t)).forEach((e=>e.dispose())),e.viewports=[i]}const i=this.calculateViewportWidth(1);e.bpPerPixel=(e.end-e.start)/i,this.referenceFrameList=[e],this.trackViews.forEach((({viewports:e})=>e.forEach((e=>e.setWidth(i))))),this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),await this.updateViews(!0)}async rescaleForMultiLocus(e){const t=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList)t.bpPerPixel*=e;for(let{viewports:e}of this.trackViews)for(let i of e)i.setWidth(t);this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),await this.updateViews()}async goto(e,t,i){await this.search(e+":"+t+"-"+i)}async search(e,t){const i=await async function(e,t){if(void 0===t||""===t.trim())return;const i=t.split(" ");let r=[];const s=async t=>{if("all"===t.trim().toLowerCase()||"*"===t)return e.genome.wholeGenomeView?{chr:"all",start:0,end:e.genome.getChromosome("all").bpLength}:void 0;let i,r;if(t.includes(":")&&(i=AF(t,e.isSoftclipped()),i&&(r=await e.genome.loadChromosome(i.chr))),!r){i=void 0;const s=await yF(e,t);s&&(i={chr:s.chr,start:s.start,end:s.end,name:(s.name||t).toUpperCase()}),i||(r=await e.genome.loadChromosome(t),r&&(i={chr:r.name}))}return i&&(r=r||await e.genome.loadChromosome(i.chr),i.chr=r.name,void 0===i.start&&void 0===i.end&&(i.start=0,i.end=r.bpLength)),i};for(let e of i){const t=await s(e);t&&r.push(t)}if(0===r.length){const e=await s(t.replaceAll(" ","+"));e&&r.push(e)}return 0===r.length?void 0:r}(this,e);return this.updateLoci(i,t)}async updateLoci(e,t){if(e&&e.length>0){this.referenceFrameList=function(e,t,i,r,s,o){return e.map((e=>{let n;if(e.bpPerPixel)n=new GF(t,e.chr,e.start,e.start+s*e.bpPerPixel,e.bpPerPixel);else{const a=Object.assign({},e);if(i&&a.name&&(a.start=Math.max(0,a.start-i),a.end+=i),!o){const e=t.getChromosome(a.chr);rs(e.bpLength,a,r)}n=new GF(t,a.chr,a.start,a.end,(a.end-a.start)/s)}return n}))}(e,this.genome,this.flanking,this.minimumBases(),this.calculateViewportWidth(e.length),this.isSoftclipped());for(let e of this.trackViews)e.removeViewportsFromColumnContainer();this.columnContainer.querySelectorAll(".igv-column-shim, .igv-column").forEach((e=>e.remove())),uv(this.columnContainer.querySelector(".igv-sample-info-column"),this.referenceFrameList.length),this.fireEvent("didchangecolumnlayout");for(let e of this.trackViews)e.createViewports(this,this.columnContainer,this.referenceFrameList);return this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),t||await this.updateViews(),!0}return!1}async loadSampleInfo(e){await this.sampleInfo.loadSampleInfo(e),this.config.sampleinfo?this.config.sampleinfo.push(e):this.config.sampleinfo=[e];for(const{sampleInfoViewport:e}of this.trackViews)e.setWidth(this.getSampleInfoColumnWidth());const t=this.findTracks((e=>"function"==typeof e.getSamples));t.length>0&&(this.sampleInfoControl.performClickWithState(this,!0),this.sampleInfoControl.setButtonVisibility(!0));for(const{sampleInfoViewport:e}of this.trackViews)e.repaint()}async discardSampleInfo(){this.sampleInfo.discard();for(const{sampleInfoViewport:e}of this.trackViews)e.setWidth(this.getSampleInfoColumnWidth());const e=this.findTracks((e=>"function"==typeof e.getSamples));e.length>0&&(this.sampleInfoControl.performClickWithState(this,!1),this.sampleInfoControl.setButtonVisibility(!1));for(const{sampleInfoViewport:e}of this.trackViews)e.repaint();await this.layoutChange()}getSampleInfoColumnWidth(){if(this.sampleInfo.attributeCount){const e=this.findTracks((e=>"function"==typeof e.getSamples)),t=e.length>0,i=this.sampleInfo.hasAttributes(),r=this.sampleInfoControl.showSampleInfo;return t&&i&&r?this.sampleInfo.attributeCount*nd+8:0}return 0}on(e,t){this.eventHandlers[e]||(this.eventHandlers[e]=[]),this.eventHandlers[e].push(t)}un(e,t){this.off(e,t)}off(e,t){if(e)if(t){const i=this.eventHandlers[e];if(i&&0!==i.length){const r=i.indexOf(t);-1!==r&&this.eventHandlers[e].splice(r,1)}else console.warn("No handlers to remove for event: "+e)}else this.eventHandlers[e]=[];else this.eventHandlers={}}fireEvent(e,t,i){const r=this.eventHandlers[e];if(void 0===r||0===r.length)return;const s=i||window;return r.map((function(e){return e.apply(s,t)}))[0]}dispose(){this.removeEventHandlers();for(let e of this.trackViews)e.dispose();this.roiManager&&this.roiManager.dispose()}toJSON(){const e={version:"3.5.0"};if(void 0!==this.showSampleNames&&(e.showSampleNames=this.showSampleNames),this.sampleNameViewportWidth&&(e.sampleNameViewportWidth=this.sampleNameViewportWidth),e.reference=this.genome.toJSON(),e.reference.fastaURL instanceof File)throw new Error(`Error. Sessions cannot include local file references ${e.reference.fastaURL.name}.`);if(e.reference.indexURL instanceof File)throw new Error(`Error. Sessions cannot include local file references ${e.reference.indexURL.name}.`);const t=[];let i=this.trackViews[0];for(let{referenceFrame:e}of i.viewports){const i=e.getLocusString();t.push(i)}e.locus=1===t.length?t[0]:t;const r=this.roiManager.toJSON();r&&(e.roi=r,this.roiManager.showOverlays||(e.showROIOverlays=!1)),this.qtlSelections.isEmpty()||(e.qtlSelections=this.qtlSelections.toJSON());const s=[],o=[];for(const{track:e}of this.trackViews)try{let t;"function"==typeof e.getState?t=ma.localFileInspection(e.getState()):e.config&&(t=ma.localFileInspection(e.config)),t&&(t.browser&&delete t.browser,t.order=e.order,s.push(t))}catch(t){const i=`Track: ${e.name}: ${t}`;console.error(i),o.push(i)}if(o.length>0){let e=1,t="Errors encountered saving session:
";for(let i of o)t+=` (${e++}) ${i.toString()}
`;throw Error(t)}e.tracks=s;const n=[];for(const e of s)for(const t of Object.keys(e))"file"!==t&&"indexFile"!==t||n.push(e[t]);const a=[];if(this.config.sampleinfo){e.sampleinfo=this.config.sampleinfo;for(const e of this.sampleInfo.sampleInfoFiles){const t=ma.localFileInspection({url:e});t.file&&a.push(t.file)}a.length>0&&n.push(...a)}return n.length>0&&alert(`This session includes reference(s) to local file(s):\n${n.map((e=>` ${e}`)).join("\n")}\nLocal files cannot be loaded automatically when a saved session is restored.`),e}compressedSession(){return function(e){const t=new Uint8Array(e.length);for(var i=0;i0?e.substring(0,t):e)+"?sessionURL=blob:"+this.compressedSession()}mouseDownOnViewport(e,t){var i;i=o(e),this.vpMouseDown={viewport:t,lastMouseX:i.x,mouseDownX:i.x,lastMouseY:i.y,mouseDownY:i.y,referenceFrame:t.referenceFrame}}cancelTrackPan(){const e=this.dragObject;this.dragObject=void 0,this.isScrolling=!1,this.vpMouseDown=void 0,e&&e.viewport.referenceFrame.start!==e.start&&(this.updateViews(),this.fireEvent("trackdragend",[e.viewport]))}isTrackPanning(){return this.dragObject}isSoftclipped(){return void 0!==this.trackViews.find((e=>!0===e.track.showSoftClips))}startTrackDrag(e){this.dragTrack=e}updateTrackDrag(e){if(e&&this.dragTrack){const t=this.dragTrack,i=this.trackViews.indexOf(e),r=this.trackViews.indexOf(t),s=this.trackViews;s[i]=t,s[r]=e;const o=this.trackViews[i].track.order;this.trackViews[r].track.order=o;const n=s.length;let a=o;if(i0;e--){const t=s[e].track;if(!(t.order>=a))break;t.order=Math.max(-Number.MAX_SAFE_INTEGER,a-1),a=t.order}this.reorderTracks()}}endTrackDrag(){this.dragTrack?(this.dragTrack=void 0,this.fireEvent("trackorderchanged",[this.getTrackOrder()])):this.dragTrack=void 0}addEventHandlers(){this.addWindowResizeHandler(),this.addRootMouseUpHandler(),this.addRootMouseLeaveHandler(),this.addColumnContainerEventHandlers(),this.addKeyboardHandler()}removeEventHandlers(){this.removeWindowResizeHandler(),this.removeRootMouseUpHandler(),this.removeRootMouseLeaveHandler(),this.removeColumnContainerEventHandlers(),this.removeKeyboardHandler()}addWindowResizeHandler(){this.boundWindowResizeHandler=ny.bind(this),window.addEventListener("resize",this.boundWindowResizeHandler)}removeWindowResizeHandler(){window.removeEventListener("resize",this.boundWindowResizeHandler)}addRootMouseUpHandler(){this.boundRootMouseUpHandler=cy.bind(this),this.root.addEventListener("mouseup",this.boundRootMouseUpHandler)}removeRootMouseUpHandler(){this.root.removeEventListener("mouseup",this.boundRootMouseUpHandler)}addRootMouseLeaveHandler(){this.boundRootMouseLeaveHandler=cy.bind(this),this.root.addEventListener("mouseleave",this.boundRootMouseLeaveHandler)}removeRootMouseLeaveHandler(){this.root.removeEventListener("mouseleave",this.boundRootMouseLeaveHandler)}addColumnContainerEventHandlers(){this.boundColumnContainerMouseMoveHandler=ay.bind(this),this.boundColumnContainerTouchMoveHandler=ay.bind(this),this.boundColumnContainerMouseLeaveHandler=cy.bind(this),this.boundColumnContainerMouseUpHandler=cy.bind(this),this.boundColumnContainerTouchEndHandler=cy.bind(this),this.columnContainer.addEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.columnContainer.addEventListener("touchmove",this.boundColumnContainerTouchMoveHandler),this.columnContainer.addEventListener("mouseleave",this.boundColumnContainerMouseLeaveHandler),this.columnContainer.addEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.columnContainer.addEventListener("touchend",this.boundColumnContainerTouchEndHandler)}removeColumnContainerEventHandlers(){this.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.columnContainer.removeEventListener("touchmove",this.boundColumnContainerTouchMoveHandler),this.columnContainer.removeEventListener("mouseleave",this.boundColumnContainerMouseLeaveHandler),this.columnContainer.removeEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.columnContainer.removeEventListener("touchend",this.boundColumnContainerTouchEndHandler)}addKeyboardHandler(){this.keyUpHandler=ly.bind(this),document.addEventListener("keyup",this.keyUpHandler)}removeKeyboardHandler(){console.log("Remove handler"),document.addEventListener("keyup",this.keyUpHandler)}static uncompressSession(e){let t;if(e.indexOf("/gzip;base64")>0){t=nr(e);let i="";for(let e of t)i+=String.fromCharCode(e);return i}return function(e){e=e.replace(/\./g,"+").replace(/_/g,"/").replace(/-/g,"=");const t=atob(e),i=[];for(let e=0;e{const s=e.data,o=s.mate;function n(e){e.chr=i.genome.getChromosomeName(e.refName);let t=!1;for(let r of i.referenceFrameList){const i=vf.fromLocusString(r.getLocusString());if(i.contains(e)){t=!0;break}if(i.overlaps(e)){r.extend(e),t=!0;break}}if(!t){const t=2e3,r=(e.start+e.end)/2;i.addMultiLocusPanel(e.chr,r-t,r+t)}}n(s),n(o)}})),this.circularViewControl=new pv(this.navbar.toggleButtonContainer,this),this.circularView.setAssembly({name:this.genome.id,id:this.genome.id,chromosomes:Kf(this.genome)}),this.circularViewVisible=t,this.circularView}get circularViewVisible(){return void 0!==this.circularView&&this.circularView.visible}set circularViewVisible(e){this.circularView&&(this.circularView.visible=e,this.circularViewControl.setState(e))}get overlayTrackButton(){return this.navbar.overlayTrackButton}get roiTableControl(){return this.navbar.roiTableControl}get sampleNameControl(){return this.navbar.sampleNameControl}get sampleInfoControl(){return this.navbar.sampleInfoControl}async blat(e){return Yl({sequence:e,browser:this,name:"Blat",title:"Blat"})}}async function ny(e){if(void 0===this.referenceFrameList||0===this.referenceFrameList.length)return;const t=this.calculateViewportWidth(this.referenceFrameList.length);this.updateReferenceFrames(t),this.updateViewportElements(t),await this.syncUIState()}function ay(e){e.preventDefault();const{x:t,y:i}=o(e);if(this.vpMouseDown){const{viewport:r,referenceFrame:s}=this.vpMouseDown,o=Math.abs(t-this.vpMouseDown.mouseDownX)>Math.abs(i-this.vpMouseDown.mouseDownY);if(!this.dragObject&&!this.isScrolling)if(o)this.vpMouseDown.mouseDownX&&Math.abs(t-this.vpMouseDown.mouseDownX)>this.constants.dragThreshold&&(this.dragObject={viewport:r,start:s.start});else if(this.vpMouseDown.mouseDownY&&Math.abs(i-this.vpMouseDown.mouseDownY)>this.constants.scrollThreshold){this.isScrolling=!0;const e=r.viewportElement.clientHeight,t=r.trackView.maxViewportContentHeight();this.vpMouseDown.r=e/t}if(this.dragObject){const i=!this.isSoftclipped();let o=this.vpMouseDown.lastMouseX-t;s.shiftPixels(o,r.viewportElement.clientWidth,i)&&this.updateViews(),this.fireEvent("trackdrag",[e])}if(this.isScrolling){const e=this.vpMouseDown.lastMouseY-i;r.trackView.scrollByPixels(e)}this.vpMouseDown.lastMouseX=t,this.vpMouseDown.lastMouseY=i}}function cy(e){this.cancelTrackPan(),this.endTrackDrag()}async function ly(e){if(this.referenceFrameList&&!(this.referenceFrameList.length>1)&&("KeyF"===e.code||"KeyB"===e.code)){const t=this.getSelectedTrackViews();if(t.length>0){const i=t[0].track;if("function"==typeof i.nextFeatureAfter){const t=this.referenceFrameList[0],r=t.viewport?t.viewport.getWidth():this.calculateViewportWidth(this.referenceFrameList.length),s="all"===t.chr.toLowerCase(),o=i.visibilityWindow;if(s||o&&o>0&&t.bpPerPixel*r>o)return;const n="KeyF"===e.code,a=t.chr,c=t.center,l=await i.nextFeatureAfter(a,c,n);if(l){const i=await this.genome.getChromosomeName(l.chr);if(a===i){const i=(l.start+l.end)/2;if(e.shiftKey){const e=this.config.minimumBases||40,s=Math.max(e,1.1*(l.end-l.start));t.start=Math.max(0,i-s/2),t.end=i+s/2,t.bpPerPixel=(t.end-t.start)/r}else t.shift(i-c);this.updateViews()}else{t.chr=i;const s=(l.start+l.end)/2;if(e.shiftKey){const e=this.config.minimumBases||40,i=Math.max(e,1.1*(l.end-l.start));t.start=Math.max(0,s-i/2),t.end=t.start+i,t.bpPerPixel=(t.end-t.start)/r}else t.start=s-r*t.bpPerPixel/2,t.end=t.start+r*t.bpPerPixel;this.updateViews()}}}}}}function hy(e,t){for(let{viewports:i}of e)for(let e of i)e.trackLabelElement&&(0===i.indexOf(e)&&!0===t?e.trackLabelElement.style.display="block":e.trackLabelElement.style.display="none")}let dy=[];function uy(e,t){void 0===t&&(t=fy);for(const i of Object.keys(t))void 0===e[i]&&(e[i]=t[i]);return e}const fy={minimumBases:40,showIdeogram:!0,showCytobandNames:!1,showCircularView:!1,showCircularViewButton:!1,showTrackLabelButton:!0,showTrackLabels:!0,showCursorTrackingGuideButton:!0,showCursorGuide:!1,showCenterGuideButton:!0,showCenterGuide:!1,showSampleNames:!1,showSVGButton:!0,showControls:!0,showNavigation:!0,showRuler:!0,flanking:1e3,pairsSupported:!0,tracks:[]},py=Rr.setApiKey;const gy=Rr.oauth;var my={AlertDialog:Ao,TrackUtils:jd,IGVGraphics:Co,MenuUtils:Bd,DataRangeDialog:Hd,createTrack:async function(e,t){return await oy.prototype.createTrack.call(t,e)},createBrowser:async function(e,t){void 0===t&&(t={}),Dh.KNOWN_GENOMES||await Dh.initializeGenomes(t),uy(t),t.queryParametersSupported&&function(e){var t,i,r,s,o,n,a,c,l;let h,d,u;if(a=window.location.href,o={},t=a.indexOf("?"),i=a.lastIndexOf("#"),t>=0)for(i<0&&(i=a.length),r=t+1;rt&&(i.indexURL=d[t]),u&&u.length>t&&(i.name=u[t]),e.tracks.push(i)}}}(t),t.apiKey&&Rr.setApiKey(t.apiKey),t.oauthToken&&Rr.setOauthToken(t.oauthToken),t.clientId&&!Cr()&&await async function(e){if(!google.accounts.oauth2.initTokenClient)throw new Error("Google accounts token client not loaded (https://accounts.google.com/gsi/client)");if(Cr())throw new Error("Google client is already initialized");const t={client_id:e.client_id||e.clientId,scope:e.scope||"https://www.googleapis.com/auth/userinfo.profile",state:e.state||"igv",error:e=>{throw new Error(e.type)},hint:e.hint,hosted_domain:e.hosted_domain},i=google.accounts.oauth2.initTokenClient(t);google.igv={tokenClient:i,apiKey:e.apiKey}}({client_id:t.clientId,apiKey:t.apiKey,scope:"https://www.googleapis.com/auth/userinfo.profile"}),t.formEmbedMode&&(Od.FORM_EMBED_MODE=!0);const i=new oy(t,e);dy.push(i);const r=t.sessionURL||t.session||t.hubURL;return r?await i.loadSession({url:r}):await i.loadSessionObject(t),i.navbar.navbarDidResize(),i},removeBrowser:function(e){e.dispose(),e.root.remove(),dy=dy.filter((t=>t!==e))},removeAllBrowsers:function(){for(let e of dy)e.dispose(),e.root.remove();dy=[]},visibilityChange:async function(){for(let e of dy)await e.visibilityChange()},setGoogleOauthToken:function(e){return Rr.setOauthToken(e)},setOauthToken:function(e,t){return Rr.setOauthToken(e,t)},oauth:gy,version:jF,setApiKey:py,TrackBase:ma,registerTrackClass:function(e,t){qF.set(e,((e,i)=>new t(e,i)))},registerTrackCreatorFunction:function(e,t){qF.set(e,t)},registerFileFormats:function(e,t){na[e]={fields:t}},loadSessionFile:oy.loadSessionFile,loadHub:Nh,uncompressSession:oy.uncompressSession,createIcon:l};return my})); + */var yf=function(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")},Af=function(){function e(e,t){for(var i=0;i1&&void 0!==arguments[1]?arguments[1]:1;return(t>0?e.toFixed(t).replace(/0+$/,"").replace(/\.$/,""):e.toString())||"0"}var kf=function(){function e(t,i,r,s){yf(this,e);var o=this;if(void 0===t);else if(Array.isArray(t))this.rgba=t;else if(void 0===r){var n=t&&""+t;n&&function(t){if(t.startsWith("hsl")){var i=t.match(/([\-\d\.e]+)/g).map(Number),r=Cf(i,4),s=r[0],n=r[1],a=r[2],c=r[3];void 0===c&&(c=1),s/=360,n/=100,a/=100,o.hsla=[s,n,a,c]}else if(t.startsWith("rgb")){var l=t.match(/([\-\d\.e]+)/g).map(Number),h=Cf(l,4),d=h[0],u=h[1],f=h[2],p=h[3];void 0===p&&(p=1),o.rgba=[d,u,f,p]}else t.startsWith("#")?o.rgba=e.hexToRgb(t):o.rgba=e.nameToRgb(t)||e.hexToRgb(t)}(n.toLowerCase())}else this.rgba=[t,i,r,void 0===s?1:s]}return Af(e,[{key:"printRGB",value:function(e){var t=(e?this.rgba:this.rgba.slice(0,3)).map((function(e,t){return xf(e,3===t?3:0)}));return e?"rgba("+t+")":"rgb("+t+")"}},{key:"printHSL",value:function(e){var t=[360,100,100,1],i=["","%","%",""],r=(e?this.hsla:this.hsla.slice(0,3)).map((function(e,r){return xf(e*t[r],3===r?3:1)+i[r]}));return e?"hsla("+r+")":"hsl("+r+")"}},{key:"printHex",value:function(e){var t=this.hex;return e?t:t.substring(0,7)}},{key:"rgba",get:function(){if(this._rgba)return this._rgba;if(!this._hsla)throw new Error("No color is set");return this._rgba=e.hslToRgb(this._hsla)},set:function(e){3===e.length&&(e[3]=1),this._rgba=e,this._hsla=null}},{key:"rgbString",get:function(){return this.printRGB()}},{key:"rgbaString",get:function(){return this.printRGB(!0)}},{key:"hsla",get:function(){if(this._hsla)return this._hsla;if(!this._rgba)throw new Error("No color is set");return this._hsla=e.rgbToHsl(this._rgba)},set:function(e){3===e.length&&(e[3]=1),this._hsla=e,this._rgba=null}},{key:"hslString",get:function(){return this.printHSL()}},{key:"hslaString",get:function(){return this.printHSL(!0)}},{key:"hex",get:function(){return"#"+this.rgba.map((function(e,t){return t<3?e.toString(16):Math.round(255*e).toString(16)})).map((function(e){return e.padStart(2,"0")})).join("")},set:function(t){this.rgba=e.hexToRgb(t)}}],[{key:"hexToRgb",value:function(e){var t=(e.startsWith("#")?e.slice(1):e).replace(/^(\w{3})$/,"$1F").replace(/^(\w)(\w)(\w)(\w)$/,"$1$1$2$2$3$3$4$4").replace(/^(\w{6})$/,"$1FF");if(!t.match(/^([0-9a-fA-F]{8})$/))throw new Error("Unknown hex color; "+e);var i=t.match(/^(\w\w)(\w\w)(\w\w)(\w\w)$/).slice(1).map((function(e){return parseInt(e,16)}));return i[3]=i[3]/255,i}},{key:"nameToRgb",value:function(t){var i=t.toLowerCase().replace("at","T").replace(/[aeiouyldf]/g,"").replace("ght","L").replace("rk","D").slice(-5,4),r=_f[i];return void 0===r?r:e.hexToRgb(r.replace(/\-/g,"00").padStart(6,"f"))}},{key:"rgbToHsl",value:function(e){var t=Cf(e,4),i=t[0],r=t[1],s=t[2],o=t[3];i/=255,r/=255,s/=255;var n=Math.max(i,r,s),a=Math.min(i,r,s),c=void 0,l=void 0,h=(n+a)/2;if(n===a)c=l=0;else{var d=n-a;switch(l=h>.5?d/(2-n-a):d/(n+a),n){case i:c=(r-s)/d+(r1&&(i-=1),i<1/6?e+6*(t-e)*i:i<.5?t:i<2/3?e+(t-e)*(2/3-i)*6:e},h=s<.5?s*(1+r):s+r-s*r,d=2*s-h;n=l(d,h,i+1/3),a=l(d,h,i),c=l(d,h,i-1/3)}var u=[255*n,255*a,255*c].map(Math.round);return u[3]=o,u}}]),e}(),If=function(){function e(){yf(this,e),this._events=[]}return Af(e,[{key:"add",value:function(e,t,i){e.addEventListener(t,i,!1),this._events.push({target:e,type:t,handler:i})}},{key:"remove",value:function(t,i,r){this._events=this._events.filter((function(s){var o=!0;return t&&t!==s.target&&(o=!1),i&&i!==s.type&&(o=!1),r&&r!==s.handler&&(o=!1),o&&e._doRemove(s.target,s.type,s.handler),!o}))}},{key:"destroy",value:function(){this._events.forEach((function(t){return e._doRemove(t.target,t.type,t.handler)})),this._events=[]}}],[{key:"_doRemove",value:function(e,t,i){e.removeEventListener(t,i,!1)}}]),e}();function Sf(e,t,i){var r=!1;function s(e,t,i){return Math.max(t,Math.min(e,i))}function o(e,o,n){if(n&&(r=!0),r){e.preventDefault();var a=t.getBoundingClientRect(),c=a.width,l=a.height,h=o.clientX,d=o.clientY,u=s(h-a.left,0,c),f=s(d-a.top,0,l);i(u/c,f/l)}}function n(e,t){1===(void 0===e.buttons?e.which:e.buttons)?o(e,e,t):r=!1}function a(e,t){1===e.touches.length?o(e,e.touches[0],t):r=!1}e.add(t,"mousedown",(function(e){n(e,!0)})),e.add(t,"touchstart",(function(e){a(e,!0)})),e.add(window,"mousemove",n),e.add(t,"touchmove",a),e.add(window,"mouseup",(function(e){r=!1})),e.add(t,"touchend",(function(e){r=!1})),e.add(t,"touchcancel",(function(e){r=!1}))}var Ef="keydown",Nf="mousedown",Mf="focusin";function Rf(e,t){return(t||document).querySelector(e)}function Bf(e){e.preventDefault(),e.stopPropagation()}function Df(e,t,i,r,s){e.add(t,Ef,(function(e){i.indexOf(e.key)>=0&&(s&&Bf(e),r(e))}))}var Lf=function(){function e(t){yf(this,e),this.settings={popup:"right",layout:"default",alpha:!0,editor:!0,editorFormat:"hex",cancelButton:!1,defaultColor:"#0cf"},this._events=new If,this.onChange=null,this.onDone=null,this.onOpen=null,this.onClose=null,this.setOptions(t)}return Af(e,[{key:"setOptions",value:function(e){var t=this;if(e){var i=this.settings;if(e instanceof HTMLElement)i.parent=e;else{i.parent&&e.parent&&i.parent!==e.parent&&(this._events.remove(i.parent),this._popupInited=!1),function(e,t,i){for(var r in e)i&&i.indexOf(r)>=0||(t[r]=e[r])}(e,i),e.onChange&&(this.onChange=e.onChange),e.onDone&&(this.onDone=e.onDone),e.onOpen&&(this.onOpen=e.onOpen),e.onClose&&(this.onClose=e.onClose);var r=e.color||e.colour;r&&this._setColor(r)}var s=i.parent;if(s&&i.popup&&!this._popupInited){var o=function(e){return t.openHandler(e)};this._events.add(s,"click",o),Df(this._events,s,[" ","Spacebar","Enter"],o),this._popupInited=!0}else e.parent&&!i.popup&&this.show()}}},{key:"openHandler",value:function(e){if(this.show()){e&&e.preventDefault(),this.settings.parent.style.pointerEvents="none";var t=e&&e.type===Ef?this._domEdit:this.domElement;setTimeout((function(){return t.focus()}),100),this.onOpen&&this.onOpen(this.colour)}}},{key:"closeHandler",value:function(e){var t=e&&e.type,i=!1;if(e)if(t===Nf||t===Mf){var r=(this.__containedEvent||0)+100;e.timeStamp>r&&(i=!0)}else Bf(e),i=!0;else i=!0;i&&this.hide()&&(this.settings.parent.style.pointerEvents="",t!==Nf&&this.settings.parent.focus(),this.onClose&&this.onClose(this.colour))}},{key:"movePopup",value:function(e,t){this.closeHandler(),this.setOptions(e),t&&this.openHandler()}},{key:"setColor",value:function(e,t){this._setColor(e,{silent:t})}},{key:"_setColor",value:function(e,t){if("string"==typeof e&&(e=e.trim()),e){t=t||{};var i=void 0;try{i=new kf(e)}catch(e){if(t.failSilently)return;throw e}if(!this.settings.alpha){var r=i.hsla;r[3]=1,i.hsla=r}this.colour=this.color=i,this._setHSLA(null,null,null,null,t)}}},{key:"setColour",value:function(e,t){this.setColor(e,t)}},{key:"show",value:function(){if(!this.settings.parent)return!1;if(this.domElement){var e=this._toggleDOM(!0);return this._setPosition(),e}var t=function(e){var t=document.createElement("div");return t.innerHTML=e,t.firstElementChild}(this.settings.template||'
');return this.domElement=t,this._domH=Rf(".picker_hue",t),this._domSL=Rf(".picker_sl",t),this._domA=Rf(".picker_alpha",t),this._domEdit=Rf(".picker_editor input",t),this._domSample=Rf(".picker_sample",t),this._domOkay=Rf(".picker_done button",t),this._domCancel=Rf(".picker_cancel button",t),t.classList.add("layout_"+this.settings.layout),this.settings.alpha||t.classList.add("no_alpha"),this.settings.editor||t.classList.add("no_editor"),this.settings.cancelButton||t.classList.add("no_cancel"),this._ifPopup((function(){return t.classList.add("popup")})),this._setPosition(),this.colour?this._updateUI():this._setColor(this.settings.defaultColor),this._bindEvents(),!0}},{key:"hide",value:function(){return this._toggleDOM(!1)}},{key:"destroy",value:function(){this._events.destroy(),this.domElement&&this.settings.parent.removeChild(this.domElement)}},{key:"_bindEvents",value:function(){var e=this,t=this,i=this.domElement,r=this._events;function s(e,t,i){r.add(e,t,i)}s(i,"click",(function(e){return e.preventDefault()})),Sf(r,this._domH,(function(e,i){return t._setHSLA(e)})),Sf(r,this._domSL,(function(e,i){return t._setHSLA(null,e,1-i)})),this.settings.alpha&&Sf(r,this._domA,(function(e,i){return t._setHSLA(null,null,null,1-i)}));var o=this._domEdit;s(o,"input",(function(e){t._setColor(this.value,{fromEditor:!0,failSilently:!0})})),s(o,"focus",(function(e){var t=this;t.selectionStart===t.selectionEnd&&t.select()})),this._ifPopup((function(){var t=function(t){return e.closeHandler(t)};s(window,Nf,t),s(window,Mf,t),Df(r,i,["Esc","Escape"],t);var o=function(t){e.__containedEvent=t.timeStamp};s(i,Nf,o),s(i,Mf,o),s(e._domCancel,"click",t)}));var n=function(t){e._ifPopup((function(){return e.closeHandler(t)})),e.onDone&&e.onDone(e.colour)};s(this._domOkay,"click",n),Df(r,i,["Enter"],n)}},{key:"_setPosition",value:function(){var e=this.settings.parent,t=this.domElement;e!==t.parentNode&&e.appendChild(t),this._ifPopup((function(i){"static"===getComputedStyle(e).position&&(e.style.position="relative");var r=!0===i?"popup_right":"popup_"+i;["popup_top","popup_bottom","popup_left","popup_right"].forEach((function(e){e===r?t.classList.add(e):t.classList.remove(e)})),t.classList.add(r)}))}},{key:"_setHSLA",value:function(e,t,i,r,s){s=s||{};var o=this.colour,n=o.hsla;[e,t,i,r].forEach((function(e,t){(e||0===e)&&(n[t]=e)})),o.hsla=n,this._updateUI(s),this.onChange&&!s.silent&&this.onChange(o)}},{key:"_updateUI",value:function(e){if(this.domElement){e=e||{};var t=this.colour,i=t.hsla,r="hsl("+360*i[0]+", 100%, 50%)",s=t.hslString,o=t.hslaString,n=this._domH,a=this._domSL,c=this._domA,l=Rf(".picker_selector",n),h=Rf(".picker_selector",a),d=Rf(".picker_selector",c);b(0,l,i[0]),this._domSL.style.backgroundColor=this._domH.style.color=r,b(0,h,i[1]),F(0,h,1-i[2]),a.style.color=s,F(0,d,1-i[3]);var u=s,f=u.replace("hsl","hsla").replace(")",", 0)"),p="linear-gradient("+[u,f]+")";if(this._domA.style.background=p+", linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0 / 2em 2em,\n linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em / 2em 2em",!e.fromEditor){var g=this.settings.editorFormat,m=this.settings.alpha,w=void 0;switch(g){case"rgb":w=t.printRGB(m);break;case"hsl":w=t.printHSL(m);break;default:w=t.printHex(m)}this._domEdit.value=w}this._domSample.style.color=o}function b(e,t,i){t.style.left=100*i+"%"}function F(e,t,i){t.style.top=100*i+"%"}}},{key:"_ifPopup",value:function(e,t){this.settings.parent&&this.settings.popup?e&&e(this.settings.popup):t&&t()}},{key:"_toggleDOM",value:function(e){var t=this.domElement;if(!t)return!1;var i=e?"":"none",r=t.style.display!==i;return r&&(t.style.display=i),r}}]),e}(),Tf=document.createElement("style");function zf(e){if(Pf[e])return Pf[e];if(Pf["chr"+e]){const t=Pf["chr"+e];return Pf[e]=t,t}{const s=(t=Math.round(255*Math.random()).toString(10),i=Math.round(255*Math.random()).toString(10),r=Math.round(255*Math.random()).toString(10),"rgb("+t+","+i+","+r+")");return Pf[e]=s,s}var t,i,r}Tf.textContent='.picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{position:absolute;z-index:-1;opacity:0}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{display:flex;flex-flow:row wrap;justify-content:space-between;align-items:stretch;font-size:10px;width:25em;padding:.5em}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper::before{content:"";display:block;width:100%;height:0;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:1 1 auto}.layout_default .picker_sl::before{content:"";display:block;padding-bottom:100%}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{order:1;flex:1 1 auto}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;background:#f2f2f2;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;box-shadow:0 0 0 1px silver;outline:none}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{padding:.4em .6em;cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(0deg, gainsboro, transparent)}.picker_wrapper button:active{background-image:linear-gradient(0deg, transparent, gainsboro)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid #fff;border-radius:100%;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);box-shadow:0 0 0 1px silver}.picker_sl{position:relative;box-shadow:0 0 0 1px silver;background-image:linear-gradient(180deg, white, rgba(255, 255, 255, 0) 50%),linear-gradient(0deg, black, rgba(0, 0, 0, 0) 50%),linear-gradient(90deg, #808080, rgba(128, 128, 128, 0))}.picker_alpha,.picker_sample{position:relative;background:linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0/2em 2em,linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em/2em 2em;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{font-family:monospace;padding:.2em .4em}.picker_sample::before{content:"";position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;box-shadow:0 0 10px 1px rgba(0,0,0,.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:"";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}',document.documentElement.firstElementChild.appendChild(Tf),Lf.StyleElement=Tf;const Pf={chrX:"rgb(204, 153, 0)",chrY:"rgb(153, 204, 0",chrUn:"rgb(50, 50, 50)",chr1:"rgb(80, 80, 255)",chrI:"rgb(139, 155, 187)",chr2:"rgb(206, 61, 50)",chrII:"rgb(206, 61, 50)",chr2a:"rgb(216, 71, 60)",chr2b:"rgb(226, 81, 70)",chr3:"rgb(116, 155, 88)",chrIII:"rgb(116, 155, 88)",chr4:"rgb(240, 230, 133)",chrIV:"rgb(240, 230, 133)",chr5:"rgb(70, 105, 131)",chr6:"rgb(186, 99, 56)",chr7:"rgb(93, 177, 221)",chr8:"rgb(128, 34, 104)",chr9:"rgb(107, 215, 107)",chr10:"rgb(213, 149, 167)",chr11:"rgb(146, 72, 34)",chr12:"rgb(131, 123, 141)",chr13:"rgb(199, 81, 39)",chr14:"rgb(213, 143, 92)",chr15:"rgb(122, 101, 165)",chr16:"rgb(228, 175, 105)",chr17:"rgb(59, 27, 83)",chr18:"rgb(205, 222, 183)",chr19:"rgb(97, 42, 121)",chr20:"rgb(174, 31, 99)",chr21:"rgb(231, 199, 111)",chr22:"rgb(90, 101, 94)",chr23:"rgb(204, 153, 0)",chr24:"rgb(153, 204, 0)",chr25:"rgb(51, 204, 0)",chr26:"rgb(0, 204, 51)",chr27:"rgb(0, 204, 153)",chr28:"rgb(0, 153, 204)",chr29:"rgb(10, 71, 255)",chr30:"rgb(71, 117, 255)",chr31:"rgb(255, 194, 10)",chr32:"rgb(255, 209, 71)",chr33:"rgb(153, 0, 51)",chr34:"rgb(153, 26, 0)",chr35:"rgb(153, 102, 0)",chr36:"rgb(128, 153, 0)",chr37:"rgb(51, 153, 0)",chr38:"rgb(0, 153, 26)",chr39:"rgb(0, 153, 102)",chr40:"rgb(0, 128, 153)",chr41:"rgb(0, 51, 153)",chr42:"rgb(26, 0, 153)",chr43:"rgb(102, 0, 153)",chr44:"rgb(153, 0, 128)",chr45:"rgb(214, 0, 71)",chr46:"rgb(255, 20, 99)",chr47:"rgb(0, 214, 143)",chr48:"rgb(20, 255, 177)"};class Hf{constructor(e){this.tracks=[],this.chordSets=[]}addChordSet(e){this.chordSets=this.chordSets.filter((t=>t.name!==e.name)),this.chordSets.push(e);let t=this.tracks.find((t=>e.trackName===t.name));t&&(t.chordSets=t.chordSets.filter((t=>t.name!==e.name)),t.chordSets.push(e)),t||(t=new Of(e),this.tracks.push(t))}clearChords(){this.tracks=[],this.chordSets=[]}getTrack(e){return this.tracks.find((t=>e===t.name))}getChordSet(e){return this.chordSets.find((t=>e===t.name))}}class Of{constructor(e){this.name=e.trackName,this.color=e.trackColor,this.visible=!0,this.chordSets=[e],this.id=("0000"+(Math.random()*Math.pow(36,4)|0).toString(36)).slice(-4)}get chords(){if(1===this.chordSets.length)return this.chordSets[0].chords;const e=[];for(let t of this.chordSets)for(let i of t.chords)e.push(i);return e}}const Vf=Math.exp(5);class qf{static isInstalled(){return void 0!==window.JBrowseReactCircularGenomeView&&void 0!==window.React&&void 0!==window.ReactDOM}constructor(e,t){if(t=t||{},this.config=t,qf.isInstalled()){this.parent=e,this.groupByTrack=!0===t.groupByTrack,this.chordManager=new Hf(t);const i=document.createElement("div");i.className="igv-circview-container",e.appendChild(i),this.createControls(i),this.resetControlPanel();const r=document.createElement("div");r.className="igv-circview-circular-genome-view",i.appendChild(r),this.container=r,t.assembly&&this.setAssembly(t.assembly),this.width=t.width||500,this.height=t.height||500,this.setSize(this.width,this.height)}else console.error("JBrowse circular view is not installed")}createControls(e){const t=document.createElement("div");t.className="igv-circview-toolbar",e.appendChild(t),this.toolbar=t;const i=document.createElement("div");i.className="igv-circview-track-panel",e.appendChild(i),this.controlPanel=i,this.controlPanel.style.display="none";const r=document.createElement("div");r.className="igv-circview-toolbar-button-container",this.toolbar.appendChild(r),this.showControlsButton=document.createElement("div"),this.showControlsButton.className="igv-circview-button",r.appendChild(this.showControlsButton),this.showControlsButton.innerText="none"===this.controlPanel.style.display?"Show Controls":"Hide Controls",this.showControlsButton.addEventListener("click",(e=>{this.controlPanel.querySelectorAll("div").length>0&&("none"===this.controlPanel.style.display?(this.controlPanel.style.display="flex",e.target.innerText="Hide Controls"):(this.controlPanel.style.display="none",e.target.innerText="Show Controls"))}));let s=document.createElement("div");s.className="igv-circview-button",r.appendChild(s),s.innerText="Clear All",s.addEventListener("click",(()=>{this.clearChords()})),!1!==this.config.showCloseButton&&(s=document.createElement("div"),s.className="igv-circview-button",r.appendChild(s),s.innerText="Close",s.addEventListener("click",(()=>{this.visible=!1})))}resetControlPanel(){this.controlPanel.innerHTML="",this.controlPanel.appendChild(this.createGroupByCB());const e=this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets;for(let t of e)this.addToControlPanel(t)}createGroupByCB(){const e=document.createElement("input");e.type="checkbox",e.id="groupByCB",e.style.width="1.4em",e.style.height="1.4em",e.checked=this.groupByTrack,e.onclick=e=>{this.groupByTrack=e.target.checked,this.resetControlPanel(),this.render()};const t=document.createElement("label");t.for="groupByCB",t.innerText="Group by track",t.style.color="black",t.style.paddingLeft="10px";const i=document.createElement("div");return i.style.width="100%",i.style.paddingTop="5px",i.style.paddingBottom="5px",i.style.background="rgb(216, 230, 234)",i.appendChild(e),i.appendChild(t),i}addToControlPanel(e){const t=document.createElement("div");this.controlPanel.appendChild(t);const i=document.createElement("div");i.className="igv-circview-button",t.appendChild(i),i.innerText=!0===e.visible?"Hide":"Show",i.addEventListener("click",(t=>{!0===e.visible?(this.hideChordSet(e.name),t.target.innerText="Show"):(this.showChordSet(e.name),t.target.innerText="Hide")}));const r=document.createElement("input"),s=e=>200*Math.log(e*Vf),o=document.createElement("div");o.className="igv-circview-button",o.innerHTML="    ",t.appendChild(o),o.style.backgroundColor=Uf(e.color,1);const n={parent:o,popup:"right",editorFormat:"rgb",color:e.color,onChange:({rgbaString:t})=>{o.style.backgroundColor=Uf(t,1),this.setColor(e.name,t),r.value=s(Qf(e.color))}},a=new Lf(n);r.setAttribute("title","Adjust transparency of arcs"),r.type="range",r.style.width="100px",r.style.marginRight="10px",r.setAttribute("class","range"),r.setAttribute("min","0"),r.setAttribute("max","1000"),r.value=s(Qf(e.color)),r.oninput=()=>{const t=(i=r.value,Math.exp(i/200)/Vf);var i;this.setColor(e.name,Uf(e.color,t)),a.setColor(e.color)},t.appendChild(r);const c=document.createElement("div");c.style.color="black",t.appendChild(c),c.innerText=c.title=e.name}setAssembly(e){const t=this.genomeId||Wf();if(this.genomeId===t)return;this.chordManager.clearChords(),this.genomeId=t,this.chrNames=new Set(e.chromosomes.map((e=>Gf(e.name))));const i=[],r=[];for(let t of e.chromosomes){const e=Gf(t.name);r.push(t.color||zf(e)),i.push({refName:e,uniqueId:e,start:0,end:t.bpLength})}this.assembly={name:e.name,sequence:{trackId:t,type:"ReferenceSequenceTrack",adapter:{type:"FromConfigSequenceAdapter",features:i}},refNameColors:r},this.render()}addChords(e,t={}){const i=t.name||t.track||"*",r=i.split(" ")[0].replaceAll("%20"," "),s={name:i.replaceAll("%20"," "),trackName:r,chords:e,color:t.color||"black",trackColor:t.trackColor||t.color||"black",visible:!0,id:t.id||Wf()};this.chordManager.addChordSet(s),this.resetControlPanel(),this.render()}setSize(e,t){if(t=t||e,this.width=e,this.height=t,this.viewState){const i=this.viewState.session.view;i.setWidth(e),i.setHeight(t),i.setBpPerPx(i.minBpPerPx)}}getSize(){return Math.min(this.width,this.height)}clearChords(){this.chordManager.clearChords(),this.resetControlPanel(),this.render()}clearSelection(){this.viewState.pluginManager.rootModel.session.clearSelection()}show(){this.parent.style.display="block"}hide(){this.parent.style.display="none"}get visible(){return"none"!==this.parent.style.display}set visible(e){this.parent.style.display=e?"block":"none"}hideChordSet(e){let t=this.getChordSet(e);t?(t.visible=!1,this.render()):console.warn(`No track with name: ${name}`)}showChordSet(e){let t=this.getChordSet(e);t?(t.visible=!0,this.render()):console.warn(`No track with name: ${e}`)}deleteTrack(e){let t=this.tracks.findIndex((t=>e===t.name));t>=0&&this.tracks.splice(t,1),this.render()}getChordSet(e){return this.groupByTrack?this.chordManager.getTrack(e):this.chordManager.getChordSet(e)}setColor(e,t){const i=this.getChordSet(e);if(i){i.color=t;const e=i.id;for(let i of this.viewState.config.tracks)if(e===i.trackId){i.displays[0].renderer.strokeColor.set(t);break}}}render(){const{createViewState:e,JBrowseCircularGenomeView:t}=JBrowseReactCircularGenomeView;ReactDOM.unmountComponentAtNode(this.container);const i=(this.groupByTrack?this.chordManager.tracks:this.chordManager.chordSets).filter((e=>e.visible)),r=[],s=[];for(let e of i)r.push({trackId:e.id,name:e.name,assemblyNames:["forIGV"],type:"VariantTrack",adapter:{type:"FromConfigAdapter",features:e.chords}}),s.push(e.color);this.viewState=e({assembly:this.assembly,tracks:r});for(let e=0;e div {\n margin: 4px;\n}\n\n.igv-circview-track-panel {\n z-index: 1024;\n position: absolute;\n top: 33px;\n left: 0;\n width: 100%;\n height: fit-content;\n border-bottom-style: solid;\n border-bottom-color: dimgray;\n border-bottom-width: thin;\n background-color: white;\n display: flex;\n flex-flow: column;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: flex-start;\n}\n.igv-circview-track-panel > div {\n display: flex;\n flex-flow: row;\n flex-wrap: nowrap;\n justify-content: flex-start;\n align-items: center;\n}\n.igv-circview-track-panel > div > div {\n margin: 4px;\n}\n\n.igv-circview-swatch-button {\n cursor: pointer;\n padding: 5px;\n width: 8px;\n height: 8px;\n border: 1px solid #8d8b8b;\n border-radius: 16px;\n}\n\n.igv-circview-button {\n cursor: pointer;\n padding: 5px;\n color: #444;\n vertical-align: middle;\n text-align: center;\n font-family: "Open Sans", sans-serif;\n font-size: 12px;\n border: 1px solid #8d8b8b;\n border-radius: 4px;\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.2);\n}\n\n.igv-circview-button:hover {\n background: #efefef;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n.igv-circview-button:active {\n color: #007bff;\n box-shadow: 0 0 5px -1px rgba(0, 0, 0, 0.6);\n}\n\n/*# sourceMappingURL=circular-view.css.map */\n',document.head.insertBefore(e,document.head.childNodes[document.head.childNodes.length-1])}()}const $f=e=>e.startsWith("chr")?e.substring(3):e;function Kf(e){const t=[],i=[];if(e.wgChromosomeNames)for(let r of e.wgChromosomeNames){const s=e.getChromosome(r);i.push($h(s.name)),t.push({name:s.name,bpLength:s.bpLength})}return t}function Yf(e,t,i,r){const s=t.color||"rgb(0,0,255)",o=ur.addAlpha("all"===i.chr?s:$h(i.chr),r),n=ur.addAlpha(s,r),a=t.name.replaceAll(" ","%20"),c="all"===i.chr?a:`${a} ${i.chr}:${i.start}-${i.end}`;t.browser.circularView.addChords(e,{track:c,color:o,trackColor:n}),t.browser.circularViewVisible||(t.browser.circularViewVisible=!0)}class Zf{constructor(e,{minTLENPercentile:t,maxTLENPercentile:i}){this.totalCount=0,this.frCount=0,this.rfCount=0,this.ffCount=0,this.sumF=0,this.sumF2=0,this.lp=void 0===t?.1:t,this.up=void 0===i?99.5:i,this.isizes=[],this.compute(e)}compute(e){for(let r of e)if(r.isProperPair()){var t=Math.abs(r.fragmentLength);this.sumF+=t,this.sumF2+=t*t,this.isizes.push(t);var i=r.pairOrientation;if("string"==typeof i&&4===i.length)switch(""+i.charAt(0)+i.charAt(2)){case"FF":case"RR":this.ffCount++;break;case"FR":this.frCount++;break;case"RF":this.rfCount++}this.totalCount++}this.ffCount/this.totalCount>.9?this.orienation="ff":this.frCount/this.totalCount>.9?this.orienation="fr":this.rfCount/this.totalCount>.9&&(this.orienation="rf"),this.minTLEN=0===this.lp?0:Xf(this.isizes,this.lp),this.maxTLEN=Xf(this.isizes,this.up)}}function Xf(e,t){if(0!==e.length){var i=Math.floor(e.length*(t/100));return e.sort((function(e,t){return e-t})),e[i]}}const Jf="rgb(255,0,255)",ep="rgb(0,0,255)",tp="rgb(132, 178, 158)",ip=new Map;ip.set("m","rgb(255,0,0)"),ip.set("h",Jf),ip.set("o","rgb(111, 78, 129)"),ip.set("f","rgb(246, 200, 95)"),ip.set("c","rgb(157, 216, 102)"),ip.set("g","rgb(255, 160, 86)"),ip.set("e","rgb(141, 221, 208)"),ip.set("b","rgb(202, 71, 47)"),ip.set("h",Jf),ip.set("a","rgb(51,0,111)"),ip.set("NONE_A",ep),ip.set("NONE_C",ep),ip.set("NONE_T",ep),ip.set("NONE_G",ep),ip.set("NONE_N",ep);const rp=new Map;function sp(e,t,i){let r=function(e){return ip.has(e)?ip.get(e):tp}(e),s=lu(t);if(s>255)return r;const o=e+s+i;if(s<0&&(s=0),!rp.has(o)){const e="basemod2"===i?Math.max(20,Math.min(255,s*s/50-4*s+200+20)):Math.max(20,Math.min(255,.006127*s*s)),[t,n,a]=ur.rgbComponents(r);rp.set(o,`rgba(${t},${n},${a},${e/255})`)}return rp.get(o)}class op{constructor(e){this.alignmentTrack=e}updateContext(e){this.context=e}drawModifications(e,t,i,r,s,o){const{ctx:n,pixelEnd:a,bpStart:c,bpPerPixel:l}=r,h=e.getBaseModificationSets();if(h){let r;const d=s.split(":");2==d.length&&(s=d[0],r=d[1]);for(let d of e.blocks){if("S"===d.type)continue;const e=t,u=i;let f=Math.max(1,1/l);for(let t=d.seqOffset;ta)break;if(i+f<0)continue;let p,g=-1,m=255,w=0;for(let e of h)if((!r||e.modification===r)&&e.containsPosition(t)){const i=lu(e.likelihoods.get(t));m-=i,(!p||i>g)&&(p=e.modification,w=e.canonicalBase,g=i)}if(p){const t=255*o;let r;m>g&&"basemod2"===s&&m>=t?r=sp("NONE_"+w,m,s):g>=t&&(r=sp(p,g,s)),n.fillStyle=r,f<3&&(f=3,i--),n.fillRect(i,e,f,Math.max(1,u-2))}}}}}}const np=new Set(["firstOfPairStrand"]);class ap extends ma{static defaults={viewAsPairs:!1,showSoftClips:!1,showAllBases:!1,showInsertions:!0,showMismatches:!0,colorBy:void 0,groupBy:void 0,displayMode:"EXPANDED",alignmentRowHeight:14,squishedRowHeight:3,negStrandColor:"rgba(150, 150, 230, 0.75)",posStrandColor:"rgba(230, 150, 150, 0.75)",baseModPosStrandColor:"rgb(195, 195, 195)",baseModNegStrandColor:"rgb(195, 210, 195)",insertionColor:"rgb(138, 94, 161)",insertionTextColor:"white",showInsertionText:!1,deletionColor:"black",deletionTextColor:"black",showDeletionText:!1,skippedColor:"rgb(150, 170, 170)",pairConnectorColor:void 0,smallTLENColor:"rgb(0, 0, 150)",largeTLENColor:"rgb(200, 0, 0)",expectedPairOrientation:"fr",rlColor:"rgb(0, 150, 0)",rrColor:"rgb(20, 50, 200)",llColor:"rgb(0, 150, 150)",bamColorTag:"YC",hideSmallIndels:!1,indelSizeThreshold:1,highlightColor:void 0,minTLEN:void 0,maxTLEN:void 0,tagColorPallete:"Set1"};_colorTables=new Map;_baseModifications=new Set;constructor(e,t){super(e,t),(e.colorTable||e.tagColorTable)&&(this.colorTable=new $r(e.tagColorTable)),e.showTags&&e.hideTags&&console.warn("Both showTags and hideTags specified. showTags will be used."),e.showTags?(this.showTags=new Set(e.showTags),this.hiddenTags=new Set):this.hiddenTags=new Set(e.hideTags||["SA","MD"]),e.largeFragmentLengthColor&&(this.largeTLENColor=e.largeFragmentLengthColor),e.pairOrienation&&(this.expectedPairOrientation=e.pairOrientation),e.smallFragmentLengthColor&&(this.smallTLENColor=e.smallFragmentLengthColor),e.largeFragmentLengthColor&&(this.largeTLENColor=e.largeFragmentLengthColor),e.minFragmentLength&&(this.minTLEN=e.minFragmentLength),e.maxFragmentLength&&(this.maxTLEN=e.maxFragmentLength),e.displayMode&&(this.displayMode=e.displayMode.toUpperCase()),e.colorBy&&e.colorByTag&&(this.colorBy=e.colorBy+":"+e.colorByTag),this.featureSource=this.parent.featureSource,this.top=0===e.coverageTrackHeight?0:e.coverageTrackHeight+5,this.pairColors={RL:this.rlColor,RR:this.rrColor,LL:this.llColor},e.highlightedReads&&this.setHighlightedReads(e.highlightedReads),this.hasPairs=!1,this.hasSupplemental=!1,this._groupByTags=[],this._groupByPositions=[],e.groupBy&&(this.groupBy=e.groupBy,e.groupBy.startsWith("base:")&&this._groupByPositions.push(e.groupBy.substring(5)),e.groupBy.startsWith("tag:")&&this._groupByTags.push(e.groupBy.substring(4))),this._locusChange=lp.bind(this),this.browser.on("locuschange",this._locusChange)}init(e){this.parent=e.parent,delete e.parent,super.init(e)}dispose(){this.browser.off("locuschange",this._locusChange)}get baseModRenderer(){return this._baseModRenderer||(this._baseModRenderer=new op(this)),this._baseModRenderer}get baseModificationThreshold(){return this.parent.baseModificationThreshold}setTop(e,t){this.top=0===e.height||!1===t?0:5+e.height}setHighlightedReads(e,t){if(!Array.isArray(e)||!e.every((e=>"string"==typeof e)))throw new Error("AlignmentTrack.setHighlightedReads() only accept array of strings");t&&(this.highlightColor=t),this.highlightedReads=new Set(e)}computePixelHeight(e){if(e.packedGroups){let t=e.hasDownsampledIntervals()?15:0;const i="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;for(let r of e.packedGroups.values())t+=i*r.length+10;return t+5}return 0}draw(e){const t=e.features,i=e.context,r=e.bpPerPixel,s=e.bpStart,o=e.pixelWidth,n=s+o*r+1,a=this.showSoftClips,c=this.showAllBases,l=this.browser.nucleotideColors;i.save();for(let e of t.baseModificationKeys)this._baseModifications.add(e.modification);let h=t.sequence;h&&(h=h.toUpperCase());let d=0;this.colorBy||(this.colorBy=this.hasPairs?"unexpectedPair":"none");let u=e.pixelTop-up.coverageTrackHeight;this.top&&i.translate(0,this.top);const f=u+e.pixelHeight;t.hasDownsampledIntervals()?(d=15,t.downsampledIntervals.forEach((function(e){var t=(e.start-s)/r,o=(e.end-s)/r;o-t>5&&(t+=1,o-=1),Co.fillRect(i,t,2,o-t,8,{fillStyle:"black"})}))):d=0,this.alignmentsYOffset=d;const p="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight,g=t.packedGroups;if(g){let t=d;for(let r of g.keys()){const a=g.get(r),c=a.rows,l=c.length;a.pixelTop=t;for(let e=0;ef)break;if(t+rn)break;!0!==e.hidden&&(e instanceof eu?(m.call(this,e,t,r),w.call(this,e.firstAlignment,t,r),e.secondAlignment&&w.call(this,e.secondAlignment,t,r)):w.call(this,e,t,r))}t+=p}}if(a.pixelBottom=t,this.groupBy&&r){i.save(),i.font="400 12px sans-serif";const s=i.measureText(r),n=s.width+10,c=-e.pixelShift+e.viewportWidth-n-10,l=s.actualBoundingBoxAscent+s.actualBoundingBoxDescent+10,h=Math.min(a.pixelTop+l-1,a.pixelBottom);i.textAlign="center",i.fillStyle="white",i.strokeStyle="lightGray",Co.roundRect(i,c,h-s.actualBoundingBoxAscent-5,n,l,2,1,1),i.fillStyle="black",i.fillText(r,c+n/2,h),Co.dashedLine(i,0,t,o,t),i.restore(),t+=10}}}function m(e,t,o){var a=this.getConnectorColor(e.firstAlignment),c=(e.connectingStart-s)/r,l=(e.connectingEnd-s)/r,h=t+o/2;e.connectingEndn||(e.mq<=0&&(a=ur.addAlpha(a,.15)),Co.setProperties(i,{fillStyle:a,strokeStyle:a}),Co.strokeLine(i,c,h,l,h))}function w(e,d,u){if(e.start+e.lengthOnRefn)return;const f=a?e.blocks:e.blocks.filter((e=>"S"!==e.type));let g=this.getAlignmentColor(e);const m=g;e.mq<=0&&(g=ur.addAlpha(g,.15)),Co.setProperties(i,{fillStyle:g,strokeStyle:m});const w=[];for(let e=0;en))break}if(e.gaps){const t=d+u/2;for(let o of e.gaps){const e=(o.start-s)/r,n=(o.start+o.len-s)/r,a=n-e,c=o.len.toString(),l=6*c.length,h=e+a/2,u="D"===o.type?this.deletionColor:this.skippedColor;if(Co.strokeLine(i,e,t,n,t,{strokeStyle:u,lineWidth:2}),this.showDeletionText&&o.len>1&&a>=l+8){const e=h-l/2;Co.fillRect(i,e-1,d-1,l+2,12,{fillStyle:"white"}),Co.fillText(i,c,e,d+10,{font:"normal 10px monospace",fillStyle:this.deletionTextColor})}}}if(e.insertions&&this.showInsertions){let t=-1;for(let o of e.insertions){if(this.hideSmallIndels&&o.len<=this.indelSizeThreshold)continue;if(o.startn)break;const e=o.start-s,a=o.len.toString(),c=2+6*a.length,l=this.showInsertionText&&1!==o.len?Math.round(o.len/r):2,h=Math.max(Math.min(c,l),2),f=e/r-h/2;if(f-t>2){const e={fillStyle:this.insertionColor};Co.fillRect(i,f-2,d,h+4,2,e),Co.fillRect(i,f,d+2,h,u-4,e),Co.fillRect(i,f-2,d+u-2,h+4,2,e),this.showInsertionText&&o.len>1&&l>c&&Co.fillText(i,a,f+1,d+10,{font:"normal 10px monospace",fillStyle:this.insertionTextColor}),t=f}}}for(let{bbox:e,baseColor:t,readChar:s}of w){if(r<=.1&&e.height>=8){const r=Math.min(10,e.height);i.font=r+"px sans-serif";const o=e.x+e.width/2;Co.strokeText(i,s,o-i.measureText(s).width/2,r-1+e.y,{strokeStyle:t})}else Co.fillRect(i,e.x,e.y,e.width,e.height,{fillStyle:t})}if(this.colorBy&&this.colorBy.startsWith("basemod")){const t={ctx:i,bpPerPixel:r,bpStart:s,bpEnd:n,pixelEnd:o};this.baseModRenderer.drawModifications(e,d,u,t,this.colorBy,this.baseModificationThreshold)}function b(n,a){const w=[],b=n.start-t.start,F=(n.start-s)/r,v=(n.start+n.len-s)/r,y=Math.max(1,v-F),A=100/r,C=Math.min(p/2,A/6),_="S"===n.type,x=e.mq<=0||this.selectedReadName===e.readName||_||this.highlightedReads&&this.highlightedReads.has(e.readName);let k=m;this.selectedReadName===e.readName?k="red":_?k="rgb(50,50,50)":this.highlightedReads&&this.highlightedReads.has(e.readName)&&(k=this.highlightColor||"#00ff00");const I=!0===e.strand&&a===f.length-1,S=!1===e.strand&&0===a;if(I|S){let e,t;I?(e=[F,v,v+C,v,F,F],t=[d,d,d+u/2,d+u,d+u,d]):S&&(e=[v,F,F-C,F,v,v],t=[d,d,d+u/2,d+u,d+u,d]),Co.fillPolygon(i,e,t,{fillStyle:g}),x&&Co.strokePolygon(i,e,t,{strokeStyle:k})}else Co.fillRect(i,F,d,y,u,{fillStyle:g}),x&&(i.save(),i.strokeStyle=k,i.strokeRect(F,d,y,u),i.restore());if(_||c||this.showMismatches&&h&&e.seq&&"*"!==e.seq){const t=e.seq?e.seq.toUpperCase():void 0,i=e.qual,a=n.seqOffset,f=Math.max(1,1/r);for(let e=0,p=n.len;eo)break;let g=t?t.charAt(a+e):"";const m=b+e>=0?h.charAt(b+e):"";if("="===g&&(g=m),"X"===g||m!==g||_||c){let t=l[g]||"rgb(0,0,0)";if(!_&&void 0!==i&&i.length>a+e){t=cp(i[a+e],t)}w.push({bbox:{x:p,y:d,width:f,height:u},baseColor:t,readChar:g})}}}return w}}i.restore()}popupData(e){const t=this.getClickedObject(e);return t?.popupData(e.genomicLocation,this.hiddenTags,this.showTags)}menuItemList(){let t=[];t.push("
");let i=e('
');i.innerText="Color by:",t.push({name:void 0,element:i,click:void 0,init:void 0});const r=[];r.push({key:"none",label:"none"}),r.push({key:"strand",label:"read strand"}),this.hasPairs&&(r.push({key:"firstOfPairStrand",label:"first-of-pair strand"}),r.push({key:"pairOrientation",label:"pair orientation"}),r.push({key:"tlen",label:"insert size (TLEN)"}),r.push({key:"unexpectedPair",label:"pair orientation & insert size (TLEN)"})),this.colorBy&&this.colorBy.startsWith("tag:")&&r.push({key:this.colorBy,label:this.colorBy}),r.push({key:"tag",label:"tag..."});for(let e of r){const i=void 0===this.colorBy&&"none"===e.key||this.colorBy===e.key;t.push(this.colorByCB(e,i))}const s=this._baseModifications.size;if(s>0){t.push('
');let e=1===s?"base modification":"base modification (all)";if(t.push(this.basemodColorByCB({key:"basemod",label:e})),s>1)for(let e of this._baseModifications)t.push(this.basemodColorByCB({key:"basemod:"+e,label:`base modification (${au(e)})`}));if(t.push('
'),e=1===s?"base modification 2-color":"base modification 2-color (all)",t.push(this.basemodColorByCB({key:"basemod2",label:e})),s>1)for(let e of this._baseModifications)t.push(this.basemodColorByCB({key:"basemod2:"+e,label:`base modification 2-color (${au(e)})`}))}t.push("
"),i=document.createElement("div"),i.className="igv-track-menu-category",i.textContent="Group by:",t.push({name:void 0,element:i,click:void 0,init:void 0});const o=[];o.push({key:"none",label:"none"}),o.push({key:"strand",label:"read strand"}),this.hasPairs&&(o.push({key:"firstOfPairStrand",label:"first-of-pair strand"}),o.push({key:"pairOrientation",label:"pair orientation"}),o.push({key:"mateChr",label:"chromosome of mate"})),o.push({key:"chimeric",label:"chimeric"}),o.push({key:"supplementary",label:"supplementary flag"}),o.push({key:"readOrder",label:"read order"});for(let e of this._groupByTags)o.push({key:`tag:${e}`,label:`tag:${e}`});for(let e of this._groupByPositions)o.push({key:`base:${e}`,label:`base:${e}`});o.push({key:"tag",label:"tag..."});for(let e of o){const i=void 0===this.groupBy&&"none"===e.key||this.groupBy===e.key;t.push(this.groupByCB(e,i))}t.push("
"),t.push({element:ua("Show all bases",this.showAllBases),click:function(){this.alignmentTrack.showAllBases=!this.alignmentTrack.showAllBases,this.trackView.repaintViews()}}),t.push({element:ua("Show mismatches",this.showMismatches),click:function(){this.alignmentTrack.showMismatches=!this.alignmentTrack.showMismatches,this.trackView.repaintViews()}}),t.push({element:ua("Show insertions",this.showInsertions),click:function(){this.alignmentTrack.showInsertions=!this.alignmentTrack.showInsertions,this.trackView.repaintViews()}}),t.push({element:ua("Show soft clips",this.showSoftClips),click:function(){this.alignmentTrack.showSoftClips=!this.alignmentTrack.showSoftClips;const e=this.getCachedAlignmentContainers();for(let t of e)t.pack(this);this.trackView.repaintViews()}}),this.hasPairs&&(t.push("
"),t.push({element:ua("View as pairs",this.viewAsPairs),click:function(){const e=!this.alignmentTrack.viewAsPairs;if(e&&this.groupBy&&!np.has(this.groupBy))return void this.browser.alert.present(`'View as Pairs' is incompatible with 'Group By ${this.groupBy}'`);this.alignmentTrack.viewAsPairs=e;const t=this.getCachedAlignmentContainers();for(let e of t)e.pack(this);this.trackView.checkContentHeight(),this.trackView.repaintViews()}})),this.browser.circularView&&(this.hasPairs||this.hasSupplemental)&&(t.push("
"),this.hasPairs&&t.push({label:"Add discordant pairs to circular view",click:function(){for(let e of this.trackView.viewports)this.addPairedChordsForViewport(e)}}),this.hasSupplemental&&t.push({label:"Add split reads to circular view",click:function(){for(let e of this.trackView.viewports)this.addSplitChordsForViewport(e)}})),t.push("
"),i=document.createElement("div"),i.className="igv-track-menu-category",i.textContent="Display mode:",t.push({name:void 0,element:i,click:void 0,init:void 0});for(let e of["EXPANDED","SQUISHED","FULL"])t.push({element:ua(e.toLowerCase(),this.displayMode===e),click:function(){this.alignmentTrack.setDisplayMode(e)}});return t}setDisplayMode(e){const t="FULL"===this.displayMode||"FULL"===e;if(this.displayMode=e,t){const e=this.getCachedAlignmentContainers();for(let t of e)t.pack(this)}this.trackView.checkContentHeight(),this.trackView.repaintViews()}colorByCB(e,t){const i=ua(e.label,t);if("tag"!==e.key){function r(){this.alignmentTrack.colorBy=e.key,this.trackView.repaintViews()}return{name:void 0,element:i,click:r,init:void 0}}{function s(e){const t=this.alignmentTrack.colorBy.startsWith("tag:")?this.alignmentTrack.colorBy.substring(4):"";this.browser.inputDialog.present({label:"Tag Name",value:t,callback:e=>{const t=this.alignmentTrack;e?(t.colorBy="tag:"+e,t.colorTable||(t.colorTable=new Wr("Set1"))):t.colorBy=void 0,this.trackView.repaintViews()}},e)}return{name:void 0,element:i,dialog:s,init:void 0}}}basemodColorByCB(e){const t=this.colorBy===e.key;return{name:void 0,element:ua(e.label,t),click:function(){this.alignmentTrack.colorBy=e.key,this.trackView.repaintViews()},init:void 0}}groupByCB(e,t){return{name:void 0,element:ua(e.label,t),dialog:function(t){const i=()=>this.alignmentTrack.repackAlignments();if("tag"===e.key){let e="";this.alignmentTrack.groupBy&&this.alignmentTrack.groupBy.startsWith("tag:")&&(e=this.alignmentTrack.groupBy.substring(4)),this.browser.inputDialog.present({label:"Tag Name",value:e,callback:e=>{e&&(this.alignmentTrack.groupBy="tag:"+e,this.alignmentTrack._groupByTags.push(e),i())}},t)}else"none"===e.key?this.alignmentTrack.groupBy=void 0:this.alignmentTrack.groupBy=e.key,i()},init:void 0}}repackAlignments(){const e=this.getCachedAlignmentContainers();for(let t of e)"function"==typeof t.pack&&t.pack(this);this.trackView.checkContentHeight(),this.trackView.repaintViews()}contextMenuItemList(e){const t=e.viewport,i=[],r=i=>{const r=this.sortObject,s=!r||r.position!==Math.floor(e.genomicLocation)||!r.direction,o={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:i,direction:s,sortAsPairs:t.trackView.track.viewAsPairs};this.sortObject=o,t.cachedFeatures.sortRows(o),t.repaint()};i.push("Sort by..."),i.push({label:"  base",click:()=>r("BASE")}),i.push({label:"  read strand",click:()=>r("strand")}),i.push({label:"  start location",click:()=>r("START")}),i.push({label:"  insert size",click:()=>r("INSERT_SIZE")}),i.push({label:"  gap size",click:()=>r("GAP_SIZE")}),i.push({label:"  chromosome of mate",click:()=>r("MATE_CHR")}),i.push({label:"  mapping quality",click:()=>r("MQ")}),i.push({label:"  read name",click:()=>r("READ_NAME")}),i.push({label:"  aligned read length",click:()=>r("ALIGNED_READ_LENGTH")}),i.push({label:"  tag",click:()=>{const i=this.sortObject,r=!i||i.position!==Math.floor(e.genomicLocation)||!i.direction,s={label:"Tag Name",value:this.sortByTag?this.sortByTag:"",callback:i=>{if(i){const s={chr:t.referenceFrame.chr,position:Math.floor(e.genomicLocation),option:"TAG",tag:i,direction:r};this.sortByTag=i,this.sortObject=s,t.cachedFeatures.sortRows(s),t.repaint()}}};this.browser.inputDialog.present(s,e.event)}}),i.push("
");const s=`${t.referenceFrame.chr}:${F(Math.floor(e.genomicLocation)+1)}`;i.push({label:`Group by base @${s}`,click:()=>{this._groupByPositions.push(s),this.groupBy=`base:${s}`;const e=this.getCachedAlignmentContainers();for(let t of e)t.pack(this);this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),i.push("
");const o=this.getClickedObject(e);if(o){const t=this.showSoftClips,r="function"==typeof o.alignmentContaining?o.alignmentContaining(e.genomicLocation,t):o;if(r){r.isPaired()&&r.isMateMapped()&&i.push({label:"View mate in split screen",click:()=>{if(r.mate){const t=e.viewport.referenceFrame,i=this.browser.genome.getChromosome(r.mate.chr);if(i){this.selectedReadName=r.readName;const s=t.bpPerPixel*e.viewport.getWidth(),o=r.mate.position-s/2,n=r.mate.position+s/2;this.browser.addMultiLocusPanel(i.name,o,n,t)}else this.browser.alert.present(`Reference does not contain chromosome: ${r.mate.chr}`)}},init:void 0}),i.push("
");const t=r.softClippedBlocks();i.push({label:"View read sequence",click:()=>{const e=r.seq;this.browser.alert.present(e&&"*"!==e?e:"Read sequence: *")}}),t.left&&t.left.len>0&&i.push({label:"View left soft-clipped sequence",click:()=>{const e=r.seq.substring(t.left.seqOffset,t.left.seqOffset+t.left.len);this.browser.alert.present(e)}}),t.right&&t.right.len>0&&i.push({label:"View right soft-clipped sequence",click:()=>{const e=r.seq.substring(t.right.seqOffset,t.right.seqOffset+t.right.len);this.browser.alert.present(e)}}),i.push("
"),ds()&&(i.push({label:"Copy read sequence",click:async()=>{try{await navigator.clipboard.writeText(r.seq)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),t.left&&t.left.len>0&&i.push({label:"Copy left soft-clipped sequence",click:async()=>{try{const e=r.seq.substring(t.left.seqOffset,t.left.seqOffset+t.left.len);await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}),t.right&&t.right.len>0&&i.push({label:"Copy right soft-clipped sequence",click:async()=>{try{const e=r.seq.substring(t.right.seqOffset,t.right.seqOffset+t.right.len);await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(`error copying sequence to clipboard ${e}`)}}}));const s=r.seq;if(s&&"*"!==s){i.push("
"),s.length{const e=r.isNegativeStrand()?Eo(s):s,t=`${r.readName} - blat`,i=`${this.name} - ${t}`;Zl({sequence:e,browser:this.browser,name:t,title:i})}});const e=r.softClippedBlocks();e.left&&e.left.len>20&&e.left.len{const t=s.substring(e.left.seqOffset,e.left.seqOffset+e.left.len),i=r.isNegativeStrand()?Eo(t):t,o=`${r.readName} - blat left clip`,n=`${this.name} - ${o}`;Zl({sequence:i,browser:this.browser,name:o,title:n})}}),e.right&&e.right.len>20&&e.right.len{const t=s.substring(e.right.seqOffset,e.right.seqOffset+e.right.len),i=r.isNegativeStrand()?Eo(t):t,o=`${r.readName} - blat right clip`,n=`${this.name} - ${o}`;Zl({sequence:i,browser:this.browser,name:o,title:n})}})}i.push("
")}}return this.browser.circularView&&(this.hasPairs||this.hasSupplemental)&&(this.hasPairs&&i.push({label:"Add discordant pairs to circular view",click:()=>{this.addPairedChordsForViewport(t)}}),this.hasSupplemental&&i.push({label:"Add split reads to circular view",click:()=>{this.addSplitChordsForViewport(t)}}),i.push("
")),i}getClickedObject(e){let t=e.viewport.cachedFeatures;if(!t)return;const i=e.y-this.top,r=e.genomicLocation;if(t.packedGroups){let e=Number.MAX_VALUE;for(let s of t.packedGroups.values())if(e=Math.min(e,s.pixelTop),i>s.pixelTop&&i<=s.pixelBottom){const e="SQUISHED"===this.displayMode?this.squishedRowHeight:this.alignmentRowHeight;let t=Math.floor((i-s.pixelTop)/e);if(t>=0&&te.containsLocation(r,this.showSoftClips)));if(e.length>0)return e[0]}}if(i=r)return e}}getConnectorColor(e){if(this.pairConnectorColor)return this.pairConnectorColor;let t=this.colorBy;switch(t&&t.startsWith("tag:")&&(t.substring(4),t="tag"),t){case"strand":case"firstOfPairStrand":case"pairOrientation":case"tag":return this.color?"function"==typeof this.color?this.color(e):this.color:"rgb(200, 200, 200)";default:return this.getAlignmentColor(e)}}getAlignmentColor(e){let t;t=this.color?"function"==typeof this.color?this.color(e):this.color:"rgb(185, 185, 185)";let i,r=this.colorBy;switch(r&&r.startsWith("tag:")&&(i=r.substring(4),r="tag"),r){case"basemod":case"basemod2":t=e.strand?this.baseModPosStrandColor:this.baseModNegStrandColor;break;case"strand":t=e.strand?this.posStrandColor:this.negStrandColor;break;case"firstOfPairStrand":const s=e.firstOfPairStrand;void 0!==s&&(t=s?this.posStrandColor:this.negStrandColor);break;case"unexpectedPair":case"pairOrientation":if(e.pairOrientation){const i=uu[this.expectedPairOrientation];if(i){const r=this.pairColors[i[e.pairOrientation]];if(r){t=r;break}}}if("pairOrientation"===r)break;case"tlen":case"fragmentLength":e.mate&&e.isMateMapped()&&(e.mate.chr!==e.chr?t=$h(e.mate.chr):this.minTemplateLength&&Math.abs(e.fragmentLength)this.maxTemplateLength&&(t=this.largeTLENColor));break;case"tag":const o=e.tags()[i];void 0!==o&&("function"==typeof o.startsWith&&(t=ur.createColorStringSafe(o)),t||(this.colorTable||(this.colorTable=new Wr(this.tagColorPallete)),t=this.colorTable.getColor(o)))}return t}get nucleotideColors(){return this.browser.nucleotideColors}get minTemplateLength(){return void 0!==this.minTLEN?this.minTLEN:this.parent._pairedEndStats?this.parent._pairedEndStats.minTLEN:0}get maxTemplateLength(){return void 0!==this.maxTLEN?this.maxTLEN:this.parent._pairedEndStats?this.parent._pairedEndStats.maxTLEN:1e3}getState(){const e=super.getState();return this.highlightedReads&&(e.highlightedReads=Array.from(this.highlightedReads)),e}get name(){return this.parent.name}set name(e){this.parent.name=e}get color(){return this.parent.color}set color(e){this.parent.color=e}get trackView(){return this.parent.trackView}get getCachedAlignmentContainers(){return this.parent.getCachedAlignmentContainers}get sortObject(){return this.parent.sortObject}set sortObject(e){this.parent.sortObject=e}addPairedChordsForViewport(e){return this.parent.addPairedChordsForViewport(e)}addSplitChordsForViewport(e){return this.parent.addSplitChordsForViewport(e)}}function cp(e,t){let i;return i=e<5?.1:Math.max(.1,Math.min(1,.1+.9*(e-5)/15)),i=Math.round(10*i)/10,i<1&&(t=ur.addAlpha(t,i)),t}function lp(){"FULL"!==this.displayMode||this.browser.isTrackPanning()||this.repackAlignments()}function hp(e,t,i,r,s,o,n,a,c){const l=n.baseModCounts,h=n.coverageMap;if(l){let n;const d=a.split(":");2==d.length&&(a=d[0],n=d[1]);const u=Array.from(l.allModifications);u.sort(tu.compare);const f=h.getTotalCount(o);if(!u.filter((e=>n?n===e.modification:!e.modification.startsWith("NONE_"))).find((e=>l.getCount(o,e,0,!1)>0)))return;for(let d of u){if(d.modification.startsWith("NONE_")&&"basemod2"!==a)continue;if(n&&n!==d.modification&&!d.modification.startsWith("NONE_"))continue;const u=d.base,p=Io(u),g=h.getCount(o,u)+h.getCount(o,p),m=l.simplexModifications.has(d.modification)?h.getPosCount(o,u)+h.getNegCount(o,p):g;if(0==m)continue;const w="basemod2"===a,b=l.getCount(o,d,c,w);if(0==b)continue;const F=g/f*(b/m),v=Math.round(F*s),y=l.getLikelihoodSum(o,d,c,w)/b,A=i-v,C=sp(d.modification,y,a);e.fillStyle=C,e.fillRect(t,A,r,v),i=A}}}class dp{constructor(e,t){this.featureType="numeric",this.parent=t,this.featureSource=t.featureSource,this.paintAxis=Oc,this.top=0,this.autoscale=e.autoscale||void 0===e.max,e.coverageColor&&(this.color=e.coverageColor),this.autoscale||(this.dataRange={min:e.min||0,max:e.max})}get height(){return this.parent.coverageTrackHeight}draw(e){const t=e.pixelTop;e.pixelHeight;const i=this.parent.browser.nucleotideColors;if(t>this.height)return;const r=e.context,s=e.features,o=s.coverageMap;let n;o.refSeq&&(n=o.refSeq.toUpperCase());const a=e.bpPerPixel,c=e.bpStart,l=c+e.pixelWidth*a+1;let h;h=this.color?this.color:this.parent.color&&"function"!=typeof this.parent.color?ur.darkenLighten(this.parent.color,-35):"rgb(150, 150, 150)",Co.setProperties(r,{fillStyle:h,strokeStyle:h});const d=Math.max(1,1/a);for(let e=0,t=o.coverage.length;el)break;const i=o.coverage[e];if(!i)continue;const s=i.total/this.dataRange.max*this.height,n=this.height-s,h=(t-c)/a;Co.fillRect(r,h,n,d,s)}if(n)for(let e=0,t=o.coverage.length;el)break;const h=o.coverage[e];if(!h)continue;const u=h.total/this.dataRange.max*this.height;let f=this.height-u;const p=Math.floor((t-c)/a),g=n[e];if(this.parent.colorBy&&this.parent.colorBy.startsWith("basemod"))hp(r,p,this.height,d,u,t,s,this.parent.colorBy,this.parent.baseModificationThreshold);else if(h.isMismatch(g)){Co.setProperties(r,{fillStyle:i[g]}),Co.fillRect(r,p,f,d,u);let e=0;for(let t of["A","C","T","G"]){const s=(h["pos"+t]+h["neg"+t])/this.dataRange.max*this.height;f=this.height-s-e,e+=s,Co.setProperties(r,{fillStyle:i[t]}),Co.fillRect(r,p,f,d,s)}}}}getClickedObject(e){let t=e.viewport.cachedFeatures;if(!t||0===t.length)return;const i=Math.floor(e.genomicLocation),r=t.coverageMap,s=Math.floor(i-r.bpStart),o=r.coverage[s];return o?{coverage:o,baseModCounts:t.baseModCounts,hoverText:()=>r.coverage[s].hoverText()}:void 0}popupData(e){const t=[],{coverage:i,baseModCounts:r}=this.getClickedObject(e);if(i){const s=Math.floor(e.genomicLocation),o=e.viewport.referenceFrame;t.push(o.chr+":"+F(1+s)),t.push({name:"Total Count",value:i.total});let n=i.posA+i.negA;n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posA+"+, "+i.negA+"- )"),t.push({name:"A",value:n}),n=i.posC+i.negC,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posC+"+, "+i.negC+"- )"),t.push({name:"C",value:n}),n=i.posG+i.negG,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posG+"+, "+i.negG+"- )"),t.push({name:"G",value:n}),n=i.posT+i.negT,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posT+"+, "+i.negT+"- )"),t.push({name:"T",value:n}),n=i.posN+i.negN,n>0&&(n=n.toString()+" ("+Math.round(n/i.total*100)+"%, "+i.posN+"+, "+i.negN+"- )"),t.push({name:"N",value:n}),t.push("
"),t.push({name:"DEL",value:i.del.toString()}),t.push({name:"INS",value:i.ins.toString()}),r&&(t.push("
"),t.push(...r.popupData(s,this.parent.colorBy)))}return t}}class up extends ma{static defaults={alleleFreqThreshold:.2,visibilityWindow:3e4,showCoverage:!0,showAlignments:!0,height:300,coverageTrackHeight:50,baseModificationThreshold:0};constructor(e,t){super(e,t)}init(e){this.type="alignment",this.featureSource=new Ff(e,this.browser);const t=Object.assign({parent:this},e);this.coverageTrack=new dp(t,this);const i=Object.assign({parent:this},e);this.alignmentTrack=new ap(i,this.browser),super.init(e),this.showAlignments||(this._height=this.coverageTrackHeight),e.sort&&(Array.isArray(e.sort)?this.assignSort(e.sort[0]):this.assignSort(e.sort))}dispose(){this.alignmentTrack.dispose()}setHighlightedReads(e,t){this.alignmentTrack.setHighlightedReads(e,t),this.updateViews()}get expectedPairOrientation(){return this.alignmentTrack.expectedPairOrientation}get viewAsPairs(){return this.alignmentTrack.viewAsPairs}get colorBy(){return this.alignmentTrack.colorBy}set height(e){this._height=e,this.showAlignments&&(this.alignmentTrack.height=this.showCoverage?e-this.coverageTrackHeight:e)}get height(){return this._height}sort(e){e=this.assignSort(e);for(let t of this.trackView.viewports)if(t.containsPosition(e.chr,e.position)){const i=t.cachedFeatures;i&&(i.sortRows(e),t.repaint())}}assignSort(e){if(e.locus){const t=function(e){const t=e.split(":"),i=t[1].split("-"),r={chr:t[0],start:Number.parseInt(i[0].replace(/,/g,""))-1};return i.length>1?r.end=Number.parseInt(i[1].replace(/,/g,"")):r.end=r.start+1,r}(e.locus);e.chr=t.chr,e.position=t.start}else e.position--;return e.direction="ASC"===e.direction||!0===e.direction,e.chr=this.browser.genome.getChromosomeName(e.chr),this.sortObject=e,this.sortObject}async getFeatures(e,t,i,r,s){const o=await this.featureSource.getAlignments(e,t,i);if(o.viewport=s,o.hasPairs&&!this._pairedEndStats&&!this.config.maxFragmentLength){const e=new Zf(o.allAlignments(),this.config);e.totalCount>99&&(this._pairedEndStats=e)}o.pack(this.alignmentTrack);const n=this.sortObject;return n&&n.chr===e&&n.position>=t&&n.position<=i&&o.sortRows(n),this.alignmentTrack.hasPairs=this.alignmentTrack.hasPairs||o.hasPairs,o}computePixelHeight(e){return(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.computePixelHeight(e):0)}draw(e){Co.fillRect(e.context,0,e.pixelTop,e.pixelWidth,e.pixelHeight,{fillStyle:"rgb(255, 255, 255)"}),!0===this.showCoverage&&this.coverageTrackHeight>0&&!1!==this.config.showAxis?(this.trackView.axisCanvas.style.display="block",this.coverageTrack.draw(e)):this.trackView.axisCanvas.style.display="none",!0===this.showAlignments&&(this.alignmentTrack.setTop(this.coverageTrack,this.showCoverage),this.alignmentTrack.draw(e))}paintAxis(e,t,i){this.coverageTrack.paintAxis(e,t,this.coverageTrackHeight)}contextMenuItemList(e){return this.alignmentTrack.contextMenuItemList(e)}popupData(e){return!0===this.showCoverage&&e.y>=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y=this.coverageTrack.top&&e.y{if(!this.autoHeight){const e=(this.showCoverage?this.coverageTrackHeight:0)+(this.showAlignments?this.alignmentTrack.height:0);this.trackView.setTrackHeight(e)}};return e.push("
"),e.push({element:ua("Show Coverage",this.showCoverage),click:function(){this.showCoverage=!this.showCoverage,t(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e.push({element:ua("Show Alignments",this.showAlignments),click:function(){this.showAlignments=!this.showAlignments,t(),this.trackView.checkContentHeight(),this.trackView.repaintViews()}}),e}getState(){const e=super.getState();return this.sortObject&&(e.sort={chr:this.sortObject.chr,position:this.sortObject.position+1,option:this.sortObject.option,direction:this.sortObject.direction?"ASC":"DESC"}),Object.assign(e,this.alignmentTrack.getState()),e}getCachedAlignmentContainers(){return this.trackView.viewports.map((e=>e.cachedFeatures))}get dataRange(){return this.coverageTrack.dataRange}set dataRange(e){this.coverageTrack.dataRange=e}get logScale(){return this.coverageTrack.logScale}set logScale(e){this.coverageTrack.logScale=e}get autoscale(){return this.coverageTrack.autoscale}set autoscale(e){this.coverageTrack.autoscale=e}addPairedChordsForViewport(e){const t=this.maxTemplateLength,i=[],r=e.referenceFrame;for(let s of e.cachedFeatures.allAlignments())s.end>=r.start&&s.start<=r.end&&(s.paired?s.end-s.start>t&&i.push(s):s.mate&&s.mate.chr&&(s.mate.chr!==s.chr||Math.max(s.fragmentLength)>t)&&i.push(s));Yf((e=>{const t=[];for(let i of e)if(i.paired)i.firstAlignment&&i.secondAlignment&&t.push({uniqueId:i.readName,refName:$f(i.firstAlignment.chr),start:i.firstAlignment.start,end:i.firstAlignment.end,mate:{refName:$f(i.secondAlignment.chr),start:i.secondAlignment.start,end:i.secondAlignment.end}});else{const e=i.mate;e&&e.chr&&e.position&&t.push({uniqueId:i.readName,refName:$f(i.chr),start:i.start,end:i.end,mate:{refName:$f(e.chr),start:e.position-1,end:e.position}})}return t})(i),this,r,.02)}addSplitChordsForViewport(e){const t=[],i=e.referenceFrame;for(let r of e.cachedFeatures.allAlignments()){const e=r.hasTag("SA");r.end>=i.start&&r.start<=i.end&&e&&t.push(r)}Yf((e=>{const t=e=>{const t=Iu(e.tags().SA);let r=0;for(let s of t)s.start!==e.start&&i.push({uniqueId:`${e.readName}_${r++}`,refName:$f(e.chr),start:e.start,end:e.end,mate:{refName:$f(s.chr),start:s.start,end:s.start+s.lenOnRef}})},i=[];for(let i of e)i.paired?(t(i.firstAlignment),i.secondAlignment&&t(i.secondAlignment)):t(i);return i})(t),this,i,.02)}}class fp extends ma{static defaults={height:250,theta:Math.PI/4,arcOrientation:"UP",showBlocks:!0,blockHeight:3,thickness:1,alpha:.02,logScale:!0,colorBy:void 0};constructor(e,t){super(e,t)}init(e){super.init(e),!1===e.arcOrientation?this.arcOrientation="DOWN":!0===e.arcOrientation?this.arcOrientation="UP":e.arcOrientation?this.arcOrientation=e.arcOrientation.toUpperCase():this.arcOrientation="UP",this.sinTheta=Math.sin(this.theta),this.cosTheta=Math.cos(this.theta),this.arcType=function(e){if(!e.arcType)return"nested";switch(e.arcType){case"chiapet":return"inView";case"chiapetoutbound":return"partialInView";default:return e.arcType}}(e),this.painter={flipAxis:"DOWN"===this.arcOrientation,dataRange:this.dataRange,paintAxis:Oc},e.valueColumn?(this.valueColumn=e.valueColumn,this.hasValue=!0):e.useScore&&(this.hasValue=!0,this.valueColumn="score"),e.max?(this.dataRange={min:e.min||0,max:e.max},this.autoscale=!1):this.autoscale=!0,e.colorTable?this.colorTable=new $r(e.colorTable):e.colorBy&&(this.colorTable=new Wr("Set1")),e.featureSource?(this.featureSource=e.featureSource,delete e._featureSource):(e.features&&function(e){const t=[];for(let i of e)if(i.chr1===i.chr2)i.chr=i.chr1,i.start=Math.min(i.start1,i.start2),i.end=Math.max(i.end1,i.end2);else{i.chr=i.chr1,i.start=Math.min(i.start1,i.start2),i.end=Math.max(i.end1,i.end2);const e=Object.assign({},i);e.dup=!0,e.chr=e.chr2,e.start=e.start2,e.end=e.end2,t.push(e)}for(const i of t)e.push(i)}(e.features),this.featureSource=El(e,this.browser.genome),this.featureSource.getWGFeatures=bp)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow(),this.featureSource.visibilityWindow=this.visibilityWindow),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get supportsWholeGenome(){return"function"!=typeof this.featureSource.supportsWholeGenome||this.featureSource.supportsWholeGenome()}async getFeatures(e,t,i){const r=this.visibilityWindow,s=await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r});return void 0===this.hasValue&&s&&s.length>0&&(this.hasValue=void 0!==s[0].score),s}draw(e){"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?this.drawProportional(e):this.drawNested(e)}drawNested(e){const t=e.context,i=e.pixelWidth,r=e.pixelHeight,s=e.viewportWidth,o=e.bpPerPixel,n=e.bpStart,a=o;Co.fillRect(t,0,e.pixelTop,i,r,{fillStyle:"rgb(255, 255, 255)"});const c=e.features;if(c){(function(){let e=0;for(let t of c){let r=(t.start-n)/a,s=(t.end-n)/a;r>=0&&s<=i&&(e=Math.max(e,s-r))}let t=Math.min(s,e)/2;if(e>0){let e=(r-10)/t;this.theta=function(e){let t,i=[.01570925532366355,.15838444032453644,.3249196962329063,.5095254494944288,.7265425280053609,.9999999999999999],r=[.031415926535897934,.3141592653589793,.6283185307179586,.9424777960769379,1.2566370614359172,1.5707963267948966];for(t=0;te);t++);let s=0===t?0:i[t-1],o=ti)continue;let f=u-d;f<3&&(f=3,d--);const p=f/2,g=p/this.sinTheta,m=this.cosTheta*g,w=d+p;let b,F,v;if(o?(b=this.height+m,F=Math.PI+Math.PI/2-this.theta,v=Math.PI+Math.PI/2+this.theta):(b=-m,F=Math.PI/2-this.theta,v=Math.PI/2+this.theta),this.showBlocks&&"all"!==e.chr){const i=(e.start1-n)/a,r=(e.end1-n)/a,s=(e.start2-n)/a,c=(e.end2-n)/a,h=o?-this.blockHeight:this.blockHeight;t.fillRect(i,l,r-i,h),t.fillRect(s,l,c-s,h)}r&&!this.config.useScore&&f>s&&(r=wp(r,this.alpha),t.strokeStyle=r,t.fillStyle=r),t.beginPath(),t.arc(w,b,g,F,v,!1),t.stroke(),e.drawState={xc:w,yc:b,r:g}}else{let s=Math.round((e.start-n)/a),c=Math.round((e.end-n)/a);if(c<0||s>i)continue;let l=c-s;l<3&&(l=3,s--);const h=e.chr===e.chr1?e.chr2:e.chr1;t.strokeStyle=r,t.fillStyle=wp($h(h),.5),o?(t.fillRect(s,this.height/2,l,this.height/2),t.fillText(h,s+l/2,this.height/2-5),e.drawState={x:s,y:this.height/2,w:l,h:this.height/2}):(t.fillRect(s,0,l,this.height/2),t.fillText(h,s+l/2,this.height/2+13),e.drawState={x:s,y:0,w:l,h:this.height/2})}}}}drawProportional(e){const t=e.context,i=e.pixelWidth,r=e.pixelHeight,s=e.bpPerPixel,o=e.bpStart,n=s,a=e.referenceFrame.start,c=e.referenceFrame.end,l="UP"===this.arcOrientation;Co.fillRect(t,0,e.pixelTop,i,r,{fillStyle:"rgb(255, 255, 255)"});const h=e.features;if(h&&h.length>0){const r=0,s=this.getScaleFactor(r,this.dataRange.max,e.pixelHeight-1,this.logScale),d=l?e.pixelHeight:0;for(let e of h){e.drawState=void 0;const r=this.valueColumn?e[this.valueColumn]:e.score;if(void 0===r||Number.isNaN(r))continue;const h=Math.round((this.logScale?Math.log10(r+1):r)*s);if(e.chr1===e.chr2||"all"===e.chr){const{m1:i,m2:s}=pp(e,this.browser.genome);let u=Math.round((i-o)/n),f=Math.round((s-o)/n)-u;if(f<3&&(f=3,u--),rthis.dataRange.max)continue;if("proportional"!==this.arcType){const e="partialInView"===this.arcType,t=i>=a&&s<=c;let r=!1,o=!1;if(!t&&e&&(r=a<=i&&i<=c,r||(o=a<=s&&s<=c)),!(t||r||o))continue}const p=f/2,g=u+f/2;e.drawState={xc:g,yc:d,radiusX:p,radiusY:h};const m=l,w=this.getColor(e);if(t.strokeStyle=w,t.lineWidth=e.thickness||this.thickness||1,!0===t.isSVG?t.strokeEllipse(g,d,p,h,0,0,Math.PI,m):(t.beginPath(),t.ellipse(g,d,p,h,0,0,Math.PI,m),t.stroke()),this.alpha){const i=this.config.useScore&&Number.isFinite(e.score)?Math.max(.1,Math.round(10*Ic(e.score))/10):1;t.fillStyle=wp(w,i*this.alpha),!0===t.isSVG?t.fillEllipse(g,d,p,h,0,0,Math.PI,m):t.fill()}if(this.showBlocks&&"all"!==e.chr){t.fillStyle=w;const i=(e.start1-o)/n,r=(e.end1-o)/n,s=(e.start2-o)/n,a=(e.end2-o)/n,c=l?-this.blockHeight:this.blockHeight;t.fillRect(i,d,r-i,c),t.fillRect(s,d,a-s,c)}}else{let s=Math.round((e.start-o)/n),a=Math.round((e.end-o)/n);if(a<0||s>i||rthis.dataRange.max)continue;const c=Math.min(h,this.height-13);let d=a-s;d<3&&(d=3,s--);const u=e.chr===e.chr1?e.chr2:e.chr1;if(t.font="8px sans-serif",t.textAlign="center",t.fillStyle=wp($h(u),.5),l){const i=this.height-c;t.fillRect(s,i,d,c),t.fillText(u,s+d/2,i-5),e.drawState={x:s,y:i,w:d,h:c}}else t.fillRect(s,0,d,c),t.fillText(u,s+d/2,c+13),e.drawState={x:s,y:0,w:d,h:c}}}}}getColor(e){let t;if(this.colorBy){const i=e.getAttributeValue?e.getAttributeValue(this.colorBy):e[this.colorBy];t=this.colorTable.getColor(i)}else t="function"==typeof this.color?this.color(e):this.color||e.color||"rgb(180,25,137)";return this.config.useScore&&Number.isFinite(e.score)&&(t=wp(t,Ic(e.score))),t}getScaleFactor(e,t,i,r){return r?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}clearAxis(e,t,i){Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"})}paintAxis(e,t,i){const r={min:0,max:this.dataRange.max};"proportional"===this.arcType||"inView"===this.arcType||"partialInView"===this.arcType?(this.painter.flipAxis="DOWN"===this.arcOrientation,this.painter.dataRange=r,this.painter.paintAxis(e,t,i)):this.clearAxis(e,t,i)}menuItemList(){let e=[];if(this.hasValue){e.push("
");const t={nested:"Nested",proportional:"Proportional - All",inView:"Proportional - Both Ends in View",partialInView:"Proportional - One End in View"};e.push("Arc Type");for(let i of["nested","proportional","inView","partialInView"])e.push({element:ua(t[i],i===this.arcType),click:function(){this.arcType=i,this.trackView.repaintViews()}})}return e.push("
"),e.push({name:"Toggle arc direction",click:function(){this.arcOrientation="UP"===this.arcOrientation?"DOWN":"UP",this.trackView.repaintViews()}}),e.push({name:this.showBlocks?"Hide Blocks":"Show Blocks",click:function(){this.showBlocks=!this.showBlocks,this.trackView.repaintViews()}}),e.push("
"),e.push({name:"Set line thickness",click:function(e){this.browser.inputDialog.present({label:"Enter line thickness",value:this.thickness||1,callback:e=>{const t=parseFloat(e);isNaN(t)?window.alert("Invalid line thickness: "+e):(this.thickness=t,this.trackView.repaintViews())}},e)}}),e.push({name:"Set alpha",click:function(e){this.browser.inputDialog.present({label:"Enter alpha transparency (0-1)",value:this.alpha,callback:e=>{const t=parseFloat(e);isNaN(t)||t<0||t>1?window.alert("Invalid alpha: "+e):(this.alpha=t,this.trackView.repaintViews())}},e)}}),this.hasValue&&e.push({element:ua("Use score",this.config.useScore),click:()=>{this.config.useScore=!this.config.useScore,this.valueColumn="score",this.trackView.repaintViews()}}),"proportional"!==this.arcType&&"inView"!==this.arcType&&"partialInView"!==this.arcType||(e=e.concat(this.numericDataMenuItems())),this.browser.circularView&&(e.push("
"),e.push({label:"Add interactions to circular view",click:function(){for(let e of this.trackView.viewports)this.addChordsForViewport(e.referenceFrame)}})),e}contextMenuItemList(e){if(this.browser.circularView){const t=e.viewport,i=[];return i.push({label:"Add interactions to circular view",click:()=>{const e=t.referenceFrame;this.addChordsForViewport(e)}}),i.push("
"),i}}addChordsForViewport(e){let t;if("all"===e.chr)t=Object.values(this.featureSource.getAllFeatures()).flat();else{t=this.featureSource.featureCache.queryFeatures(e.chr,e.start,e.end).filter((e=>e.drawState))}if(0===t.length)return;Yf(t.map((e=>{const t=e._f||e;return{uniqueId:`${t.chr1}:${t.start1}-${t.end1}_${t.chr2}:${t.start2}-${t.end2}`,refName:$f(t.chr1),start:t.start1,end:t.end1,mate:{refName:$f(t.chr2),start:t.start2,end:t.end2}}})),this,e,.5)}doAutoscale(e){let t=0;if(e)for(let i of e){const e=this.valueColumn?i[this.valueColumn]:i.score;Number.isNaN(e)||(t=Math.max(t,e))}return{min:0,max:t}}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){const t=e._||e;if(i.push({name:"Region 1",value:gp(t.chr1,t.start1,t.end1,t.strand1)}),i.push({name:"Region 2",value:gp(t.chr2,t.start2,t.end2,t.strand2)}),t.name&&i.push({name:"Name",value:t.name}),void 0!==t.value&&i.push({name:"Value",value:t.value}),void 0!==t.score&&i.push({name:"Score",value:t.score}),void 0!==t.type&&i.push({name:"Type",value:t.type}),t.extras&&this.header&&this.header.columnNames){const e=this.header.columnNames,r=this.header.hiccups?6:10;for(let s=r;s=t-a&&e.canvasX<=t+o+a&&e.canvasY>=r&&e.canvasY<=r+n){const r=-Math.abs(e.canvasX-(t+o/2));i.push({score:r,feature:s});break}}}return i.length>1&&i.sort(((e,t)=>e.score-t.score)),i.map((e=>e.feature))}}function pp(e,t){let i=(e.start1+e.end1)/2,r=(e.start2+e.end2)/2;if("all"===e.chr&&(i=t.getGenomeCoordinate(e.chr1,i),r=t.getGenomeCoordinate(e.chr2,r)),i>r){const e=i;i=r,r=e}return{m1:i,m2:r}}function gp(e,t,i,r){return r&&"."!==r?`${e}:${F(t+1)}-${F(i)} (${r})`:`${e}:${F(t+1)}-${F(i)}`}const mp=new Map;function wp(e,t){const i=`${e}_${t}`;let r=mp.get(i);return r||(r=ur.addAlpha(e,t),mp.set(i,r)),r}function bp(e){const t=e=>{const t=Object.assign({},e);return t.chr="all",t.start=i.getGenomeCoordinate(e.chr1,e.start1),t.end=i.getGenomeCoordinate(e.chr2,e.end2),t},i=this.genome;let r,s=0;for(let t of i.wgChromosomeNames){let i=e[t];if(i)for(let e of i)e.dup||(s++,e.score&&(!r||e.score>r.score)&&(r=e))}const o=this.maxWGCount,n=r&&r.score>0&&s>o?5:1,a=Math.floor(o/n),c=r&&r.score>0?Math.log(r.score)/n:Number.MAX_SAFE_INTEGER;let l,h=[],d=[];for(let e=0;e=400){const e=Error(s.statusText);throw e.code=o,e}return s.arrayBuffer()}}class yp{constructor(e){this.file=e.file,this.fetchSize=e.fetchSize||16e3,this.maxSize=e.maxSize||1e6,this.buffers=[]}async read(e,t){let i=this.buffers.filter((i=>i.overlaps(e,e+t)));for(let r of i)if(r.contains(e,e+t))return r.slice(e,e+t);if(0===i.length){let i=Math.max(t,this.fetchSize);this.buffers.sort(((e,t)=>e.start-t.start));const r=function(e,t,i){let r=i-1,s=e.length;for(;1+r>1);t(e[i])?s=i:r=i}return s}(this.buffers,(t=>t.start>e),0);re.start-t.start));const r=[];let s=e;for(let e of i){if(ss){const e=s,t=o-e,i=await this.file.read(e,t),n=new Ap(e,i);r.push(n)}const n=r[0].start,a=function(e){const t=e.reduce(((e,t)=>e+t.byteLength),0),i=new Uint8Array(t);let r=0;for(let t of e)i.set(new Uint8Array(t),r),r+=t.byteLength;return i.buffer}(r.map((e=>e.buffer))),c=new Ap(n,a),l=new Set(i);return this.buffers=this.buffers.filter((e=>!l.has(e))),this.addBuffer(c),c.slice(e,e+t)}}addBuffer(e){const t=this.buffers.reduce(((e,t)=>e+t.size),0)+e.size;if(t>this.maxSize){const e=t-this.maxSize;this.buffers.sort(((e,t)=>e.creationTime-t.creationTime));let i,r=0;for(i=0;ie));i++);this.buffers=ithis.buffer.byteLength)throw Error("buffer bounds error");return this.buffer.slice(e-this.start,t-this.start)}get end(){return this.start+this.buffer.byteLength}get size(){return this.buffer.byteLength}contains(e,t){return e>=this.start&&t<=this.end}overlaps(e,t){return e>this.start&&ethis.start&&t(((e,t,i)=>{t in e?_p(e,t,{enumerable:!0,configurable:!0,writable:!0,value:i}):e[t]=i})(e,"symbol"!=typeof t?t+"":t,i),i);async function kp(e,t,i=0){var r=new Map;for(let[s,o]of e.entries()){let e=await Bp.unpack_from_async("<"+o,t,i);i+=Bp.calcsize(o),1==e.length&&(e=e[0]),r.set(s,e)}return r}function Ip(e,t,i=0){var r=new Map;for(let[s,o]of e.entries()){let e=Bp.unpack_from("<"+o,t,i);i+=Bp.calcsize(o),1==e.length&&(e=e[0]),r.set(s,e)}return r}function Sp(e){e||e()}function Ep(e){var t="<"+Array.from(e.values()).join("");return Bp.calcsize(t)}function Np(e,t=8){return Math.ceil(e/t)*t}var Mp={u:"Uint",i:"Int",f:"Float"};function Rp(e){var t,i,r=Bp._is_big_endian(e);if(/S/.test(e))t="getString",i=0|((e.match(/S(\d*)/)||[])[1]||1);else{let[r,s,o]=e.match(/[<>=!@]?(i|u|f)(\d*)/);i=parseInt(o||4,10),t="get"+Mp[s]+(8*i).toFixed()}return[t,r,i]}var Bp=new class{constructor(){this.big_endian=function(){const e=new Uint8Array(4);return!((new Uint32Array(e.buffer)[0]=1)&e[0])}(),this.getters={s:"getUint8",b:"getInt8",B:"getUint8",h:"getInt16",H:"getUint16",i:"getInt32",I:"getUint32",l:"getInt32",L:"getUint32",q:"getInt64",Q:"getUint64",f:"getFloat32",d:"getFloat64"},this.byte_lengths={s:1,b:1,B:1,h:2,H:2,i:4,I:4,l:4,L:4,q:8,Q:8,f:4,d:8};let e=Object.keys(this.byte_lengths).join("");this.fmt_size_regex="(\\d*)(["+e+"])"}calcsize(e){for(var t,i=0,r=new RegExp(this.fmt_size_regex,"g");null!==(t=r.exec(e));){let e=parseInt(t[1]||1,10),r=t[2];i+=e*this.byte_lengths[r]}return i}_is_big_endian(e){return!/^)/.test(e)||this.big_endian)}async unpack_from_async(e,t,i){i=Number.parseInt(i||0);const r=this.calcsize(e),s=await t.slice(i,i+r);let o=0;for(var n,a=new Dp(s),c=[],l=this._is_big_endian(e),h=new RegExp(this.fmt_size_regex,"g");null!==(n=h.exec(e));){let e=parseInt(n[1]||1,10),t=n[2],i=this.getters[t],r=this.byte_lengths[t];if("s"==t)c.push((new TextDecoder).decode(s.slice(o,o+e))),o+=e;else for(var d=0;de+(t<<8*i)),0);return n}var zp=class{constructor(e,t){this.buf=e,this.offset=t,this.dtype=this.determine_dtype()}async determine_dtype(){let e=await kp(Pp,this.buf,this.offset);this.offset+=Hp;let t=15&e.get("class_and_version");if(t==Op)return this._determine_dtype_fixed_point(e);if(t==Vp)return this._determine_dtype_floating_point(e);if(t==qp)throw"Time datatype class not supported.";if(t==Up)return this._determine_dtype_string(e);if(t==Qp)throw"Bitfield datatype class not supported.";if(t==Gp)return{datatype_class:Gp,size:e.get("size")};if(t==jp)return this._determine_dtype_compound(e);if(t==Wp)return["REFERENCE",e.get("size")];if(t==$p)return this.determine_dtype();if(t==Yp)throw"Array datatype class not supported.";if(t==Kp){let t=this._determine_dtype_vlen(e);if("VLEN_SEQUENCE"==t[0]){t=["VLEN_SEQUENCE",this.determine_dtype()]}return t}throw"Invalid datatype class "+t}_determine_dtype_fixed_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;var r;return i=(8&e.get("class_bit_field_0"))>0?"i":"u",r=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=4,r+i+t.toFixed()}_determine_dtype_floating_point(e){let t=e.get("size");if(![1,2,4,8].includes(t))throw"Unsupported datatype size";var i;return i=0==(1&e.get("class_bit_field_0"))?"<":">",this.offset+=12,i+"f"+t.toFixed()}_determine_dtype_string(e){return"S"+e.get("size").toFixed()}_determine_dtype_vlen(e){return 1!=(1&e.get("class_bit_field_0"))?["VLEN_SEQUENCE",0,0]:["VLEN_STRING",e.get("class_bit_field_0")>>4,1&e.get("class_bit_field_1")]}_determine_dtype_compound(e){throw"Compound type not yet implemented!"}},Pp=new Map([["class_and_version","B"],["class_bit_field_0","B"],["class_bit_field_1","B"],["class_bit_field_2","B"],["size","I"]]),Hp=Ep(Pp);Ep(new Map([["offset","I"],["dimensionality","B"],["reserved_0","B"],["reserved_1","B"],["reserved_2","B"],["permutation","I"],["reserved_3","I"],["dim_size_1","I"],["dim_size_2","I"],["dim_size_3","I"],["dim_size_4","I"]]));var Op=0,Vp=1,qp=2,Up=3,Qp=4,Gp=5,jp=6,Wp=7,$p=8,Kp=9,Yp=10;function Zp(e){let t=e.length;for(;--t>=0;)e[t]=0}Zp(new Array(576)),Zp(new Array(60)),Zp(new Array(512)),Zp(new Array(256)),Zp(new Array(29)),Zp(new Array(30));var Xp=(e,t,i,r)=>{let s=65535&e,o=e>>>16&65535,n=0;for(;0!==i;){n=i>2e3?2e3:i,i-=n;do{s=s+t[r++]|0,o=o+s|0}while(--n);s%=65521,o%=65521}return s|o<<16},Jp=new Uint32Array((()=>{let e,t=[];for(var i=0;i<256;i++){e=i;for(var r=0;r<8;r++)e=1&e?3988292384^e>>>1:e>>>1;t[i]=e}return t})()),eg=(e,t,i,r)=>{const s=Jp,o=r+i;e^=-1;for(let i=r;i>>8^s[255&(e^t[i])];return-1^e},tg={2:"need dictionary",1:"stream end",0:"","-1":"file error","-2":"stream error","-3":"data error","-4":"insufficient memory","-5":"buffer error","-6":"incompatible version"},ig={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_MEM_ERROR:-4,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8},rg=(e,t)=>Object.prototype.hasOwnProperty.call(e,t),sg=function(e){const t=Array.prototype.slice.call(arguments,1);for(;t.length;){const i=t.shift();if(i){if("object"!=typeof i)throw new TypeError(i+"must be non-object");for(const t in i)rg(i,t)&&(e[t]=i[t])}}return e},og=e=>{let t=0;for(let i=0,r=e.length;i=252?6:Ey>=248?5:Ey>=240?4:Ey>=224?3:Ey>=192?2:1;ag[254]=ag[254]=1;var cg=e=>{if("function"==typeof TextEncoder&&TextEncoder.prototype.encode)return(new TextEncoder).encode(e);let t,i,r,s,o,n=e.length,a=0;for(s=0;s>>6,t[o++]=128|63&i):i<65536?(t[o++]=224|i>>>12,t[o++]=128|i>>>6&63,t[o++]=128|63&i):(t[o++]=240|i>>>18,t[o++]=128|i>>>12&63,t[o++]=128|i>>>6&63,t[o++]=128|63&i);return t},lg=(e,t)=>{const i=t||e.length;if("function"==typeof TextDecoder&&TextDecoder.prototype.decode)return(new TextDecoder).decode(e.subarray(0,t));let r,s;const o=new Array(2*i);for(s=0,r=0;r4)o[s++]=65533,r+=n-1;else{for(t&=2===n?31:3===n?15:7;n>1&&r1?o[s++]=65533:t<65536?o[s++]=t:(t-=65536,o[s++]=55296|t>>10&1023,o[s++]=56320|1023&t)}}return((e,t)=>{if(t<65534&&e.subarray&&ng)return String.fromCharCode.apply(null,e.length===t?e:e.subarray(0,t));let i="";for(let r=0;r{(t=t||e.length)>e.length&&(t=e.length);let i=t-1;for(;i>=0&&128==(192&e[i]);)i--;return i<0||0===i?t:i+ag[e[i]]>t?i:t};var dg=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0},ug=function(e,t){let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_,x;const k=e.state;i=e.next_in,_=e.input,r=i+(e.avail_in-5),s=e.next_out,x=e.output,o=s-(t-e.avail_out),n=s+(e.avail_out-257),a=k.dmax,c=k.wsize,l=k.whave,h=k.wnext,d=k.window,u=k.hold,f=k.bits,p=k.lencode,g=k.distcode,m=(1<>>24,u>>>=F,f-=F,F=b>>>16&255,0===F)x[s++]=65535&b;else{if(!(16&F)){if(64&F){if(32&F){k.mode=12;break e}e.msg="invalid literal/length code",k.mode=30;break e}b=p[(65535&b)+(u&(1<>>=F,f-=F),f<15&&(u+=_[i++]<>>24,u>>>=F,f-=F,F=b>>>16&255,16&F){if(y=65535&b,F&=15,fa){e.msg="invalid distance too far back",k.mode=30;break e}if(u>>>=F,f-=F,F=s-o,y>F){if(F=y-F,F>l&&k.sane){e.msg="invalid distance too far back",k.mode=30;break e}if(A=0,C=d,0===h){if(A+=c-F,F2;)x[s++]=C[A++],x[s++]=C[A++],x[s++]=C[A++],v-=3;v&&(x[s++]=C[A++],v>1&&(x[s++]=C[A++]))}else{A=s-y;do{x[s++]=x[A++],x[s++]=x[A++],x[s++]=x[A++],v-=3}while(v>2);v&&(x[s++]=x[A++],v>1&&(x[s++]=x[A++]))}break}if(64&F){e.msg="invalid distance code",k.mode=30;break e}b=g[(65535&b)+(u&(1<>3,i-=v,f-=v<<3,u&=(1<{const c=a.bits;let l,h,d,u,f,p,g=0,m=0,w=0,b=0,F=0,v=0,y=0,A=0,C=0,_=0,x=null,k=0;const I=new Uint16Array(16),S=new Uint16Array(16);let E,N,M,R=null,B=0;for(g=0;g<=fg;g++)I[g]=0;for(m=0;m=1&&0===I[b];b--);if(F>b&&(F=b),0===b)return s[o++]=20971520,s[o++]=20971520,a.bits=1,0;for(w=1;w0&&(0===e||1!==b))return-1;for(S[1]=0,g=1;g852||2===e&&C>592)return 1;for(;;){E=g-y,n[m]p?(N=R[B+n[m]],M=x[k+n[m]]):(N=96,M=0),l=1<>y)+h]=E<<24|N<<16|M}while(0!==h);for(l=1<>=1;if(0!==l?(_&=l-1,_+=l):_=0,m++,0===--I[g]){if(g===b)break;g=t[i+n[m]]}if(g>F&&(_&u)!==d){for(0===y&&(y=F),f+=w,v=g-y,A=1<852||2===e&&C>592)return 1;d=_&u,s[d]=F<<24|v<<16|f-o}}return 0!==_&&(s[f+_]=g-y<<24|64<<16),a.bits=F,0},{Z_FINISH:Fg,Z_BLOCK:vg,Z_TREES:yg,Z_OK:Ag,Z_STREAM_END:Cg,Z_NEED_DICT:_g,Z_STREAM_ERROR:xg,Z_DATA_ERROR:kg,Z_MEM_ERROR:Ig,Z_BUF_ERROR:Sg,Z_DEFLATED:Eg}=ig,Ng=12,Mg=30,Rg=e=>(e>>>24&255)+(e>>>8&65280)+((65280&e)<<8)+((255&e)<<24);function Bg(){this.mode=0,this.last=!1,this.wrap=0,this.havedict=!1,this.flags=0,this.dmax=0,this.check=0,this.total=0,this.head=null,this.wbits=0,this.wsize=0,this.whave=0,this.wnext=0,this.window=null,this.hold=0,this.bits=0,this.length=0,this.offset=0,this.extra=0,this.lencode=null,this.distcode=null,this.lenbits=0,this.distbits=0,this.ncode=0,this.nlen=0,this.ndist=0,this.have=0,this.next=null,this.lens=new Uint16Array(320),this.work=new Uint16Array(288),this.lendyn=null,this.distdyn=null,this.sane=0,this.back=0,this.was=0}var Dg,Lg,Tg=e=>{if(!e||!e.state)return xg;const t=e.state;return e.total_in=e.total_out=t.total=0,e.msg="",t.wrap&&(e.adler=1&t.wrap),t.mode=1,t.last=0,t.havedict=0,t.dmax=32768,t.head=null,t.hold=0,t.bits=0,t.lencode=t.lendyn=new Int32Array(852),t.distcode=t.distdyn=new Int32Array(592),t.sane=1,t.back=-1,Ag},zg=e=>{if(!e||!e.state)return xg;const t=e.state;return t.wsize=0,t.whave=0,t.wnext=0,Tg(e)},Pg=(e,t)=>{let i;if(!e||!e.state)return xg;const r=e.state;return t<0?(i=0,t=-t):(i=1+(t>>4),t<48&&(t&=15)),t&&(t<8||t>15)?xg:(null!==r.window&&r.wbits!==t&&(r.window=null),r.wrap=i,r.wbits=t,zg(e))},Hg=(e,t)=>{if(!e)return xg;const i=new Bg;e.state=i,i.window=null;const r=Pg(e,t);return r!==Ag&&(e.state=null),r},Og=!0,Vg=e=>{if(Og){Dg=new Int32Array(512),Lg=new Int32Array(32);let t=0;for(;t<144;)e.lens[t++]=8;for(;t<256;)e.lens[t++]=9;for(;t<280;)e.lens[t++]=7;for(;t<288;)e.lens[t++]=8;for(bg(1,e.lens,0,288,Dg,0,e.work,{bits:9}),t=0;t<32;)e.lens[t++]=5;bg(2,e.lens,0,32,Lg,0,e.work,{bits:5}),Og=!1}e.lencode=Dg,e.lenbits=9,e.distcode=Lg,e.distbits=5},qg=(e,t,i,r)=>{let s;const o=e.state;return null===o.window&&(o.wsize=1<=o.wsize?(o.window.set(t.subarray(i-o.wsize,i),0),o.wnext=0,o.whave=o.wsize):(s=o.wsize-o.wnext,s>r&&(s=r),o.window.set(t.subarray(i-r,i-r+s),o.wnext),(r-=s)?(o.window.set(t.subarray(i-r,i),0),o.wnext=r,o.whave=o.wsize):(o.wnext+=s,o.wnext===o.wsize&&(o.wnext=0),o.whaveHg(e,15),inflateInit2:Hg,inflate:(e,t)=>{let i,r,s,o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v,y,A,C,_=0;const x=new Uint8Array(4);let k,I;const S=new Uint8Array([16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15]);if(!e||!e.state||!e.output||!e.input&&0!==e.avail_in)return xg;i=e.state,i.mode===Ng&&(i.mode=13),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,d=a,u=c,C=Ag;e:for(;;)switch(i.mode){case 1:if(0===i.wrap){i.mode=13;break}for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=eg(i.check,x,2,0),l=0,h=0,i.mode=2;break}if(i.flags=0,i.head&&(i.head.done=!1),!(1&i.wrap)||(((255&l)<<8)+(l>>8))%31){e.msg="incorrect header check",i.mode=Mg;break}if((15&l)!==Eg){e.msg="unknown compression method",i.mode=Mg;break}if(l>>>=4,h-=4,A=8+(15&l),0===i.wbits)i.wbits=A;else if(A>i.wbits){e.msg="invalid window size",i.mode=Mg;break}i.dmax=1<>8&1),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=eg(i.check,x,2,0)),l=0,h=0,i.mode=3;case 3:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>8&255,x[2]=l>>>16&255,x[3]=l>>>24&255,i.check=eg(i.check,x,4,0)),l=0,h=0,i.mode=4;case 4:for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>8),512&i.flags&&(x[0]=255&l,x[1]=l>>>8&255,i.check=eg(i.check,x,2,0)),l=0,h=0,i.mode=5;case 5:if(1024&i.flags){for(;h<16;){if(0===a)break e;a--,l+=r[o++]<>>8&255,i.check=eg(i.check,x,2,0)),l=0,h=0}else i.head&&(i.head.extra=null);i.mode=6;case 6:if(1024&i.flags&&(f=i.length,f>a&&(f=a),f&&(i.head&&(A=i.head.extra_len-i.length,i.head.extra||(i.head.extra=new Uint8Array(i.head.extra_len)),i.head.extra.set(r.subarray(o,o+f),A)),512&i.flags&&(i.check=eg(i.check,r,f,o)),a-=f,o+=f,i.length-=f),i.length))break e;i.length=0,i.mode=7;case 7:if(2048&i.flags){if(0===a)break e;f=0;do{A=r[o+f++],i.head&&A&&i.length<65536&&(i.head.name+=String.fromCharCode(A))}while(A&&f>9&1,i.head.done=!0),e.adler=i.check=0,i.mode=Ng;break;case 10:for(;h<32;){if(0===a)break e;a--,l+=r[o++]<>>=7&h,h-=7&h,i.mode=27;break}for(;h<3;){if(0===a)break e;a--,l+=r[o++]<>>=1,h-=1,3&l){case 0:i.mode=14;break;case 1:if(Vg(i),i.mode=20,t===yg){l>>>=2,h-=2;break e}break;case 2:i.mode=17;break;case 3:e.msg="invalid block type",i.mode=Mg}l>>>=2,h-=2;break;case 14:for(l>>>=7&h,h-=7&h;h<32;){if(0===a)break e;a--,l+=r[o++]<>>16^65535)){e.msg="invalid stored block lengths",i.mode=Mg;break}if(i.length=65535&l,l=0,h=0,i.mode=15,t===yg)break e;case 15:i.mode=16;case 16:if(f=i.length,f){if(f>a&&(f=a),f>c&&(f=c),0===f)break e;s.set(r.subarray(o,o+f),n),a-=f,o+=f,c-=f,n+=f,i.length-=f;break}i.mode=Ng;break;case 17:for(;h<14;){if(0===a)break e;a--,l+=r[o++]<>>=5,h-=5,i.ndist=1+(31&l),l>>>=5,h-=5,i.ncode=4+(15&l),l>>>=4,h-=4,i.nlen>286||i.ndist>30){e.msg="too many length or distance symbols",i.mode=Mg;break}i.have=0,i.mode=18;case 18:for(;i.have>>=3,h-=3}for(;i.have<19;)i.lens[S[i.have++]]=0;if(i.lencode=i.lendyn,i.lenbits=7,k={bits:i.lenbits},C=bg(0,i.lens,0,19,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid code lengths set",i.mode=Mg;break}i.have=0,i.mode=19;case 19:for(;i.have>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=m,h-=m,i.lens[i.have++]=b;else{if(16===b){for(I=m+2;h>>=m,h-=m,0===i.have){e.msg="invalid bit length repeat",i.mode=Mg;break}A=i.lens[i.have-1],f=3+(3&l),l>>>=2,h-=2}else if(17===b){for(I=m+3;h>>=m,h-=m,A=0,f=3+(7&l),l>>>=3,h-=3}else{for(I=m+7;h>>=m,h-=m,A=0,f=11+(127&l),l>>>=7,h-=7}if(i.have+f>i.nlen+i.ndist){e.msg="invalid bit length repeat",i.mode=Mg;break}for(;f--;)i.lens[i.have++]=A}}if(i.mode===Mg)break;if(0===i.lens[256]){e.msg="invalid code -- missing end-of-block",i.mode=Mg;break}if(i.lenbits=9,k={bits:i.lenbits},C=bg(1,i.lens,0,i.nlen,i.lencode,0,i.work,k),i.lenbits=k.bits,C){e.msg="invalid literal/lengths set",i.mode=Mg;break}if(i.distbits=6,i.distcode=i.distdyn,k={bits:i.distbits},C=bg(2,i.lens,i.nlen,i.ndist,i.distcode,0,i.work,k),i.distbits=k.bits,C){e.msg="invalid distances set",i.mode=Mg;break}if(i.mode=20,t===yg)break e;case 20:i.mode=21;case 21:if(a>=6&&c>=258){e.next_out=n,e.avail_out=c,e.next_in=o,e.avail_in=a,i.hold=l,i.bits=h,ug(e,u),n=e.next_out,s=e.output,c=e.avail_out,o=e.next_in,r=e.input,a=e.avail_in,l=i.hold,h=i.bits,i.mode===Ng&&(i.back=-1);break}for(i.back=0;_=i.lencode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,i.length=b,0===w){i.mode=26;break}if(32&w){i.back=-1,i.mode=Ng;break}if(64&w){e.msg="invalid literal/length code",i.mode=Mg;break}i.extra=15&w,i.mode=22;case 22:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}i.was=i.length,i.mode=23;case 23:for(;_=i.distcode[l&(1<>>24,w=_>>>16&255,b=65535&_,!(m<=h);){if(0===a)break e;a--,l+=r[o++]<>F)],m=_>>>24,w=_>>>16&255,b=65535&_,!(F+m<=h);){if(0===a)break e;a--,l+=r[o++]<>>=F,h-=F,i.back+=F}if(l>>>=m,h-=m,i.back+=m,64&w){e.msg="invalid distance code",i.mode=Mg;break}i.offset=b,i.extra=15&w,i.mode=24;case 24:if(i.extra){for(I=i.extra;h>>=i.extra,h-=i.extra,i.back+=i.extra}if(i.offset>i.dmax){e.msg="invalid distance too far back",i.mode=Mg;break}i.mode=25;case 25:if(0===c)break e;if(f=u-c,i.offset>f){if(f=i.offset-f,f>i.whave&&i.sane){e.msg="invalid distance too far back",i.mode=Mg;break}f>i.wnext?(f-=i.wnext,p=i.wsize-f):p=i.wnext-f,f>i.length&&(f=i.length),g=i.window}else g=s,p=n-i.offset,f=i.length;f>c&&(f=c),c-=f,i.length-=f;do{s[n++]=g[p++]}while(--f);0===i.length&&(i.mode=21);break;case 26:if(0===c)break e;s[n++]=i.length,c--,i.mode=21;break;case 27:if(i.wrap){for(;h<32;){if(0===a)break e;a--,l|=r[o++]<{if(!e||!e.state)return xg;let t=e.state;return t.window&&(t.window=null),e.state=null,Ag},inflateGetHeader:(e,t)=>{if(!e||!e.state)return xg;const i=e.state;return 2&i.wrap?(i.head=t,t.done=!1,Ag):xg},inflateSetDictionary:(e,t)=>{const i=t.length;let r,s,o;return e&&e.state?(r=e.state,0!==r.wrap&&11!==r.mode?xg:11===r.mode&&(s=1,s=Xp(s,t,i,0),s!==r.check)?kg:(o=qg(e,t,i,i),o?(r.mode=31,Ig):(r.havedict=1,Ag))):xg},inflateInfo:"pako inflate (from Nodeca project)"};var Qg=function(){this.text=0,this.time=0,this.xflags=0,this.os=0,this.extra=null,this.extra_len=0,this.name="",this.comment="",this.hcrc=0,this.done=!1},Gg=Object.prototype.toString,{Z_NO_FLUSH:jg,Z_FINISH:Wg,Z_OK:$g,Z_STREAM_END:Kg,Z_NEED_DICT:Yg,Z_STREAM_ERROR:Zg,Z_DATA_ERROR:Xg,Z_MEM_ERROR:Jg}=ig;function em(e){this.options=sg({chunkSize:65536,windowBits:15,to:""},e||{});const t=this.options;t.raw&&t.windowBits>=0&&t.windowBits<16&&(t.windowBits=-t.windowBits,0===t.windowBits&&(t.windowBits=-15)),!(t.windowBits>=0&&t.windowBits<16)||e&&e.windowBits||(t.windowBits+=32),t.windowBits>15&&t.windowBits<48&&(15&t.windowBits||(t.windowBits|=15)),this.err=0,this.msg="",this.ended=!1,this.chunks=[],this.strm=new dg,this.strm.avail_out=0;let i=Ug.inflateInit2(this.strm,t.windowBits);if(i!==$g)throw new Error(tg[i]);if(this.header=new Qg,Ug.inflateGetHeader(this.strm,this.header),t.dictionary&&("string"==typeof t.dictionary?t.dictionary=cg(t.dictionary):"[object ArrayBuffer]"===Gg.call(t.dictionary)&&(t.dictionary=new Uint8Array(t.dictionary)),t.raw&&(i=Ug.inflateSetDictionary(this.strm,t.dictionary),i!==$g)))throw new Error(tg[i])}function tm(e,t){const i=new em(t);if(i.push(e),i.err)throw i.msg||tg[i.err];return i.result}em.prototype.push=function(e,t){const i=this.strm,r=this.options.chunkSize,s=this.options.dictionary;let o,n,a;if(this.ended)return!1;for(n=t===~~t?t:!0===t?Wg:jg,"[object ArrayBuffer]"===Gg.call(e)?i.input=new Uint8Array(e):i.input=e,i.next_in=0,i.avail_in=i.input.length;;){for(0===i.avail_out&&(i.output=new Uint8Array(r),i.next_out=0,i.avail_out=r),o=Ug.inflate(i,n),o===Yg&&s&&(o=Ug.inflateSetDictionary(i,s),o===$g?o=Ug.inflate(i,n):o===Xg&&(o=Yg));i.avail_in>0&&o===Kg&&i.state.wrap>0&&0!==e[i.next_in];)Ug.inflateReset(i),o=Ug.inflate(i,n);switch(o){case Zg:case Xg:case Yg:case Jg:return this.onEnd(o),this.ended=!0,!1}if(a=i.avail_out,i.next_out&&(0===i.avail_out||o===Kg))if("string"===this.options.to){let e=hg(i.output,i.next_out),t=i.next_out-e,s=lg(i.output,e);i.next_out=t,i.avail_out=r-t,t&&i.output.set(i.output.subarray(e,e+t),0),this.onData(s)}else this.onData(i.output.length===i.next_out?i.output:i.output.subarray(0,i.next_out));if(o!==$g||0!==a){if(o===Kg)return o=Ug.inflateEnd(this.strm),this.onEnd(o),this.ended=!0,!0;if(0===i.avail_in)break}}return!0},em.prototype.onData=function(e){this.chunks.push(e)},em.prototype.onEnd=function(e){e===$g&&("string"===this.options.to?this.result=this.chunks.join(""):this.result=og(this.chunks)),this.chunks=[],this.err=e,this.msg=this.strm.msg};var im=function(e,t){return(t=t||{}).raw=!0,tm(e,t)},rm={Inflate:em,inflate:tm,inflateRaw:im,ungzip:tm,constants:ig},{Inflate:sm,inflate:om,inflateRaw:nm,ungzip:am}=rm,cm=om,lm=am;var hm=new Map([[1,function(e,t){let i=new Uint8Array(e);return cm(i).buffer}],[2,function(e,t){let i=e.byteLength,r=new Uint8Array(i),s=Math.floor(i/t),o=new DataView(e);for(var n=0;nHH",e,i);if(c%=65535,s!=(a%=65535)||o!=c)throw'ValueError("fletcher32 checksum invalid")'}(e),e.slice(0,-4)}]]),dm=class{constructor(e,t){this.fh=e,this.offset=t,this.depth=null}async init(){this.all_nodes=new Map,await this._read_root_node(),await this._read_children()}async _read_children(){let e=this.depth;for(;e>0;){for(var t of this.all_nodes.get(e))for(var i of t.get("addresses"))this._add_node(await this._read_node(i,e-1));e--}}async _read_root_node(){let e=await this._read_node(this.offset,null);this._add_node(e),this.depth=e.get("node_level")}_add_node(e){let t=e.get("node_level");this.all_nodes.has(t)?this.all_nodes.get(t).push(e):this.all_nodes.set(t,[e])}async _read_node(e,t){let i=await this._read_node_header(e,t);return i.set("keys",[]),i.set("addresses",[]),i}async _read_node_header(e){throw"NotImplementedError: must define _read_node_header in implementation class"}},um=class extends dm{constructor(){super(...arguments),xp(this,"B_LINK_NODE",new Map([["signature","4s"],["node_type","B"],["node_level","B"],["entries_used","H"],["left_sibling","Q"],["right_sibling","Q"]]))}async _read_node_header(e,t){let i=await kp(this.B_LINK_NODE,this.fh,e);if(null!=t&&i.get("node_level")!=t)throw"node level does not match";return i}},fm=class extends um{constructor(e,t){super(e,t),xp(this,"NODE_TYPE",0),this.ready=this.init()}async _read_node(e,t){let i=await this._read_node_header(e,t);e+=Ep(this.B_LINK_NODE);let r=[],s=[],o=i.get("entries_used");for(var n=0;n=0&&F[A]>=e[A];A--)F[A]=0,b[A]=w[A],A>0&&(F[A-1]+=1,b[A-1]+=1);if(b.slice(0,-1).every((function(e,i){return e=0;n--){if(t&1<0?s*=r:s=r}}return o}_nrecords_max(e,t,i){return Math.floor((e-10-i)/(t+i))}_required_bytes(e){return Math.ceil(Lp(e)/8)}_int_format(e){return["0&&(h=(await Bp.unpack_from_async(a,this.fh,i))[0],i+=s),c.push([r,l,h])}}return o.set("keys",a),o.set("addresses",c),o}async _read_node_header(e,t){let i=await kp(this.B_LINK_NODE,this.fh,e);return i.set("node_level",t),i}*iter_records(){for(let e of this.all_nodes.values())for(let t of e)for(let e of t.get("keys"))yield e}_parse_record(e){throw"NotImplementedError"}},mm=class extends gm{constructor(){super(...arguments),xp(this,"NODE_TYPE",5)}async _parse_record(e,t,i){let r=(await Bp.unpack_from_async("0)throw"Filter info size not supported on FractalHeap";if(t.get("btree_address_huge_objects")!=_m)throw"Huge objects not implemented in FractalHeap";t.set("btree_address_huge_objects",null),t.get("root_block_address")==_m&&t.set("root_block_address",null);let i=t.get("log2_maximum_heap_size"),r=this._min_size_nbits(i),s=new Map([["signature","4s"],["version","B"],["heap_header_adddress","Q"],["block_offset",`${r}B`]]);this.indirect_block_header=new Map(s),this.indirect_block_header_size=Ep(s),2&~t.get("flags")||s.set("checksum","I"),this.direct_block_header=s,this.direct_block_header_size=Ep(s);let o=t.get("maximum_direct_block_size");this._managed_object_offset_size=this._min_size_nbits(i);let n=Math.min(o,t.get("max_managed_object_size"));this._managed_object_length_size=this._min_size_integer(n);let a=t.get("starting_block_size"),c=t.get("table_width");if(!(a>0))throw"Starting block size == 0 not implemented";let l=Number(Math.floor(Math.log2(o)));Sp(1n<0)for await(let e of this._iter_indirect_block(this.fh,f,p))u.push(e);else{let e=await this._read_direct_block(this.fh,f,a);u.push(e)}let g=u.reduce(((e,t)=>e+t.byteLength),0),m=new Uint8Array(g),w=0;u.forEach((e=>{m.set(new Uint8Array(e),w),w+=e.byteLength})),this.managed=m.buffer}async _read_direct_block(e,t,i){let r=await e.slice(t,t+i);return Sp("FHDB"==Ip(this.direct_block_header,r).get("signature")),r}get_data(e){let t=Bp.unpack_from(">4&3,r=1;if(0==i){Sp(0==t>>6);let i=this._managed_object_offset_size,s=Tp(i,e,r);r+=i,i=this._managed_object_length_size;let o=Tp(i,e,r);return this.managed.slice(s,s+o)}throw 1==i?"tiny objectID not supported in FractalHeap":2==i?"huge objectID not supported in FractalHeap":"unknown objectID type in FractalHeap"}_min_size_integer(e){return this._min_size_nbits(Lp(e))}_min_size_nbits(e){return Math.ceil(e/8)}async*_iter_indirect_block(e,t,i){let r=await kp(this.indirect_block_header,e,t);t+=this.indirect_block_header_size,Sp("FHIB"==r.get("signature"));let s=r.get("block_offset").reduce(((e,t,i)=>e+(t<<8*i)),0);r.set("block_offset",s);let[o,n]=this._indirect_info(i),a=[];for(let i=0;ithis._chunks))}get shape(){let e=this.find_msg_type(dw)[0].get("offset_to_message");return async function(e,t){let i=(await Bp.unpack_from_async("255&&(o=(await Bp.unpack_from_async("0;e.set("optional",a);let c,l=(await Bp.unpack_from_async("0&&(c=(await Bp.unpack_from_async(`${o}s`,i,t))[0],t+=o),e.set("name",c);let h=await Bp.unpack_from_async(`<${l}i`,i,t);t+=4*l,e.set("client_data_values",h),s.push(e)}}return this._filter_pipeline=s,this._filter_pipeline}find_msg_type(e){return this.msgs.filter((function(t){return t.get("type")==e}))}async get_attributes(){let e={},t=this.find_msg_type(bw);for(let i of t){let t=i.get("offset_to_message"),[r,s]=await this.unpack_attribute(t);e[r]=s}return e}async get_fillvalue(){var e,t=this.find_msg_type(pw)[0].get("offset_to_message");let i=(await Bp.unpack_from_async("=s&&([o,s]=a[++c],l=0);let t=await kp(Xm,e,o+l),i=o+l+Jm;if(t.set("offset_to_message",i),t.get("type")==Fw){var[u,f]=await Bp.unpack_from_async("=n-tw){let e=c[++l];if(null==e)break;[s,n]=e,h=0}let t=await kp(ew,e,s+h),i=s+h+tw+r;if(t.set("offset_to_message",i),t.get("type")==Fw){var[d,u]=await Bp.unpack_from_async("0,c=(4&r)>0;(8&r)>0?(s=(await Bp.unpack_from_async("0&&(t+=8);let s=(2&r)>0?sw:rw,o=await kp(s,e,t),n=new Map;for(let[e,t]of o.entries())n.set(e,t==Om?null:t);return n}get is_dataset(){return this.find_msg_type(dw).length>0}async get_data(){let e=this.find_msg_type(mw)[0].get("offset_to_message");var[t,i,r,s]=await this._get_data_message_properties(e);if(0==r)throw"Compact storage of DataObject not implemented";return 1==r?this._get_contiguous_data(s):2==r?this._get_chunked_data(e):void 0}async _get_data_message_properties(e){let t,i,r,[s,o,n]=await Bp.unpack_from_async("=1&&s<=4),[s,t,i,r]}async _get_contiguous_data(e){let[t]=await Bp.unpack_from_async("=!@\|]?(i|u|f|S)(\d*)/.test(r)){let[e,i,o]=Rp(r),a=new Array(s);const c=await this.fh.slice(t,t+o*s);let l=new Dp(c);for(var n=0;n=1&&t<=3);var a="<"+(i-1).toFixed()+"I",c=await Bp.unpack_from_async(a,this.fh,o);this._chunks=c,this._chunk_dims=i,this._chunk_address=n}}}};var Om=Bp.unpack_from("this.get(e)))}length(){return this.keys.length}_dereference(e){if(!e)throw"cannot deference null reference";let t=this.file._get_object_by_address(e);if(null==t)throw"reference not found in file";return t}async get(e){if("number"==typeof e)return this._dereference(e);var t=_w(e);if("/"==t)return this.file;if("."==t)return this;if(/^\//.test(t))return this.file.get(t.slice(1));if(""!=function(e){let t="/",i=e.lastIndexOf(t)+1,r=e.slice(0,i),s=new RegExp("^"+t+"+$"),o=new RegExp(t+"$");r&&!s.test(r)&&(r=r.replace(o,""));return r}(t))var[i,r]=t.split(/\/(.*)/);else var i=t,r=".";if(!(i in this._links))throw i+" not found in group";var s=_w(this.name+"/"+i);let o=this._links[i];if("string"==typeof o)try{return this.get(o)}catch(e){return null}var n=new Hm(this.file._fh,o);if(await n.ready,n.is_dataset){if("."!=r)throw s+" is a dataset, not a group";return new Cw(s,n,this)}var a=new yw(s,this);return await a.init(n),a.get(r)}visit(e){return this.visititems(((t,i)=>e(t)))}visititems(e){var t=this.name.length;/\/$/.test(this.name)||(t+=1);for(var i=this.values.slice();i;){let r=i.shift();1==i.length&&console.log(r);let s=e(r.name.slice(t),r);if(null!=s)return s;r instanceof yw&&(i=i.concat(r.values))}return null}get attrs(){return null==this._attrs&&(this._attrs=this._dataobjects.get_attributes()),this._attrs}},Aw=class extends yw{constructor(e,t,i){super("/",null),this.ready=this.init(e,t,i)}async init(e,t,i){var r=new bm(e,0);await r.ready;var s=await r.get_offset_to_dataobjects(),o=new Hm(e,s);if(await o.ready,this.parent=this,this.file=this,this.name="/",this._dataobjects=o,this._attrs=null,this._keys=null,this._fh=e,this.filename=t||"",this.mode="r",this.userblock_size=0,i&&i.index)this.index=i.index;else{let t;if(i&&i.indexOffset)t=i.indexOffset;else{const e=await this.attrs;if(e.hasOwnProperty("_index_offset"))t=e._index_offset;else{const e=this.indexName||"_index",i=await o.find_link(e);i&&(t=i[1])}}if(t)try{const i=new Hm(e,t);await i.ready;const r=await i.get_data(),s=lm(r),o=(new TextDecoder).decode(s);this.index=JSON.parse(o)}catch(e){console.error(`Error loading index by offset ${e}`)}}this.index&&this.name in this.index?this._links=this.index[this.name]:this._links=await o.get_links()}_get_object_by_address(e){return this._dataobjects.offset==e?this:this.visititems((e=>{e._dataobjects.offset}))}},Cw=class extends Array{constructor(e,t,i){super(),this.parent=i,this.file=i.file,this.name=e,this._dataobjects=t,this._attrs=null,this._astype=null}get value(){var e=this._dataobjects.get_data();return null==this._astype?this.getValue(e):e.astype(this._astype)}get shape(){return this._dataobjects.shape}get attrs(){return this._dataobjects.get_attributes()}get dtype(){return this._dataobjects.dtype}get fillvalue(){return this._dataobjects.get_fillvalue()}async to_array(){return function(e,t){const i=e.length,r=t.reduce(((e,t)=>e*t),1);i!==r&&console.warn(`shape product: ${r} does not match length of flattened array: ${i}`);let s=e;const o=t.slice(1).reverse();for(let e of o){const t=[],{length:i}=s;let r=0;for(;r{let t=e.indexOf("\0");return t>=0?e.substring(0,t):e})):e}};function _w(e){return e.replace(/\/(\/)+/g,"/")}async function xw(e){var t;e.url&&("function"==typeof(t=e.url).slice&&"function"==typeof t.arrayBuffer)&&(e.file=e.url,e.url=void 0);const i=void 0!==e.url;let r=e.reader?e.reader:kw(e);const s=e.fetchSize||2e3,o=e.maxSize||2e5;i&&(r=new yp({file:r,fetchSize:s,maxSize:o}));const n=new Iw(r),a=await async function(e){if(e.index)return e.index;{let t;if(e.indexReader)t=e.indexReader;else{let i;if(e.indexURL)i=Object.assign({url:e.indexURL},e);else if(e.indexPath)i=Object.assign({path:e.indexPath},e);else{if(!e.indexFile)return;i=Object.assign({file:e.indexFile},e)}t=kw(i)}const i=await t.read(),r=(new TextDecoder).decode(i);return JSON.parse(r)}}(e),c=e.indexOffset,l=function(e){if(e.url)return Sw(e.url);if(e.path)return Sw(e.path);if(e.file)return e.file.name}(e),h=new Aw(n,l,{index:a,indexOffset:c});return await h.ready,h}function kw(e){if(e.url)return new vp(e);if(e.path)return new NodeLocalFile(e);if(e.file)return new Cp(e.file);throw Error("One of 'url', 'path (node only)', or 'file (browser only)' must be specified")}class Iw{constructor(e){this.fileReader=e}async slice(e,t){return this.fileReader.read(e,t-e)}}function Sw(e){const t=e.lastIndexOf("/");return t>0?e.substring(t+1):e}class Ew{constructor(e,t){this.chrom=e,this.signal_bin_size=t;this.signals={raw_RD:`his_rd_p_${this.chrom}_${this.signal_bin_size}`,gc_RD:`his_rd_p_${this.chrom}_${this.signal_bin_size}_GC`,gc_partition:`his_rd_p_${this.chrom}_${this.signal_bin_size}_partition_GC_merge`,baf:`snp_likelihood_${this.chrom}_${this.signal_bin_size}_mask`,baf_i1:`snp_i1_${this.chrom}_${this.signal_bin_size}_mask`,Mosaic_segments:`his_rd_p_${this.chrom}_${this.signal_bin_size}_partition_GC_mosaic_segments_2d`,Mosaic_calls:`his_rd_p_${this.chrom}_${this.signal_bin_size}_partition_GC_mosaic_call_2d`}}}class Nw{constructor(e,t=1e5){this.config=e,this.bin_size=t,this.h5_obj=void 0,this.pytorKeys=[],this.availableBins=[]}async fetch(){if(!this.h5_obj){const e=Object.assign(this.config,{fetchSize:1e6,maxSize:2e8});this.h5_obj=await xw(e)}return this.h5_obj}async get_keys(){return(await this.fetch()).keys}async get_rd_signal(e=this.bin_size,t=void 0){const i=await this.fetch();this.pytorKeys=i.keys;const r=new Mw(this.pytorKeys);this.availableBins=r.getAllBins(),this.availableBins.includes(e)||(e=this.availableBins.at(-1));const s=await this.getChromosomes(t);let o=await this.rd_stat(e);const n=await this.getWigFeatures(s,e,o);return this.setCallers(n),{[e]:n}}async getWigFeatures(e,t,i){const r={RD_Raw:[],RD_Raw_gc_coor:[],ReadDepth:[],"2D":[],BAF1:[],BAF2:[]};for(const s of e){const e=new Ew(s,t);r.RD_Raw.push(...await this.get_chr_signal(s,t,e.signals.raw_RD,i)),r.RD_Raw_gc_coor.push(...await this.get_chr_signal(s,t,e.signals.gc_RD,i)),r.ReadDepth.push(...await this.get_chr_signal(s,t,e.signals.gc_partition,i)),r["2D"].push(...await this.rd_call_combined(s,t,i,e));const[o,n]=await this.getBafSignals(s,t,e.signals.baf_i1);r.BAF1.push(...o),r.BAF2.push(...n)}return r}async getChromosomes(e){const t=await this.h5_obj.get("rd_chromosomes"),i=await t.value;if(e){let t=new Set(e);return i.filter((e=>t.has(e)))}return i}setCallers(e){this.callers=[],e.ReadDepth.length&&this.callers.push("ReadDepth"),e["2D"].length&&this.callers.push("2D")}decode_segments(e){let t=[],i=[];for(let r of e)4294967295==r?(t.push(i),i=[]):i.push(r);return t}async rd_call_combined(e,t,i,r){let s,o=[],n=r.signals.Mosaic_segments;if(this.pytorKeys.includes(n)){const e=await this.h5_obj.get(n);let t=await e.value;s=this.decode_segments(t)}let a=r.signals.Mosaic_calls;if(this.pytorKeys.includes(a)){const r=await this.h5_obj.get(a);let n=await r.to_array();s.forEach(((r,s)=>{r.forEach(((r,a)=>{o.push({chr:e,start:r*t,end:(r+1)*t,value:n[0][s]/i[4]*2})}))}))}return o}async rd_stat(e){let t,i=`rd_stat_${e}_auto`;if(this.pytorKeys.includes(i)){const e=await this.h5_obj.get(i);t=await e.value}return t}async get_chr_signal(e,t,i,r){let s=[];if(this.pytorKeys.includes(i)){const o=await this.h5_obj.get(i);(await o.value).forEach(((i,o)=>{s.push({chr:e,start:o*t,end:(o+1)*t,value:i/r[4]*2})}))}return s}async getBafSignals(e,t,i,r=-1){const s=[],o=[];if(this.pytorKeys.includes(i)){const n=await this.h5_obj.get(i);(await n.to_array()).forEach(((i,n)=>{isNaN(i)||(s.push({chr:e,start:n*t,end:(n+1)*t,value:r*(.5-i)}),.5!==i&&o.push({chr:e,start:n*t,end:(n+1)*t,value:r*(.5+i)}))}))}return[s,o]}}class Mw{constructor(e){this.signals=e}getAllBins(){const e=this.getRdBins(),t=this.getSnpBins();return[...new Set([...e,...t])].sort(((e,t)=>e-t))}getRdBins(){return this.extractBins(/^his_rd_p_(.*)_(\d+)$/)}getSnpBins(){return this.extractBins(/^snp_likelihood_(.*)_(\d+)_mask$/)}extractBins(e){return[...new Set(this.signals.map((t=>t.match(e))).filter((e=>null!==e)).map((e=>Number(e[2]))))]}}function Rw(e){if(e.length<4)return e;let t,i,r,s,o,n;return t=e.slice().sort(((e,t)=>e-t)),t.length/4%1==0?(i=.5*(t[t.length/4]+t[t.length/4+1]),r=.5*(t[t.length*(3/4)]+t[t.length*(3/4)+1])):(i=t[Math.floor(t.length/4+1)],r=t[Math.ceil(t.length*(3/4)+1)]),s=r-i,o=r+1.5*s,n=i-1.5*s,t.filter((e=>e>=n&&e<=o))}function Bw(e){let t=Rw(e);const i=t.length,r=t.reduce(((e,t)=>e+t))/i,s=Math.sqrt(t.map((e=>Math.pow(e-r,2))).reduce(((e,t)=>e+t))/i);return[r,s]}var Dw={range_function:function(e,t,i){return Array(Math.ceil((t-e)/i)).fill(e).map(((e,t)=>e+t*i))},getDistParams:Bw,linspace:function(e,t,i){if(void 0===i&&(i=Math.max(Math.round(t-e)+1,1)),i<2)return 1===i?[e]:[];var r=Array(i);for(let s=--i;s>=0;s--)r[s]=(s*t+(i-s)*e)/i;return r},GetFit:class{constructor(e){this.allBins=e}getValues(){return Object.values(this.allBins).reduce(((e,t)=>e.concat(t.filter((e=>e.binScore>0)).map((e=>e.binScore)))),[])}getMean(e){return e.reduce((function(e,t){return e+t}))/e.length}fit_data(){return Bw(this.getValues())}histogram(e,t){const i=t[1]-t[0],r=[];e.forEach(((e,s)=>{t.forEach(((t,s)=>{if(r[t]||(r[t]={count:0}),t<=e&&e{s.push(e.count)})),s}},filterOutliers:Rw};function Lw(e,t){return isNaN(e)||isNaN(t)||t<=0?NaN:0===e?.5:.5+.5*(Tw(.5*t,.5,1)-Tw(.5*t,.5,t/(t+e*e)))*Math.sign(e)}function Tw(e,t,i){if(0==i)return 0;if(1==i)return 1;{let r=Ow(e+t)-Ow(e)-Ow(t)+e*Math.log(i)+t*Math.log(1-i);return i<(e+1)/(e+t+2)?Math.exp(r)*zw(e,t,i)/e:1-Math.exp(r)*zw(t,e,1-i)/t}}function zw(e,t,i,r=1e3){let s=1,o=1,n=1,a=e+t,c=e+1,l=e-1,h=1-a*i/c;for(let d=0;d<=r;d++){let r=parseFloat(d+1),u=r+r,f=r*(t-r)*i/((l+u)*(e+u)),p=s+f*o,g=h+f*n;f=-(e+r)*(a+r)*i/((c+u)*(e+u));let m=g+f*h,w=s;if(o=p/m,n=g/m,s=(p+f*s)/m,h=1,Math.abs(s-w)<3e-7*Math.abs(s))return s}}function Pw(e){if(0==e||1==e)return 1;return e*Pw(e-1)}function Hw(e){let t;var i=[75122.633153,80916.6278952,36308.2951477,8687.24529705,1168.92649479,83.8676043424,2.50662827511],r=0,s=1;if(0==e)t=1e99;else if(e%1==0)t=Pw(e-1);else{for(let t=0;t1&&void 0!==arguments[1]?arguments[1]:{};if(!function(e){const t=Zw.call(e);return t.endsWith("Array]")&&!t.includes("Big")}(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");var i=t.fromIndex,r=void 0===i?0:i,s=t.toIndex,o=void 0===s?e.length:s;if(r<0||r>=e.length||!Number.isInteger(r))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=r||o>e.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var n=e[r],a=r+1;an&&(n=e[a]);return n}const Jw=Object.prototype.toString;function eb(e){var t=arguments.length>1&&void 0!==arguments[1]?arguments[1]:{};if(!function(e){const t=Jw.call(e);return t.endsWith("Array]")&&!t.includes("Big")}(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");var i=t.fromIndex,r=void 0===i?0:i,s=t.toIndex,o=void 0===s?e.length:s;if(r<0||r>=e.length||!Number.isInteger(r))throw new Error("fromIndex must be a positive integer smaller than length");if(o<=r||o>e.length||!Number.isInteger(o))throw new Error("toIndex must be an integer greater than fromIndex and at most equal to length");for(var n=e[r],a=r+1;a1&&void 0!==arguments[1]?arguments[1]:{};if(!Yw(e))throw new TypeError("input must be an array");if(0===e.length)throw new TypeError("input must not be empty");if(void 0!==i.output){if(!Yw(i.output))throw new TypeError("output option must be an array if specified");t=i.output}else t=new Array(e.length);var r=eb(e),s=Xw(e);if(r===s)throw new RangeError("minimum and maximum input values are equal. Cannot rescale a constant array");var o=i.min,n=void 0===o?i.autoMinMax?r:0:o,a=i.max,c=void 0===a?i.autoMinMax?s:1:a;if(n>=c)throw new RangeError("min option must be smaller than max option");for(var l=(c-n)/(s-r),h=0;h=0&&i?` ${lb(e,t-1)}`:lb(e,t)).padEnd(t)}function lb(e,t){let i=e.toString();if(i.length<=t)return i;let r=e.toFixed(t);if(r.length>t&&(r=e.toFixed(Math.max(0,t-(r.length-t)))),r.length<=t&&!r.startsWith("0.000")&&!r.startsWith("-0.000"))return r;let s=e.toExponential(t);return s.length>t&&(s=e.toExponential(Math.max(0,t-(s.length-t)))),s.slice(0)}function hb(e,t,i){let r=i?e.rows:e.rows-1;if(t<0||t>r)throw new RangeError("Row index out of range")}function db(e,t,i){let r=i?e.columns:e.columns-1;if(t<0||t>r)throw new RangeError("Column index out of range")}function ub(e,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==e.columns)throw new RangeError("vector size must be the same as the number of columns");return t}function fb(e,t){if(t.to1DArray&&(t=t.to1DArray()),t.length!==e.rows)throw new RangeError("vector size must be the same as the number of rows");return t}function pb(e,t){if(!rb.isAnyArray(t))throw new TypeError("row indices must be an array");for(let i=0;i=e.rows)throw new RangeError("row indices are out of range")}function gb(e,t){if(!rb.isAnyArray(t))throw new TypeError("column indices must be an array");for(let i=0;i=e.columns)throw new RangeError("column indices are out of range")}function mb(e,t,i,r,s){if(5!==arguments.length)throw new RangeError("expected 4 arguments");if(bb("startRow",t),bb("endRow",i),bb("startColumn",r),bb("endColumn",s),t>i||r>s||t<0||t>=e.rows||i<0||i>=e.rows||r<0||r>=e.columns||s<0||s>=e.columns)throw new RangeError("Submatrix indices are out of range")}function wb(e,t=0){let i=[];for(let r=0;r=s)throw new RangeError("min must be smaller than max");let n=s-r,a=new Ab(e,t);for(let i=0;ii?(s=!0,i=t):(r=!1,s=!0);e++}return r}isReducedEchelonForm(){let e=0,t=0,i=-1,r=!0,s=!1;for(;ei?(s=!0,i=t):(r=!1,s=!0);for(let i=t+1;ie.get(r,i)&&(r=s);if(0===e.get(r,i))i++;else{e.swapRows(t,r);let s=e.get(t,i);for(let r=i;r=0;)if(0===e.maxRow(r))r--;else{let s=0,o=!1;for(;se[t]&&(e[t]=this.get(t,i));return e}case"column":{const e=new Array(this.columns).fill(Number.NEGATIVE_INFINITY);for(let t=0;te[i]&&(e[i]=this.get(t,i));return e}case void 0:{let e=this.get(0,0);for(let t=0;te&&(e=this.get(t,i));return e}default:throw new Error(`invalid option: ${e}`)}}maxIndex(){Fb(this);let e=this.get(0,0),t=[0,0];for(let i=0;ie&&(e=this.get(i,r),t[0]=i,t[1]=r);return t}min(e){if(this.isEmpty())return NaN;switch(e){case"row":{const e=new Array(this.rows).fill(Number.POSITIVE_INFINITY);for(let t=0;tt&&(t=this.get(e,i));return t}maxRowIndex(e){hb(this,e),Fb(this);let t=this.get(e,0),i=[e,0];for(let r=1;rt&&(t=this.get(e,r),i[1]=r);return i}minRow(e){if(hb(this,e),this.isEmpty())return NaN;let t=this.get(e,0);for(let i=1;it&&(t=this.get(i,e));return t}maxColumnIndex(e){db(this,e),Fb(this);let t=this.get(0,e),i=[0,e];for(let r=1;rt&&(t=this.get(r,e),i[0]=r);return i}minColumn(e){if(db(this,e),this.isEmpty())return NaN;let t=this.get(0,e);for(let i=1;i1;r/=2)1&r&&(t=t.mmul(i)),i=i.mmul(i);return t}strassen2x2(e){e=Ab.checkMatrix(e);let t=new Ab(2,2);const i=this.get(0,0),r=e.get(0,0),s=this.get(0,1),o=e.get(0,1),n=this.get(1,0),a=e.get(1,0),c=this.get(1,1),l=e.get(1,1),h=(i+c)*(r+l),d=(n+c)*r,u=i*(o-l),f=c*(a-r),p=(i+s)*l,g=h+f-p+(s-c)*(a+l),m=u+p,w=d+f,b=h-d+u+(n-i)*(r+o);return t.set(0,0,g),t.set(0,1,m),t.set(1,0,w),t.set(1,1,b),t}strassen3x3(e){e=Ab.checkMatrix(e);let t=new Ab(3,3);const i=this.get(0,0),r=this.get(0,1),s=this.get(0,2),o=this.get(1,0),n=this.get(1,1),a=this.get(1,2),c=this.get(2,0),l=this.get(2,1),h=this.get(2,2),d=e.get(0,0),u=e.get(0,1),f=e.get(0,2),p=e.get(1,0),g=e.get(1,1),m=e.get(1,2),w=e.get(2,0),b=e.get(2,1),F=e.get(2,2),v=(i-o)*(-u+g),y=(-i+o+n)*(d-u+g),A=(o+n)*(-d+u),C=i*d,_=(-i+c+l)*(d-f+m),x=(-i+c)*(f-m),k=(c+l)*(-d+f),I=(-s+l+h)*(g+w-b),S=(s-h)*(g-b),E=s*w,N=(l+h)*(-w+b),M=(-s+n+a)*(m+w-F),R=(s-a)*(m-F),B=(n+a)*(-w+F),D=C+E+r*p,L=(i+r+s-o-n-l-h)*g+y+A+C+I+E+N,T=C+_+k+(i+r+s-n-a-c-l)*m+E+M+B,z=v+n*(-d+u+p-g-m-w+F)+y+C+E+M+R,P=v+y+A+C+a*b,H=E+M+R+B+o*f,O=C+_+x+l*(-d+f+p-g-m-w+b)+I+S+E,V=I+S+E+N+c*u,q=C+_+x+k+h*F;return t.set(0,0,D),t.set(0,1,L),t.set(0,2,T),t.set(1,0,z),t.set(1,1,P),t.set(1,2,H),t.set(2,0,O),t.set(2,1,V),t.set(2,2,q),t}mmulStrassen(e){e=Ab.checkMatrix(e);let t=this.clone(),i=t.rows,r=t.columns,s=e.rows,o=e.columns;function n(e,t,i){let r=e.rows,s=e.columns;if(r===t&&s===i)return e;{let r=vb.zeros(t,i);return r=r.setSubMatrix(e,0,0),r}}r!==s&&console.warn(`Multiplying ${i} x ${r} and ${s} x ${o} matrix: dimensions do not match.`);let a=Math.max(i,s),c=Math.max(r,o);return t=n(t,a,c),function e(t,i,r,s){if(r<=512||s<=512)return t.mmul(i);r%2==1&&s%2==1?(t=n(t,r+1,s+1),i=n(i,r+1,s+1)):r%2==1?(t=n(t,r+1,s),i=n(i,r+1,s)):s%2==1&&(t=n(t,r,s+1),i=n(i,r,s+1));let o=parseInt(t.rows/2,10),a=parseInt(t.columns/2,10),c=t.subMatrix(0,o-1,0,a-1),l=i.subMatrix(0,o-1,0,a-1),h=t.subMatrix(0,o-1,a,t.columns-1),d=i.subMatrix(0,o-1,a,i.columns-1),u=t.subMatrix(o,t.rows-1,0,a-1),f=i.subMatrix(o,i.rows-1,0,a-1),p=t.subMatrix(o,t.rows-1,a,t.columns-1),g=i.subMatrix(o,i.rows-1,a,i.columns-1),m=e(vb.add(c,p),vb.add(l,g),o,a),w=e(vb.add(u,p),l,o,a),b=e(c,vb.sub(d,g),o,a),F=e(p,vb.sub(f,l),o,a),v=e(vb.add(c,h),g,o,a),y=e(vb.sub(u,c),vb.add(l,d),o,a),A=e(vb.sub(h,p),vb.add(f,g),o,a),C=vb.add(m,F);C.sub(v),C.add(A);let _=vb.add(b,v),x=vb.add(w,F),k=vb.sub(m,w);k.add(b),k.add(y);let I=vb.zeros(2*C.rows,2*C.columns);return I=I.setSubMatrix(C,0,0),I=I.setSubMatrix(_,C.rows,0),I=I.setSubMatrix(x,0,C.columns),I=I.setSubMatrix(k,C.rows,C.columns),I.subMatrix(0,r-1,0,s-1)}(t,e=n(e,a,c),a,c)}scaleRows(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{min:t=0,max:i=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(i))throw new TypeError("max must be a number");if(t>=i)throw new RangeError("min must be smaller than max");let r=new Ab(this.rows,this.columns);for(let e=0;e0&&sb(s,{min:t,max:i,output:s}),r.setRow(e,s)}return r}scaleColumns(e={}){if("object"!=typeof e)throw new TypeError("options must be an object");const{min:t=0,max:i=1}=e;if(!Number.isFinite(t))throw new TypeError("min must be a number");if(!Number.isFinite(i))throw new TypeError("max must be a number");if(t>=i)throw new RangeError("min must be smaller than max");let r=new Ab(this.rows,this.columns);for(let e=0;ei||t<0||t>=this.columns||i<0||i>=this.columns)throw new RangeError("Argument out of range");let r=new Ab(e.length,i-t+1);for(let s=0;s=this.rows)throw new RangeError(`Row index out of range: ${e[s]}`);r.set(s,o-t,this.get(e[s],o))}return r}subMatrixColumn(e,t,i){if(void 0===t&&(t=0),void 0===i&&(i=this.rows-1),t>i||t<0||t>=this.rows||i<0||i>=this.rows)throw new RangeError("Argument out of range");let r=new Ab(i-t+1,e.length);for(let s=0;s=this.columns)throw new RangeError(`Column index out of range: ${e[s]}`);r.set(o-t,s,this.get(o,e[s]))}return r}setSubMatrix(e,t,i){if((e=Ab.checkMatrix(e)).isEmpty())return this;mb(this,t,t+e.rows-1,i,i+e.columns-1);for(let r=0;r=0))throw new TypeError("nColumns must be a positive integer");for(let i=0;i=0)this.#x(e,t);else{if(!rb.isAnyArray(e))throw new TypeError("First argument must be a positive number or an array");{const i=e;if("number"!=typeof(t=(e=i.length)?i[0].length:0))throw new TypeError("Data must be a 2D array with at least one element");this.data=[];for(let r=0;r"number"==typeof e)))throw new TypeError("Input data contains non-numeric values");this.data.push(Float64Array.from(i[r]))}this.rows=e,this.columns=t}}}set(e,t,i){return this.data[e][t]=i,this}get(e,t){return this.data[e][t]}removeRow(e){return hb(this,e),this.data.splice(e,1),this.rows-=1,this}addRow(e,t){return void 0===t&&(t=e,e=this.rows),hb(this,e,!0),t=Float64Array.from(ub(this,t)),this.data.splice(e,0,t),this.rows+=1,this}removeColumn(e){db(this,e);for(let t=0;t>e);return this},e.prototype.signPropagatingRightShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t>e.get(t,i));return this},e.signPropagatingRightShift=function(e,i){return new t(e).signPropagatingRightShift(i)},e.prototype.rightShift=function(e){return"number"==typeof e?this.rightShiftS(e):this.rightShiftM(e)},e.prototype.rightShiftS=function(e){for(let t=0;t>>e);return this},e.prototype.rightShiftM=function(e){if(e=t.checkMatrix(e),this.rows!==e.rows||this.columns!==e.columns)throw new RangeError("Matrices dimensions must be equal");for(let t=0;t>>e.get(t,i));return this},e.rightShift=function(e,i){return new t(e).rightShift(i)},e.prototype.zeroFillRightShift=e.prototype.rightShift,e.prototype.zeroFillRightShiftS=e.prototype.rightShiftS,e.prototype.zeroFillRightShiftM=e.prototype.rightShiftM,e.zeroFillRightShift=e.rightShift,e.prototype.not=function(){for(let e=0;e=0)this.#k=new Ab(e,e);else if(this.#k=new Ab(e),!this.isSymmetric())throw new TypeError("not symmetric data")}clone(){const e=new Cb(this.diagonalSize);for(const[t,i,r]of this.upperRightEntries())e.set(t,i,r);return e}toMatrix(){return new Ab(this)}get(e,t){return this.#k.get(e,t)}set(e,t,i){return this.#k.set(e,t,i),this.#k.set(t,e,i),this}removeCross(e){return this.#k.removeRow(e),this.#k.removeColumn(e),this}addCross(e,t){void 0===t&&(t=e,e=this.diagonalSize);const i=t.slice();return i.splice(e,1),this.#k.addRow(e,i),this.#k.addColumn(e,t),this}applyMask(e){if(e.length!==this.diagonalSize)throw new RangeError("Mask size do not match with matrix size");const t=[];for(const[i,r]of e.entries())r||t.push(i);t.reverse();for(const e of t)this.removeCross(e);return this}toCompact(){const{diagonalSize:e}=this,t=new Array(e*(e+1)/2);for(let i=0,r=0,s=0;s=e&&(i=++r);return t}static fromCompact(e){const t=e.length,i=(Math.sqrt(8*t+1)-1)/2;if(!Number.isInteger(i))throw new TypeError(`This array is not a compact representation of a Symmetric Matrix, ${JSON.stringify(e)}`);const r=new Cb(i);for(let s=0,o=0,n=0;n=i&&(s=++o);return r}*upperRightEntries(){for(let e=0,t=0;e=this.diagonalSize&&(t=++e)}}*upperRightValues(){for(let e=0,t=0;e=this.diagonalSize&&(t=++e)}}}Cb.prototype.klassType="SymmetricMatrix";class _b extends Cb{static isDistanceMatrix(e){return Cb.isSymmetricMatrix(e)&&"DistanceMatrix"===e.klassSubType}constructor(e){if(super(e),!this.isDistance())throw new TypeError("Provided arguments do no produce a distance matrix")}set(e,t,i){return e===t&&(i=0),super.set(e,t,i)}addCross(e,t){return void 0===t&&(t=e,e=this.diagonalSize),(t=t.slice())[e]=0,super.addCross(e,t)}toSymmetricMatrix(){return new Cb(this)}clone(){const e=new _b(this.diagonalSize);for(const[t,i,r]of this.upperRightEntries())t!==i&&e.set(t,i,r);return e}toCompact(){const{diagonalSize:e}=this,t=new Array((e-1)*e/2);for(let i=1,r=0,s=0;s=e&&(i=1+ ++r);return t}static fromCompact(e){const t=e.length;if(0===t)return new this(0);const i=(Math.sqrt(8*t+1)+1)/2;if(!Number.isInteger(i))throw new TypeError(`This array is not a compact representation of a DistanceMatrix, ${JSON.stringify(e)}`);const r=new this(i);for(let s=1,o=0,n=0;n=i&&(s=1+ ++o);return r}}_b.prototype.klassSubType="DistanceMatrix";class xb extends vb{constructor(e,t,i){super(),this.matrix=e,this.rows=t,this.columns=i}}class kb extends xb{constructor(e,t,i){pb(e,t),gb(e,i),super(e,t.length,i.length),this.rowIndices=t,this.columnIndices=i}set(e,t,i){return this.matrix.set(this.rowIndices[e],this.columnIndices[t],i),this}get(e,t){return this.matrix.get(this.rowIndices[e],this.columnIndices[t])}}class Ib extends vb{constructor(e,t={}){const{rows:i=1}=t;if(e.length%i!==0)throw new Error("the data length is not divisible by the number of rows");super(),this.rows=i,this.columns=e.length/i,this.data=e}set(e,t,i){let r=this._calculateIndex(e,t);return this.data[r]=i,this}get(e,t){let i=this._calculateIndex(e,t);return this.data[i]}_calculateIndex(e,t){return e*this.columns+t}}class Sb extends vb{constructor(e){super(),this.data=e,this.rows=e.length,this.columns=e[0].length}set(e,t,i){return this.data[e][t]=i,this}get(e,t){return this.data[e][t]}}class Eb{constructor(e){let t,i,r,s,o,n,a,c,l,h=(e=Sb.checkMatrix(e)).clone(),d=h.rows,u=h.columns,f=new Float64Array(d),p=1;for(t=0;tMath.abs(c[s])&&(s=t);if(s!==i){for(r=0;r=0;s--){for(r=0;rt?r.set(s,t,e.get(s,t)):s===t?r.set(s,t,1):r.set(s,t,0);return r}get upperTriangularMatrix(){let e=this.LU,t=e.rows,i=e.columns,r=new Ab(t,i);for(let s=0;sMath.abs(t)?(i=t/e,Math.abs(e)*Math.sqrt(1+i*i)):0!==t?(i=e/t,Math.abs(t)*Math.sqrt(1+i*i)):0}class Mb{constructor(e){let t,i,r,s,o=(e=Sb.checkMatrix(e)).clone(),n=e.rows,a=e.columns,c=new Float64Array(a);for(r=0;r=0;o--){for(s=0;s=0;i--){for(e=0;e=0;e--)if(0!==f[e]){for(let t=e+1;t=0;e--){if(e0;){let e,t;for(e=A-2;e>=-1&&-1!==e;e--){const t=Number.MIN_VALUE+_*Math.abs(f[e]+Math.abs(f[e+1]));if(Math.abs(m[e])<=t||Number.isNaN(m[e])){m[e]=0;break}}if(e===A-2)t=4;else{let i;for(i=A-1;i>=e&&i!==e;i--){let t=(i!==A?Math.abs(m[i]):0)+(i!==e+1?Math.abs(m[i-1]):0);if(Math.abs(f[i])<=_*t){f[i]=0;break}}i===e?t=3:i===A-1?t=1:(t=2,e=i)}switch(e++,t){case 1:{let t=m[A-2];m[A-2]=0;for(let i=A-2;i>=e;i--){let s=Nb(f[i],t),o=f[i]/s,n=t/s;if(f[i]=s,i!==e&&(t=-n*m[i-1],m[i-1]=o*m[i-1]),l)for(let e=0;e=f[e+1]);){let t=f[e];if(f[e]=f[e+1],f[e+1]=t,l&&et&&s.set(o,i,e.get(o,i)/this.s[i]);let o=this.U,n=o.rows,a=o.columns,c=new Ab(i,n);for(let e=0;ee&&t++;return t}get diagonal(){return Array.from(this.s)}get threshold(){return Number.EPSILON/2*Math.max(this.m,this.n)*this.s[0]}get leftSingularVectors(){return this.U}get rightSingularVectors(){return this.V}get diagonalMatrix(){return Ab.diag(this.s)}}function Bb(e,t,i=!1){return e=Sb.checkMatrix(e),t=Sb.checkMatrix(t),i?new Rb(e).solve(t):e.isSquare()?new Eb(e).solve(t):new Mb(e).solve(t)}function Db(e,t){let i=[];for(let r=0;rs)return new Array(t.rows+1).fill(0);{let e=t.addRow(i,[0]);for(let t=0;t0;a--){for(d=0,n=0,l=0;l0&&(o=-o),t[a]=d*o,n-=s*o,i[a-1]=s-o,c=0;cl)do{for(s=i[l],d=(i[l+1]-s)/(2*t[l]),u=Nb(d,1),d<0&&(u=-u),i[l]=t[l]/(d+u),i[l+1]=t[l]*(d+u),f=i[l+1],o=s-i[l],n=l+2;n=l;n--)for(m=g,g=p,F=b,s=p*t[n],o=p*d,u=Nb(d,t[n]),t[n+1]=b*u,b=t[n]/u,p=d/u,d=p*i[n]-b*s,i[n+1]=o+b*(p*s+b*i[n]),c=0;cA*y);i[l]=i[l]+v,t[l]=0}for(n=0;n=l;a--)i[a]=t.get(a,l-1)/h,n+=i[a]*i[a];for(o=Math.sqrt(n),i[l]>0&&(o=-o),n-=i[l]*o,i[l]=i[l]-o,c=l;c=l;a--)s+=i[a]*t.get(a,c);for(s/=n,a=l;a<=u;a++)t.set(a,c,t.get(a,c)-s*i[a])}for(a=0;a<=u;a++){for(s=0,c=u;c>=l;c--)s+=i[c]*t.get(a,c);for(s/=n,c=l;c<=u;c++)t.set(a,c,t.get(a,c)-s*i[c])}i[l]=h*i[l],t.set(l,l-1,h*o)}}for(a=0;a=d+1;l--)if(0!==t.get(l,l-1)){for(a=l+1;a<=u;a++)i[a]=t.get(a,l-1);for(c=l;c<=u;c++){for(o=0,a=l;a<=u;a++)o+=i[a]*r.get(a,c);for(o=o/i[l]/t.get(l,l-1),a=l;a<=u;a++)r.set(a,c,r.get(a,c)+o*i[a])}}}(o,e,t,n),function(e,t,i,r,s){let o,n,a,c,l,h,d,u,f,p,g,m,w,b,F,v=e-1,y=0,A=e-1,C=Number.EPSILON,_=0,x=0,k=0,I=0,S=0,E=0,N=0,M=0;for(o=0;oA)&&(i[o]=s.get(o,o),t[o]=0),n=Math.max(o-1,0);n=y;){for(c=v;c>y&&(E=Math.abs(s.get(c-1,c-1))+Math.abs(s.get(c,c)),0===E&&(E=x),!(Math.abs(s.get(c,c-1))=0){for(N=k>=0?k+N:k-N,i[v-1]=u+N,i[v]=i[v-1],0!==N&&(i[v]=u-d/N),t[v-1]=0,t[v]=0,u=s.get(v,v-1),E=Math.abs(u)+Math.abs(N),k=u/E,I=N/E,S=Math.sqrt(k*k+I*I),k/=S,I/=S,n=v-1;n0)){for(E=Math.sqrt(E),f=c&&(N=s.get(l,l),S=u-N,E=f-N,k=(S*E-d)/s.get(l+1,l)+s.get(l,l+1),I=s.get(l+1,l+1)-N-S-E,S=s.get(l+2,l+1),E=Math.abs(k)+Math.abs(I)+Math.abs(S),k/=E,I/=E,S/=E,l!==c)&&!(Math.abs(s.get(l,l-1))*(Math.abs(I)+Math.abs(S))l+2&&s.set(o,o-3,0);for(a=l;a<=v-1&&(b=a!==v-1,a!==l&&(k=s.get(a,a-1),I=s.get(a+1,a-1),S=b?s.get(a+2,a-1):0,u=Math.abs(k)+Math.abs(I)+Math.abs(S),0!==u&&(k/=u,I/=u,S/=u)),0!==u);a++)if(E=Math.sqrt(k*k+I*I+S*S),k<0&&(E=-E),0!==E){for(a!==l?s.set(a,a-1,-E*u):c!==l&&s.set(a,a-1,-s.get(a,a-1)),k+=E,u=k/E,f=I/E,N=S/E,I/=k,S/=k,n=a;n=0;v--)if(k=i[v],I=t[v],0===I)for(c=v,s.set(v,v,1),o=v-1;o>=0;o--){for(d=s.get(o,o)-k,S=0,n=c;n<=v;n++)S+=s.get(o,n)*s.get(n,v);if(t[o]<0)N=d,E=S;else if(c=o,0===t[o]?s.set(o,v,0!==d?-S/d:-S/(C*x)):(u=s.get(o,o+1),f=s.get(o+1,o),I=(i[o]-k)*(i[o]-k)+t[o]*t[o],h=(u*E-N*S)/I,s.set(o,v,h),s.set(o+1,v,Math.abs(u)>Math.abs(N)?(-S-d*h)/u:(-E-f*h)/N)),h=Math.abs(s.get(o,v)),C*h*h>1)for(n=o;n<=v;n++)s.set(n,v,s.get(n,v)/h)}else if(I<0)for(c=v-1,Math.abs(s.get(v,v-1))>Math.abs(s.get(v-1,v))?(s.set(v-1,v-1,I/s.get(v,v-1)),s.set(v-1,v,-(s.get(v,v)-k)/s.get(v,v-1))):(F=zb(0,-s.get(v-1,v),s.get(v-1,v-1)-k,I),s.set(v-1,v-1,F[0]),s.set(v-1,v,F[1])),s.set(v,v-1,0),s.set(v,v,1),o=v-2;o>=0;o--){for(p=0,g=0,n=c;n<=v;n++)p+=s.get(o,n)*s.get(n,v-1),g+=s.get(o,n)*s.get(n,v);if(d=s.get(o,o)-k,t[o]<0)N=d,S=p,E=g;else if(c=o,0===t[o]?(F=zb(-p,-g,d,I),s.set(o,v-1,F[0]),s.set(o,v,F[1])):(u=s.get(o,o+1),f=s.get(o+1,o),m=(i[o]-k)*(i[o]-k)+t[o]*t[o]-I*I,w=2*(i[o]-k)*I,0===m&&0===w&&(m=C*x*(Math.abs(d)+Math.abs(I)+Math.abs(u)+Math.abs(f)+Math.abs(N))),F=zb(u*S-N*p+I*g,u*E-N*g-I*p,m,w),s.set(o,v-1,F[0]),s.set(o,v,F[1]),Math.abs(u)>Math.abs(N)+Math.abs(I)?(s.set(o+1,v-1,(-p-d*s.get(o,v-1)+I*s.get(o,v))/u),s.set(o+1,v,(-g-d*s.get(o,v)-I*s.get(o,v-1))/u)):(F=zb(-S-f*s.get(o,v-1),-E-f*s.get(o,v),N,I),s.set(o+1,v-1,F[0]),s.set(o+1,v,F[1]))),h=Math.max(Math.abs(s.get(o,v-1)),Math.abs(s.get(o,v))),C*h*h>1)for(n=o;n<=v;n++)s.set(n,v-1,s.get(n,v-1)/h),s.set(n,v,s.get(n,v)/h)}for(o=0;oA)for(n=o;n=y;n--)for(o=y;o<=A;o++){for(N=0,a=y;a<=Math.min(n,A);a++)N+=r.get(o,a)*s.get(a,n);r.set(o,n,N)}}(o,c,a,n,e)}this.n=o,this.e=c,this.d=a,this.V=n}get realEigenvalues(){return Array.from(this.d)}get imaginaryEigenvalues(){return Array.from(this.e)}get eigenvectorMatrix(){return this.V}get diagonalMatrix(){let e,t,i=this.n,r=this.e,s=this.d,o=new Ab(i,i);for(e=0;e0?o.set(e,e+1,r[e]):r[e]<0&&o.set(e,e-1,r[e])}return o}}function zb(e,t,i,r){let s,o;return Math.abs(i)>Math.abs(r)?(s=r/i,o=i+s*r,[(e+s*t)/o,(t-s*e)/o]):(s=i/r,o=r+s*i,[(s*e+t)/o,(s*t-e)/o])}class Pb{constructor(e){if(!(e=Sb.checkMatrix(e)).isSymmetric())throw new Error("Matrix is not symmetric");let t,i,r,s=e,o=s.rows,n=new Ab(o,o),a=!0;for(i=0;i0,n.set(i,i,Math.sqrt(Math.max(e,0))),r=i+1;r=0;o--)for(s=0;so;t++)l=e.transpose().mmul(n).div(n.transpose().mmul(n).get(0,0)),l=l.div(l.norm()),a=e.mmul(l).div(l.transpose().mmul(l).get(0,0)),t>0&&(d=a.clone().sub(h).pow(2).sum()),h=a.clone(),i?(c=i.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),c=c.div(c.norm()),n=i.mmul(c).div(c.transpose().mmul(c).get(0,0))):n=a;if(i){let t=e.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0));t=t.div(t.norm());let r=e.clone().sub(a.clone().mmul(t.transpose())),s=n.transpose().mmul(a).div(a.transpose().mmul(a).get(0,0)),o=i.clone().sub(a.clone().mulS(s.get(0,0)).mmul(c.transpose()));this.t=a,this.p=t.transpose(),this.w=l.transpose(),this.q=c,this.u=n,this.s=a.transpose().mmul(a),this.xResidual=r,this.yResidual=o,this.betas=s}else this.w=l.transpose(),this.s=a.transpose().mmul(a).sqrt(),this.t=r?a.clone().div(this.s.get(0,0)):a,this.xResidual=e.sub(a.mmul(l.transpose()))}}jw.AbstractMatrix=vb,jw.CHO=Pb,jw.CholeskyDecomposition=Pb,jw.DistanceMatrix=_b,jw.EVD=Tb,jw.EigenvalueDecomposition=Tb,jw.LU=Eb,jw.LuDecomposition=Eb;var Ob=jw.Matrix=Ab;jw.MatrixColumnSelectionView=class extends xb{constructor(e,t){gb(e,t),super(e,e.rows,t.length),this.columnIndices=t}set(e,t,i){return this.matrix.set(e,this.columnIndices[t],i),this}get(e,t){return this.matrix.get(e,this.columnIndices[t])}},jw.MatrixColumnView=class extends xb{constructor(e,t){db(e,t),super(e,e.rows,1),this.column=t}set(e,t,i){return this.matrix.set(e,this.column,i),this}get(e){return this.matrix.get(e,this.column)}},jw.MatrixFlipColumnView=class extends xb{constructor(e){super(e,e.rows,e.columns)}set(e,t,i){return this.matrix.set(e,this.columns-t-1,i),this}get(e,t){return this.matrix.get(e,this.columns-t-1)}},jw.MatrixFlipRowView=class extends xb{constructor(e){super(e,e.rows,e.columns)}set(e,t,i){return this.matrix.set(this.rows-e-1,t,i),this}get(e,t){return this.matrix.get(this.rows-e-1,t)}},jw.MatrixRowSelectionView=class extends xb{constructor(e,t){pb(e,t),super(e,t.length,e.columns),this.rowIndices=t}set(e,t,i){return this.matrix.set(this.rowIndices[e],t,i),this}get(e,t){return this.matrix.get(this.rowIndices[e],t)}},jw.MatrixRowView=class extends xb{constructor(e,t){hb(e,t),super(e,1,e.columns),this.row=t}set(e,t,i){return this.matrix.set(this.row,t,i),this}get(e,t){return this.matrix.get(this.row,t)}},jw.MatrixSelectionView=kb,jw.MatrixSubView=class extends xb{constructor(e,t,i,r,s){mb(e,t,i,r,s),super(e,i-t+1,s-r+1),this.startRow=t,this.startColumn=r}set(e,t,i){return this.matrix.set(this.startRow+e,this.startColumn+t,i),this}get(e,t){return this.matrix.get(this.startRow+e,this.startColumn+t)}},jw.MatrixTransposeView=class extends xb{constructor(e){super(e,e.columns,e.rows)}set(e,t,i){return this.matrix.set(t,e,i),this}get(e,t){return this.matrix.get(t,e)}},jw.NIPALS=Hb,jw.Nipals=Hb,jw.QR=Mb,jw.QrDecomposition=Mb,jw.SVD=Rb,jw.SingularValueDecomposition=Rb,jw.SymmetricMatrix=Cb,jw.WrapperMatrix1D=Ib,jw.WrapperMatrix2D=Sb,jw.correlation=function(e,t=e,i={}){e=new Ab(e);let r=!1;if("object"!=typeof t||Ab.isMatrix(t)||rb.isAnyArray(t)?t=new Ab(t):(i=t,t=e,r=!0),e.rows!==t.rows)throw new TypeError("Both matrices must have the same number of rows");const{center:s=!0,scale:o=!0}=i;s&&(e.center("column"),r||t.center("column")),o&&(e.scale("column"),r||t.scale("column"));const n=e.standardDeviation("column",{unbiased:!0}),a=r?n:t.standardDeviation("column",{unbiased:!0}),c=e.transpose().mmul(t);for(let t=0;tt?o[e]=1/o[e]:o[e]=0;return s.mmul(Ab.diag(o).mmul(r.transpose()))},jw.solve=Bb,jw.wrap=function(e,t){if(rb.isAnyArray(e))return e[0]&&rb.isAnyArray(e[0])?new Sb(e):new Ib(e,t);throw new Error("the argument is not an array")};const Ub=Ob;Vb.Matrix&&Vb.Matrix;const Qb=qb;function Gb(e,t,i,r,s,o,n){let a=i,c=Ub.eye(t.length,t.length,a);const l=s(t);let h=new Float64Array(e.x.length);for(let t=0;te}else{if(!Uw(a))throw new Error("weights should be a number or array with length equal to the number of data points");if(a.lengthe}else m=e=>1/a[e]**2}if(void 0!==r){if("number"!=typeof r)throw new Error("timeout should be a number");let e=Date.now()+1e3*r;w=()=>Date.now()>e}else w=()=>!1;let y=new Array(e.x.length);for(let e=0;eg?c=Math.max(c/h,1e-7):(m=d,c=Math.min(c*l,1e7)),r())throw new Error(`The execution time is over to ${i.timeout} seconds`);w=m<=u}return{parameterValues:n,parameterError:m,iterations:b}}class Wb{constructor(e){this.binScores=e}get_histogram(){let e=Math.max(...this.binScores),t=Math.floor(e/1e3),i=this.range(0,Math.floor(e/t)*t+t,t);const{counts:r,bins:s}=this.histogram(this.binScores,i);return{counts:r,bins:s}}range(e,t,i){const r=[];for(let s=e;s{for(let r=0;r=t[r]&&ee*Math.exp(-Math.pow(r-t,2)/(2*Math.pow(i,2)))/(Math.sqrt(2*Math.PI)*i)}get_initial_model_values(e,t){const i=t.slice(1,-1).reduce(((e,t)=>e+t),0);if(0===i)return console.debug("Problem with fit: all data points have zero value. Return zeros instead fit parameters!"),null;const r=(e[1]-e[0])*i,s=e.reduce(((e,i,r)=>e+i*t[r]),0)/i,o=e.reduce(((e,i,r)=>e+t[r]*Math.pow(i-s,2)),0),n=Math.sqrt(o/i);return[r,s,n]}normal_fit(e,t){const i={initialValues:this.get_initial_model_values(e,t),maxIterations:100};return jb({x:e,y:t},this.normal_distribution,i)}}class $b{constructor(e,t){this.binSize=e,this.refGenome=t,this.gcBin=this.getGCbinSize()}getGCbinSize(){for(let e of[1e5,1e4])if(this.binSize%e==0)return e;return!1}async getBinGC(){const e={};if(!this.gcBin)return e;const t="https://storage.googleapis.com/cnvpytor_data/gcInfoData/GCinfo.json";try{const i=(await Rr.loadJson(t,{timeout:5e3})).find((e=>e.id===this.refGenome));if(!i)return console.warn("GC data not found for ",this.refGenome),e;const r=i.Bins.find((e=>e.BinSize===this.gcBin));if(!r)return console.warn("GC data not found for ",this.refGenome," Bin : ",this.gcBin),e;let s=`${t.split("/").slice(0,-1).join("/")}${r.fileURL}`;(await Rr.load(s,{})).split("\n").forEach((t=>{if(""!==t.trim()){const[i,r,s,o,n]=t.split("\t");e[i]||(e[i]=[]),e[i].push({start:+r,gcContent:+s,gcCount:+o,atCount:+n})}}))}catch(e){console.error(e),console.warn("Errors loading GC correction data.")}return e}}class Kb extends $b{constructor(e,t,i){super(t,i),this.wigFeatures=e,this.binSize=t,this.refGenome=i}async apply_gcCorrection(){if(!this.wigFeatures)return console.error("BinScore data is not available."),null;const e=Object.values(this.wigFeatures).reduce(((e,t)=>e.concat(t.filter((e=>e.binScore>0)).map((e=>e.binScore)))),[]);let t=new Wb(e);const{counts:i,bins:r}=t.get_histogram();let s=t.normal_fit(r,i);this.globalMean=s.parameterValues[1],this.globalStd=s.parameterValues[2],this.gcData=await this.getBinGC(),this.gcFlag=Object.keys(this.gcData).length>0,this.binScoreField=this.gcFlag?"gcCorrectedBinScore":"binScore",this.getGcCorrectionSignal(this.globalMean)}getGcCorrectionSignal(e){let t=this.getGcCorrection(e);Object.keys(this.wigFeatures).forEach((e=>{this.wigFeatures[e].forEach((e=>{e.binScore?e.gcCorrectedBinScore=Math.round(t[e.gc]*e.binScore):e.gcCorrectedBinScore=null}))}))}getGcCorrection(e){const t={};if(this.gcFlag){let i=this.getGCbinSize();const r={};let s=parseInt(this.binSize/i);for(let e in this.wigFeatures)for(let t=0;t{let s,o=r[i];if(o.length<4)s=o.reduce(((e,t)=>e+t),0)/o.length;else{let e=new Wb(r[i]);const{counts:t,bins:o}=e.get_histogram();s=e.normal_fit(o,t).parameterValues[1]}t[i]=e/s}))}return t}formatDataStructure(e,t=1){const i=[];for(const[s,o]of Object.entries(this.wigFeatures))for(let s of o){var r={...s};1!=t&&(r.value=s[e]/t*2),i.push(r)}return i}formatDataStructure_BAF(e,t=-1){const i=[],r=[];for(const[s,o]of Object.entries(this.wigFeatures))o.forEach((s=>{var o={...s},n={...s};let a=s[e];.5!=a&&(n.value=t*(1-a),r.push(n)),o.value=t*a,i.push(o)}));return[i,r]}}function Yb(e){return e.reduce((function(e,t){return e>t?e:t}))}function Zb(e,t,i,r){return t*Math.exp(-1*(e-i)**2/(2*r**2))/Math.sqrt(2*Math.PI)/r}function Xb(e,t,i,r){return Math.exp(-1*(e-i)**2/(t**2+r**2))}function Jb(e,t){let i;try{i=e.reduce(((e,i,r)=>e+Math.min(i,t[r])))}catch{return console.log("Failed to find likelihood overlap: ",e,t),0}return i}function eF(e,t,i,r){return 0==t&&0==r?{nl:.5*(e+i),ne:0}:{nl:(e*r*r+i*t*t)/(t*t+r*r),ne:Math.sqrt(t*t*r*r/(t*t+r*r))}}function tF(e,t){let i=parseInt(t*(e.length-1)),r=t*(e.length-1)-i;return iMath.floor(t/2)&&(r=t-1-r);const s=(t/2-r)/(t+1),o=Math.floor((t/2+r)/2),n=t-1-o;let a=e.slice(o,n+1).reduce(((e,t)=>e+t),0)/e.reduce(((e,t)=>e+t),0);return r===Math.floor(t/2)&&(a=1),{mean:s,p:a}}var rF={CombinedCaller:class extends Kb{constructor(e,t,i){super(e,t,i)}async call_2d(e=null,t=null,i="both",r=.1,s=0,o=10,n=0){await this.apply_gcCorrection();let a=this.gcFlag?"gcCorrectedBinScore":"binScore",c=null==e?.05*this.binSize/3e9:e,l=null==t?parseInt(this.binSize/1e4):t,h=[],d=[],u=[],f=[],p=[],g=[];for(const[e,t]of Object.entries(this.wigFeatures)){let e=[],i=[],o=[];t.forEach(((t,r)=>{t.hets_count>4&&t.dp_count>l&&t[a]&&(e.push([r]),i.push(t[a]),o.push(t.likelihood_score),delete t.likelihood_score)}));let n=[];for(let e=1;eMath.sqrt(Math.sqrt(e)**2+this.globalStd**2+Math.pow(g[t]/2,2)))),w=[];for(let t=0;t0;){w=w.filter((e=>"number"==typeof e));let t=Yb(w);if(isNaN(t)&&console.log("NaN value",w),te*o[n+1][t])),s=r.reduce(((e,t)=>e+t))}catch{console.log(o),console.log("max_overlap:",t,n,w.length),console.log("likelihood: ",n,o[n],o[n+1]),console.log("nlh: ",s)}if(i[n]=a.nl,m[n]=a.ne,o[n]=r.map((function(e){return e/s})),e[n].push(...e[n+1]),i.splice(n+1,1),m.splice(n+1,1),e.splice(n+1,1),o.splice(n+1,1),w.splice(n,1),n0){let e=Xb(i[n-1],m[n-1],i[n],m[n])*Jb(o[n-1],o[n]);w[n-1]=e}}let b=-1;for(;;){w=[];for(let t=0;te*o[s+1][t])),a=r.reduce(((e,t)=>e+t));o[s]=r.map((function(e){return e/a})),e[s].push(...e[s+1]),e[s]=e[s].sort(((e,t)=>e-t)),i.splice(n,1),m.splice(n,1),e.splice(n,1),o.splice(n,1),n>=e.length&&(s+=1,n=s+1)}else n+=1,n>=e.length&&(s+=1,n=s+1)}if(b==e.length)break;b=e.length}e.forEach(((e,r)=>{let n=iF(o[r]);e.length>1&&(e.forEach(((e,o)=>{d.push(t[e]),n.mean<=s&&h.push(t[e]),t[e].segment_score=i[r]})),u.push(i[r]),f.push(m[r]),p.push(o[r]))}))}let m=parseInt(1e3*(1-n));0==m&&(m=1);let w=Dw.linspace(n,1,m),b={},F={};for(let e=10;e>-1;e--)for(let t=0;t1-t+t*e/2)),a=e/2;e>0?(r=.5-t/(t+o),s=w.map(((e,i)=>.5-(1-e+e*t)/(2-2*e+(t+o)*e)))):(r=0,s=w.map(((e,t)=>0*e)));for(let i=0;i{if(!isNaN(s[t])){let r=Zb(e*this.globalMean,1,u[i],f[i])*tF(p[i],.5+s[t]);l+=r,r>h&&(h=r,d=w[t])}})),i in b?b[i].push([e,t,o,l/w.length,d]):b[i]=[e,t,o,l/w.length,d]}for(let e=0;ee[3]-t[3]));else if(b[e].sort(((e,t)=>e[3]-t[3])),"both"==i&&(F[e].sort(((e,t)=>e[3]-t[3])),F[e][0][3]>b[e][0][3])){let t=b[e].filter((t=>t[0]!=F[e][0][0]&&t[1]<=F[e][0][1]));b[e]=[F[e][0]].push(...t)}for(let e=0;e{var s={...e};1!=i&&(s.value=e[t]/i*2),r.push(s)}));return r}}};const sF=2871e6;function oF(e){for(var t=1,i=1,r=1*e,s=1;s<50;s++)t*=s,r+=(i*=-1)*Math.pow(e,2*s+1)/(t*(2*s+1));return 2*r/Math.sqrt(3.14159265358979)}function nF(e,t,i,r,s){var o=new lF(i.slice(r,s));return 0==o.std&&(o.std=t>0?t*o.mean/e:1),hF(e,o.mean,o.std,s-r)/(s-r)}function aF(e,t,i,r,s){var o=new lF(i.slice(r,s));if(o.meano&!l&c0&&(h=nF(e,t,i,r-1,s)),s-r>2)var d=nF(e,t,i,r+1,s),u=nF(e,t,i,r,s-1);if(se+t))/e.length,this.std=Math.sqrt(e.reduce(((e,t)=>(t-this.mean)**2))/e.length)}}function hF(e,t,i,r){0==i&&(i=1);var s=(e-t)/i*Math.sqrt(r);return 1-Vw.TdistributionCDF(Math.abs(s),r-1)}function dF(e,t,i,r,s,o){0==t&&(t=1),0==s&&(s=1);var n=(e-r)/Math.sqrt(t**2/i+s**2/o),a=(t**2/i+s**2/o)**2*(i-1)*(o-1)/(t**4*(o-1)/i**2+s**4*(i-1)/o**2);return 1-Vw.TdistributionCDF(Math.abs(n),parseInt(a+.5))}var uF={Partition:class{constructor(e,t,i){this.rd=e,this.mean=t,this.std=i,this.bin_bands=[2,3,4,5,6,7,8,10,12,14,16,20,24,28,32,40,48,56,64,80,96,112,128]}get_rd_signal_bandwidth(e){var t=[];return e.forEach(((e,i)=>{var r=0;r=e>this.mean/4?this.mean/(this.std**2*e):4/this.std**2,t.push(r)})),t}meanShiftCaller(e,t=3){var i={};return Object.entries(this.rd).forEach((([e,r])=>{var s=new Array(r.length).fill(!1),o=new Array(r.length);for(let e=0;e{var n=s.map(((e,t)=>!e)),a=[];Object.entries(r).forEach((([e,t])=>{a.push(t.binScore)}));var c=[0],l=0;for(let e=0;e0&&(c.push(c[c.length-1]+l-1),l=0):l+=1;c.shift();for(let i=0;i=a.length||Math.abs(t-i)>=a.length)){var u=(i-t)*Math.exp(-.5*(i-t)**2/e**2)*Math.exp(-.5*(a[t]-a[i])**2*h[t]);d[t]+=u}for(var f=new Array,p=0;p=0&&f.push(p);f.push(d.length-1),f=f.concat(c).sort(((e,t)=>e-t)),f=Array.from(new Set(f));var g=0;for(p=0;pe+t))/m.length;a.fill(w,g,f[p]+1),g=f[p]+1}}p=0;for(var b=0;p.01&&f.push(p+1)}f.unshift(0),f.push(o.length),s=new Array(this.rd.length).fill(!1);for(p=1;p1))continue;v[0]=f[p-2];var y=[f[p],f[p]];if(!(p.01/sF*bin_size*(A+C))continue;if(dF(x.mean,x.std,x.data.length,N.mean,N.std,N.data.length)>.01/sF*bin_size*(A+_))continue}if(hF(this.mean,x.mean,x.std,x.data.length)>.05)continue;let e=a.slice(F[0],F[1]);var M=new lF(e);s.fill(!0,F[0],F[1]),o.fill(M.mean,F[0],F[1])}})),i[e]=o})),i}call_mean_shift(e=3){for(var t=new Array(this.rd.length).fill(!1),i=new Array(this.rd.length),r=0;r{var o=t.map(((e,t)=>!e)),n=[];o.forEach(((e,t)=>{e&&n.push(this.rd[t])}));for(var a=[0],c=0,l=0;l0&&(a.push(a[a.length-1]+c-1),c=0):c+=1;a.shift();for(var h=0;h=n.length||Math.abs(l-f)>=n.length)){var p=(f-l)*Math.exp(-.5*(f-l)**2/r**2)*Math.exp(-.5*(n[l]-n[f])**2*d[l]);u[l]+=p}var g=new Array;for(l=0;l=0&&g.push(l);g.push(u.length-1),g=g.concat(a).sort(((e,t)=>e-t)),g=Array.from(new Set(g));var m=0;for(l=0;le+t))/w.length;n.fill(b,m,g[l]+1),m=g[l]+1}}for(l=0,f=0;l.01&&g.push(l+1)}g.unshift(0),g.push(i.length),t=new Array(this.rd.length).fill(!1);for(l=1;l1){v[0]=g[l-2];var y=[g[l],g[l]];if(l3.483106931382794e-9*(A+C))continue;if(dF(x.mean,x.std,x.data.length,N.mean,N.std,N.data.length)>3.483106931382794e-9*(A+_))continue}if(!(hF(this.mean,x.mean,x.std,x.data.length)>.05)){var M=new lF(this.rd.slice(F[0],F[1]));t.fill(!0,F[0],F[1]),i.fill(M.mean,F[0],F[1])}}}}}})),i}cnv_calling(e=1e5){var t=.25*this.mean,i=this.mean-t,r=this.mean+t,s=2971e6,o=this.meanShiftCaller(e),n={},a=[];return Object.entries(o).forEach((([c,l])=>{for(var h=!1;!h;){h=!0;var d=new Array(1).fill(0);for(let e=0;e.01&&d.push(e+1)}d.push(l.length);for(let e=0;e0&&(f=Math.abs(l[d[e]]-l[d[e-1]])),e{m.push(t.binScore)}));for(var w,b=new Array(l.length).fill(""),F=0,v=.05*e/s;FA+1){var C=cF(this.mean,this.std,m,A,_,v);if(C){var _=C;b.fill("D",A,_)}}for(A=F;Fr;)F+=1;(_=F)>A+1&&(C=cF(this.mean,this.std,m,A,_,v))&&(_=C,b.fill("A",A,_)),F==y&&(F+=1)}for(F=0;FA+1&&(aF(this.mean,this.std,m,A,_)<1682935038707506e-26&&b.fill(["d"]*(_-A),A,_),F-=1),F+=1}(F=0)=b.length););if(F>A){var k=new lF(x.slice(A,F));x.fill(k.mean,A,F)}F{i.forEach(((i,r)=>{t[e]&&(i.partitionLevel=parseInt(t[e][r]))}))}));return{binScore:this.formatDataStructure("binScore",this.globalMean),gcCorrectedBinScore:this.formatDataStructure("gcCorrectedBinScore",this.globalMean),segmentsCNV:this.formatDataStructure("partitionLevel",this.globalMean)}}getRDSignalBandWidth(e){const t=this.globalMean/4,i=4/this.globalStd**2;return e.map((e=>e>t?this.globalMean/(this.globalStd**2*e):i))}partition(e=3){let t={};Object.keys(this.wigFeatures).sort(((e,t)=>e.localeCompare(t,void 0,{numeric:!0}))).forEach((e=>{t[e]=this.wigFeatures[e]}));let i=this.gcFlag?"gcCorrectedBinScore":"binScore";var r={};for(const[n,a]of Object.entries(t)){var s=new Array(a.length).fill(!1),o=a.map(((e,t)=>s[t]?void 0:e[i]));this.binBands.forEach(((t,i)=>{var r=s.map(((e,t)=>!e)),n=o.filter(((e,t)=>!s[t])),a=[0],c=0;s.forEach((e=>{e?c>0&&(a.push(a[a.length-1]+c-1),c=0):e||c++})),a.shift();for(let i=0;i=0&&u.push(f);u.push(h.length-1),u=u.concat(a).sort(((e,t)=>e-t)),u=Array.from(new Set(u));var p=0;for(f=0;fe+t))/g.length;n.fill(m,p,u[f]+1),p=u[f]+1}}f=0;for(var w=0;f.01&&u.push(f+1)}u.unshift(0),u.push(o.length),s=new Array(this.wigFeatures.length).fill(!1);for(f=1;f1))continue;F[0]=u[f-2];var v=[u[f],u[f]];if(!(f.01/sF*this.binSize*(y+A))continue;if(dF(_.mean,_.std,_.data.length,E.mean,E.std,E.data.length)>.01/sF*this.binSize*(y+C))continue}if(hF(this.globalMean,_.mean,_.std,_.data.length)>.05)continue;let e=n.slice(b[0],b[1]);var N=new lF(e);s.fill(!0,b[0],b[1]),o.fill(N.mean,b[0],b[1])}})),r[n]=o}return r}cnvCalling(e){var t=.25*this.globalMean,i=this.globalMean-t,r=this.globalMean+t,s=2971e6,o={},n=[];return Object.entries(e).forEach((([a,c])=>{for(var l=!1;!l;){l=!0;var h=new Array(1).fill(0);for(let e=0;e.01&&h.push(e+1)}h.push(c.length);for(let i=0;i0&&(u=Math.abs(c[h[i]]-c[h[i-1]])),i{g.push(t.binScore)}));for(var m,w=new Array(c.length).fill(""),b=0,F=.05*this.binSize/s;by+1){var A=cF(this.globalMean,this.std,g,y,C,F);if(A){var C=A;w.fill("D",y,C)}}for(y=b;br;)b+=1;(C=b)>y+1&&(A=cF(this.globalMean,this.std,g,y,C,F))&&(C=A,w.fill("A",y,C)),b==v&&(b+=1)}for(b=0;by+1&&(aF(this.globalMean,this.std,g,y,C)<1682935038707506e-26&&w.fill(["d"]*(C-y),y,C),b-=1),b+=1}(b=0)=w.length););if(b>y){var x=new lF(_.slice(y,b));_.fill(x.mean,y,b)}b=0;e--){var i;let r=this.allVariants[e];this.allVariants.splice(e,1);let s=r.chr;i=Math.max(Math.floor(r.start/this.rowBinSize),0),t[s]||(t[s]=[]),t[s][i]||(t[s][i]={chr:s,start:i*this.rowBinSize,end:(i+1)*this.rowBinSize,dp_sum_score:0,dp_count:0,hets_count:0,hets:[]});const o=Object.values(r.calls);if(1!==o.length)throw Error(`Unexpected number of genotypes: ${o.length}. CNVPytor expects 1 and only 1 genotype`);const n=o[0],a=n.info.DP;a&&(t[s][i].dp_sum_score+=Number.parseInt(a),t[s][i].dp_count++);let c=n.info.AD.split(","),l=n.genotype;if(0==l[0]&&1==l[1]||1==l[0]&&0==l[1]){t[s][i].hets_count++;let e=parseInt(c[0]),r=parseInt(c[1]);t[s][i].hets.push({ref:e,alt:r})}}this.chromosomes=Object.keys(t);let r="ReadDepth"==e;var s,o=this.adjust_bin_size(t,r);if("ReadDepth"==e){let e=new uF.MeanShiftCaller(o,this.binSize,this.refGenome),t=await e.callMeanshift();s=[t.binScore,t.gcCorrectedBinScore,t.segmentsCNV];var n=e.formatDataStructure_BAF("max_likelihood",-1)}else if("2D"==e){let e=new rF.CombinedCaller(o,this.binSize,this.refGenome),t=await e.call_2d();s=[t.binScore,t.gcCorrectedBinScore,t.segmentScore];n=e.formatDataStructure_BAF("max_likelihood",-1)}return[s,n]}format_BAF_likelihood(e){const t=[];for(const[r,s]of Object.entries(e))for(let e of s){var i={...e};.5!=e.value&&(i.value=1-e.value,t.push(i))}return t}get_max_min_score(e){if(e.likelihood_score.length>0){const t=Math.max(...e.likelihood_score),i=e.likelihood_score.indexOf(t);e.value=Math.max(i/100,1-i/100),e.min_score=Math.min(i/100,1-i/100)}else e.score=0;return e}adjust_bin_size(e,t=!1){var i={};const r=this.binSize/150;for(let n of this.chromosomes){i[n]||(i[n]=[]);for(let a=0;apF(t.ref,t.alt,e)));else{var o=0;i[n][a].likelihood_score=Dw.linspace(0,1,100).map(((e,r)=>{var s=i[n][a].likelihood_score[r]*pF(t.ref,t.alt,e);return o+=s,s})),i[n][a].likelihood_score=Dw.linspace(0,1,100).map(((e,t)=>i[n][a].likelihood_score[t]/o))}i[n][a].dp_count>0&&(i[n][a].binScore=i[n][a].dp_sum_score/i[n][a].dp_count*r);const l=this.get_max_min_score(i[n][a]);i[n][a].max_likelihood=l.value,t&&delete i[n][a].likelihood_score}}return i}}function pF(e,t,i,r=!0){return Math.pow(i,e)*Math.pow(1-i,t)+Math.pow(i,t)*Math.pow(1-i,e)}class gF extends ma{static DEFAULT_TRACK_HEIGHT=250;constructor(e,t){super(e,t)}init(e){this.featureType="numeric",this.type="cnvpytor",e.max||(this.defaultScale=!0,this.autoscale=!1),e.height||(e.height=gF.DEFAULT_TRACK_HEIGHT),this.type="cnvpytor",this.graphType=e.graphType||"points",this.bin_size=e.bin_size||1e5,this.signal_name=e.signal_name||"rd_snp",this.cnv_caller=e.cnv_caller||"2D",this.colors=e.colors||["gray","black","green","blue"],this.hasChroms={},super.init(e)}get supportsWholeGenome(){return!0}get_signals(){let e=[];return"rd_snp"==this.signal_name?e=["RD_Raw","RD_Raw_gc_coor",this.cnv_caller,"BAF1","BAF2"]:"rd"==this.signal_name?e=["RD_Raw","RD_Raw_gc_coor",this.cnv_caller]:"snp"==this.signal_name?e=["BAF1","BAF2"]:"cnh"==this.signal_name&&(e=[this.cnv_caller]),e}get_signal_colors(){return[{singal_name:"RD_Raw",color:this.colors[0]},{singal_name:"RD_Raw_gc_coor",color:this.colors[1]},{singal_name:"ReadDepth",color:this.colors[2]},{singal_name:"2D",color:this.colors[2]},{singal_name:"BAF1",color:this.colors[3]},{singal_name:"BAF2",color:this.colors[3]}]}async postInit(){if("vcf"==this.config.format){let e;this.featureSource?e=Object.values(this.featureSource.getAllFeatures()).flat():(this.featureSource=this.featureSource||El(this.config,this.browser.genome),this.header=await this.getHeader(),e=this.featureSource.reader.features);const t=this.browser.config.genome,i=new fF(e,this.bin_size,t);let r,s,o;this.wigFeatures_obj={},this.wigFeatures_obj[this.bin_size]={},"2D"==this.cnv_caller?(o=await i.read_rd_baf("2D"),r=o[0],s=o[1],this.wigFeatures_obj[this.bin_size]["2D"]=r[2],this.available_callers=["2D"]):(o=await i.read_rd_baf(),r=o[0],s=o[1],this.wigFeatures_obj[this.bin_size].ReadDepth=r[2],this.available_callers=["ReadDepth"]),this.wigFeatures_obj[this.bin_size].RD_Raw=r[0],this.wigFeatures_obj[this.bin_size].RD_Raw_gc_coor=r[1],this.wigFeatures_obj[this.bin_size].BAF1=s[0],this.wigFeatures_obj[this.bin_size].BAF2=s[1],this.available_bins=[this.bin_size],this.set_available_callers()}else{this.cnvpytor_obj=new Nw(this.config,this.bin_size);let e=[...new Set(this.browser.referenceFrameList.map((e=>e.chr)))],t=this.getAliasChromsList(e);this.wigFeatures_obj=await this.cnvpytor_obj.get_rd_signal(this.bin_size,t),this.update_hasChroms(this.wigFeatures_obj,e),this.available_bins=this.cnvpytor_obj.availableBins,this.available_bins.includes(this.bin_size)||(this.bin_size=this.available_bins.at(-1)),this.available_callers=this.cnvpytor_obj.callers,this.set_available_callers()}this.tracks=[];const e=[];this.signals=this.get_signals(),this.signal_colors=this.get_signal_colors();for(let t in this.wigFeatures_obj)for(const[i,r]of Object.entries(this.wigFeatures_obj[t]))if(this.signals.includes(i)){let t={type:"wig",isMergedTrack:!0};t.features=r,t.name=i,t.color=this.signal_colors.filter((e=>e.singal_name===i)).map((e=>e.color));const s=await this.browser.createTrack(t);s?(s.autoscale=!1,this.tracks.push(s)):console.warn("Could not create track "+t),"function"==typeof s.postInit&&e.push(s.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return Promise.all(e)}getAliasChromsList(e){let t=e.map((e=>{let t=this.browser.genome.chromAlias.aliasRecordCache.get(e);return Object.values(t)}));return t=t.flat(),t}set_available_callers(){this.available_callers.includes(this.cnv_caller)||(this.available_callers.length>0?this.cnv_caller=this.available_callers[0]:this.cnv_caller=null)}async getHeader(){if(!this.header){if("function"==typeof this.featureSource.getHeader){const e=await this.featureSource.getHeader();e&&(this.callSets=e.callSets||[]),this.header=e}this.sampleKeys=this.callSets?this.callSets.map((e=>e.sample)):[],this.sampleNames=this.sampleKeys}return this.header}get height(){return this._height}set height(e){if(this._height=e,this.tracks)for(let t of this.tracks)t.height=e,t.config.height=e}menuItemList(){let e=[];void 0!==this.flipAxis&&e.push({label:"Flip y-axis",click:function(){this.flipAxis=!this.flipAxis,this.trackView.repaintViews()}}),e=e.concat(this.numericDataMenuItems()),e.push("
"),e.push("Bin Sizes");for(let t of this.available_bins)e.push({element:ua(t,t===this.bin_size),click:async function(){this.bin_size=t,this.trackView.startSpinner(),await this.recreate_tracks(t),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}});e.push("
"),e.push("Signal Type");let t={rd_snp:"RD and BAF Likelihood",rd:"RD Signal",snp:"BAF Likelihood"};for(let i in t)e.push({element:ua(t[i],i===this.signal_name),click:async function(){this.signal_name=i,await this.recreate_tracks(this.bin_size),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}});e.push("
"),e.push("CNV caller");for(let t of this.available_callers)e.push({element:ua(t,t===this.cnv_caller),click:async function(){this.cnv_caller=t,this.trackView.startSpinner(),await this.recreate_tracks(this.bin_size),this.clearCachedFeatures(),this.trackView.updateViews(),this.trackView.repaintViews()}});if(this.variantState){e.push("
");for(let t of this.available_callers)e.push({label:"Convert to variant track",click:()=>{this.convertToVariant()}})}return e}async recreate_tracks(e){this.tracks=[];const t=[];if(!(e in this.wigFeatures_obj))if(Object.keys(this.hasChroms).length>0){let t=[...new Set(this.browser.referenceFrameList.map((e=>e.chr)))];"all"==t[0]&&(t=this.browser.genome.chromosomeNames),this.wigFeatures_obj={...this.wigFeatures_obj,...await this.cnvpytor_obj.get_rd_signal(e,t)},this.update_hasChroms(this.wigFeatures_obj,t)}else this.wigFeatures_obj={...this.wigFeatures_obj,...await this.cnvpytor_obj.get_rd_signal(e)};this.signals=this.get_signals(),this.signal_colors=this.get_signal_colors();for(const[i,r]of Object.entries(this.wigFeatures_obj[e]))if(this.signals.includes(i)){let e={type:"wig",isMergedTrack:!0};e.features=r,e.name=i,e.color=this.signal_colors.filter((e=>e.singal_name===i)).map((e=>e.color));const s=await this.browser.createTrack(e);s?(s.autoscale=!1,this.tracks.push(s)):console.warn("Could not create track "+e),"function"==typeof s.postInit&&t.push(s.postInit())}this.flipAxis=!!this.config.flipAxis&&this.config.flipAxis,this.logScale=!!this.config.logScale&&this.config.logScale,this.autoscale=this.config.autoscale,this.autoscale||(this.dataRange={min:this.config.min||0,max:this.config.max});for(let e of this.tracks)e.autoscale=!1,e.dataRange=this.dataRange;return Promise.all(t)}update_hasChroms(e,t){for(let i in e)this.hasChroms[i]||(this.hasChroms[i]=new Set),t.forEach((e=>this.hasChroms[i].add(e)));return this.hasChroms}async getFeatures(e,t,i,r){if(Object.keys(this.hasChroms).length>0&&0!=this.hasChroms[this.bin_size].size){let e=[...new Set(this.browser.referenceFrameList.map((e=>e.chr)))];"all"==e[0]&&(e=this.browser.genome.chromosomeNames);let t=e.filter((e=>!this.hasChroms[this.bin_size].has(e)));if(0!=t.length){let e=this.getAliasChromsList(t),i=await this.cnvpytor_obj.get_rd_signal(this.bin_size,e);this.update_hasChroms(i,t);for(let e in i)for(const[t,r]of Object.entries(i[e]))await this.wigFeatures_obj[e][t].push(...r);for(let e of this.tracks)await e.featureSource.updateFeatures(this.wigFeatures_obj[this.bin_size][e.name])}}if(this.tracks){const s=this.tracks.map((s=>s.getFeatures(e,t,i,r)));return Promise.all(s)}}getScaleFactor(e,t,i,r){return r?i/(Math.log10(t+1)-(e<=0?0:Math.log10(e+1))):i/(t-e)}computeYPixelValue(e,t){return(this.flipAxis?e-this.dataRange.min:this.dataRange.max-e)*t}computeYPixelValueInLogScale(e,t){let i=this.dataRange.max,r=this.dataRange.min;return i<=0?0:(r<=-1&&(r=0),r=r<=0?0:Math.log10(r+1),i=Math.log10(i+1),e=Math.log10(e+1),(this.flipAxis?e-r:i-e)*t)}draw(e){const t=e.features;if(!t)return;if(this.defaultScale&&("rd_snp"==this.signal_name?this.dataRange={min:this.config.min||this.dataRange.min||-1,max:this.config.max||this.dataRange.max||5}:"rd"==this.signal_name?this.dataRange={min:this.config.min||this.dataRange.min||0,max:this.config.max||this.dataRange.max||5}:"snp"==this.signal_name&&(this.dataRange={min:this.config.min||this.dataRange.min||-1,max:this.config.max||this.dataRange.max||0})),this.autoscale&&(this.dataRange=function(e,t){let i=0,r=-Number.MAX_VALUE;for(let e of t)for(let t of e)void 0===t.value||Number.isNaN(t.value)||(i=Math.min(i,t.value),r=Math.max(r,t.value));return{min:i,max:r}}(e.referenceFrame.chr,t)),this.tracks)for(let i=0,r=this.tracks.length;ithis.logScale?this.computeYPixelValueInLogScale(e,i):this.computeYPixelValue(e,i);if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=r(t.y),s={strokeStyle:t.color,strokeWidth:1};t.dotted?Co.dashedLine(e.context,0,i,e.pixelWidth,i,5,s):Co.strokeLine(e.context,0,i,e.pixelWidth,i,s)}let s=r(2);Co.dashedLine(e.context,0,s,e.pixelWidth,s,5,{strokeStyle:"lightgray",strokeWidth:.5})}paintAxis(e,t,i){var r,s,o,n,a,c,l,h={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};if(void 0===this.dataRange||void 0===this.dataRange.max||void 0===this.dataRange.min)return;let d=void 0!==this.flipAxis&&this.flipAxis;function u(e){return e<0?Math.abs(e):0===e?"0":Math.abs(e)>=10||e%1==0?e.toFixed():Math.abs(e)>=1?e.toFixed(1):e.toFixed(2)}Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"}),r=(l=.95*t)-8,a={x:s=l,y:o=n=.01*i},Co.strokeLine(e,r,o,s,n,h),Co.fillText(e,u(d?this.dataRange.min:this.dataRange.max),r+4,o+12,h),c={x:s,y:o=n=.99*i},Co.strokeLine(e,r,o,s,n,h),Co.fillText(e,u(d?this.dataRange.max:this.dataRange.min),r+4,o-4,h),Co.strokeLine(e,a.x,a.y,c.x,c.y,h);const f=this.getScaleFactor(this.dataRange.min,this.dataRange.max,i,this.logScale),p=e=>this.logScale?this.computeYPixelValueInLogScale(e,f):this.computeYPixelValue(e,f),g=Math.ceil((this.dataRange.max-this.dataRange.min)/10);for(let t=Math.ceil(this.dataRange.min+1);t0&&t.push("
"),t.push(`
${this.tracks[r].name}
`);const s=this.tracks[r].popupData(e,i[r]);t.push(...s)}return t}}async convertToVariant(){this.variantState&&(Object.setPrototypeOf(this,bF.prototype),this.init(this.variantState),await this.postInit(),this.trackView.clearCachedFeatures(),this.variantState.trackHeight&&this.trackView.setTrackHeight(this.variantState.trackHeight),this.trackView.checkContentHeight(),this.trackView.updateViews(),delete this.variantState)}}const mF=b,wF=10;class bF extends ma{static defaultColor="rgb(0,0,150)";static defaults={displayMode:"EXPANDED",sortDirection:"ASC",showGenotypes:!0,expandedVariantHeight:10,squishedVariantHeight:2,squishedCallHeight:1,expandedCallHeight:10,expandedVGap:2,squishedVGap:1,expandedGroupGap:10,squishedGroupGap:5,featureHeight:14,noGenotypeColor:"rgb(200,180,180)",noCallColor:"rgb(225, 225, 225)",nonRefColor:"rgb(200, 200, 215)",mixedColor:"rgb(200, 220, 200)",homrefColor:"rgb(200, 200, 200)",homvarColor:"rgb(17,248,254)",hetvarColor:"rgb(34,12,253)",refColor:"rgb(0,0,220)",altColor:"rgb(255,0,0)",visibilityWindow:void 0,labelDisplayMode:void 0,type:"variant"};_sortDirections=new Map;constructor(e,t){super(e,t)}init(e){if(super.init(e),e.variantHeight&&(this.expandedVariantHeight=e.variantHeight),this.featureSource=El(e,this.browser.genome),this.colorTables=new Map,e.colorTable){const t=e.colorBy||"*";this.colorTables.set(t,new $r(e.colorTable))}if(this.strokecolor=e.strokecolor,this._context_hook=e.context_hook,e.color&&(this.colorBy=void 0),this.nVariantRows=1,e.samples)for(let t of e.samples)this.sampleKeys=e.samples;e.sort&&(this.initialSort=e.sort),this._colorByItems=new Map([["none","None"]])}async postInit(){if(this.header=await this.getHeader(),this.header.INFO){const e=new Set(Object.keys(this.header.INFO));this.config.colorBy?this.colorBy=this.config.colorBy:!this.config.color&&e.has("AF")&&(this.colorBy="AF"),e.has("AF")&&this._colorByItems.set("AF","Allele frequency"),e.has("VT")&&this._colorByItems.set("VT","Variant Type"),e.has("SVTYPE")&&this._colorByItems.set("SVTYPE","SV Type")}if(this.config.colorBy&&!this._colorByItems.has(this.config.colorBy)&&this._colorByItems.set(this.config.colorBy,this.config.colorBy),!this.disposed){if(this.header&&!this.sampleKeys&&(this.sampleKeys=this.header.sampleNameMap?Array.from(this.header.sampleNameMap.keys()):[]),void 0===this.visibilityWindow&&!1!==this.config.indexed){const e=x(this.config.url)?this.config.url.name:this.config.url;mF(e)&&e.toLowerCase().includes("gnomad")?this.visibilityWindow=1e3:"function"==typeof this.featureSource.defaultVisibilityWindow?this.visibilityWindow=await this.featureSource.defaultVisibilityWindow():this.visibilityWindow=1e6}return this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}}get supportsWholeGenome(){return!this.config.indexURL||!0===this.config.supportsWholeGenome}get color(){return this._color||bF.defaultColor}set color(e){this._color=e,e&&(this.colorBy=void 0)}async getHeader(){return this.header||"function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader()),this.header}getSampleCount(){return this.sampleKeys?this.sampleKeys.length:0}async getFeatures(e,t,i,r){void 0===this.header&&(this.header=await this.getHeader());const s=await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:this.visibilityWindow});if(this.initialSort){const e=this.initialSort;if(void 0===e.option||"GENOTYPE"===e.option.toUpperCase())this.sortSamplesByGenotype(e,s);else if("ATTRIBUTE"===e.option.toUpperCase()&&e.attribute){const t="ASC"===e.direction?1:-1;this.sortByAttribute(e.attribute,t)}this.initialSort=void 0}return s}hasSamples(){return this.getSampleCount()>0}getSamples(){const e="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,t="COLLAPSED"===this.displayMode?1:this.nVariantRows,i="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,r=t*(("SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight)+e),s=wF+t*(i+e);return{names:this.sampleKeys,yOffset:s,height:r}}computePixelHeight(e){if(!e||0===e.length)return wF;const t="COLLAPSED"===this.displayMode?1:this.nVariantRows,i="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,r="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,s="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight,o=!1===this.showGenotypes?0:this.getSampleCount()*t;return wF+t*(r+i)+i+(o+1)*(s+i)}variantRowCount(e){this.nVariantRows=e}draw({context:e,pixelWidth:t,pixelHeight:i,bpPerPixel:r,bpStart:s,pixelTop:o,features:n}){Co.fillRect(e,0,o,t,i,{fillStyle:"rgb(255, 255, 255)"});const a="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,c="COLLAPSED"===this.displayMode?1:this.nVariantRows,l="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight;this.variantBandHeight=wF+c*(l+a);let h=this.sampleColumns;const d=this.hasSamples();if(h&&d&&!1!==this.showGenotypes&&Co.strokeLine(e,0,this.variantBandHeight,t,this.variantBandHeight,{strokeStyle:"rgb(224,224,224) "}),n){const i="SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight,o="SQUISHED"===this.displayMode?this.squishedVGap:this.expandedVGap,a=s+t*r+1;for(let t of n){if(this._filter&&!this._filter(t))continue;if(t.enda)break;const n="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,c=wF+("COLLAPSED"===this.displayMode?0:t.row*(n+o)),l=n;let h=(t.start-s)/r,u=(t.end-s)/r,f=Math.max(1,u-h);f<3?(f=3,h-=1):f>5&&(h+=1,f-=2);const p=t._f||t;let g;try{g=p.alleleFreq()}catch(e){console.log(e)}if("AF"===this.colorBy&&g){const t=Math.min(1,g)*l,i=l-t;e.fillStyle=p.isFiltered()?this.refColorFiltered:this.refColor,e.fillRect(h,c,f,i),e.fillStyle=p.isFiltered()?this.altColorFiltered:this.altColor,e.fillRect(h,c+i,f,t)}else e.fillStyle=this.getColorForFeature(p),e.fillRect(h,c,f,l);let m=this.getVariantStrokecolor(p);if(m&&(e.strokeStyle=m,e.strokeRect(h,c,f,l)),this.callContextHook(p,e,h,c,f,l),d&&!1!==this.showGenotypes){const t="COLLAPSED"===this.displayMode?1:this.nVariantRows;this.sampleYOffset=this.variantBandHeight+o,this.sampleHeight=t*(i+o);let r=0;for(let t of this.sampleKeys){const s=this.header.sampleNameMap.get(t),n=p.calls[s];if(n){const t="COLLAPSED"===this.displayMode?0:p.row,s=this.sampleYOffset+r*this.sampleHeight+t*(i+o);let a=!0,c=!0,l=!1;if(n.genotype)for(let e of n.genotype){if("."===e){l=!0;break}0!==e&&(c=!1),0===e&&(a=!1)}n.genotype?e.fillStyle=l?this.noCallColor:c?this.homrefColor:a?this.homvarColor:this.hetvarColor:e.fillStyle=this.noGenotypeColor,e.fillRect(h,s,f,i)}r++}}}}else console.log("No feature list")}get refColorFiltered(){return this._refColorFiltered||(this._refColorFiltered=ur.addAlpha(this.refColor,.2)),this._refColorFiltered}get altColorFiltered(){return this._altColorFiltered||(this._altColorFiltered=ur.addAlpha(this.altColor,.2)),this._altColorFiltered}getColorForFeature(e){const t=e._f||e;let i;if(this.colorBy&&"none"!==this.colorBy){const e=t.getAttributeValue(this.colorBy);i=void 0!==e?this.getVariantColorTable(this.colorBy).getColor(e):"gray"}else i=this.color?"function"==typeof this.color?this.color(e):this.color:"NONVARIANT"===t.type?this.nonRefColor:"MIXED"===t.type?this.mixedColor:this.color;return t.isFiltered()&&(i=ur.addAlpha(i,.2)),i}getVariantStrokecolor(e){const t=e._f||e;let i;return i=this.strokecolor?"function"==typeof this.strokecolor?this.strokecolor(t):this.strokecolor:void 0,i}callContextHook(e,t,i,r,s,o){if(this._context_hook&&"function"==typeof this._context_hook){const n=e._f||e;t.save(),this._context_hook(n,t,i,r,s,o),t.restore()}}clickedFeatures(e){let t=super.clickedFeatures(e);const i="EXPANDED"===this.displayMode?this.expandedVGap:this.squishedVGap,r=i+("SQUISHED"===this.displayMode?this.squishedCallHeight:this.expandedCallHeight),s=e.y;if(s<=this.variantBandHeight){const e="SQUISHED"===this.displayMode?this.squishedVariantHeight:this.expandedVariantHeight,r=Math.floor((s-wF)/(e+i));"COLLAPSED"!==this.displayMode&&(t=t.filter((e=>e.row===r)))}else if(this.sampleKeys){const e=s-this.variantBandHeight,i=Math.floor(e/this.sampleHeight);if(i>=0&&ie.row===s)),n=this.sampleKeys[i],a=this.header.sampleNameMap.get(n);t=o.map((e=>{const t=e.calls[a];return t.genotypeString=function(e,t){if(e.genotype){let i="";if("."===t.alternateBases)i="No Call";else{const r=t.alternateBases.split(",");for(let s of e.genotype)if(i.length>0&&(i+=" | "),"."===s)i+=".";else if(0===s)i+=t.referenceBases;else{i+=r[s-1].replace("<","<")}}return i}}(t,e),t}))}}return t}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,r=this.browser.genome.id;let s=[];for(let e of t){const t=e._f||e;if(s.length>0&&s.push({html:'
'}),"function"==typeof t.popupData){const e=t.popupData(i,r);Array.prototype.push.apply(s,e)}}return s}menuItemList(){const t=[];if(this.header.INFO&&this.header.INFO){const i=this._colorByItems;t.push("
");const r=e('
');r.textContent="Color by:",t.push({name:void 0,element:r,click:void 0,init:void 0});for(let e of i.keys()){const r=this.colorBy===e;t.push(this.colorByCB({key:e,label:i.get(e)},r))}t.push(this.colorByCB({key:"info",label:"Info field..."}))}if(!0===dd(this.browser.sampleInfo,this.sampleKeys)){t.push("
"),t.push("Sort by attribute:");for(const e of this.browser.sampleInfo.attributeNames)if(this.sampleKeys.some((t=>{const i=this.browser.sampleInfo.getAttributes(t);return i&&i[e]}))){const i=document.createElement("div");i.innerHTML=`  ${e.split(sd.emptySpaceReplacement).join(" ")}`;const r=()=>{const t=this._sortDirections.get(e)||1;this.sortByAttribute(e,t),this.config.sort={option:"ATTRIBUTE",attribute:e,direction:t>0?"ASC":"DESC"},this._sortDirections.set(e,-1*t)};t.push({element:i,click:r})}}t.push("
"),this.getSampleCount()>0&&(t.push({element:e('
')}),t.push({element:ua("Show Genotypes",this.showGenotypes),click:function(){this.showGenotypes=!this.showGenotypes,this.trackView.checkContentHeight(),this.trackView.repaintViews(),this.browser.sampleNameControl.performClickWithState(this.browser,this.showGenotypes),this.browser.sampleInfoControl.performClickWithState(this.browser,this.showGenotypes)}})),t.push({element:e('
')});for(let e of["COLLAPSED","SQUISHED","EXPANDED"]){t.push({element:ua({COLLAPSED:"Collapse",SQUISHED:"Squish",EXPANDED:"Expand"}[e],e===this.displayMode),click:function(){this.displayMode=e,this.trackView.checkContentHeight(),this.trackView.repaintViews()}})}return this.browser.circularView&&(t.push("
"),t.push({label:"Add SVs to circular view",click:function(){for(let e of this.trackView.viewports)this.sendChordsForViewport(e)}})),this.canCovertToPytor()&&(t.push("
"),t.push({label:"Convert to CNVpytor track",click:function(){this.convertToPytor()}})),t}contextMenuItemList(e){const t=[];if(this.hasSamples()&&this.showGenotypes){const i=e.viewport.referenceFrame,r=e.genomicLocation,s=i.toBP(2.5),o=this._sortDirections.get("genotype")||1;this._sortDirections.set("genotype",-1*o),t.push({label:"Sort by genotype",click:t=>{const i={direction:o,option:"genotype",chr:e.viewport.referenceFrame.chr,start:Math.floor(r-s),end:Math.ceil(r+s)},n=e.viewport.cachedFeatures;this.sortSamplesByGenotype(i,n),this.config.sort=i}}),t.push("
")}if(this.browser.circularView){const i=e.viewport;t.push({label:"Add SVs to Circular View",click:()=>{this.sendChordsForViewport(i)}}),t.push("
")}return t}async sortSamplesByGenotype({chr:e,position:t,start:i,end:r,direction:s},o){if(void 0===i&&(i=t-1),void 0===r&&(r=t),o||(o=await this.featureSource.getFeatures({chr:e,start:i,end:r})),!o)return;const n=new Map,a="ASC"===s?1:-1;for(let e of o)if(!(e.endr)break;for(let t of e.calls){const e=t.sample,i=t.zygosityScore();n.set(e,n.has(e)?n.get(e)+i:i)}}this.sampleKeys.sort((function(e,t){let i=n.get(e)||0,r=n.get(t)||0;return a*(i-r)})),this.trackView.repaintViews()}sortByAttribute(e,t){this.config.sort={option:"ATTRIBUTE",attribute:e,direction:1===t?"ASC":"DESC"},this.sampleKeys=this.browser.sampleInfo.sortSampleKeysByAttribute(this.sampleKeys,e,t),this.trackView.repaintViews()}sendChordsForViewport(e){const t=e.referenceFrame;let i;if("all"===t.chr){const e=this.featureSource.getAllFeatures(),t=Object.keys(e).map((t=>e[t]));i=[].concat(...t)}else i=this.featureSource.featureCache.queryFeatures(t.chr,t.start,t.end);Yf(i.filter((e=>{const t=e._f||e;return t.info&&t.info.CHR2&&t.info.END&&(t.info.CHR2!==t.chr||Math.abs(Number.parseInt(t.info.END)-t.pos)>1e6)})).map((e=>{const t=e._f||e,i=Number.parseInt(t.info.END),r=i-100,s=i+100;return{uniqueId:`${t.chr}:${t.start}-${t.end}_${t.info.CHR2}:${t.info.END}`,refName:$f(t.chr),start:t.start,end:t.end,mate:{refName:$f(t.info.CHR2),start:r,end:s}}})),this,t,.5)}colorByCB(e,t){const i=ua(e.label,t);if("info"!==e.key){function r(){const t="none"===e.key?void 0:e.key;this.colorBy=t,this.config.colorBy=t,this.trackView.repaintViews()}return{name:void 0,element:i,click:r,init:void 0}}{function s(e){this.browser.inputDialog.present({label:"Info field",value:"",callback:e=>{e?(this.colorBy=e,this._colorByItems.set(e,e)):this.colorBy=void 0,this.trackView.repaintViews()}},e)}return{name:void 0,element:i,dialog:s,init:void 0}}}getState(){const e=super.getState();return this.color&&"function"!=typeof this.color&&(e.color=this.color),e}getVariantColorTable(e){if(this.colorTables.has(e))return this.colorTables.get(e);if(this.colorTables.has("*"))return this.colorTables.get("*");{let t;if("SVTYPE"===e)t=FF;else t=new Wr("Set1");return this.colorTables.set(e,t),t}}paintAxis(){}canCovertToPytor(){return!this.config.indexURL&&(!!this.header&&(1===Object.keys(this.sampleKeys).length&&this.header.FORMAT&&this.header.FORMAT.AD&&this.header.FORMAT.DP))}async convertToPytor(){this.variantState={...this.config,...this.getState()},this.variantState.trackHeight=this.height,this.trackView.startSpinner(),setTimeout((async()=>{try{const e=Object.assign({},this.config);Object.setPrototypeOf(this,gF.prototype),this.init(e),await this.postInit(),this.trackView.clearCachedFeatures(),this.trackView.setTrackHeight(this.config.height||gF.DEFAULT_TRACK_HEIGHT),this.trackView.checkContentHeight(),this.trackView.updateViews()}finally{this.trackView.stopSpinner()}}),100)}getFilterableAttributes(){return this.header.INFO}_repackCachedFeatures(){for(let e of this.trackView.viewports)if(e.cachedFeatures){const t=this.config.maxRows||Number.MAX_SAFE_INTEGER;ga(e.cachedFeatures,t,this._filter)}}}const FF=new $r({DEL:"#ff2101",INS:"#001888",DUP:"#028401",INV:"#008688",CNV:"#8931ff",BND:"#891100","*":"#002eff"}),vF={timeout:5e3,type:"plain",url:"https://igv.org/genomes/locus.php?genome=$GENOME$&name=$FEATURE$",coords:0};async function yF(e,t){const i=e.searchConfig||vF;let r;t=t.toUpperCase();const s=e.tracks.filter((e=>e.searchable));for(let e of s){const i=await e.search(t);if(i)return i}if(e.config&&!1!==e.config.search)try{return r=await async function(e,t,i){let r=i.url.replace("$FEATURE$",t.toUpperCase());r.indexOf("$GENOME$")>-1&&(r=r.replace("$GENOME$",e.genome.id?e.genome.id:"hg19"));const s=i.timeout?{timeout:i.timeout}:void 0,o=await Rr.loadString(r,s);return function(e,t,i){let r;r="plain"===i.type?function(e,t){const i=[],r=v(t);for(let t of r){const r=t.split("\t");if(r.length>=3){const t=r[1].split(":"),s=t[1].split("-");i.push({chromosome:e.genome.getChromosomeName(t[0].trim()),start:parseInt(s[0].replace(/,/g,"")),end:parseInt(s[1].replace(/,/g,"")),name:r[0].toUpperCase()})}}return i}(e,t):JSON.parse(t);i.resultsField&&(r=r[i.resultsField]);if(r&&0!==r.length){const e=i.chromosomeField||"chromosome",t=i.startField||"start",s=i.endField||"end",o=i.coords||1;let n;n=Array.isArray(r)?r[0]:r,n.hasOwnProperty(e)&&n.hasOwnProperty(t)||console.error("Search service results must include chromosome and start fields: "+n);const a=n[e];let c=n[t]-o,l=n[s];void 0===l&&(l=c+1);const h={chr:a,start:c,end:l};if(!n.type||n.type,i.geneField&&i.snpField){const e=n[i.geneField]||n[i.snpField];e&&(h.name=e.toUpperCase())}return h}return}(e,o,i)}(e,t,i),r}catch(e){console.log("Search service not available "+e)}}function AF(e,t=!1){const i=e.split("\t");if(i.length>2)try{const e=i[0],t=parseInt(i[1].replace(/,/g,""),10)-1,r=parseInt(i[2].replace(/,/g,""),10);if(!isNaN(t)&&!isNaN(r))return{chr:e,start:t,end:r}}catch(e){}const r=e.split(":"),s={chr:r[0]};if(r.length>1){let e,i=r[1].split("-");if(i.length>2){if(!r[1].startsWith("-"))return;{const e=r[1].indexOf("-",1);if(e>0){i=[r[1].substring(0,e),r[1].substring(e+1)]}}}if(e=i[0].replace(/,/g,""),isNaN(e))return;if(s.start=parseInt(e,10)-1,s.end=s.start+1,1===i.length&&(s.start-=20,s.end+=20),2===i.length){if(e=i[1].replace(/,/g,""),isNaN(e))return;if(s.end=parseInt(e,10),s.start<0&&!t){const e=-extent.start;s.start+=e,s.end+=e}}}return s}class CF extends ma{constructor(e,t){super(e,t)}init(e){super.init(e),this.type="qtl",this.name=e.name;const t=e.minLogP||e.min,i=e.maxLogP||e.max;this.dataRange={min:void 0!==t?t:3.5,max:i||25},this.autoscale=!i||e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||2,this.height=e.height||100,this.disableButtons=e.disableButtons,this.featureSource=El(e,this.browser.genome)}paintAxis(e,t,i){const r=(this.dataRange.max-this.dataRange.min)/i,s={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});const o=Math.ceil(10*(this.dataRange.max-this.dataRange.min)/i);for(let n=4;n<=this.dataRange.max;n+=o){const o=.85*t,a=o-5,c=o,l=i-(n-this.dataRange.min)/r;Co.strokeLine(e,a,l,c,l,s),l>8&&Co.fillText(e,n,a-1,l+2,s)}s.textAlign="center",Co.fillText(e,"-log10(pvalue)",t/4,i/2,s,{rotate:{angle:-90}})}async getFeatures(e,t,i){const r=this.visibilityWindow;return await this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r})}draw(e){const{context:t,referenceFrame:i,pixelWidth:r,pixelHeight:s}=e;this.background&&Co.fillRect(t,0,0,r,s,{fillStyle:this.background}),Co.strokeLine(t,0,s-1,r,s-1,{strokeStyle:this.divider}),i.feature&&i.feature.match(/RS[0-9]+/);const o=i=>{const o=i?2*this.dotSize:this.dotSize,n=e.bpStart,a=(this.dataRange.max-this.dataRange.min)/s;for(let d of e.features){const u=(d.start-n+.5)/e.bpPerPixel;if(u<0)continue;if(u>r)break;const f=d.phenotype;let p;if(this.browser.qtlSelections.qtl?(l=this.browser.qtlSelections.qtl,h=d,p=l.chr===h.chr&&l.start===h.start&&l.pValue===h.pValue):p=this.browser.qtlSelections.snps.size>0?this.browser.qtlSelections.hasSnp(d.snp)&&this.browser.qtlSelections.hasPhenotype(f):this.browser.qtlSelections.hasPhenotype(f),!i||p){var c=-Math.log(d.pValue)/Math.LN10;if(c>=this.dataRange.min){let e;c>this.dataRange.max?(c=this.dataRange.max,e=!0):e=!1;const r=Math.max(0+o,s-Math.round((c-this.dataRange.min)/a));let n;d.px=u,d.py=r,d.radius=o,i&&p?(n=this.browser.qtlSelections.colorForGene(f),Co.setProperties(t,{fillStyle:n,strokeStyle:"black"})):(n=e?"rgb(150, 150, 150)":"rgb(180, 180, 180)",Co.setProperties(t,{fillStyle:n,strokeStyle:n})),Co.fillCircle(t,u,r,o),Co.strokeCircle(t,u,r,o)}}}var l,h};o(!1),o(!0)}popupData(e,t){if(void 0===t&&(t=e.viewport.cachedFeatures),!t||0===t.length)return[];const i=this.name,r=[];for(let s of this._clickedFeatures(e,t))r.length>0&&r.push("
"),"function"==typeof s.popupData?r.push(...s.popupData(e)):r.push({name:"snp id",value:s.snp},{name:"gene id",value:s.gencodeId},{name:"gene name",value:s.geneSymbol},{name:"p value",value:s.pValue},{name:"tissue",value:i});return r}_clickedFeatures(e,t){const i=(e,t)=>Math.sqrt((e.px-t.canvasX)*(e.px-t.canvasX)+(e.py-t.canvasY)*(e.py-t.canvasY)),r=t.filter((t=>i(t,e)<6));if(r.length>1){r.sort(((t,r)=>i(t,e)-i(r,e)));const t=i(r[0],e);return r.filter((r=>i(r,e)<=t))}return r}contextMenuItemList(e){const t=[],i=e.viewport.cachedFeatures;if(i){const r=this._clickedFeatures(e,i);r.length>0&&(t.push({label:"Highlight associated features",click:async()=>{this.browser.qtlSelections.clear();for(let e of r)this.browser.qtlSelections.qtl=e,this.browser.qtlSelections.addPhenotype(e.phenotype);this.browser.repaintViews()}}),t.push("
"))}return t}menuItemList(){const e=[];return e.push(...this.numericDataMenuItems()),e.push("
"),e.push({label:"Search for...",dialog:function(e){this.browser.inputDialog.present({label:"Search for snp or phenotype",value:"",callback:async e=>{if(e){e=e.trim().toUpperCase();const t=t=>((t.phenotype&&t.phenotype.toUpperCase())===e||t.snp&&t.snp.toUpperCase()===e)&&-Math.log(t.pValue)/Math.LN10>this.dataRange.min;let i,r,s,o=await this.featureSource.findFeatures(t);if(0==o.length){await this.browser.search(e)&&(o=await this.featureSource.findFeatures(t))}if(o.length>0){this.browser.qtlSelections.clear();const t=new Set;i=o[0].chr,r=o[0].start,s=o[0].end;for(let n of o)n.snp&&n.snp.toUpperCase()===e&&this.browser.qtlSelections.addSnp(n.snp),this.browser.qtlSelections.addPhenotype(n.phenotype),t.add(n.phenotype),n.chr===i&&(r=Math.min(r,n.start),s=Math.max(s,n.end));const n=this.browser.genome.getChromosomeName(i);for(let e of t){const t=await yF(this.browser,e);t&&n===this.browser.genome.getChromosomeName(t.chr)&&(r=Math.min(r,t.start),s=Math.max(s,t.end))}const a=Math.floor(.1*(s-r));r=Math.max(0,r-a),s+=a,await this.browser.search(`${i}:${r}-${s}`)}}}},e)}}),e}doAutoscale(e){let t=this.config.max||25;if(e.length>0){const i=e.map((e=>-Math.log(e.pValue)/Math.LN10));i.sort(((e,t)=>e-t));t=i[Math.floor(i.length*(this.autoscalePercentile/100))]}return this.dataRange.max=Math.max(t,10),this.dataRange}}const _F={X:"rgb(204, 153, 0)",Y:"rgb(153, 204, 0)",Un:"darkGray)",1:"rgb(80, 80, 255)",2:"rgb(206, 61, 50)","2a":"rgb(210, 65, 55)","2b":"rgb(215, 70, 60)",3:"rgb(116, 155, 88)",4:"rgb(240, 230, 133)",5:"rgb(70, 105, 131)",6:"rgb(186, 99, 56)",7:"rgb(93, 177, 221)",8:"rgb(128, 34, 104)",9:"rgb(107, 215, 107)",10:"rgb(213, 149, 167)",11:"rgb(146, 72, 34)",12:"rgb(131, 123, 141)",13:"rgb(199, 81, 39)",14:"rgb(213, 143, 92)",15:"rgb(122, 101, 165)",16:"rgb(228, 175, 105)",17:"rgb(59, 27, 83)",18:"rgb(205, 222, 183)",19:"rgb(97, 42, 121)",20:"rgb(174, 31, 99)",21:"rgb(231, 199, 111)",22:"rgb(90, 101, 94)",23:"rgb(204, 153, 0)",24:"rgb(153, 204, 0)",25:"rgb(51, 204, 0)",26:"rgb(0, 204, 51)",27:"rgb(0, 204, 153)",28:"rgb(0, 153, 204)",29:"rgb(10, 71, 255)",30:"rgb(71, 117, 255)",31:"rgb(255, 194, 10)",32:"rgb(255, 209, 71)",33:"rgb(153, 0, 51)",34:"rgb(153, 26, 0)",35:"rgb(153, 102, 0)",36:"rgb(128, 153, 0)",37:"rgb(51, 153, 0)",38:"rgb(0, 153, 26)",39:"rgb(0, 153, 102)",40:"rgb(0, 128, 153)",41:"rgb(0, 51, 153)",42:"rgb(26, 0, 153)",43:"rgb(102, 0, 153)",44:"rgb(153, 0, 128)",45:"rgb(214, 0, 71)",46:"rgb(255, 20, 99)",47:"rgb(0, 214, 143)",48:"rgb(20, 255, 177)"};for(let Ny of Object.keys(_F)){_F["chr"+Ny]=_F[Ny]}for(let My=1;My<=48;My++){if(10===My)continue;const Ry=xF(My);_F[Ry]=_F[My.toString()]}function xF(e){if(!+e)return!1;for(var t=String(+e).split(""),i=["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM","","X","XX","XXX","XL","L","LX","LXX","LXXX","XC","","I","II","III","IV","V","VI","VII","VIII","IX"],r="",s=3;s--;)r=(i[+t.pop()+10*s]||"")+r;return Array(+t.join("")+1).join("M")+r}class kF extends ma{constructor(e,t){super(e,t)}init(e){super.init(e),this.useChrColors=void 0===e.useChrColors||e.useChrColors,this.trait=e.trait,this.posteriorProbability=e.posteriorProbability,this.valueProperty="bed"===e.format?"score":"value",this.height=e.height||100,this.autoscale=e.autoscale,this.autoscalePercentile=void 0===e.autoscalePercentile?98:e.autoscalePercentile,this.background=e.background,this.divider=e.divider||"rgb(225,225,225)",this.dotSize=e.dotSize||3,this.popoverWindow=void 0===e.popoverWindow?1e8:e.popoverWindow,this.useChrColors?this.colorScale=new $r(e.colorTable||_F):e.color?this.colorScale=new Wc(e.color):this.colorScale=new Qc(e.colorScale||{thresholds:[5e-8,5e-4,.5],colors:["rgb(255,50,50)","rgb(251,100,100)","rgb(251,170,170)","rgb(227,238,249)"]}),this.featureSource=El(e,this.browser.genome)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),this.autoscale||(this.posteriorProbability?this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?1:this.config.max}:this.dataRange={min:void 0===this.config.min?0:this.config.min,max:void 0===this.config.max?25:this.config.max}),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get supportsWholeGenome(){return!0}async getFeatures(e,t,i){const r=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r})}draw(e){const t=e.features,i=e.context,r=e.pixelWidth,s=e.pixelHeight;if(this.background&&Co.fillRect(i,0,0,r,s,{fillStyle:this.background}),Co.strokeLine(i,0,s-1,r,s-1,{strokeStyle:this.divider}),t){const o=e.bpPerPixel,n=e.bpStart,a=n+r*o+1;for(let e of t){const t=e.start;if(ta)break;let r;if(this.posteriorProbability)r=e[this.valueProperty];else{const t=e[this.valueProperty];if(!t)continue;r=-Math.log10(t)}const c=this.useChrColors?e._f?e._f.chr:e.chr:r,l=this.colorScale.getColor(c),h=(this.dataRange.max-this.dataRange.min)/s,d=Math.round((t-n)/o),u=Math.max(this.dotSize,s-Math.round((r-this.dataRange.min)/h));l&&Co.setProperties(i,{fillStyle:l,strokeStyle:"black"}),Co.fillCircle(i,d,u,this.dotSize),e.px=d,e.py=u}}}paintAxis(e,t,i){Co.fillRect(e,0,0,t,i,{fillStyle:"rgb(255, 255, 255)"});var r={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};const s=(this.dataRange.max-this.dataRange.min)/i;if(this.posteriorProbability){const t=.1;for(let o=this.dataRange.min;o0&&i.push("
"),5==s){i.push("...");break}if(o=o._f||o,"function"==typeof o.popupData)i=i.concat(o.popupData());else{const e=o[this.valueProperty],t=o.chr,s=F(o.start+1);i.push({name:"chromosome",value:t}),i.push({name:"position",value:s}),i.push({name:"name",value:o.name}),r.posteriorProbability?i.push({name:"posterior probability",value:e}):i.push({name:"pValue",value:e})}s++}}}return i}menuItemList(){return this.numericDataMenuItems()}doAutoscale(e){if(e.length>0){const t=this.valueProperty,i=this.posteriorProbability,r=e.map((function(e){const r=e[t];return{value:i?r:-Math.log(r)/Math.LN10}}));this.dataRange=is(r)}else this.posteriorProbability?this.dataRange={min:this.config.min||0,max:this.config.max||1}:this.dataRange={min:this.config.max||25,max:this.config.min||0};return this.dataRange}}class IF extends ma{constructor(e,t){super(e,t)}init(e){super.init(e),this.autoscale=e.autoscale||void 0===e.max,this.dataRange={min:e.min||0,max:e.max},this.windowFunction=e.windowFunction||"mean",this.paintAxis=Oc,this.graphType=e.graphType||"bar",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=El(this.config,this.browser.genome),this.visibilityWindow=-1,this.featureSource.visibilityWindow=this.visibilityWindow}async postInit(){if("function"==typeof this.featureSource.getHeader){if(this.header=await this.featureSource.getHeader(),this.disposed)return;if(this.sampleKeys=this.header.columnNames.slice(3),this.setTrackProperties(this.header),this.header.hasOwnProperty("clickToHighlight")){let e=this.header.clickToHighlight;this.config.clickToHighlight=e,this.config.samplesClickedToHighlight={}}if(this.header.hasOwnProperty("onlyHandleClicksForHighlightedSamples")&&(this.config.onlyHandleClicksForHighlightedSamples=!0),this.header.hasOwnProperty("highlight")){this.config.highlightSamples={};let e=this.header.highlight;Array.isArray(e)||(e=[e]);for(let t of e){const e=t.split(";");2===e.length&&(this.config.highlightSamples[e[0]]=e[1])}}}this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor}menuItemList(){return this.numericDataMenuItems()}async getFeatures(e,t,i){const r=await this.featureSource.getFeatures({chr:e,start:0,end:Number.MAX_SAFE_INTEGER,visibilityWindow:this.visibilityWindow});let s,o;for(let e=1;et&&(s=e-1),void 0===o&&r[e].start>i){o=e+1;break}return void 0===s&&(s=0),void 0===o&&(o=r.length),r.slice(s,o)}draw(e){const{features:t,context:i,bpPerPixel:r,bpStart:s,pixelWidth:o,pixelHeight:n}=e,a=e=>(this.dataRange.max-e)/(this.dataRange.max-this.dataRange.min)*n,c=function(e){let t=Math.floor((e-s)/r);return isNaN(t)&&console.warn("isNaN(x). feature start "+F(e)+" bp start "+F(s)),t};if(t&&t.length>0&&(void 0===this.dataRange.min&&(this.dataRange.min=0),this.dataRange.max>this.dataRange.min)){const e=this.config.highlightSamples,r=this.config.onlyHandleClicksForHighlightedSamples,s=this.config.clickToHighlight;let o=-1,n={},l=[],h=[];this.clickDetectorCache={};for(let d of t){const t=c(d.start),u=c(d.end),f=o>=0?c(o):t;if(!isNaN(t)&&!isNaN(u)){this.clickDetectorCache[t]=[],this.clickDetectorCache[u]=[];for(let o=0;o=1){const o=n[c],h=a(o),d=e&&e[c];d?l.push([f,h,t,g,d]):s&&c in this.config.samplesClickedToHighlight?l.push([f,h,t,g,this.config.samplesClickedToHighlight[c]]):Co.strokeLine(i,f,h,t,g,{strokeStyle:"#D9D9D9"}),r&&!(c in e)||this.clickDetectorCache[t].push([f,h,t,g,c,d||"gray"])}if(u-t>=1){const o=e&&e[c];o?h.push([t,g,u,g,o]):s&&c in this.config.samplesClickedToHighlight?h.push([t,g,u,g,this.config.samplesClickedToHighlight[c]]):Co.strokeLine(i,t,g,u,g,{strokeStyle:"gray"}),r&&!(c in e)||this.clickDetectorCache[u].push([t,g,u,g,c,o||"gray"])}n[c]=p}o=d.end}}for(let e of l)Co.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:1.3});for(let e of h)Co.strokeLine(i,e[0],e[1],e[2],e[3],{strokeStyle:e[4],lineWidth:2})}(e=>{if(this.config.hasOwnProperty("guideLines"))for(let t of this.config.guideLines)if(t.hasOwnProperty("color")&&t.hasOwnProperty("y")&&t.hasOwnProperty("dotted")){let i=a(t.y),r={strokeStyle:t.color,strokeWidth:2};t.dotted?Co.dashedLine(e.context,0,i,e.pixelWidth,i,5,r):Co.strokeLine(e.context,0,i,e.pixelWidth,i,r)}})(e)}doAutoscale(e){let t,i;return e.length>0?(t=Number.MAX_VALUE,i=-Number.MAX_VALUE,e.forEach((function(e){t=Math.min(t,...e.values),i=Math.max(i,...e.values)})),t-=.01,i+=.01):(t=0,i=100),{min:t,max:i}}clickedFeatures(e){const t=e.canvasX,i=e.canvasY;let r=null;for(r of Object.keys(this.clickDetectorCache))if(r=parseInt(r),r>=t)break;if(r){let e=Number.MAX_VALUE,n=[];const a=this.clickDetectorCache[r];for(let r of a){const s=r[0],o=r[2];if(to)return[];const a=r[1],c=r[3];if(iMath.max(a,c)+10)continue;const l=SF(t,i,s,a,o,c);l0?c/l:0}class EF extends ma{static defaults={height:300,theta:Math.PI/2,arcOrientation:"UP"};constructor(e,t){super(e,t),!1===e.arcOrientation?this.arcOrientation="DOWN":!0===e.arcOrientation?this.arcOrientation="UP":e.arcOrientation?this.arcOrientation=e.arcOrientation.toUpperCase():this.arcOrientation="UP","bp"===e.format?this.featureSource=new MF(e,t.genome):this.featureSource=new Fl(e,t.genome)}async getFeatures(e,t,i){const r=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,visibilityWindow:r})}draw(e){const t=e.context,i=Math.PI/2,r=e.pixelWidth,s=e.pixelHeight;e.viewportWidth;const o=e.bpPerPixel,n=e.bpStart,a=o,c="UP"===this.arcOrientation;Co.fillRect(t,0,e.pixelTop,r,s,{fillStyle:"rgb(255, 255, 255)"});const l=e.features;if(l){NF(l,1);for(let e of l)if(e.startLeft){let r=Math.round((e.startLeft-n)/a),s=Math.round((e.startRight-n)/a),o=Math.round((e.endLeft-n)/a),l=Math.round((e.endRight-n)/a);t.fillStyle=e.color,t.strokeStyle=e.color,t.beginPath();let h=(r+l)/2,d=(l-r)/2,u=this.height,f=Math.PI+(Math.PI/2-i),p=2*Math.PI-(Math.PI/2-i);c?(t.arc(h,u,d,f,p),t.lineTo(o,u)):(u=0,t.arc(h,u,d,p,f),t.lineTo(l,u));const g=(s+o)/2,m=(o-s)/2,w=u;c?(t.arc(g,w,m,p,f,!0),t.lineTo(r,w)):(t.arc(g,w,m,f,p,!0),t.lineTo(o,w)),t.stroke(),t.fill(),e.drawState={x1:h,y1:u,r1:d,x2:g,y2:w,r2:m,sa:f,ea:p}}else{let r=Math.round((e.start-n)/a),s=Math.round((e.end-n)/a);t.strokeStyle=e.color,t.beginPath();let o=(r+s)/2,l=(s-r)/2,h=this.height,d=Math.PI+(Math.PI/2-i),u=2*Math.PI-(Math.PI/2-i);c?t.arc(o,h,l,d,u):(h=0,t.arc(o,h,l,u,d)),t.stroke(),e.drawState={x1:o,y1:h,r1:l,sa:d,ea:u}}}}clickedFeatures(e){const t=super.clickedFeatures(e),i=[];NF(t,-1);for(let r of t){const t=r.drawState,s=e.canvasX-t.x1,o=e.canvasY-t.y1,n=Math.sqrt(s*s+o*o),a=t.r1+3;let c,l;if(void 0===t.x2)c=n,l=t.r1-3;else{const i=e.canvasX-t.x2,r=e.canvasY-t.y2;c=Math.sqrt(i*i+r*r),l=t.r2-3}if(nl){i.push(r);break}}return i}popupData(e,t){if(void 0===t&&(t=this.clickedFeatures(e)),t&&t.length>0)return this.extractPopupData(t[0],this.getGenomeId())}menuItemList(){return[{name:"Toggle arc direction",click:function(){this.arcOrientation="UP"===this.arcOrientation?"DOWN":"UP",this.trackView.repaintViews()}}]}}function NF(e,t){e.sort((function(e,i){const r=void 0===e.score?-Number.MAX_VALUE:e.score,s=void 0===i.score?-Number.MAX_VALUE:i.score;return(void 0===t?1:t)*(r-s)}))}class MF{constructor(e,t){this.config=e,this.genome=t}async getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s}){const o=this.genome;if(!this.featureCache){const e=ts(this.config),t=await Rr.loadByteArray(this.config.url,e);if(!t)return null;const i=Wa(t);let r,s=!0;const a=[],c=[],l=[],h=new Set;for(;void 0!==(r=i.nextLine());){const e=r.split("\t");if(s&&r.startsWith("color:")){const t="rgb("+e[1]+","+e[2]+","+e[3]+")";a.push(t),e.length>4&&c.push(e[4])}else{s=!1;const t=e[0],i=Number.parseInt(e[1])-1,r=Number.parseInt(e[2])-1,o=Number.parseInt(e[3]),d=Number.parseInt(e[4]);var n=Number.parseInt(e[5]);const u=a[n];let f;f=i<=d?{chr:t,startLeft:Math.min(i,r),startRight:Math.max(i,r),endLeft:Math.min(o,d),endRight:Math.max(o,d),color:u,score:n}:{chr:t,startLeft:Math.min(o,d),startRight:Math.max(o,d),endLeft:Math.min(i,r),endRight:Math.max(i,r),color:u,score:n},f.start=f.startLeft,f.end=f.endRight,c.length>n&&(f.description=c[n]),h.add(t),l.push(f)}}this.chromAliasManager=new fc(h,o),this.featureCache=new cn(l)}const a=this.chromAliasManager?await this.chromAliasManager.getAliasName(e):e;return this.featureCache.queryFeatures(a,t,i)}}class RF{constructor(e){this.browser=e,this.type="ideogram",this.id="ideogram",this.height=e.config.showCytobandNames?20:16,this.order=Number.MIN_SAFE_INTEGER,this.disableButtons=!0,this.ignoreTrackMenu=!0,this.showCytobandNames=e.config.showCytobandNames}computePixelHeight(e){return this.height}draw({context:e,referenceFrame:t,pixelWidth:i,pixelHeight:r,features:s}){const o=t.chr,n=t.genome.getChromosome(o);if(void 0===n||i<=0||r<=0||"all"===o.toLowerCase())return;!function({ctx:e,chr:t,referenceFrame:i,genome:r,width:s,height:o,stainColors:n,features:a,showCytobandNames:c}){const l=1,h=.5*l,d=0;if(void 0===r)return;Co.fillRect(e,0,0,s,o,{fillStyle:ur.greyScale(255)});const u=a;if(u){const t=d+o/2,i=[],r=[];if(0===u.length)return;const a=s/u[u.length-1].end;e.beginPath(),Co.roundRect(e,h,h+d,s-2*h,o-2*h,(o-2*h)/2,0,1),e.clip();for(let s=0;s0&&h[h.length-1].end&&(l=Math.max(l,h[h.length-1].end),n.bpLength=l),a4);e.save(),e.beginPath(),e.rect(i,2+s,c,a),e.clip();const h=i+c/2,d=2+s+a/2+1;let u;u=null!==n?.2126*n+.7152*n+.0722*n:39.764;const f=u<128?"white":"black";Co.fillText(e,t,h,d,{fillStyle:f,textAlign:"center",textBaseline:"middle",font:`${l}px sans-serif`}),e.restore()}function DF(e,t){if("c"===t.type)return{color:"rgb(150, 10, 10)",shade:null};{let r=t.stain,s=230;"p"===t.type&&(s=Math.floor(230-r/100*230));var i=e[s];return i||(i="rgb("+s+","+s+","+s+")",e[s]=i),{color:i,shade:s}}}let LF=new Wr("Dark2");["GT/AG","CT/AC","GC/AG","CT/GC","AT/AC","GT/AT","non-canonical"].forEach((e=>{LF.getColor(e)}));class TF extends ma{static defaults={margin:10,colorByNumReadsThreshold:5,height:100};constructor(e,t){super(e,t)}init(e){super.init(e),this.type=e.type||"junctions",e._featureSource?(this.featureSource=e._featureSource,delete e._featureSource):this.featureSource=e.featureSource?e.featureSource:El(e,this.browser.genome)}async postInit(){if("function"!=typeof this.featureSource.getHeader||(this.header=await this.featureSource.getHeader(),!this.disposed))return this.header&&this.setTrackProperties(this.header),void 0===this.visibilityWindow&&"function"==typeof this.featureSource.defaultVisibilityWindow&&(this.visibilityWindow=await this.featureSource.defaultVisibilityWindow()),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor,this}get supportsWholeGenome(){return!1}async getFeatures(e,t,i,r){const s=this.visibilityWindow;return this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s})}computePixelHeight(e){return this.height}draw(e){const t=e.features,i=e.context,r=e.bpPerPixel,s=e.bpStart,o=e.pixelWidth,n=e.pixelHeight,a=s+o*r+1;if(this.isMergedTrack||Co.fillRect(i,0,e.pixelTop,o,n,{fillStyle:"rgb(255, 255, 255)"}),t){const o={};o.referenceFrame=e.viewport.referenceFrame,o.referenceFrameStart=o.referenceFrame.start,o.referenceFrameEnd=o.referenceFrameStart+o.referenceFrame.toBP(e.viewport.getWidth()),o.featureZoomOutTracker={};for(let e of t)if(!(e.enda)break;this.renderJunction(e,s,r,n,i,o)}}else console.log("No feature list")}renderJunction(e,t,i,r,s,o){e.isVisible=!1;const n=Math.round((e.start-t)/i),a=Math.round((e.end-t)/i),c=(n+a)/2;if(a-n<=3){if(c in o.featureZoomOutTracker)return;o.featureZoomOutTracker[c]=!0}if(this.config.hideAnnotatedJunctions&&"true"===e.attributes.annotated_junction)return;if(this.config.hideUnannotatedJunctions&&"false"===e.attributes.annotated_junction)return;if(this.config.hideMotifs&&this.config.hideMotifs.includes(e.attributes.motif))return;if(this.config.hideStrand===e.strand)return;if(this.config.minJunctionEndsVisible){let t=0;if(e.start>=o.referenceFrameStart&&e.start<=o.referenceFrameEnd&&(t+=1),e.end>=o.referenceFrameStart&&e.end<=o.referenceFrameEnd&&(t+=1),t0&&h/d>this.config.maxFractionMultiMappedReads)return;if(e.attributes.maximum_spliced_alignment_overhang&&parseInt(e.attributes.maximum_spliced_alignment_overhang)this.config.maxSamplesWithThisJunction)return;if(e.attributes.num_samples_total&&(e.attributes.percent_samples_with_this_junction=100*u/Number(e.attributes.num_samples_total),this.config.minPercentSamplesWithThisJunction&&(e.attributes.percent_samples_with_this_junctionthis.config.maxPercentSamplesWithThisJunction)))return}const f=this.margin,p=r,g=f+.5*p;let m=f;const w=f+p-10,b=(n+c)/2,F=(c+a)/2;let v,y,A=1;e.attributes.line_width?A=Number(e.attributes.line_width):(void 0===this.config.thicknessBasedOn||"numUniqueReads"===this.config.thicknessBasedOn?A=l:"numReads"===this.config.thicknessBasedOn?A=d:"numSamplesWithThisJunction"===this.config.thicknessBasedOn&&void 0!==u&&(A=u),A=1+Math.log(A+1)/Math.log(12)),void 0===this.config.bounceHeightBasedOn||"random"===this.config.bounceHeightBasedOn?v=(e.start+e.end)%7:"distance"===this.config.bounceHeightBasedOn?v=6*(e.end-e.start)/(o.referenceFrameEnd-o.referenceFrameStart):"thickness"===this.config.bounceHeightBasedOn&&(v=2*A),m+=p*Math.max(7-v,0)/10,y=e.attributes.color?e.attributes.color:void 0===this.config.colorBy||"numUniqueReads"===this.config.colorBy?l>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"numReads"===this.config.colorBy?d>this.config.colorByNumReadsThreshold?"blue":"#AAAAAA":"isAnnotatedJunction"===this.config.colorBy?"true"===e.attributes.annotated_junction?"#b0b0ec":"orange":"strand"===this.config.colorBy?"+"===e.strand?"#b0b0ec":"#ecb0b0":"motif"===this.config.colorBy?LF.getColor(e.attributes.motif):"#AAAAAA";let C="";e.attributes.label?C=e.attributes.label.replace(/_/g," "):void 0===this.config.labelWith||"uniqueReadCount"===this.config.labelWith?C=l:"totalReadCount"===this.config.labelWith?C=d:"numSamplesWithThisJunction"===this.config.labelWith?void 0!==u&&(C=u):"percentSamplesWithThisJunction"===this.config.labelWith?void 0!==e.attributes.percent_samples_with_this_junction&&(C=e.attributes.percent_samples_with_this_junction.toFixed(0)+"%"):"motif"===this.config.labelWith&&void 0!==e.attributes.motif&&(C+=e.attributes.motif),"uniqueReadCount"===this.config.labelWithInParen?C+=" ("+l+")":"totalReadCount"===this.config.labelWithInParen?C+=" ("+d+")":"multiMappedReadCount"===this.config.labelWithInParen?h>0&&(C+=" (+"+h+")"):"numSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==u&&(C+=" ("+u+")"):"percentSamplesWithThisJunction"===this.config.labelWithInParen?void 0!==e.attributes.percent_samples_with_this_junction&&(C+=" ("+e.attributes.percent_samples_with_this_junction.toFixed(0)+"%)"):"motif"===this.config.labelWithInParen&&void 0!==e.attributes.motif&&(C+=` ${e.attributes.motif}`),e.isVisible=!0,s.beginPath(),s.moveTo(n,w),s.bezierCurveTo(b,m,F,m,a,w),s.lineWidth=A,s.strokeStyle=y,s.stroke();const _=(e,t,i,r)=>{e.beginPath(),e.moveTo(t,i),e.lineTo(t-r/2,i-r),e.lineTo(t+r/2,i-r),e.lineTo(t,i),e.closePath(),e.fill()};if(e.attributes.left_shape||e.attributes.right_shape){s.fillStyle=y;const t=s.lineWidth>2?10:7;e.attributes.left_shape&&_(s,n,w,t),e.attributes.right_shape&&_(s,a,w,t)}s.fillText(C,c-s.measureText(C).width/2,(7*m+g)/8)}clickedFeatures(e){return super.clickedFeatures(e).filter((function(e){return e.isVisible&&e.attributes}))}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=e.genomicLocation,r=[];for(let e of t){const t="function"==typeof e.popupData?e.popupData(i):this.extractPopupData(e._f||e,this.getGenomeId());t&&(r.length>0&&r.push("

"),Array.prototype.push.apply(r,t))}return r}dispose(){this.trackView=void 0}}const zF={min:0,max:3e3,color:"rgb(0,0,255)"};class PF{constructor(e){e=e||zF,this.max=e.max,this.min=e.min||0,this.cache=[],this.nbins=1e3,this.binsize=(this.max-this.min)/this.nbins,this.updateColor(e.color||"rgb(0,0,255)"),this.br=255,this.bg=255,this.bb=255}updateColor(e){const t=e.substring(4).replace(")","").split(",");3===t.length&&(this.r=Number.parseInt(t[0].trim()),this.g=Number.parseInt(t[1].trim()),this.b=Number.parseInt(t[2].trim())),this.cache=[]}setMinMax(e,t){this.min=e,this.max=t,this.cache=[],this.binsize=(this.max-this.min)/this.nbins}getColor(e){if(e<=this.min)return"white";if(e>=this.max)return`rgb(${this.r},${this.g},${this.b})`;const t=Math.floor((Math.min(this.max,e)-this.min)/this.binsize);if(void 0===this.cache[t]){const i=(e-this.min)/(this.max-this.min),r=1-i;this.cache[t]=`rgb(${Math.floor(i*this.r+r*this.br)},${Math.floor(i*this.g+r*this.bg)},${Math.floor(i*this.b+r*this.bb)})`}return this.cache[t]}toJson(){return{min:this.min,max:this.max,color:`rgb(${this.r},${this.g},${this.b})`}}static parse(e){const t=e.split(","),i={min:Number.parseFloat(t[0]),max:Number.parseFloat(t[1]),color:`${t[2]},${t[3]},${t[4]}`};return new PF(i)}}class HF extends ma{static defaults={height:300,rowHeight:3,min:.5,max:3,scale:1,visibilityWindow:1e4,supportHiDPI:!1,startSize:4,stepSize:2};constructor(e,t){super(e,t)}init(e){super.init(e),this.type="shoebox",e.max&&(this.dataRange={min:e.min||0,max:e.max});const t=Object.assign({},this.config);t.format="shoebox",this.featureSource=El(t,this.browser.genome)}async postInit(){if("function"==typeof this.featureSource.getHeader&&(this.header=await this.featureSource.getHeader(),this.disposed))return;this.header&&(this.header.scale&&(this.header.scale=Number.parseFloat(this.header.scale)),this.setTrackProperties(this.header),this.rowCount=this.header.firstFeature?this.header.firstFeature.values.length:100);const e=this.dataRange.min,t=this.dataRange.max;this.colorScale=new PF({min:e,max:t,color:this.color}),this.scale||(this.scale=1),this._initialColor=this.color||this.constructor.defaultColor,this._initialAltColor=this.altColor||this.constructor.defaultColor}get color(){return this._color||"rgb(0,0,255)"}set color(e){this._color=e,this.colorScale&&this.colorScale.updateColor(e)}menuItemList(){const e=[];e.push("
");let t=document.createElement("div");t.textContent="Set row height";const i=this.browser;return e.push({element:t,dialog:function(e){const t={label:"Row Height",value:this.rowHeight,callback:()=>{const e=parseInt(this.browser.inputDialog.value,10);if(void 0!==e){i.sampleNameViewportWidth=void 0;const t=[];this.trackView.track.selected?t.push(...this.trackView.browser.getSelectedTrackViews().map((({track:e})=>e))):t.push(this);for(const i of t)i.rowHeight=e,i.rowHeight*i.rowCount"),t=document.createElement("div"),t.textContent="Set data range",e.push({element:t,dialog:function(e){this.trackView.track.selected?this.browser.dataRangeDialog.configure(this.trackView.browser.getSelectedTrackViews()):this.browser.dataRangeDialog.configure(this.trackView),this.browser.dataRangeDialog.present(e)}}),e}setDataRange({min:e,max:t}){this.dataRange.min=e,this.dataRange.max=t,this.colorScale.setMinMax(e,t),this.trackView.repaintViews()}async getFeatures(e,t,i,r){const s=this.visibilityWindow;return await this.featureSource.getFeatures({chr:e,start:t,end:i,bpPerPixel:r,visibilityWindow:s})}draw({context:e,pixelTop:t,pixelWidth:i,pixelHeight:r,features:s,bpPerPixel:o,bpStart:n}){if(Co.fillRect(e,0,t,i,r,{fillStyle:"rgb(255, 255, 255)"}),s&&s.length>0){const a=this.rowHeight,c=t+r,l=n+i*o+1,h=a;for(let i of s){if(i.endl)continue;const r=Math.floor((i.start-n)/o),s=Math.floor((i.end-n)/o),d=Math.max(1,s-r);for(let s=i.values.length-1;s>=0;s--){const o=i.values[s];if(o>=this.dataRange.min){const n=(i.values.length-1-s)*a;if(n+ac)continue;const l=this.colorScale.getColor(o);e.fillStyle=l,e.fillRect(r,n,d,h)}}}}}paintAxis(e,t,i){var r={font:"normal 10px Arial",textAlign:"right",strokeStyle:"black"};const s=this.startSize+this.rowCount*this.stepSize,o=this.startSize,n=(s-o)/i;for(let t=50;t<=s;t+=50){const s=Math.max(10,i-Math.round((t-o)/n));Co.strokeLine(e,35,s,40,s,r),t>o&&Co.fillText(e,OF(t),30,s+4,r)}r.textAlign="center",r.font="normal 10px Arial",Co.fillText(e,"Footprint size (bp)",10,i/2,r,{rotate:{angle:-90}})}computePixelHeight(e){return e&&0!==e.length?e[0].values.length*this.rowHeight:0}clickedFeatures(e){const t=super.clickedFeatures(e),i=e.y;return t.filter((function(e){const t=e.pixelRect;return t&&i>=t.y&&i<=t.y+t.h}))}hoverText(e){const t=this.clickedFeatures(e);if(t&&t.length>0)return`${t[0].sample}: ${t[0].value}`}popupData(e,t){void 0===t&&(t=this.clickedFeatures(e));const i=[];for(let e of t){i.length>0&&(i.push("
"),i.push("
"));const t=e._f||e,r="function"==typeof t.popupData?t.popupData(this.type,this.browser.genome.id):this.extractPopupData(t);Array.prototype.push.apply(i,r)}return i}get supportsWholeGenome(){return!1}getState(){const e=super.getState();return e.colorScale=this.colorScale.toJson(),e}}function OF(e){return Number.isInteger(e)||e%1==0?e:Math.abs(e)>=10?e.toFixed():Math.abs(e)>=1?e.toFixed(1):Math.abs(e)>=.1?e.toFixed(2):e.toExponential(1)}class VF extends ma{static defaults={};constructor(e,t){super(e,t)}init(e){if(super.init(e),!e.images)throw Error("images are required");this.locus=e.locus,this.type="image",this.resolutionAware=!0}async postInit(){this._images=[];for(let e of this.config.images){const t=new Image;t.onload=()=>{e.img=t,e.bpPerPixel=(e.end-e.start)/t.width,this._images.push(e)},t.onerror=e=>{console.error(e)},t.src=e.src}}computePixelHeight(e){return e?e.height:0}menuItemList(){return[]}async getFeatures(e,t,i,r){return this.selectImage(e,t,i,r)}selectImage(e,t,i,r){if(0==this._images.length)return null;this._images.sort(((e,t)=>e.bpPerPixelr)return e;const s=this._images[this._images.length-1];return s.chr===e?s:null}draw({context:e,pixelTop:t,pixelWidth:i,pixelHeight:r,features:s,bpPerPixel:o,bpStart:n}){const a=s.img;if(a){const t=a.width,i=a.height,r=(s.end-s.start)/t/o,c=(s.start-n)/o;e.drawImage(a,c,0,r*t,i)}}get supportsWholeGenome(){return!1}}const qF=new Map([["ideogram",(e,t)=>new RF(e,t)],["sequence",(e,t)=>new sh(e,t)],["feature",(e,t)=>new Gl(e,t)],["seg",(e,t)=>new Yd(e,t)],["mut",(e,t)=>new Yd(e,t)],["maf",(e,t)=>new Yd(e,t)],["shoebox",(e,t)=>new HF(e,t)],["wig",(e,t)=>new ml(e,t)],["merged",(e,t)=>new vd(e,t)],["alignment",(e,t)=>new up(e,t)],["interaction",(e,t)=>new fp(e,t)],["interact",(e,t)=>new fp(e,t)],["variant",(e,t)=>new bF(e,t)],["qtl",(e,t)=>new CF(e,t)],["eqtl",(e,t)=>new CF(e,t)],["gwas",(e,t)=>new kF(e,t)],["arc",(e,t)=>new EF(e,t)],["gcnv",(e,t)=>new IF(e,t)],["junction",(e,t)=>new TF(e,t)],["blat",(e,t)=>new Yl(e,t)],["cnvpytor",(e,t)=>new gF(e,t)],["image",(e,t)=>new VF(e,t)]]);class UF{constructor(e,t){const i=(new DOMParser).parseFromString(e,"text/xml");this.processRootNode(i,t);const r=i.getElementsByTagName("Resource"),s=i.getElementsByTagName("Track"),o=s&&s.length>0,n=[];this.tracks=n;const a=new Map;Array.from(r).forEach((function(e,t){var i={url:e.getAttribute("path"),indexURL:e.getAttribute("index"),order:t};a.set(i.url,i),o||n.push(i)})),o&&Array.from(s).forEach((function(e){const t=e.getElementsByTagName("Track");if(t&&t.length>0){const i={type:"merged",tracks:[]};QF(e,i),n.push(i),Array.from(t).forEach((function(e){e.processed=!0;const t=e.getAttribute("id"),r=a.get(t);r&&(i.tracks.push(r),QF(e,r),r.autoscale=!1,i.height=r.height)}))}else if(!e.processed){const t=e.getAttribute("id"),i=a.get(t);i&&(n.push(i),QF(e,i))}}))}processRootNode(e,t){const i=e.getElementsByTagName("Session");!i||i.length;const r=i.item(0),s=r.getAttribute("genome"),o=r.getAttribute("locus"),n=r.getAttribute("ucscID");t&&t.hasOwnProperty(s)?this.genome=s:(this.reference={fastaURL:s},n&&(this.reference.id=n)),o&&(this.locus=o)}}function QF(e,t){t.name=e.getAttribute("name");const i=e.getAttribute("color");i&&(t.color="rgb("+i+")");const r=e.getAttribute("altColor");i&&(t.altColor="rgb("+r+")");const s=e.getAttribute("height");s&&(t.height=parseInt(s));const o=e.getAttribute("autoScale");o&&(t.autoscale="true"===o);const n=e.getAttribute("autoscaleGroup");n&&(t.autoscaleGroup=n);const a=e.getAttribute("windowFunction");a&&(t.windowFunction=a);const c=e.getAttribute("visibilityWindow")||e.getAttribute("featureVisibilityWindow");c&&(t.visibilityWindow=c);const l=e.getAttribute("indexed");l&&(t.indexed="true"===l);const h=e.getAttribute("normalize");h&&(t.normalize="true"===h);const d=e.getElementsByTagName("DataRange");if(d.length>0){const e=d.item(0);t.min=Number(e.getAttribute("minimum")),t.max=Number(e.getAttribute("maximum")),t.logScale="LOG"===e.getAttribute("type")}}class GF{constructor(e,t,i,r,s){this.genome=e,this.chr=t,this.start=i,this.end=r,this.bpPerPixel=s,this.id=n()}get center(){return(this.start+this.end)/2}get locusSearchString(){return`${this.chr}:${this.start+1}-${this.end}`}extend(e){const t=Math.min(e.start,this.start),i=Math.max(e.end,this.end),r=(i-t)/(this.end-this.start);this.start=t,this.end=i,this.bpPerPixel*=r}calculateEnd(e){return this.start+this.bpPerPixel*e}calculateCenter(e){return this.start+this.bpPerPixel*e/2}calculateBPP(e,t){return(e-this.start)/t}set(e){this.chr=e.chr,this.start=e.start,this.bpPerPixel=e.bpPerPixel}toPixels(e){return e/this.bpPerPixel}toBP(e){return this.bpPerPixel*e}shift(e){this.start+=e,this.end+=e}shiftPixels(e,t,i){const r=this.start,s=e*this.bpPerPixel;return this.start+=s,i&&this.clampStart(t),this.end=this.start+t*this.bpPerPixel,r!==this.start}clampStart(e){const t=this.genome.getChromosome(this.chr).bpStart||0;if(this.start=Math.max(t,this.start),e){const{bpLength:t}=this.genome.getChromosome(this.chr),i=t-e*this.bpPerPixel;this.start>i&&(this.start=i)}}async zoomWithScaleFactor(e,t,i,r){const s=void 0===r?this.start+this.toBP(i/2):r,o=this.start,n=this.bpPerPixel,a=this.getChromosome().bpLength,c=t<1?e.minimumBases()/i:a/i;this.bpPerPixel=t<1?Math.max(this.bpPerPixel*t,c):Math.min(this.bpPerPixel*t,c);const l=this.bpPerPixel*i;this.start=s-.5*l,this.clampStart(i),this.end=this.start+l;(o!==this.start||n!==this.bpPerPixel)&&await e.updateViews(!0)}getChromosome(){return this.genome.getChromosome(this.chr)}updateForViewportWidth(e){const{chr:t}=this,{bpLength:i}=this.getChromosome(),r=this.toBP(e);Dh.isWholeGenomeView(t)||r>i?this.bpPerPixel=i/e:this.end=this.start+this.toBP(e)}getMultiLocusLabelBPLengthOnly(e){const t=" ",i=Math.floor(this.start)+1,r=Math.round(this.start+this.bpPerPixel*e);return`${t}${this.chr}${t}${ns(r-i)}${t}`}getMultiLocusLabelLocusOnly(e){const t=" ",{chr:i,start:r,end:s}=this.getPresentationLocusComponents(e);return`${t}${i}:${r}-${s}${t}`}getMultiLocusLabel(e){const t=" ",{chr:i,start:r,end:s}=this.getPresentationLocusComponents(e),o=Math.floor(this.start)+1;return`${t}${i}:${r}-${s}${t}${t}(${ns(Math.round(this.start+this.bpPerPixel*e)-o)})${t}`}getPresentationLocusComponents(e){if("all"===this.chr)return{chr:this.chr};{const t=F(Math.floor(this.start)+1),i=F(Math.round(this.start+this.bpPerPixel*e));return{chr:this.chr,start:t,end:i}}}getLocusString(){if("all"===this.chr)return"all";return`${this.genome.getChromosomeDisplayName(this.chr)}:${F(Math.floor(this.start)+1)}-${F(Math.round(this.end))}`}description(e){console.log(` ${e||""} referenceFrame - ${this.chr} bpp ${this.bpPerPixel.toFixed(3)} start ${F(Math.round(this.start))} end ${F(Math.round(this.end))} `)}overlaps(e){return this.chr===e.chr&&this.end>=e.start&&e.end>=this.start}}function jF(){return"3.5.0"}const WF="Maximum sequence count exceeded";class $F{constructor(e,i){this.container=t({class:"igv-chromosome-select-widget-container"}),i.appendChild(this.container),this.select=document.createElement("select"),this.select.setAttribute("name","chromosome-select-widget"),this.container.appendChild(this.select),this.select.addEventListener("change",(async()=>{if(this.select.blur(),""!==this.select.value&&WF!==this.select.value)if("all"===this.select.value.trim().toLowerCase()||"*"===this.select.value){if(e.genome.wholeGenomeView){const t=e.genome.getChromosome("all");e.updateLoci([{chr:"all",start:0,end:t.bpLength}])}}else{const t=await e.genome.loadChromosome(this.select.value),i={chr:t.name};void 0===i.start&&void 0===i.end&&(i.start=0,i.end=t.bpLength),e.updateLoci([i])}})),this.showAllChromosomes=!1!==e.config.showAllChromosomes,this.genome=e.genome}show(){this.container.style.display="flex"}hide(){this.container.style.display="none"}setValue(e){this.select.value=this.genome.getChromosomeDisplayName(e)}update(e){this.genome=e;const t=e.wgChromosomeNames?e.wgChromosomeNames.map((t=>e.getChromosomeDisplayName(t))):[];if(this.showAllChromosomes&&e.chromosomeNames.length>1){const i=new Set(t);let r=0;for(let s of e.chromosomeNames){if(1e3===++r){t.push(WF);break}i.has(s)||(s=e.getChromosomeDisplayName(s),t.push(s))}}this.select.innerHTML="",e.showWholeGenomeView()&&t.unshift("all");for(let i of t){const t=document.createElement("option");t.setAttribute("value",i),t.innerText=e.getChromosomeDisplayName(i),this.select.appendChild(t)}}}class KF{constructor(e,i){this.container=t({class:"igv-windowsize-panel-container"}),e.appendChild(this.container),i.on("locuschange",(e=>{this.updatePanel(e)})),this.browser=i}show(){this.container.style.display="block"}hide(){this.container.style.display="none"}updatePanel(e){const t=this.browser.calculateViewportWidth(this.browser.referenceFrameList.length);this.container.innerText=1===e.length?ns(Math.round(t*e[0].bpPerPixel)):""}}class YF extends bd{constructor(e,t,i,r){super(e,t,"Select Tracks",Fd,'\n multi select\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n','\n multi select hover\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n',!1),this.navbar=i,this.enableMultiTrackSelection=!1,this.button.addEventListener("mouseenter",(e=>{!1===r&&this.setState(!0)})),this.button.addEventListener("mouseleave",(e=>{!1===r&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{this.setMultiTrackSelection(!this.enableMultiTrackSelection)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler)}setMultiTrackSelection(e){this.enableMultiTrackSelection=e,this.setState(this.enableMultiTrackSelection),!1===this.enableMultiTrackSelection&&this.navbar.overlayTrackButton.setVisibility(!1);for(const t of this.browser.trackViews)t.enableTrackSelection(e)}}class ZF extends bd{constructor(e,t){super(e,t,"Crosshairs",Fd,'\n cursor\n \n \n \n \n \n \n \n \n \n \n','\n cursor hover\n \n \n \n \n \n \n \n \n \n \n',t.doShowCursorGuide),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowCursorGuide&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowCursorGuide&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{t.doShowCursorGuide=!t.doShowCursorGuide,t.setCursorGuideVisibility(t.doShowCursorGuide),this.setState(t.doShowCursorGuide)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(t.config.showCursorTrackingGuideButton)}}class XF extends bd{constructor(e,t){super(e,t,"Center Line",Fd,'\n centerline\n \n \n \n \n \n \n','\n centerline hover\n \n \n \n \n \n \n',t.config.showCenterGuide),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowCenterLine&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowCenterLine&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{t.doShowCenterLine=!t.doShowCenterLine,t.setCenterLineVisibility(t.doShowCenterLine),this.setState(t.doShowCenterLine)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(t.config.showCenterGuideButton)}}class JF extends bd{constructor(e,t){super(e,t,"Track Labels",Fd,'\n track labels\n \n \n \n \n \n \n \n \n \n','\n track labels hover\n \n \n \n \n \n \n \n \n \n',t.config.showTrackLabels),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowTrackLabels&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowTrackLabels&&this.setState(!1)}));this.boundMouseClickHandler=(()=>{t.doShowTrackLabels=!t.doShowTrackLabels,t.setTrackLabelVisibility(t.doShowTrackLabels),this.setState(t.doShowTrackLabels)}).bind(this),this.button.addEventListener("click",this.boundMouseClickHandler),this.setVisibility(t.config.showTrackLabelButton)}}class ev extends bd{constructor(e,t){super(e,t,["ROI","Regions of Interest Table"],Fd,'\n roi\n \n \n \n \n ROI\n \n \n \n','\n roi hover\n \n \n \n \n ROI\n \n \n \n',!1),this.button.addEventListener("mouseenter",(()=>{!1===t.doShowROITable&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.doShowROITable&&this.setState(!1)})),this.button.addEventListener("click",(()=>this.buttonHandler(!t.doShowROITable))),this.setVisibility(!1)}buttonHandler(e){this.setState(e),this.browser.setROITableVisibility(e)}}class tv extends bd{constructor(e,t){super(e,t,"Sample Info",Fd,'\n sample info\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 sample info hover\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',!1),this.showSampleInfo=!1,this.button.addEventListener("mouseenter",(()=>{!1===this.showSampleInfo&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===this.showSampleInfo&&this.setState(!1)})),this.button.addEventListener("click",(()=>{this.performClickWithState(t,void 0)}))}performClickWithState(e,t){this.showSampleInfo=void 0===t?!this.showSampleInfo:t;e.columnContainer.querySelector(".igv-sample-info-column").style.display=!1===this.showSampleInfo?"none":"flex",this.setState(this.showSampleInfo),e.layoutChange()}setButtonVisibility(e){this.showSampleInfo=e,this.setState(this.showSampleInfo),!0===this.showSampleInfo?this.show():this.hide()}}class iv extends bd{constructor(e,t){super(e,t,"Sample Names",'\n \n \n \n \n \n \n \n \n','\n sample names\n \n \n \n \n \n \n \n \n','\n sample names hover\n \n \n \n \n \n \n \n \n',t.config.showSampleNames),this.button.addEventListener("mouseenter",(()=>{!1===t.showSampleNames&&this.setState(!0)})),this.button.addEventListener("mouseleave",(()=>{!1===t.showSampleNames&&this.setState(!1)})),this.button.addEventListener("click",(()=>{this.performClickWithState(t,void 0)})),!0===t.config.showSampleNameButton?this.show():this.hide()}performClickWithState(e,t){e.showSampleNames=void 0===t?!e.showSampleNames:t;e.columnContainer.querySelector(".igv-sample-name-column").style.display=!1===e.showSampleNames?"none":"flex",this.setState(e.showSampleNames),e.layoutChange()}}class rv{constructor(e,i){this.parent=e,this.popover=t({class:"igv-ui-dropdown"}),e.appendChild(this.popover),this.popoverContent=t(),this.popover.appendChild(this.popoverContent),this.popover.style.display="none",this.shim=i}configure(e){if(0===e.length)return;const t=ps(e,this.popover);for(const{element:e}of t)this.popoverContent.appendChild(e)}present(e){this.popover.style.display="block";let{x:t,y:i}=a(e,this.parent);this.popover.style.left=`${t+this.shim.left}px`,this.popover.style.top=`${i+this.shim.top}px`}_present(e){this.popover.style.display="block";let{x:t,y:i,width:r}=a(e,this.parent);t+=this.shim.left,i+=this.shim.top,this.popover.style.top=`${i}px`;const{width:s}=this.popover.getBoundingClientRect(),o=t+s,n=o-r;this.popover.style.left=`${o>r?t-n:t}px`}dismiss(){this.popover.style.display="none"}}class sv extends bd{constructor(e,t){super(e,t,"Save Image",Fd,'\n save image\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n','\n save image\n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n \n',!1),this.button.addEventListener("mouseenter",(()=>this.setState(!0))),this.button.addEventListener("mouseleave",(()=>{for(const e of this.button.querySelectorAll("div"))if("block"===e.style.display)return;this.setState(!1)})),this.dropdown=new rv(this.button.parentNode,{top:24,left:-88});const i=[{label:"Save as SVG",click:e=>{this.browser.saveSVGtoFile("igvjs.svg"),this.dropdown.dismiss()}},{label:"Save as PNG",click:e=>{this.browser.savePNGtoFile("igvjs.png"),this.dropdown.dismiss()}}];this.dropdown.configure(i),this.button.addEventListener("click",(e=>{let t;if(e.target===this.button)t=!0;else if(e.target.closest("svg")){e.target.closest("div")===this.button&&(t=!0)}!0===t&&("none"===this.dropdown.popover.style.display?this.dropdown.present(e):this.dropdown.dismiss())})),this.setVisibility(t.config.showSVGButton)}navbarResizeHandler(e){this.dropdown.dismiss(),super.navbarResizeHandler(e)}}const ov=function(e,i,r){const s=t({class:"igv-navbar-button"});e.appendChild(s),s.textContent=r.label,s.addEventListener("click",(()=>r.callback(i)))};let nv=23,av=0;class cv{constructor(e,i,r){this.browser=i,this.zoomContainer=t({class:"igv-zoom-widget"}),r.appendChild(this.zoomContainer),this.zoomOutButton=t(),this.zoomContainer.appendChild(this.zoomOutButton),this.zoomOutButton.appendChild(l("minus-circle")),this.zoomOutButton.addEventListener("click",(()=>{i.zoomOut()}));const s=t();this.zoomContainer.appendChild(s),this.slider=document.createElement("input"),this.slider.type="range",this.slider.min="0",this.slider.max=`${nv}`,s.appendChild(this.slider),this.slider.addEventListener("change",(e=>{e.preventDefault(),e.stopPropagation();const t=i.referenceFrameList[0],{bpLength:r}=t.genome.getChromosome(t.chr),{end:s,start:o}=t,n=s-o,a=r/Math.pow(2,e.target.valueAsNumber);i.zoomWithScaleFactor(a/n)})),this.zoomInButton=t(),this.zoomContainer.appendChild(this.zoomInButton),this.zoomInButton.appendChild(l("plus-circle")),this.zoomInButton.addEventListener("click",(()=>{i.zoomIn()})),i.on("locuschange",(e=>{this.browser.isMultiLocusMode()?this.disable():(this.enable(),this.update(e))}))}update(e){if(this.slider){const t=e[0],{bpLength:i}=t.genome.getChromosome(t.chr),{start:r,end:s}=t;nv=Math.ceil(Math.log2(i/this.browser.minimumBases())),this.slider.max=`${nv}`;const o=i/(s-r);av=Math.log2(o),this.slider.value=`${Math.round(av)}`}}enable(){this.slider&&(this.slider.disabled=!1)}disable(){this.slider&&(this.slider.disabled=!0)}hide(){this.zoomContainer.style.display="none"}show(){this.zoomContainer.style.display="block"}hideSlider(){this.slider&&(this.slider.style.display="none")}showSlider(){this.slider&&(this.slider.style.display="block")}}class lv{constructor(e,t){this.browser=t,this.config=e,this.currentClass="igv-navbar-text-button";const i=document.createElement("div");i.className="igv-navbar",this.navigation=i;const r=document.createElement("div");r.className="igv-navbar-left-container",i.appendChild(r),this.navbarLeftContainer=r;const s=document.createElement("div");s.className="igv-logo",r.appendChild(s);const o=function(){const e=document.createElementNS("http://www.w3.org/2000/svg","svg");e.setAttribute("width","690px"),e.setAttribute("height","324px"),e.setAttribute("viewBox","0 0 690 324"),e.setAttribute("version","1.1"),e.setAttribute("xmlns","http://www.w3.org/2000/svg"),e.setAttribute("xmlns:xlink","http://www.w3.org/1999/xlink");const t=document.createElementNS("http://www.w3.org/2000/svg","title");t.textContent="IGV",e.appendChild(t);const i=document.createElementNS("http://www.w3.org/2000/svg","g");i.setAttribute("id","Page-1"),i.setAttribute("stroke","none"),i.setAttribute("stroke-width","1"),i.setAttribute("fill","none"),i.setAttribute("fill-rule","evenodd"),e.appendChild(i);const r=document.createElementNS("http://www.w3.org/2000/svg","g");r.setAttribute("id","IGV"),r.setAttribute("fill","#666666"),i.appendChild(r);const s=document.createElementNS("http://www.w3.org/2000/svg","polygon");s.setAttribute("id","Path"),s.setAttribute("points","379.54574 8.00169252 455.581247 8.00169252 515.564813 188.87244 532.884012 253.529506 537.108207 253.529506 554.849825 188.87244 614.833392 8.00169252 689.60164 8.00169252 582.729511 320.722144 486.840288 320.722144"),r.appendChild(s);const o=document.createElementNS("http://www.w3.org/2000/svg","path");o.setAttribute("d","M261.482414,323.793286 C207.975678,323.793286 168.339046,310.552102 142.571329,284.069337 C116.803612,257.586572 103.919946,217.158702 103.919946,162.784513 C103.919946,108.410325 117.437235,67.8415913 144.472217,41.0770945 C171.507199,14.3125977 212.903894,0.930550071 268.663545,0.930550071 C283.025879,0.930550071 298.232828,1.84616386 314.284849,3.6774189 C330.33687,5.50867394 344.839793,7.97378798 357.794056,11.072835 L357.794056,68.968378 C339.48912,65.869331 323.578145,63.5450806 310.060654,61.9955571 C296.543163,60.4460336 284.574731,59.6712835 274.154998,59.6712835 C255.850062,59.6712835 240.502308,61.4320792 228.111274,64.9537236 C215.720241,68.4753679 205.793482,74.2507779 198.330701,82.2801269 C190.867919,90.309476 185.587729,100.87425 182.48997,113.974767 C179.392212,127.075284 177.843356,143.345037 177.843356,162.784513 C177.843356,181.942258 179.251407,198.000716 182.067551,210.960367 C184.883695,223.920018 189.671068,234.41436 196.429813,242.443709 C203.188559,250.473058 212.059279,256.178037 223.042241,259.558815 C234.025202,262.939594 247.683295,264.629958 264.01693,264.629958 C268.241146,264.629958 273.098922,264.489094 278.590403,264.207362 C284.081883,263.925631 289.643684,263.50304 295.275972,262.939577 L295.275972,159.826347 L361.595831,159.826347 L361.595831,308.579859 C344.698967,313.087564 327.239137,316.750019 309.215815,319.567334 C291.192494,322.38465 275.281519,323.793286 261.482414,323.793286 L261.482414,323.793286 L261.482414,323.793286 Z"),o.setAttribute("id","Path"),r.appendChild(o);const n=document.createElementNS("http://www.w3.org/2000/svg","polygon");return n.setAttribute("id","Path"),n.setAttribute("points","0.81355666 5.00169252 73.0472883 5.00169252 73.0472883 317.722144 0.81355666 317.722144"),r.appendChild(n),e}();o.style.width="34px",o.style.height="32px",s.appendChild(o),this.currentGenome=document.createElement("div"),this.currentGenome.className="igv-current-genome",r.appendChild(this.currentGenome),this.currentGenome.textContent="";const n=document.createElement("div");n.className="igv-navbar-genomic-location",r.appendChild(n),this.chromosomeSelectWidget=new $F(t,n),!1!==e.showChromosomeWidget?this.chromosomeSelectWidget.show():this.chromosomeSelectWidget.hide();const a=document.createElement("div");a.className="igv-locus-size-group",n.appendChild(a);const c=document.createElement("div");c.className="igv-search-container",a.appendChild(c),this.searchInput=document.createElement("input"),this.searchInput.className="igv-search-input",this.searchInput.type="text",this.searchInput.placeholder="Locus Search",c.appendChild(this.searchInput),this.searchInput.addEventListener("keyup",(e=>{e.stopImmediatePropagation()})),this.searchInput.addEventListener("change",(()=>{this.doSearch(this.searchInput.value)}));const h=document.createElement("div");h.className="igv-search-icon-container",c.appendChild(h);const d=l("search");h.appendChild(d),h.addEventListener("click",(()=>{this.doSearch(this.searchInput.value)})),this.windowSizePanel=new KF(a,t);const u=document.createElement("div");u.className="igv-navbar-right-container",i.appendChild(u),this.navbarRightContainer=u;const f=document.createElement("div");f.className="igv-navbar-toggle-button-container",u.appendChild(f),this.toggleButtonContainer=f,this.overlayTrackButton=new Cd(f,t),this.overlayTrackButton.setVisibility(!1);const p=!1!==e.showMultiSelectButton;if(this.multiTrackSelectButton=new YF(f,t,this,p),this.cursorGuideButton=new ZF(f,t),this.centerLineButton=new XF(f,t),this.trackLabelControl=new JF(f,t),this.roiTableControl=new ev(f,t),this.sampleInfoControl=new tv(f,t),this.sampleNameControl=new iv(f,t),!0===e.showSVGButton&&(this.saveImageControl=new sv(f,t)),e.customButtons)for(let i of e.customButtons)new ov(f,t,i);this.zoomWidget=new cv(e,t,u),!1===e.showNavigation&&(this.navigation.style.display="none")}navbarDidResize(){const e=this.currentNavbarButtonClass();"igv-navbar-text-button"===e&&(this.textButtonContainerWidth=this.navbarRightContainer.getBoundingClientRect().width);const t=this.browser,i=t.isMultiLocusWholeGenomeView()||t.referenceFrameList&&Dh.isWholeGenomeView(t.referenceFrameList[0].chr);i?this.windowSizePanel.hide():this.windowSizePanel.show();const{x:r,width:s}=this.navbarLeftContainer.getBoundingClientRect(),o=r+s,{x:n}=this.navbarRightContainer.getBoundingClientRect();let a;if("igv-navbar-text-button"===e&&n-o<8)a="igv-navbar-icon-button";else if(this.textButtonContainerWidth&&"igv-navbar-icon-button"===e){this.navigation.offsetWidth-o-this.textButtonContainerWidth>8&&(a="igv-navbar-text-button")}let c;a&&e!==a&&(this.currentClass=a,this.browser.fireEvent("navbar-resize",[a])),c=i?"igv-zoom-widget-hidden":this.navigation.offsetWidth>860?"igv-zoom-widget":"igv-zoom-widget-900",this.zoomWidget.zoomContainer.className="",this.zoomWidget.zoomContainer.classList.add(c)}updateGenome(e){let t=e.id&&e.id.length<20?e.id:`${e.id.substring(0,8)}...${e.id.substring(e.id.length-8)}`;this.currentGenome.textContent=t,this.currentGenome.setAttribute("title",e.description);!1!==this.config.showChromosomeWidget&&!1!==e.showChromosomeWidget&&e.chromosomeNames&&e.chromosomeNames.length>1?(this.chromosomeSelectWidget.update(e),this.chromosomeSelectWidget.show()):this.chromosomeSelectWidget.hide()}updateLocus(e,t){this.searchInput&&(this.searchInput.value=e),this.chromosomeSelectWidget&&(this.chromosomeSelectWidget.select.value=t)}currentNavbarButtonClass(){return this.currentClass}setEnableTrackSelection(e){this.multiTrackSelectButton.setMultiTrackSelection(e)}getEnableTrackSelection(){return this.multiTrackSelectButton.enableMultiTrackSelection}hide(){this.navigation.style.display="none"}show(){this.navigation.style.display="flex"}async doSearch(e){await this.browser.search(e)||this.browser.alert.present(new Error(`Unrecognized locus: ${e} `))}}const hv=(e,t)=>{const i=0===e?t.nextElementSibling:t.previousElementSibling;t.remove(),i.remove()},dv=e=>{const i=t({class:"igv-column-shim"});hs(i,e);const r=t({class:"igv-column"});return hs(r,i),r},uv=(e,i)=>{for(let r=0;r1&&r>0){ls(t({class:"igv-column-shim"}),s)}}};class fv{constructor(e,i,r){this.browser=e,this.referenceFrame=i,this.column=r,this.container=t({class:"igv-center-line"}),r.appendChild(this.container),e.doShowCenterLine?this.show():this.hide()}repaint(){if(this.referenceFrame){if(1/this.referenceFrame.bpPerPixel>1){const e=Math.floor(this.referenceFrame.toPixels(1));this.container.style.width=`${e}px`,this.container.classList.remove("igv-center-line-thin"),this.container.classList.add("igv-center-line-wide")}else this.container.style.width="1px",this.container.classList.remove("igv-center-line-wide"),this.container.classList.add("igv-center-line-thin")}}show(){this.isVisible=!0,this.container.style.display="block",this.repaint()}hide(){this.isVisible=!1,this.container.style.display="none"}resize(){this.repaint()}}const pv=function(e,i){this.button=t({class:"igv-navbar-button"}),e.appendChild(this.button),this.button.textContent="circular view",this.button.addEventListener("click",(()=>{i.circularViewVisible=!i.circularViewVisible})),this.browser=i,this.setVisibility(i.config.showCircularViewButton),this.setState(i.circularViewVisible)};pv.prototype.setVisibility=function(e){!0===e?this.show():this.hide()},pv.prototype.setState=function(e){!0===e?this.button.classList.add("igv-navbar-button-clicked"):this.button.classList.remove("igv-navbar-button-clicked")},pv.prototype.show=function(){this.button.style.display="block",this.setState(this.browser.circularViewVisible)},pv.prototype.hide=function(){this.button.style.display="none"};class gv{constructor(e,i){this.browser=e,this.container=t({class:"igv-roi-menu"}),i.appendChild(this.container);const r=t();this.container.appendChild(r),u(r,(()=>this.container.style.display="none")),this.body=t(),this.container.appendChild(this.body),this.container.style.display="none"}async present(e,t,i,r,s,o){const n=this.menuItems(e,t,i,r,s,o);this.browser.menuPopup.presentTrackContextMenu(i,n)}menuItems(e,t,i,r,s,o){const n=e.name?[`${e.name}
`]:[];return"name"in t&&n.push(`ROI Set: ${t.name}`),n.length>0&&n.push("
"),t.isUserDefined&&this.#I(n,e,i),ds()&&e.end-e.start<1e6&&this.#S(n,e),e.end-e.start<=25e3&&this.#E(n,e),this.#N(n,e),t.isUserDefined&&this.#M(n,e,t,r,s,o),n}#M(e,t,i,r,s,o){e.push("
"),e.push({label:"Delete",click:async()=>{i.removeFeature(t);const e=await i.getAllFeatures();0===Object.keys(e).length&&r.deleteUserDefinedROISet(),r.deleteRegionWithKey(o.dataset.region,s),r.repaintTable()}})}#S(e,t){e.push({label:"Copy reference sequence",click:async()=>{this.container.style.display="none";let e=await this.browser.genome.getSequence(t.chr,t.start,t.end);e||(e="Unknown sequence");try{await navigator.clipboard.writeText(e)}catch(e){console.error(e),this.browser.alert.present(void 0,`Failed to copy the sequence to the clipboard. (${e.message})`)}}})}#I(e,t,i){e.push({label:"Set description ...",click:()=>{const e={label:"Description",value:t.name||"",callback:()=>{const e=this.browser.inputDialog.value||"";t.name=e.trim(),this.browser.roiManager.repaintTable()}};this.browser.inputDialog.present(e,i)}})}#N(e,t){const i=this.browser.findTracks((e=>"function"==typeof e.sortByValue));if(i.length>0){e.push("
");const{chr:r,start:s,end:o}=t;e.push({label:"Sort by value (ascending)",click:()=>Promise.all(i.map((e=>e.sortByValue({option:"VALUE",direction:"ASC",chr:r,start:s,end:o}))))}),e.push('
'),e.push({label:"Sort by value (descending)",click:()=>Promise.all(i.map((e=>e.sortByValue({option:"VALUE",direction:"DESC",chr:r,start:s,end:o}))))})}}#E(e,t){e.push({label:"BLAT reference sequence",click:async()=>{this.container.style.display="none";const{chr:e,start:i,end:r}=t;let s=await this.browser.genome.getSequence(e,i,r);if(s){const t=`blat: ${e}:${i+1}-${r}`,o=`blat: ${e}:${i+1}-${r}`;Zl({sequence:s,browser:this.browser,name:t,title:o})}}})}dispose(){this.container.innerHTML=""}}class mv extends jl{constructor(e){const t={browser:e,parent:e.columnContainer,headerTitle:"Regions of Interest",dismissHandler:()=>e.roiTableControl.buttonHandler(!1),gotoButtonHandler:mv.gotoButtonHandler};t.columnFormat=mv.getColumnFormatConfiguration(!0),super(Object.assign({width:"640px"},t))}tableRowDOM(e){const i=t({class:"igv-roi-table-row"}),{setName:r,feature:s}=e;i.dataset.region=vv(s.chr,s.start,s.end);let o=[s.chr,F(s.start),F(s.end),s.name||"",r];4===this.columnFormat.length&&(o=o.slice(0,4));for(let e=0;ee.remove())),e.length>0){const t=e.sort(((e,t)=>e.feature.chr.localeCompare(t.feature.chr)||e.feature.start-t.feature.start||e.feature.end-t.feature.end));for(let e of t){const t=this.tableRowDOM(e);this.tableRowContainer.appendChild(t)}}}set footerDOM(e){super.footerDOM=e,this.gotoButton.textContent="Go to selected region(s)";const i=t({class:"igv-roi-table-button"});this._footerDOM.appendChild(i),i.id="igv-roi-hide-show-button",i.textContent="Copy Sequence",i.title="One region only of max size 1 mb",this.copySequenceButton=i,wv(this.copySequenceButton,!1),this.boundCopySequenceButtonHandler=async function(e){e.preventDefault(),e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected");if(t.length>0){const e=[];for(let i of t){const{locus:t}=Av(i.dataset.region);e.push(t)}for(let e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");if(this.setTableRowSelectionState(!1),e.length>0){const{chr:t,start:i,end:r}=AF(e[0],this.browser.isSoftclipped()),s=await this.browser.genome.getSequence(t,i,r);await navigator.clipboard.writeText(s)}}}.bind(this),this.copySequenceButton.addEventListener("click",this.boundCopySequenceButtonHandler);const r=t({class:"igv-roi-table-button"});this._footerDOM.appendChild(r),r.id="igv-roi-hide-show-button",r.textContent="Hide Overlays",this.toggleROIButton=r,this.boundToggleDisplayButtonHandler=function(e){e.preventDefault(),e.stopPropagation(),this.roiManager.toggleROIs()}.bind(this),this.toggleROIButton.addEventListener("click",this.boundToggleDisplayButtonHandler)}get roiManager(){return this.browser.roiManager}setTableRowSelectionState(e){super.setTableRowSelectionState(e);const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected");if(t.length>0&&t.length<2){const{locus:e}=Av(t[0].dataset.region),{chr:i,start:r,end:s}=AF(e,this.browser.isSoftclipped());wv(this.copySequenceButton,s-r<1e6)}else wv(this.copySequenceButton,!1)}dispose(){document.removeEventListener("click",this.boundGotoButtonHandler),document.removeEventListener("click",this.boundCopySequenceButtonHandler),document.removeEventListener("click",this.boundToggleDisplayButtonHandler),this.browser.roiTableControl.buttonHandler(!1),super.dispose()}static getColumnFormatConfiguration(e){return!0===e?[{label:"Chr",width:"20%"},{label:"Start",width:"15%"},{label:"End",width:"15%"},{label:"Description",width:"30%"},{label:"ROI Set",width:"20%"}]:[{label:"Chr",width:"25%"},{label:"Start",width:"20%"},{label:"End",width:"20%"},{label:"Description",width:"35%"}]}static gotoButtonHandler(e){e.stopPropagation();const t=this.tableDOM.querySelectorAll(".igv-roi-table-row-selected"),i=[];for(let e of t){const{locus:t}=Av(e.dataset.region);i.push(t)}for(let e of this.tableDOM.querySelectorAll(".igv-roi-table-row"))e.classList.remove("igv-roi-table-row-selected");this.setTableRowSelectionState(!1),i.length>0&&this.browser.search(i.join(" "))}}function wv(e,t){e.style.pointerEvents=t?"auto":"none",e.style.color=Gr(t?"licorice":"silver"),e.style.borderColor=Gr(t?"licorice":"silver")}class bv{constructor(e){this.browser=e,this.roiMenu=new gv(e,e.columnContainer),this.roiTable=new mv(e,e.columnContainer),this.top=0,this.roiSets=[],this.showOverlays=!0,this.boundLocusChangeHandler=Fv.bind(this),e.on("locuschange",this.boundLocusChangeHandler)}async reset(){this.roiSets.length>0&&this.browser.roiTableControl.setVisibility(!0);const e=this.roiSets.map((e=>this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:e})));e.length>0&&await Promise.all(e);const t=await this.getTableRecords();this.roiTable.renderTable(t),this.roiSets.length>0&&this.setOverlayVisibility(this.showOverlays)}setOverlayVisibility(e){const t=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let i=0;i0&&!1===i[0].isVisible&&(this.showOverlays=!1);for(let e of i)!e.name&&e.url&&(e.name=await os(e.url)),e.url&&!e.format&&(e.format=await bf(e)),this.roiSets.push(new Qh(e,t));await this.reset()}clearROIs(){this.roiTable.clearTable();const e=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let t of e)t.remove();for(let e of this.roiSets)e.dispose();this.roiSets=[]}async getTableRecords(){const e=[];for(let t of this.roiSets){const i=t.name||"",r=await t.getAllFeatures();for(let t of Object.keys(r))for(let s of r[t])e.push({setName:i,feature:s})}return e}presentTable(){this.roiTable.present()}async repaintTable(){const e=await this.getTableRecords();this.roiTable.renderTable(e)}dismissTable(){this.roiTable.dismiss()}roiTableIsVisible(){return this.roiTable.isVisible()}async updateUserDefinedROISet(e){let t=await this.getUserDefinedROISet();void 0===t&&(t=this.initializeUserDefinedROISet()),t.addFeature(e),this.setROITableButtonVisibility(!0),await this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:t});const i=await this.getTableRecords();this.roiTable.renderTable(i)}setROITableButtonVisibility(e){this.browser.roiTableControl.setVisibility(e)}toggleROIs(){this.showOverlays=!this.showOverlays,this.setOverlayVisibility(this.showOverlays)}async renderAllROISets(){for(let e of this.roiSets)await this.renderROISet({browser:this.browser,pixelTop:this.top,roiSet:e})}async renderROISet({browser:e,pixelTop:t,roiSet:i}){const r=e.columnContainer.querySelectorAll(".igv-column");for(let s=0;sa)&&e.remove()}const h=await i.getFeatures(o,n,a);if(h)for(let l of h){const h=vv(o,l.start,l.end),{x:d,width:u}=Gh(Math.max(n,l.start),Math.min(a,l.end),n,c),f=r[s].querySelector(yv(h));if(f)f.style.left=`${d}px`,f.style.width=`${u}px`;else{const o=this.createRegionElement(e.columnContainer,t,d,u,i,h,l);r[s].appendChild(o)}}}}createRegionElement(e,i,r,s,o,n,c){const l=t({class:"igv-roi-region"});l.style.top=`${i}px`,l.style.left=`${r}px`,l.style.width=`${s}px`;const h=`${this.getROIRegionTopMargin()}px`;l.style.marginTop=h,l.dataset.color=o.color,l.dataset.region=n,this.showOverlays?l.style.backgroundColor=o.color:l.style.backgroundColor="rgba(0, 0, 0, 0)";const d=t();return l.appendChild(d),d.style.backgroundColor=o.headerColor,d.addEventListener("click",(t=>{t.preventDefault(),t.stopPropagation(),a(t,e),this.roiMenu.present(c,o,t,this,e,l)})),l}updateROIRegionPositions(){const e=`${this.getROIRegionTopMargin()}px`,t=this.browser.columnContainer.querySelectorAll(".igv-column");for(let i=0;inew Set(["ideogram","ruler"]).has(e.type))),[t,i]=e.map((e=>e.trackView.viewports[0].viewportElement)).map((e=>function(e){const t=window.getComputedStyle(e),i=parseInt(t.marginTop),r=parseInt(t.marginBottom),{top:s,bottom:o,height:n}=e.getBoundingClientRect();return{top:Math.floor(s)-i,bottom:Math.floor(o)+r,height:Math.floor(n)+i+r}}(e)));return(t?t.height:0)+(i?i.height:0)+-.5}renderSVGContext(e,t,{deltaX:i,deltaY:r}){for(const s of e.querySelectorAll(".igv-roi-region")){const{x:e,y:o,width:n,height:a}=s.getBoundingClientRect();t.fillStyle=s.style.backgroundColor,t.fillRect(e-i,o+r,n,a);const c=s.querySelector("div"),{x:l,y:h,width:d,height:u}=c.getBoundingClientRect();t.fillStyle=c.style.backgroundColor,t.fillRect(l-i,h+r,d,u)}}getUserDefinedROISet(){return this.roiSets.find((e=>!0===e.isUserDefined))}deleteUserDefinedROISet(){this.roiSets=this.roiSets.filter((e=>!0!==e.isUserDefined))}initializeUserDefinedROISet(){const e=new Qh({name:"user defined",isUserDefined:!0,features:[]},this.browser.genome);return this.roiSets.push(e),e}async deleteRegionWithKey(e,t){t.querySelectorAll(yv(e)).forEach((e=>e.remove()));0===(await this.getTableRecords()).length&&(this.browser.roiTableControl.buttonHandler(!1),this.setROITableButtonVisibility(!1))}toJSON(){return this.roiSets.map((e=>e.toJSON()))}dispose(){this.browser.off("locuschange",this.boundLocusChangeHandler);const e=this.browser.columnContainer.querySelectorAll(".igv-roi-region");for(let t of e)t.remove();this.roiMenu&&this.roiMenu.dispose(),this.roiTable&&this.roiTable.dispose();for(let e of this.roiSets)e.dispose();for(let e of Object.keys(this))this[e]=void 0}}function Fv(){this.renderAllROISets()}function vv(e,t,i){return`${e}-${t}-${i}`}function yv(e){return`[data-region="${e}"]`}function Av(e){let t=e.split("-"),i=parseInt(t.pop()),r=parseInt(t.pop()),s=t.join("-");return{chr:s,start:r,end:i,locus:`${s}:${r}-${i}`,bedRecord:`${s}\t${r}\t${i}`}}class Cv{constructor(e,t){this.name=e.name,this.featureSource=e.featureSource||El(e,t),this.color=e.color||qh}async getFeatures(e,t,i){return this.featureSource.getFeatures({chr:e,start:t,end:i})}draw(e){const{context:t,bpPerPixel:i,bpStart:r,pixelTop:s,pixelHeight:o,pixelWidth:n,features:a}=e;if(!a)return;const c=r+n*i+1;for(let{start:e,end:n}of a){if(nc)break;const{x:a,width:l}=Gh(e,n,r,i);Co.fillRect(t,a,s,l,o,{fillStyle:this.color})}}}class _v{constructor(e){this.config=e,this.url=e.path||e.url}async read(e,t){const i={start:e,size:t};return Rr.loadArrayBuffer(this.url,{range:i})}}class xv{constructor(e){this.file=e}async read(e,t){const i=this.file;return void 0!==e?i.slice(e,e+t).arrayBuffer():i.arrayBuffer()}}class kv{constructor(e,t){this.file=e,this.rateLimiter=t}async read(e,t){const i=this.file,r=this.rateLimiter;return new Promise((function(s,o){r.limiter((async function(i){try{const r=await i.read(e,t);s(r)}catch(e){o(e)}}))(i)}))}}class Iv{constructor(e){this.file=e.file,this.size=e.size||64e3,this.position=0,this.bufferStart=0,this.bufferLength=0,this.buffer=void 0}async read(e,t){const i=e,r=e+t,s=this.bufferStart,o=this.bufferStart+this.bufferLength;if(t>this.size)return this.buffer=void 0,this.bufferStart=0,this.bufferLength=0,this.file.read(e,t);if(i>=s&&r<=o){const e=i-s,r=e+t;return this.buffer.slice(e,r)}if(is){const r=s-i,o=await this.file.read(e,r),n=t-r;if(n>0){const e=this.buffer.slice(0,n);return Sv(o,e)}return o}if(!(io))return this.buffer=await this.file.read(e,this.size),this.bufferStart=e,this.bufferLength=this.buffer.byteLength,this.buffer.slice(0,t);{const e=o-i,r=this.bufferLength-e,s=this.buffer.slice(r,this.bufferLength),n=t-e;if(!(n>0))return s;try{this.buffer=await this.file.read(o,this.size),this.bufferStart=o,this.bufferLength=this.buffer.byteLength;const e=this.buffer.slice(0,n);return Sv(s,e)}catch(e){if(e.code&&416===e.code)return s;throw e}}}}var Sv=function(e,t){var i=new Uint8Array(e.byteLength+t.byteLength);return i.set(new Uint8Array(e),0),i.set(new Uint8Array(t),e.byteLength),i.buffer};const Ev=function(e,t){this.littleEndian=void 0===t||t,this.position=0,this.view=e,this.length=e.byteLength};function Nv(e,t){this.block=e,this.offset=t}Ev.prototype.available=function(){return this.length-this.position},Ev.prototype.remLength=function(){return this.length-this.position},Ev.prototype.hasNext=function(){return this.position=0;i--)t=256*t+e[i];else for(i=0;i0&&(r+=String.fromCharCode(i));return r},Ev.prototype.getFixedLengthTrimmedString=function(e){var t,i,r="";for(t=0;t32&&(r+=String.fromCharCode(i));return r},Ev.prototype.getFloat=function(){var e=this.view.getFloat32(this.position,this.littleEndian);return this.position+=4,e},Ev.prototype.getDouble=function(){var e=this.view.getFloat64(this.position,this.littleEndian);return this.position+=8,e},Ev.prototype.skip=function(e){return this.position+=e,this.position},Ev.prototype.getVPointer=function(){var e=this.position,t=this.view.getUint8(e+1)<<8|this.view.getUint8(e),i=4294967296*(255&this.view.getUint8(e+6))+16777216*(255&this.view.getUint8(e+5))+65536*(255&this.view.getUint8(e+4))+256*(255&this.view.getUint8(e+3))+(255&this.view.getUint8(e+2));return this.position+=8,new Nv(i,t)},Nv.prototype.isLessThan=function(e){return this.blocke.block||this.block===e.block&&this.offset>e.offset},Nv.prototype.print=function(){return this.block+":"+this.offset};class Mv{constructor(e,t){this.chr1=e,this.chr2=t}getKey(){return this.chr1.name+"_"+this.chr2.name+"_"+this.zoom.unit+"_"+this.zoom.binSize}getBlockNumbers(e,t,i){if(e.chr==this.chr2&&t.chr===this.chr1){const i=e;e=t,t=i}const r=this.chr1===this.chr2,s=this.zoom.binSize,o=this.blockBinCount,n=this.blockColumnCount;return i<9||!r?function(){const i=e.start/s,a=e.end/s,c=t.start/s,l=t.end/s,h=Math.floor(i/o),d=Math.floor((a-1)/o),u=Math.floor(c/o),f=Math.floor((l-1)/o),p=[];for(let e=u;e<=f;e++)for(let t=h;t<=d;t++){let i;i=r&&e0;){const e=t.getInt(),i=t.getLong(),r=t.getInt();this.blockIndex[e]={filePosition:i,size:r}}}getBlockIndexEntry(e){return this.blockIndex[e]}}class Bv{constructor(e,t,i){this.chr1=e,this.chr2=t,this.bpZoomData=[],this.fragZoomData=[];for(let e of i)"BP"===e.zoom.unit?this.bpZoomData.push(e):this.fragZoomData.push(e)}findZoomForResolution(e,t){const i="FRAG"===t?this.fragZoomData:this.bpZoomData;for(let t=1;tt){const i=e;e=t,t=i}return`${e}_${t}`}static parseMatrix(e,t){const i=new Ev(new DataView(e)),r=i.getInt(),s=i.getInt(),o=t[r],n=t[s];let a=i.getInt();const c=[];for(;a-- >0;){const e=Mv.parseMatrixZoomData(o,n,i);c.push(e)}return new Bv(r,s,c)}}class Dv{constructor(e,t,i){this.bin1=e,this.bin2=t,this.counts=i}getKey(){return this.bin1+"_"+this.bin2}}class Lv{constructor(e=10){this.max=e,this.map=new Map}get(e){let t=this.map.get(e);return t&&(this.map.delete(e),this.map.set(e,t)),t}set(e,t){this.map.has(e)?this.map.delete(e):this.map.size===this.max&&this.map.delete(this.first()),this.map.set(e,t)}has(e){return this.map.has(e)}clear(){this.map.clear()}first(){return this.map.keys().next().value}}class Tv{constructor(e,t,i,r){this.file=e,this.filePosition=t,this.nValues=i,this.dataType=r,this.cache=void 0}async getValues(e,t){if(!this.cache||ethis.cache.end){const i=Math.max(0,e-1e3),r=Math.min(this.nValues,t+1e3),s=this.filePosition+i*this.dataType,o=r-i,n=o*this.dataType,a=await this.file.read(s,n);if(!a)return;const c=new Ev(new DataView(a)),l=[];for(let e=0;e=0||t.indexOf("www.googleapis.com/drive")>0?this.file=new kv(i,Hv):this.file=i}}var t}async init(){this.initialized||(await this.readHeaderAndFooter(),this.initialized=!0)}async getVersion(){if(void 0===this.version){const e=await this.file.read(0,128);if(!e)return;const t=new Ev(new DataView(e));return this.magic=t.getString(),this.version=t.getInt(),this.version}return this.version}async getMetaData(){return await this.init(),this.meta}async readHeaderAndFooter(){let e=await this.file.read(0,16);if(!e||0===e.byteLength)throw Error("File content is empty");let t=new Ev(new DataView(e));if(this.magic=t.getString(),this.version=t.getInt(),this.version<5)throw Error("Unsupported hic version: "+this.version);this.footerPosition=t.getLong(),await this.readFooter();const i=Object.values(this.masterIndex).reduce(((e,t)=>Math.min(e,t.start)),Number.MAX_VALUE),r=i-16;e=await this.file.read(16,r),t=new Ev(new DataView(e)),this.genomeId=t.getString(),this.version>=9&&(this.normVectorIndexPosition=t.getLong(),this.normVectorIndexSize=t.getLong()),this.attributes={};let s=t.getInt();for(;s-- >0;)this.attributes[t.getString()]=t.getString();this.chromosomes=[],this.chromosomeIndexMap={};let o=t.getInt(),n=0;for(;o-- >0;){const e={index:n,name:t.getString(),size:this.version<9?t.getInt():t.getLong()};"all"===e.name.toLowerCase()&&(this.wholeGenomeChromosome=e,this.wholeGenomeResolution=Math.round(2*e.size)),this.chromosomes.push(e),this.chromosomeIndexMap[e.name]=e.index,n++}this.bpResolutions=[];let a=t.getInt();for(;a-- >0;)this.bpResolutions.push(t.getInt());if(this.loadFragData){this.fragResolutions=[];let e=t.getInt();if(e>0)for(;e-- >0;)this.fragResolutions.push(t.getInt())}this.chrAliasTable={};for(let e of Object.keys(this.chromosomeIndexMap))e.startsWith("chr")?this.chrAliasTable[e.substr(3)]=e:"MT"===e?this.chrAliasTable.chrM=e:this.chrAliasTable["chr"+e]=e;this.meta={version:this.version,genome:this.genomeId,chromosomes:this.chromosomes,resolutions:this.bpResolutions}}async readFooter(){const e=this.version<9?8:12;let t=await this.file.read(this.footerPosition,e);if(!t)return null;let i=new Ev(new DataView(t));const r=this.version<9?i.getInt():i.getLong();let s=i.getInt();const o=196*s;for(t=await this.file.read(this.footerPosition+e,Math.min(o,r)),i=new Ev(new DataView(t)),this.masterIndex={};s-- >0;){const e=i.getString(),t=i.getLong(),r=i.getInt();this.masterIndex[e]={start:t,size:r}}if(this.expectedValueVectors={},this.version>5){const e=this.version<9?4:8;this.normExpectedValueVectorsPosition=this.footerPosition+e+r}return this}async printIndexStats(){let e,t=0,i=0;await await this.init();for(let r of Object.keys(this.masterIndex)){const s=this.masterIndex[r];t+=s.size,s.size>i&&(i=s.size,e=r)}console.log(`${i} ${e} ${this.config.url}`)}async getMatrix(e,t){const i=Bv.getKey(e,t);if(this.matrixCache.has(i))return this.matrixCache.get(i);{const r=await this.readMatrix(e,t);return this.matrixCache.set(i,r),r}}async readMatrix(e,t){if(await this.init(),e>t){const i=e;e=t,t=i}const i=Bv.getKey(e,t),r=this.masterIndex[i];if(!r)return;const s=await this.file.read(r.start,r.size);return s?Bv.parseMatrix(s,this.chromosomes):void 0}async getContactRecords(e,t,i,r,s,o=!1){await this.init();const n=this.chromosomeIndexMap[this.getFileChrName(t.chr)],a=this.chromosomeIndexMap[this.getFileChrName(i.chr)];if(n>a||n===a&&t.start>=i.end){const e=t;t=i,i=e}const c=await this.getBlocks(t,i,r,s);if(!c||0===c.length)return[];const l=[],h=t.start/s,d=t.end/s,u=i.start/s,f=i.end/s,p=Math.floor(h),g=Math.ceil(d),m=Math.floor(u),w=Math.ceil(f);for(let n of c)if(n){let a,c,b=e&&"NONE"!==e;const F=this.getFileChrName(t.chr),v=this.getFileChrName(i.chr);if(b){const t=await this.getNormalizationVector(e,F,r,s),i=F===v?t:await this.getNormalizationVector(e,v,r,s);t&&i?(a=await t.getValues(p,g),c=await i.getValues(m,w)):b=!1}for(let e of n.records)if(o||e.bin1>=h&&e.bin1=u&&e.bin210&&(this.percentile95=Qv(n.records,95))}return l}async getBlocks(e,t,i,r){const s=(e,t)=>`${t.getKey()}_${e}`;await this.init();const o=this.getFileChrName(e.chr),n=this.getFileChrName(t.chr),a=this.chromosomeIndexMap[o],c=this.chromosomeIndexMap[n];if(void 0===a)return console.log("No chromosome named: "+e.chr),[];if(void 0===c)return console.log("No chromosome named: "+t.chr),[];const l=await this.getMatrix(a,c);if(!l)return console.log("No matrix for "+e.chr+"-"+t.chr),[];const h=l.getZoomData(r,i);if(!h){let i=`No data avalailble for resolution: ${r} for map ${e.chr}-${t.chr}`;throw new Error(i)}const d=h.getBlockNumbers(e,t,this.version),u=[],f=[];for(let e of d){const t=s(e,h);this.blockCache.has(r,t)?u.push(this.blockCache.get(r,t)):f.push(e)}const p=f.map((e=>this.readBlock(e,h))),g=await Promise.all(p);for(let e of g)e&&this.blockCache.set(r,s(e.blockNumber,h),e);return u.concat(g)}async readBlock(e,t){const i=await t.blockIndex.getBlockIndexEntry(e);if(i){let r=await this.file.read(i.filePosition,i.size);if(!r)return;r=new Yi(new Uint8Array(r)).buffer;const s=new Ev(new DataView(r)),o=s.getInt(),n=[];if(this.version<7)for(let e=0;e0;)this.parseNormVectorEntry(i);return this.normVectorIndex}async readNormExpectedValuesAndNormVectorIndex(){if(await this.init(),void 0===this.normExpectedValueVectorsPosition)return;const e=await this.skipExpectedValues(this.normExpectedValueVectorsPosition);let t=4,i=await this.file.read(e,4);if(0===i.byteLength)return;const r=new Ev(new DataView(i)).getInt(),s={start:e+t,size:30*r};i=await this.file.read(s.start,s.size),this.normalizedExpectedValueVectors={},this.normVectorIndex={},await async function i(r,s){const o=new Ev(new DataView(s));for(;r-- >0;){if(o.available()<100){r++,t+=o.position;const s=Math.max(1e3,30*r),n={start:e+t,size:s},a=await this.file.read(n.start,n.size);return i.call(this,r,a)}this.parseNormVectorEntry(o)}t+=o.position}.call(this,r,i),this.config.nvi=e.toString()+","+t}async skipExpectedValues(e){const t=this.version,i=new Iv({file:this.file,size:256e3}),r={start:e,size:4},s=await i.read(r.start,r.size),o=new Ev(new DataView(s)).getInt();return 0===o?e+4:async function e(r,s){let o={start:r,size:500},n=0,a=r,c=await i.read(o.start,o.size),l=new Ev(new DataView(c));l.getString(),l.getString(),l.getInt();const h=t<9?l.getInt():l.getLong();n+=l.position+h*(t<9?8:4),o={start:r+n,size:4},c=await i.read(o.start,o.size),l=new Ev(new DataView(c));const d=l.getInt();return n+=4+d*(4+(t<9?8:4)),s--,0===s?a+n:e(a+n,s)}(e+4,o)}getZoomIndexForBinSize(e,t){let i;if("BP"===(t=t||"BP"))i=this.bpResolutions;else{if("FRAG"!==t)throw new Error("Invalid unit: "+t);i=this.fragResolutions}for(let t=0;te.counts));i.sort((function(e,t){return e-t}));return i[Math.floor(t/100*e.length)]}class Gv{aliasRecordCache=new Map;constructor(e,t){this.genomeID=e,this.update(e,t)}async preload(){}getChromosomeName(e){return this.aliasRecordCache.has(e)?this.aliasRecordCache.get(e).chr:e}getChromosomeAlias(e,t){const i=this.aliasRecordCache.get(e);return i&&i[t]||e}update(e,t){if(t){const i=[];for(let r of t){if(this.aliasRecordCache.has(r))continue;const t={chr:r};if(i.push(t),r.startsWith("gi|")){const e=Gv.getNCBIName(r);t["ncbi-gi-versioned"]=e;const i=e.lastIndexOf(".");if(i>0){const e=e.substring(0,i);t["ncbi-gi"]=e}}else if("chrM"===r?t.ncbi="MT":"MT"===r?t.ucsc="chrM":r.toLowerCase().startsWith("chr")&&Number.isInteger(Number(r.substring(3)))?t.ncbi=r.substring(3):Number.isInteger(Number(r))&&(t.ucsc="chr"+r),e.startsWith("hg")||e.startsWith("GRCh")||"1kg_ref"===e||"b37"===e)switch(r){case"23":t.ucsc="chrX",t.assembly="X";break;case"24":t.ucsc="chrY",t.assembly="Y";break;case"chrX":t.ncbi="23",t.assembly="X";break;case"chrY":t.ncbi="24",t.assembly="Y";break;case"X":t.ucsc="chrX",t.ncbi="23";break;case"Y":t.ucsc="chrY",t.ncbi="24"}else if(e.startsWith("mm")||e.startsWith("GRCm")||e.startsWith("rheMac"))switch(r){case"21":t.ucsc="chrX",t.assembly="X";break;case"22":t.ucsc="chrY",t.assembly="Y";break;case"chrX":t.ncbi="21",t.assembly="X";break;case"chrY":t.ncbi="22",t.assembly="Y";break;case"X":t.ucsc="chrX",t.ncbi="21";break;case"Y":t.ucsc="chrY",t.ncbi="22"}}for(let e of i){Gv.addCaseAliases(e);for(let t of Object.values(e))this.aliasRecordCache.set(t,e)}}}search(e){return this.aliasRecordCache.get(e)}static getNCBIName(e){const t=e.split("\\|");return t[t.length-1]}static addCaseAliases(e){const t=e.chr.toUpperCase(),i=e.chr.toLowerCase(),r=e.chr.charAt(0).toUpperCase()+e.chr.slice(1);e.chr!==t&&(e._uppercase=t),e.chr!==i&&(e._lowercase=i),e.chr!==r&&(e._cap=r);const s=e.chr.startsWith("chr")?e.chr.substring(3):"chr"+e.chr;e._chrprefix_=s}}class jv{aliasRecordCache=new Map;constructor(e,t,i){(t=t||{}).url=e,this.reader=new Nc(t,i)}async preload(e){await this.reader.preload();for(let t of e)await this.search(t)}getChromosomeName(e){return this.aliasRecordCache.has(e)?this.aliasRecordCache.get(e).chr:e}getChromosomeAlias(e,t){const i=this.aliasRecordCache.get(e);return i&&i[t]||e}async search(e){if(!this.aliasRecordCache.has(e)){const t=await this.reader.search(e);if(t){Gv.addCaseAliases(t);for(let e of Object.keys(t))"start"!==e&&"end"!==e&&this.aliasRecordCache.set(t[e],t)}}return this.aliasRecordCache.get(e)}}class Wv{aliasRecordCache=new Map;constructor(e,t,i){this.aliasURL=e,this.config=t,this.genome=i}async preload(e){}getChromosomeName(e){return this.aliasRecordCache.has(e)?this.aliasRecordCache.get(e).chr:e}getChromosomeAlias(e,t){const i=this.aliasRecordCache.get(e);return i&&i[t]||e}async loadAliases(){const e=await Rr.loadString(this.aliasURL,ts(this.config)),t=v(e),i=t[0];i.startsWith("#")&&(this.headings=i.substring(1).split("\t").map((e=>e.trim())),this.altNameSets=this.headings.slice(1));const r=this.genome.chromosomeNames?new Set(this.genome.chromosomeNames):new Set;for(let e of t)if(!e.startsWith("#")&&e.length>0){const t=e.split("\t");let i=t.find((e=>r.has(e)));i||(i=t[0]);const s={chr:i};Gv.addCaseAliases(s);for(let e=0;enew $v(e.start,e.end,e.name,e.gieStain)))}}class Yv{cytobands=new Map;constructor(e,t){this.url=e,this.config=t}async getCytobands(e){return 0===this.cytobands.size&&await this.#B(),this.cytobands.get(e)}async#B(){let e,t;if(as(this.url)){const t=nr(this.url);e="";const i=t.length;for(let r=0;r0&&this.cytobands.set(t,i)}}function Zv(e){if(!function(e){return t=e.fastaURL,(t&&"string"==typeof t||t instanceof String)&&(e.fastaURL.startsWith("https://igv.org")||["igv.org.genomes","igv.broadinstitute.org","igv.genepattern.org","igvdata.broadinstitute.org","igv-genepattern-org"].some((t=>e.fastaURL.includes(t))));var t}(e)||!Xv[e.id])return;const t=Xv[e.id];t&&(delete e.fastaURL,e.indexURL&&delete e.indexURL,e.twoBitURL=t.twoBitURL,t.twoBitBptURL&&(e.twoBitBptURL=t.twoBitBptURL),t.chromSizesURL&&(e.chromSizesURL=t.chromSizesURL))}const Xv={hs1:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hs1/bigZips/hs1.chrom.sizes.txt"},hg38:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/hg38.chrom.sizes"},hg19:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg19/bigZips/hg19.chrom.sizes"},hg18:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg18/bigZips/hg18.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/hg18/bigZips/hg18.chrom.sizes"},mm39:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm39/bigZips/mm39.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm39/bigZips/mm39.chrom.sizes"},mm10:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm10/bigZips/mm10.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm10/bigZips/mm10.chrom.sizes"},mm9:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm9/bigZips/mm9.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/mm9/bigZips/mm9.chrom.sizes"},rn7:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/015/227/675/GCF_015227675.2/GCF_015227675.2.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/015/227/675/GCF_015227675.2/GCF_015227675.2.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/015/227/675/GCF_015227675.2/GCF_015227675.2.chrom.sizes.txt"},rn6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/895/GCF_000001895.5/GCF_000001895.5.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/895/GCF_000001895.5/GCF_000001895.5.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/895/GCF_000001895.5/GCF_000001895.5.chrom.sizes.txt"},gorGor6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor6/bigZips/gorGor6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor6/bigZips/gorGor6.chrom.sizes"},gorGor4:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor4/bigZips/gorGor4.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/gorGor4/bigZips/gorGor4.chrom.sizes"},panTro6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro6/bigZips/panTro6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro6/bigZips/panTro6.chrom.sizes"},panTro5:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro5/bigZips/panTro5.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro5/bigZips/panTro5.chrom.sizes"},panTro4:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro4/bigZips/panTro4.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panTro4/bigZips/panTro4.chrom.sizes"},macFas5:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/macFas5/bigZips/macFas5.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/macFas5/bigZips/macFas5.chrom.sizes"},panPan2:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panPan2/bigZips/panPan2.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/panPan2/bigZips/panPan2.chrom.sizes"},canFam6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam6/bigZips/canFam6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam6/bigZips/canFam6.chrom.sizes"},canFam5:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam5/bigZips/canFam5.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam5/bigZips/canFam5.chrom.sizes"},canFam4:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam4/bigZips/canFam4.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam4/bigZips/canFam4.chrom.sizes"},canFam3:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam3/bigZips/canFam3.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/canFam3/bigZips/canFam3.chrom.sizes"},bosTau9:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau9/bigZips/bosTau9.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau9/bigZips/bosTau9.chrom.sizes"},bosTau8:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau8/bigZips/bosTau8.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/bosTau8/bigZips/bosTau8.chrom.sizes"},susScr11:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/susScr11/bigZips/susScr11.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/susScr11/bigZips/susScr11.chrom.sizes"},galGal6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/galGal6/bigZips/galGal6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/galGal6/bigZips/galGal6.chrom.sizes"},danRer11:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer11/bigZips/danRer11.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer11/bigZips/danRer11.chrom.sizes"},danRer10:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer10/bigZips/danRer10.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/danRer10/bigZips/danRer10.chrom.sizes"},ce11:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/ce11/bigZips/ce11.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/ce11/bigZips/ce11.chrom.sizes"},dm6:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm6/bigZips/dm6.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm6/bigZips/dm6.chrom.sizes"},dm3:{twoBitURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm3/bigZips/dm3.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/goldenPath/dm3/bigZips/dm3.chrom.sizes"},sacCer3:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/146/045/GCF_000146045.2/GCF_000146045.2.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/146/045/GCF_000146045.2/GCF_000146045.2.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/146/045/GCF_000146045.2/GCF_000146045.2.chrom.sizes.txt"},"GCF_000002945.1":{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/002/945/GCF_000002945.1/GCF_000002945.1.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/002/945/GCF_000002945.1/GCF_000002945.1.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/002/945/GCF_000002945.1/GCF_000002945.1.chrom.sizes.txt"},"GCF_009858895.2":{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/009/858/895/GCF_009858895.2/GCF_009858895.2.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/009/858/895/GCF_009858895.2/GCF_009858895.2.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/009/858/895/GCF_009858895.2/GCF_009858895.2.chrom.sizes.txt"},tair10:{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/735/GCF_000001735.3/GCF_000001735.3.2bit",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCF/000/001/735/GCF_000001735.3/GCF_000001735.3.chrom.sizes.txt"},"GCA_000022165.1":{twoBitURL:"https://hgdownload.soe.ucsc.edu/hubs/GCA/000/022/165/GCA_000022165.1/GCA_000022165.1.2bit",twoBitBptURL:"https://hgdownload.soe.ucsc.edu/hubs/GCA/000/022/165/GCA_000022165.1/GCA_000022165.1.2bit.bpt",chromSizesURL:"https://hgdownload.soe.ucsc.edu/hubs/GCA/000/022/165/GCA_000022165.1/GCA_000022165.1.chrom.sizes.txt"}},Jv=new Map([["1kg_ref","hg18"],["1kg_v37","hg19"],["b37","hg19"]]);class ey{#D;#L=new Map;static async createGenome(e,t){Zv(e);const i=new ey(e,t);return await i.init(),i}constructor(e,t){this.config=e,this.browser=t,this.id=e.id||function(e){return void 0!==e.id?e.id:e.fastaURL&&b(e.fastaURL)&&!e.fastaURL.startsWith("data:")?e.fastaURL:e.fastaURL&&e.fastaURL.name?e.fastaURL.name:""}(e),this.ucscID=e.ucscID||Jv.get(this.id)||this.id,this.blatDB=e.blatDB||this.ucscID,this.name=e.name,this.nameSet=e.nameSet||"ucsc"}async init(){const e=this.config;if(this.sequence=await Zo(e,this.browser),!1!==e.showIdeogram&&!1!==e.wholeGenomeView&&(e.cytobandURL?this.cytobandSource=new Yv(e.cytobandURL,Object.assign({},e)):e.cytobandBbURL&&(this.cytobandSource=new Kv(e.cytobandBbURL,Object.assign({},e),this))),this.sequence.chromosomes?this.chromosomes=this.sequence.chromosomes:e.chromSizesURL?this.chromosomes=await async function(e){const t=new Map;let i;if(as(e)){let t=nr(e);i="";for(let e of t)i+=String.fromCharCode(e)}else i=await Rr.load(e,{});const r=Oo(i);let s=0;for(let e of r){const i=e.split("\t");if(i.length>1){const e=Number.parseInt(i[1]);t.set(i[0],new No(i[0],s++,e))}}return t}(e.chromSizesURL):this.chromosomes=new Map,this.sequence.chromosomeNames?this.chromosomeNames=this.sequence.chromosomeNames:this.chromosomes.size>0&&(this.chromosomeNames=Array.from(this.chromosomes.keys())),e.chromAliasBbURL?this.chromAlias=new jv(e.chromAliasBbURL,Object.assign({},e),this):e.aliasURL?this.chromAlias=new Wv(e.aliasURL,Object.assign({},e),this):this.chromosomeNames&&(this.chromAlias=new Gv(this.id,this.chromosomeNames)),!1!==e.wholeGenomeView&&this.chromosomes.size>0&&(e.chromosomeOrder?(Array.isArray(e.chromosomeOrder)?this.#D=e.chromosomeOrder:this.#D=e.chromosomeOrder.split(",").map((e=>e.trim())),await this.chromAlias.preload(this.#D),this.#D=this.#D.map((e=>this.getChromosomeName(e))).filter((e=>this.chromosomes.has(e)))):(this.#D=function(e){const t=[];let i,r=1;for(let s of e.values()){if(i){if(s.bpLength1,this.wholeGenomeView){const e=this.#D.reduce(((e,t)=>e+this.chromosomes.get(t).bpLength),0);this.chromosomes.set("all",new No("all",0,e))}}get description(){return this.config.description||`${this.id}\n${this.name}`}get infoURL(){return this.config.infoURL}showWholeGenomeView(){return this.wholeGenomeView}toJSON(){return Object.assign({},this.config,{tracks:void 0})}get initialLocus(){return this.config.locus?this.config.locus:this.getHomeChromosomeName()}getHomeChromosomeName(){return this.showWholeGenomeView()&&this.chromosomes.has("all")?"all":this.chromosomeNames?this.chromosomeNames[0]:void 0}getChromosomeName(e){return this.chromAlias?this.chromAlias.getChromosomeName(e,this.chromosomes.keys()):e}getChromosomeDisplayName(e){return this.nameSet&&this.chromAlias&&this.chromAlias.getChromosomeAlias(e,this.nameSet)||e}getChromosome(e){return this.chromAlias&&(e=this.chromAlias.getChromosomeName(e)),this.chromosomes.get(e)}async loadChromosome(e){const t=await this.getAliasRecord(e);if(t&&(e=t.chr),!this.chromosomes.has(e)){let t;const i=await this.sequence.getSequenceRecord(e);i&&(t=new No(e,0,i.bpLength)),this.chromosomes.set(e,t)}return this.chromosomes.get(e)}async getAliasRecord(e){if(this.#L.has(e))return this.#L.get(e);if(this.chromAlias){let t=await this.chromAlias.search(e);if(t||e===e.toLowerCase()||(t=await this.chromAlias.search(e.toLowerCase())),t){const e=t.chr.toUpperCase(),i=t.chr.toLowerCase(),r=t.chr.charAt(0).toUpperCase()+t.chr.slice(1);t.chr!==e&&(t._uppercase=e),t.chr!==i&&(t._lowercase=i),t.chr!==r&&(t._cap=r)}return this.#L.set(e,t),t}}async getCytobands(e){if(this.cytobandSource){const t=this.getChromosomeName(e);return await this.cytobandSource.getCytobands(t)}}getChromosomes(){return this.chromosomes}get wgChromosomeNames(){return this.#D?this.#D.slice():void 0}get showChromosomeWidget(){return this.config.showChromosomeWidget}getGenomeCoordinate(e,t){var i=this.getCumulativeOffset(e);if(void 0!==i)return i+t}getChromosomeCoordinate(e){let t;void 0===this.cumulativeOffsets&&(this.cumulativeOffsets=computeCumulativeOffsets.call(this));let i=0;for(let r of this.#D){const s=this.cumulativeOffsets[r];if(s>e){return{chr:t,position:e-i}}t=r,i=s}return{chr:this.#D[this.#D.length-1],position:0}}getCumulativeOffset(e){void 0===this.cumulativeOffsets&&(this.cumulativeOffsets=function(){let e={},t=0;for(let i of this.#D){e[i]=Math.floor(t);t+=this.getChromosome(i).bpLength}return e}.call(this));const t=this.getChromosomeName(e);return this.cumulativeOffsets[t]}getGenomeLength(){if(!this.bpLength){let e=0;for(let t of this.#D){e+=this.chromosomes.get(t).bpLength}this.bpLength=e}return this.bpLength}async getSequence(e,t,i){return e=this.getChromosomeName(e),this.sequence.getSequence(e,t,i)}getSequenceInterval(e,t,i){return"function"==typeof this.sequence.getSequenceInterval?this.sequence.getSequenceInterval(e,t,i):void 0}getHubURLs(){return this.config.hubs}}class ty{constructor(){this.clear()}clear(){this.phenotypeColors=new Map,this.snps=new Set,this.qtl=null}isEmpty(){return 0===this.phenotypeColors.size&&0===this.snps.size&&null===this.qtl}addSnp(e){e=e.toUpperCase(),this.snps.add(e)}addPhenotype(e){e=e.toUpperCase();const t=this.phenotypeColors.size;if(!this.phenotypeColors.has(e.toUpperCase())){const i=t0&&(e.phenotypes=Array.from(this.phenotypeColors.keys())),this.snps.size>0&&(e.snps=Array.from(this.snps)),this.qtl&&(e.qtl=this.qtl),e}static fromJSON(e){const t=new ty;if(e.phenotypes)for(let i of e.phenotypes)t.addPhenotype(i);if(e.snps)for(let i of e.snps)t.addSnp(i);return e.qtl&&(t.qtl=e.qtl),t}}const iy=[];iy.push("rgb(228,26,28)"),iy.push("rgb(55,126,184)"),iy.push("rgb(77,175,74)"),iy.push("rgb(166,86,40)"),iy.push("rgb(152,78,163)"),iy.push("rgb(255,127,0)"),iy.push("rgb(247,129,191)"),iy.push("rgb(255,255,51)"),iy.push("rgb(102,194,165)"),iy.push("rgb(252,141,98)"),iy.push("rgb(141, 160, 203)"),iy.push("rgb(231, 138, 195)"),iy.push("rgb(166, 216, 84)"),iy.push("rgb(255, 217, 47)"),iy.push("rgb(229, 196, 148)"),iy.push("rgb( 141, 211, 199)"),iy.push("rgb(255, 255, 179)"),iy.push("rgb(190, 186, 218)"),iy.push("rgb(251, 128, 114)"),iy.push("rgb(128, 177, 211)"),iy.push("rgb(253, 180, 98)"),iy.push("rgb(179, 222, 105)"),iy.push("rgb(252, 205, 229)"),iy.push("rgb(188, 128, 189)"),iy.push("rgb(204, 235, 197)"),iy.push("rgb(255, 237, 111)");class ry{constructor(e,i){this.browser=i,this.columnContainer=e,this.horizontalGuide=t({class:"igv-cursor-guide-horizontal"}),e.appendChild(this.horizontalGuide),this.verticalGuide=t({class:"igv-cursor-guide-vertical"}),e.appendChild(this.verticalGuide),this.addMouseHandler(i),this.setVisibility(i.config.showCursorGuide)}addMouseHandler(e){this.boundMouseMoveHandler=function(t){t.target.tagName;const{x:i,y:r}=a(t,this.columnContainer);if(this.horizontalGuide.style.top=`${r}px`,"CANVAS"===t.target.tagName){const r=function(e,t){for(;e.parentElement;){if(e.parentElement.classList.contains(t))return e.parentElement;e=e.parentElement}return}(t.target,"igv-viewport");if(r&&e.getRulerTrackView()){this.verticalGuide.style.left=`${i}px`;const s=e.root.querySelectorAll(".igv-column");let o;const n=r.parentElement;for(let e=0;e',this._output=document.createRange().createContextualFragment(s).firstChild,this.input_container.appendChild(this._output);const o=t({class:"igv-ui-generic-dialog-ok-cancel"});this.container.appendChild(o),this.ok=t(),o.appendChild(this.ok),this.ok.textContent="OK",this.cancel=t(),o.appendChild(this.cancel),this.cancel.textContent="Cancel",r(this.container),this._input.addEventListener("input",(()=>{const e=parseFloat(this._input.value)/this._scaleFactor;this.callback(e),this._output.value=`${e.toFixed(this._precision)}`}),!1),this.ok.addEventListener("click",(()=>{if("function"==typeof this.callback){const e=parseFloat(this._input.value)/this._scaleFactor;this.callback(e),this.callback=void 0}this._input.value=void 0,r(this.container)}));const n=()=>{this._input.value=void 0,r(this.container)};this.cancel.addEventListener("click",n),u(i,n),p(this.container,i)}get value(){return vo.sanitize(this._input.value)}present(e,t){this.label.textContent=e.label,this._scaleFactor=e.scaleFactor,this._precision=e.precision||2;const[i,r,o]=[e.min,e.max,e.value].map((e=>Math.floor(this._scaleFactor*e).toString()));this._input.min=i,this._input.max=r,this._input.value=o;const n=parseFloat(o)/this._scaleFactor;this._output.value=`${n.toFixed(this._precision)}`,this.callback=e.callback||e.click,s(this.container),this.clampLocation(t.clientX,t.clientY)}clampLocation(e,t){const{width:i,height:r}=this.container.getBoundingClientRect(),s=window.innerHeight,o=window.innerWidth,n=Math.min(s-r,t),a=Math.min(o-i,e);this.container.style.left=`${a}px`,this.container.style.top=`${n}px`}}class oy{constructor(){this.eventHandlers=new Map}on(e,t){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(t)}un(e,t){this.off(e,t)}off(e,t){if(e)if(t){const i=this.eventHandlers.get(e);if(i&&0!==i.length){const e=i.indexOf(t);-1!==e&&i.splice(e,1)}else console.warn("No handlers to remove for event: "+e)}else this.eventHandlers.delete(e);else this.eventHandlers.clear()}emit(e,t,i){const r=this.eventHandlers.get(e);if(void 0===r||0===r.length)return;const s=i||globalThis;return r.map((function(e){return e.apply(s,t)}))}}class ny{qtlSelections=new ty;constructor(e,i){this.config=e,this.guid=n(),this.namespace=".browser_"+this.guid,this.parent=i,this.eventEmitter=new oy;let r=i.shadowRoot;if(!r){r=i.attachShadow({mode:"open"});const e=new CSSStyleSheet;e.replaceSync('.igv-ui-dropdown{cursor:default;position:absolute;top:0;left:0;z-index:2048;border-color:#7f7f7f;border-style:solid;border-width:1px;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;background-color:#fff}.igv-ui-dropdown>div{overflow-y:auto;overflow-x:hidden;background-color:#fff}.igv-ui-dropdown>div>div{padding:4px;width:100%;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:1px;background-color:#fff}.igv-ui-dropdown>div>div:last-child{border-bottom-color:rgba(0,0,0,0);border-bottom-width:0}.igv-ui-dropdown>div>div:hover{cursor:pointer;background-color:rgba(0,0,0,.04)}.igv-ui-popover{cursor:default;position:absolute;z-index:2048;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:1px;font-family:"Open Sans",sans-serif;font-size:small;background-color:#fff}.igv-ui-popover>div:first-child{display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;width:100%;height:24px;cursor:move;border-top-width:0;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-popover>div:first-child>div:first-child{margin-left:4px}.igv-ui-popover>div:first-child>div:last-child{margin-right:4px;height:12px;width:12px;color:#7f7f7f}.igv-ui-popover>div:first-child>div:last-child:hover{cursor:pointer;color:#444}.igv-ui-popover>div:last-child{user-select:text;overflow-y:auto;overflow-x:hidden;max-height:400px;max-width:800px;background-color:#fff;border-bottom-width:0;border-bottom-left-radius:5px;border-bottom-right-radius:5px}.igv-ui-popover>div:last-child>div{margin-left:4px;margin-right:4px;min-width:220px;overflow-x:hidden;text-overflow:ellipsis;white-space:nowrap}.igv-ui-popover>div:last-child>div>span{font-weight:bolder}.igv-ui-popover>div:last-child hr{width:100%}.igv-track-label-popover{position:absolute;z-index:2048;border:1px solid #7f7f7f;border-radius:5px;background:#fff;font-family:"Open Sans",sans-serif;font-size:small;min-width:260px;max-width:800px;box-shadow:0 2px 8px rgba(0,0,0,.12);user-select:text}.igv-track-label-popover__header{display:flex;align-items:center;justify-content:space-between;height:24px;background:#eee;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom:1px solid #7f7f7f;padding:0 8px;cursor:move}.igv-track-label-popover__title{font-weight:bold;font-size:1em;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.igv-track-label-popover__close{width:14px;height:14px;color:#7f7f7f;display:flex;align-items:center;justify-content:center;border-radius:2px;cursor:pointer;transition:background .2s,color .2s;margin-left:8px}.igv-track-label-popover__close svg{width:14px;height:14px}.igv-track-label-popover__close:hover,.igv-track-label-popover__close:focus{background:#ddd;color:#444;outline:none}.igv-track-label-popover__body{max-height:400px;overflow-y:auto;padding:8px 0;background:#fff;border-bottom-left-radius:5px;border-bottom-right-radius:5px}.igv-track-label-popover__row{display:flex;align-items:baseline;margin:0 12px 4px 12px;min-width:220px;white-space:nowrap;overflow-x:hidden;text-overflow:ellipsis}.igv-track-label-popover__key{font-weight:bold;margin-right:.5em}.igv-track-label-popover__value{font-weight:normal;flex:1 1 auto;overflow-x:hidden;text-overflow:ellipsis}.igv-track-label-popover hr{width:100%;border:none;border-top:1px solid #7f7f7f;margin:8px 0}.igv-ui-alert-dialog-container{position:fixed;top:20%;left:50%;transform:translateX(-50%);z-index:2048;box-sizing:content-box;width:400px;height:200px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;outline:none;font-family:"Open Sans",sans-serif;font-size:15px;font-weight:400;background-color:#fff;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:space-between;align-items:center}.igv-ui-alert-dialog-container>div:first-child{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-alert-dialog-container>div:first-child div:first-child{padding-left:8px}.igv-ui-alert-dialog-container .igv-ui-alert-dialog-body{-webkit-user-select:text;-moz-user-select:text;-ms-user-select:text;user-select:text;color:#373737;width:100%;height:calc(100% - 24px - 64px);overflow-y:scroll}.igv-ui-alert-dialog-container .igv-ui-alert-dialog-body .igv-ui-alert-dialog-body-copy{margin:16px;width:auto;height:auto;overflow-wrap:break-word;word-break:break-word;background-color:#fff;border:unset}.igv-ui-alert-dialog-container>div:last-child{width:100%;margin-bottom:10px;background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-ui-alert-dialog-container>div:last-child div{margin:unset;width:40px;height:30px;line-height:30px;text-align:center;color:#fff;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;border-color:#2b81af;border-style:solid;border-width:thin;border-radius:4px;background-color:#2b81af}.igv-ui-alert-dialog-container>div:last-child div:hover{cursor:pointer;border-color:#25597f;background-color:#25597f}.igv-ui-generic-dialog-container{box-sizing:content-box;position:fixed;top:20%;left:75%;z-index:2048;background-color:#fff;cursor:pointer;width:300px;height:fit-content;padding-bottom:16px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-header div:hover{cursor:pointer;color:#444}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-one-liner{color:#373737;width:95%;line-height:24px;text-align:left;margin-top:8px;padding-left:8px;overflow-wrap:break-word;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input{margin-top:8px;width:95%;height:24px;color:#373737;line-height:24px;padding-left:8px;background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input>div{width:fit-content;height:100%;font-size:16px;text-align:right;padding-right:8px;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-label-input input{width:50%;font-size:16px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input{margin-top:8px;width:calc(100% - 16px);height:24px;color:#373737;line-height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input input{font-size:16px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input input[type=range]{width:70%;-webkit-appearance:none;background:linear-gradient(90deg, white, black);outline:none;margin:0}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-input output{display:block;height:100%;width:20%;font-size:16px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel{width:100%;height:28px;padding-top:16px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div{color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:first-child{margin-left:32px;margin-right:0;background-color:#5ea4e0}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:last-child{margin-left:0;margin-right:32px;background-color:#c4c4c4}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-ui-generic-dialog-container .igv-ui-generic-dialog-ok-cancel>div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-ui-generic-container{position:fixed;cursor:pointer;background-color:#fff;z-index:2048;box-sizing:content-box;width:300px;height:200px;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-ui-generic-container>div:nth-child(1){cursor:move;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;height:24px;width:100%;background-color:#ddd}.igv-ui-generic-container>div:nth-child(1)>div{display:block;color:#5f5f5f;cursor:pointer;width:14px;height:14px;margin-right:8px;margin-bottom:4px}.igv-ui-colorpicker-container{background-color:#eee;height:fit-content;flex-direction:column;flex-wrap:nowrap}.igv-ui-colorpicker-container>div:nth-child(2){display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-ui-colorpicker-container>div:nth-child(3){box-sizing:border-box;position:relative;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;padding:.5rem;font-family:"Open Sans",sans-serif;font-size:1rem;font-weight:400;width:100%;border-top-style:solid;border-top-width:thin;border-top-color:#373737}.igv-ui-colorpicker-container>div:nth-child(4){width:100%;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-ui-color-swatch{position:relative;box-sizing:content-box;display:flex;flex-flow:row;flex-wrap:wrap;justify-content:center;align-items:center;margin:2px;width:32px;height:32px;border-style:solid;border-width:0;border-color:#fff;border-radius:3px}.igv-ui-color-swatch-shim{cursor:pointer;position:relative;box-sizing:content-box;display:flex;flex-flow:row;flex-wrap:wrap;justify-content:center;align-items:center;width:32px;height:32px;background-color:#fff;border-style:solid;border-width:thin;border-color:#fff;border-radius:4px}.igv-ui-dialog{z-index:2048;position:fixed;width:fit-content;height:fit-content;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;background-color:#fff;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400}.igv-ui-dialog .igv-ui-dialog-header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-ui-dialog .igv-ui-dialog-header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-ui-dialog .igv-ui-dialog-header div:hover{cursor:pointer;color:#444}.igv-ui-dialog .igv-ui-dialog-one-liner{width:95%;height:24px;line-height:24px;text-align:left;margin:8px;overflow-wrap:break-word;background-color:#fff;font-weight:bold}.igv-ui-dialog .igv-ui-dialog-ok-cancel{width:100%;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-dialog .igv-ui-dialog-ok-cancel div{margin:16px;margin-top:32px;color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:first-child{background-color:#5ea4e0}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:last-child{background-color:#c4c4c4}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-ui-dialog .igv-ui-dialog-ok-cancel div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-ui-dialog .igv-ui-dialog-ok{width:100%;height:36px;margin-top:32px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-ui-dialog .igv-ui-dialog-ok div{width:98px;height:36px;line-height:36px;text-align:center;color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;border-color:#fff;border-style:solid;border-width:thin;border-radius:4px;background-color:#2b81af}.igv-ui-dialog .igv-ui-dialog-ok div:hover{cursor:pointer;background-color:#25597f}.igv-ui-panel,.igv-ui-panel-row,.igv-ui-panel-column{z-index:2048;background-color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;justify-content:flex-start;align-items:flex-start}.igv-ui-panel-column{display:flex;flex-direction:column}.igv-ui-panel-row{display:flex;flex-direction:row}.igv-ui-textbox{background-color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;justify-content:flex-start;align-items:flex-start}.igv-ui-table{background-color:#fff}.igv-ui-table thead{position:sticky;top:0}.igv-ui-table th{text-align:left}.igv-ui-table td{padding-right:20px}.igv-ui-table tr:hover{background-color:#add8e6}.igv-roi-seg-filter-dialog{box-sizing:content-box;position:fixed;top:20%;left:75%;transform:translateX(-50%);z-index:2048;background-color:#fff;cursor:pointer;width:350px;height:fit-content;padding-bottom:16px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-roi-seg-filter-dialog__header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:5px;border-top-right-radius:5px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-roi-seg-filter-dialog__header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-roi-seg-filter-dialog__header div:hover{cursor:pointer;color:#444}.igv-roi-seg-filter-dialog__radio-group{margin-top:8px;display:flex;flex-direction:column;justify-content:flex-start;align-items:flex-start}.igv-roi-seg-filter-dialog__radio-group label{display:flex;align-items:center;gap:4px;cursor:pointer}.igv-roi-seg-filter-dialog__radio-group input[type=radio]{cursor:pointer}.igv-roi-seg-filter-dialog__radio-group .op{display:flex;flex-direction:row;justify-content:flex-start;align-items:center;margin-left:16px;margin-bottom:8px;gap:2px}.igv-roi-seg-filter-dialog__radio-group .op input[type=radio]{display:block;margin:0}.igv-roi-seg-filter-dialog__radio-group .op label{display:block;margin-left:4px}.igv-roi-seg-filter-dialog__one-liner{color:#373737;width:95%;line-height:24px;text-align:left;margin-top:8px;padding-left:8px;overflow-wrap:break-word;background-color:#fff}.igv-roi-seg-filter-dialog__input{margin-top:8px;width:80%;height:24px;color:#373737;line-height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-roi-seg-filter-dialog__input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-roi-seg-filter-dialog__input input{font-size:16px}.igv-roi-seg-filter-dialog__ok-cancel{width:100%;height:28px;padding-top:16px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-roi-seg-filter-dialog__ok-cancel>div{color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child{margin-left:32px;margin-right:0;background-color:#5ea4e0}.igv-roi-seg-filter-dialog__ok-cancel>div:last-child{margin-left:0;margin-right:32px;background-color:#c4c4c4}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child.disabled{cursor:not-allowed;background-color:#ccc;opacity:.6}.igv-roi-seg-filter-dialog__ok-cancel>div:first-child.disabled:hover{cursor:not-allowed;background-color:#ccc}.igv-roi-seg-filter-dialog__ok-cancel>div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-clear-filters__container{font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;display:flex;flex-direction:column;max-width:300px;background-color:#fff;padding:12px;gap:8px;border-color:#7f7f7f;border-radius:5px;border-style:solid;border-width:thin}.igv-clear-filters__row{display:flex;align-items:flex-start;padding:12px;gap:12px;cursor:pointer}.igv-clear-filters__row:last-of-type{border-bottom:none}.igv-clear-filters__track-container{border-bottom:1px solid #7f7f7f;padding-bottom:8px;margin-bottom:8px}.igv-clear-filters__track-container:last-of-type{border-bottom:none;margin-bottom:0}.igv-clear-filters__track-header{display:flex;align-items:center;padding:8px 12px;gap:12px;background-color:#f5f5f5;border-radius:4px;margin-bottom:4px;font-weight:500;font-size:14px}.igv-clear-filters__track-name{color:#333;font-weight:600}.igv-clear-filters__filter-checkbox{flex:0 0 16px;width:16px;height:16px;margin-top:2px;cursor:pointer}.igv-clear-filters__checkbox{flex:0 0 16px;width:16px;height:16px;margin-top:2px;cursor:pointer}.igv-clear-filters__content{display:flex;flex-direction:row;flex:1;gap:4px}.igv-clear-filters__description{color:#333;font-size:14px;line-height:1.4}.igv-clear-filters__region{color:#666;font-family:monospace;font-size:12px;line-height:1.4}.igv-clear-filters__button-container{display:flex;gap:8px;margin-top:8px}.igv-clear-filters__button{display:flex;align-items:center;justify-content:center;flex:1;padding:10px;background-color:#5ea4e0;color:#fff;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px;cursor:pointer;font-size:14px;font-weight:400;transition:background-color .2s ease}.igv-clear-filters__button:hover{background-color:#3b5c7f}.igv-clear-filters__button--cancel{background-color:#c4c4c4}.igv-clear-filters__button--cancel:hover{background-color:#7f7f7f}.igv-navbar{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;box-sizing:border-box;width:100%;color:#444;font-size:12px;font-family:"Open Sans",sans-serif;font-weight:400;line-height:32px;padding-left:8px;padding-right:8px;margin-top:2px;margin-bottom:6px;height:32px;border-style:solid;border-radius:3px;border-width:thin;border-color:#bfbfbf;background-color:#f3f3f3}.igv-navbar .igv-navbar-left-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;height:32px;line-height:32px}.igv-navbar .igv-navbar-left-container .igv-logo{width:34px;height:32px;margin-right:8px}.igv-navbar .igv-navbar-left-container .igv-current-genome{height:32px;margin-left:4px;margin-right:4px;user-select:none;line-height:32px;vertical-align:middle;text-align:center}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;height:100%}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-chromosome-select-widget-container{display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:space-around;align-items:center;height:100%;width:125px;margin-right:4px}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-chromosome-select-widget-container select{display:block;cursor:pointer;width:100px;height:75%;outline:none;font-size:12px;font-family:"Open Sans",sans-serif;font-weight:400}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center;margin-left:8px;height:22px}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;width:240px;height:22px;line-height:22px}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container input.igv-search-input{cursor:text;width:85%;height:22px;line-height:22px;font-size:12px;font-family:"Open Sans",sans-serif;font-weight:400;text-align:left;padding-left:8px;margin-right:8px;outline:none;border-style:solid;border-radius:3px;border-width:thin;border-color:#bfbfbf;background-color:#fff}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-search-container .igv-search-icon-container{cursor:pointer;height:16px;width:16px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-navbar .igv-navbar-left-container .igv-navbar-genomic-location .igv-locus-size-group .igv-windowsize-panel-container{margin-left:4px;user-select:none}.igv-navbar .igv-navbar-right-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center}.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container{position:relative;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-navbar .igv-navbar-right-container .igv-navbar-toggle-button-container-hidden{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;height:100%}.igv-navbar .igv-navbar-right-container .igv-zoom-widget{color:#737373;font-size:18px;margin-left:8px;user-select:none;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div{cursor:pointer;margin-left:unset;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:first-child{height:20px;width:20px;margin-left:unset;margin-right:4px}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:last-child{height:20px;width:20px;margin-left:4px;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget div:nth-child(even){display:block;height:fit-content}.igv-navbar .igv-navbar-right-container .igv-zoom-widget input{display:block;width:125px}.igv-navbar .igv-navbar-right-container .igv-zoom-widget svg{display:block}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900{color:#737373;font-size:18px;height:32px;line-height:32px;margin-left:8px;user-select:none;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div{cursor:pointer;margin-left:unset;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:first-child{height:20px;width:20px;margin-left:unset;margin-right:4px}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:last-child{height:20px;width:20px;margin-left:4px;margin-right:unset}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 div:nth-child(even){width:0;height:0;display:none}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 input{width:0;height:0;display:none}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-900 svg{display:block}.igv-navbar .igv-navbar-right-container .igv-zoom-widget-hidden{display:none}.igv-navbar-button{display:block;box-sizing:unset;padding-left:6px;padding-right:6px;height:18px;text-transform:capitalize;user-select:none;line-height:18px;text-align:center;vertical-align:middle;font-family:"Open Sans",sans-serif;font-size:11px;font-weight:200;color:#737373;background-color:#f3f3f3;border-color:#737373;border-style:solid;border-width:thin;border-radius:6px}.igv-navbar-button:hover{cursor:pointer}.igv-navbar-button-clicked{color:#fff;background-color:#737373}.igv-navbar-icon-button{cursor:pointer;position:relative;width:24px;height:24px;margin-left:4px;margin-right:4px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-icon-button>div:first-child{z-index:512;position:absolute;top:36px;left:-18px;width:24px;height:24px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-icon-button>div:last-child{z-index:512;position:absolute;top:36px;left:18px;width:24px;height:24px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-text-button{cursor:pointer;position:relative;margin-left:2px;margin-right:2px;border:none;display:flex;justify-content:center;align-items:center}.igv-navbar-text-button>div:nth-child(2){z-index:512;position:absolute;top:36px;left:0;width:38px;height:18px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}.igv-navbar-text-button>div:nth-child(3){z-index:512;position:absolute;top:36px;left:42px;width:38px;height:18px;border:none;background-size:contain;background-repeat:no-repeat;background-position:center}#igv-text-button-label{text-anchor:middle;dominant-baseline:middle}.igv-navbar-text-button-svg-inactive rect{stroke:#737373;fill:#fff}.igv-navbar-text-button-svg-inactive text{fill:#737373}.igv-navbar-text-button-svg-inactive tspan{dominant-baseline:middle}.igv-navbar-text-button-svg-hover rect{stroke:#737373;fill:#737373}.igv-navbar-text-button-svg-hover text{fill:#fff}.igv-navbar-text-button-svg-hover tspan{dominant-baseline:middle}#igv-save-svg-group rect{stroke:#737373;fill:#fff}#igv-save-svg-group text{fill:#737373}#igv-save-svg-group:hover rect{stroke:#737373;fill:#737373}#igv-save-svg-group:hover text{fill:#fff}#igv-save-png-group rect{stroke:#737373;fill:#fff}#igv-save-png-group text{fill:#737373}#igv-save-png-group:hover rect{stroke:#737373;fill:#737373}#igv-save-png-group:hover text{fill:#fff}.igv-zoom-in-notice-container{z-index:256;position:absolute;top:8px;left:50%;transform:translate(-50%, 0%);display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:center;align-items:center;background-color:#fff}.igv-zoom-in-notice-container>div{padding-left:4px;padding-right:4px;padding-top:2px;padding-bottom:2px;width:100%;height:100%;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;color:#3f3f3f}.igv-zoom-in-notice{position:absolute;top:10px;left:50%}.igv-zoom-in-notice div{position:relative;left:-50%;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;color:#3f3f3f;background-color:hsla(0,0%,100%,.51);z-index:64}.igv-container-spinner{position:absolute;top:90%;left:50%;transform:translate(-50%, -50%);z-index:1024;width:24px;height:24px;pointer-events:none;color:#737373}.igv-multi-locus-close-button{position:absolute;top:2px;right:0;padding-left:2px;padding-right:2px;width:12px;height:12px;color:#666;background-color:#fff;z-index:1000}.igv-multi-locus-close-button>svg{vertical-align:top}.igv-multi-locus-close-button:hover{cursor:pointer;color:#434343}.igv-multi-locus-ruler-label{z-index:64;position:absolute;top:2px;left:0;width:100%;height:12px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-multi-locus-ruler-label>div{font-family:"Open Sans",sans-serif;font-size:12px;color:#101010;background-color:#fff}.igv-multi-locus-ruler-label>div{cursor:pointer}.igv-multi-locus-ruler-label-square-dot{z-index:64;position:absolute;left:50%;top:5%;transform:translate(-50%, 0%);background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-multi-locus-ruler-label-square-dot>div:first-child{width:14px;height:14px}.igv-multi-locus-ruler-label-square-dot>div:last-child{margin-left:16px;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;color:#101010}.igv-ruler-sweeper{display:none;pointer-events:none;position:absolute;top:26px;bottom:0;left:0;width:0;z-index:99999;background-color:rgba(68,134,247,.25)}.igv-ruler-tooltip{pointer-events:none;z-index:128;position:absolute;top:0;left:0;width:1px;height:32px;background-color:rgba(0,0,0,0);display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-ruler-tooltip>div{pointer-events:none;width:128px;height:auto;padding:1px;color:#373737;font-size:10px;font-family:"Open Sans",sans-serif;font-weight:400;background-color:#fff;border-style:solid;border-width:thin;border-color:#373737}.igv-track-label{position:absolute;left:8px;top:8px;width:auto;height:auto;max-width:50%;padding-left:4px;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;text-align:center;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-color:#444;border-radius:2px;border-style:solid;border-width:thin;background-color:#fff;z-index:128;cursor:pointer}.igv-track-label:hover,.igv-track-label:focus,.igv-track-label:active{background-color:#e8e8e8}.igv-track-label-popup-shim{position:absolute;right:8px;top:8px;width:auto;height:auto;max-width:50%;padding-left:4px;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;text-align:center;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-color:#444;border-radius:2px;border-style:solid;border-width:thin;background-color:#fff;z-index:128}.igv-attribute-group-label{position:absolute;right:5px;z-index:128;width:auto;height:auto;max-width:50%;padding-left:4px;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;text-align:center;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-color:#444;border-radius:2px;border-style:solid;border-width:thin;background-color:#fff}.igv-attribute-group-line{position:absolute;left:0px;width:100%;height:1px;background-color:rgba(0,0,0,0);border-top:1px dotted #666;pointer-events:none;z-index:127}.igv-center-line{display:none;pointer-events:none;position:absolute;top:0;bottom:0;left:50%;transform:translateX(-50%);z-index:8;user-select:none;-moz-user-select:none;-webkit-user-select:none;border-left-style:dashed;border-left-width:thin;border-right-style:dashed;border-right-width:thin}.igv-center-line-wide{background-color:rgba(0,0,0,0);border-left-color:rgba(127,127,127,.51);border-right-color:rgba(127,127,127,.51)}.igv-center-line-thin{background-color:rgba(0,0,0,0);border-left-color:rgba(127,127,127,.51);border-right-color:rgba(0,0,0,0)}.igv-cursor-guide-horizontal{display:none;pointer-events:none;user-select:none;-moz-user-select:none;-webkit-user-select:none;position:absolute;left:0;right:0;top:50%;height:1px;z-index:32;margin-left:50px;margin-right:54px;border-top-style:dotted;border-top-width:thin;border-top-color:rgba(127,127,127,.76)}.igv-cursor-guide-vertical{pointer-events:none;user-select:none;-moz-user-select:none;-webkit-user-select:none;position:absolute;top:0;bottom:0;left:50%;width:1px;z-index:32;border-left-style:dotted;border-left-width:thin;border-left-color:rgba(127,127,127,.76);display:none}.igv-user-feedback{position:fixed;top:50%;left:50%;transform:translate(-50%, -50%);width:512px;height:360px;z-index:2048;background-color:#fff;border-color:#a2a2a2;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;color:#444;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-user-feedback div:first-child{position:relative;height:24px;width:100%;background-color:#fff;border-bottom-color:#a2a2a2;border-bottom-style:solid;border-bottom-width:thin}.igv-user-feedback div:first-child div{position:absolute;top:2px;width:16px;height:16px;background-color:rgba(0,0,0,0)}.igv-user-feedback div:first-child div:first-child{left:8px}.igv-user-feedback div:first-child div:last-child{cursor:pointer;right:8px}.igv-user-feedback div:last-child{width:100%;height:calc(100% - 24px);border-width:0}.igv-user-feedback div:last-child div{width:auto;height:auto;margin:8px}.igv-generic-dialog-container{position:fixed;top:20%;left:75%;width:300px;height:200px;border-color:#7f7f7f;border-radius:4px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;z-index:2048;background-color:#fff;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-header{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;width:100%;height:24px;cursor:move;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee}.igv-generic-dialog-container .igv-generic-dialog-header div{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-generic-dialog-container .igv-generic-dialog-header div:hover{cursor:pointer;color:#444}.igv-generic-dialog-container .igv-generic-dialog-one-liner{color:#373737;width:95%;height:24px;line-height:24px;text-align:left;margin-top:8px;padding-left:8px;overflow-wrap:break-word;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-label-input{margin-top:8px;width:95%;height:24px;color:#373737;line-height:24px;padding-left:8px;background-color:#fff;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-label-input div{width:30%;height:100%;font-size:16px;text-align:right;padding-right:8px;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-label-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-label-input input{width:50%;font-size:16px}.igv-generic-dialog-container .igv-generic-dialog-input{margin-top:8px;width:calc(100% - 16px);height:24px;color:#373737;line-height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-input input{display:block;height:100%;width:100%;padding-left:4px;font-family:"Open Sans",sans-serif;font-weight:400;color:#373737;text-align:left;outline:none;border-style:solid;border-width:thin;border-color:#7f7f7f;background-color:#fff}.igv-generic-dialog-container .igv-generic-dialog-input input{font-size:16px}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel{width:100%;height:28px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div{margin-top:32px;color:#fff;font-family:"Open Sans",sans-serif;font-size:14px;font-weight:400;width:75px;height:28px;line-height:28px;text-align:center;border-color:rgba(0,0,0,0);border-style:solid;border-width:thin;border-radius:2px}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:first-child{margin-left:32px;margin-right:0;background-color:#5ea4e0}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:last-child{margin-left:0;margin-right:32px;background-color:#c4c4c4}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:first-child:hover{cursor:pointer;background-color:#3b5c7f}.igv-generic-dialog-container .igv-generic-dialog-ok-cancel div:last-child:hover{cursor:pointer;background-color:#7f7f7f}.igv-generic-dialog-container .igv-generic-dialog-ok{width:100%;height:36px;margin-top:32px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-generic-dialog-container .igv-generic-dialog-ok div{width:98px;height:36px;line-height:36px;text-align:center;color:#fff;font-family:"Open Sans",sans-serif;font-size:medium;font-weight:400;border-color:#fff;border-style:solid;border-width:thin;border-radius:4px;background-color:#2b81af}.igv-generic-dialog-container .igv-generic-dialog-ok div:hover{cursor:pointer;background-color:#25597f}.igv-generic-container{position:fixed;top:20%;left:75%;transform:translateX(-50%);z-index:2048;background-color:#fff;cursor:pointer;display:flex;flex-direction:row;flex-wrap:wrap;justify-content:flex-start;align-items:center}.igv-generic-container>div:nth-child(1){cursor:move;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center;height:24px;width:100%;background-color:#ddd}.igv-generic-container>div:nth-child(1) i{display:block;color:#5f5f5f;cursor:pointer;width:14px;height:14px;margin-right:8px;margin-bottom:4px}.igv-menu-popup{position:absolute;top:0;left:0;width:max-content;max-width:400px;z-index:2048;cursor:pointer;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;color:#4b4b4b;background:#fff;border-radius:4px;border-color:#7f7f7f;border-style:solid;border-width:thin;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-end;text-align:left}.igv-menu-popup>div:not(:first-child){width:100%}.igv-menu-popup>div:not(:first-child)>div{background:#fff}.igv-menu-popup>div:not(:first-child)>div.context-menu{padding-left:4px;padding-right:4px}.igv-menu-popup>div:not(:first-child)>div:last-child{border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom-color:rgba(0,0,0,0);border-bottom-style:solid;border-bottom-width:thin}.igv-menu-popup>div:not(:first-child)>div:hover{background:#efefef}.igv-menu-popup-shim{padding-left:8px;padding-right:8px;padding-bottom:1px;padding-top:1px}.igv-menu-popup-header{position:relative;width:100%;height:24px;cursor:move;border-top-color:rgba(0,0,0,0);border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-menu-popup-header div{margin-right:4px;height:12px;width:12px;color:#7f7f7f}.igv-menu-popup-header div:hover{cursor:pointer;color:#444}.igv-menu-popup-check-container{display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-start;align-items:center;width:100%;height:20px;margin-right:4px;background-color:rgba(0,0,0,0)}.igv-menu-popup-check-container div{padding-top:2px;padding-left:8px}.igv-menu-popup-check-container div:first-child{position:relative;width:12px;height:12px}.igv-menu-popup-check-container div:first-child svg{position:absolute;width:12px;height:12px}.igv-loading-spinner-container{z-index:1024;position:absolute;top:50%;left:50%;transform:translate(-50%, -50%);width:32px;height:32px;display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:center;align-items:center}.igv-loading-spinner-container>div{box-sizing:border-box;width:100%;height:100%;border-radius:50%;border:4px solid rgba(128,128,128,.5);border-top-color:#fff;animation:spin 1s ease-in-out infinite;-webkit-animation:spin 1s ease-in-out infinite}@keyframes spin{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}@-webkit-keyframes spin{to{-webkit-transform:rotate(360deg);transform:rotate(360deg)}}.igv-roi-menu{position:absolute;z-index:512;font-family:"Open Sans",sans-serif;font-size:small;font-weight:400;color:#4b4b4b;background-color:#fff;width:192px;border-radius:4px;border-color:#7f7f7f;border-style:solid;border-width:thin;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch}.igv-roi-menu>div:first-child{height:24px;border-top-color:rgba(0,0,0,0);border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:flex-end;align-items:center}.igv-roi-menu>div:first-child>div{margin-right:4px;height:12px;width:12px;color:#7f7f7f}.igv-roi-menu>div:first-child>div:hover{cursor:pointer;color:#444}.igv-roi-menu>div:last-child{background-color:#fff;border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom-color:rgba(0,0,0,0);border-bottom-style:solid;border-bottom-width:0;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;text-align:start;vertical-align:middle}.igv-roi-menu>div:last-child>div{height:24px;padding-left:4px;border-bottom-style:solid;border-bottom-width:thin;border-bottom-color:#7f7f7f}.igv-roi-menu>div:last-child>div:not(:first-child):hover{cursor:pointer;background-color:rgba(127,127,127,.1)}.igv-roi-menu>div:last-child div:first-child{font-style:italic;text-align:center;padding-right:4px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}.igv-roi-menu>div:last-child>div:last-child{border-bottom-width:0;border-bottom-color:rgba(0,0,0,0)}.igv-roi-placeholder{font-style:normal;color:rgba(75,75,75,.6)}.igv-roi-table{position:absolute;z-index:1024;display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;resize:both;overflow:hidden;width:min-content;max-width:1600px;border-color:#7f7f7f;border-radius:4px;border-style:solid;border-width:thin;font-family:"Open Sans",sans-serif;font-size:12px;font-weight:400;background-color:#fff;cursor:default}.igv-roi-table>div{height:24px;font-size:14px;text-align:start;vertical-align:middle;line-height:24px}.igv-roi-table>div:first-child{border-color:rgba(0,0,0,0);border-top-left-radius:4px;border-top-right-radius:4px;border-top-width:0;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin;background-color:#eee;cursor:move;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-between;align-items:center}.igv-roi-table>div:first-child>div:first-child{text-align:center;white-space:nowrap;text-overflow:ellipsis;overflow:hidden;margin-left:4px;margin-right:4px;width:calc(100% - 4px - 12px)}.igv-roi-table>div:first-child>div:last-child{margin-right:4px;margin-bottom:2px;height:12px;width:12px;color:#7f7f7f}.igv-roi-table>div:first-child>div:last-child>svg{display:block}.igv-roi-table>div:first-child>div:last-child:hover{cursor:pointer;color:#444}.igv-roi-table>.igv-roi-table-description{padding:4px;margin-left:4px;word-break:break-all;overflow-y:auto;display:flex;flex-flow:row;flex-wrap:nowrap;background-color:rgba(0,0,0,0)}.igv-roi-table>.igv-roi-table-goto-explainer{margin-top:5px;margin-left:4px;color:#7f7f7f;font-style:italic;height:24px;border-top:solid #d3d3d3;background-color:rgba(0,0,0,0)}.igv-roi-table>.igv-roi-table-column-titles{height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:stretch;align-items:stretch;padding-right:16px;background-color:#fff;border-top-color:#7f7f7f;border-top-style:solid;border-top-width:thin;border-bottom-color:#7f7f7f;border-bottom-style:solid;border-bottom-width:thin}.igv-roi-table>.igv-roi-table-column-titles>div{font-size:14px;vertical-align:middle;line-height:24px;text-align:left;margin-left:4px;height:24px;overflow:hidden;text-overflow:ellipsis;border-right-color:#7f7f7f;border-right-style:solid;border-right-width:thin}.igv-roi-table>.igv-roi-table-column-titles>div:last-child{border-right:unset}.igv-roi-table>.igv-roi-table-row-container{display:flex;flex-flow:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;overflow:auto;height:360px;flex:1 1 auto;background-color:rgba(0,0,0,0)}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row{height:24px;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:stretch;align-items:stretch}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row>div{font-size:14px;vertical-align:middle;line-height:24px;text-align:left;margin-left:4px;height:24px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;border-right-color:rgba(0,0,0,0);border-right-style:solid;border-right-width:thin}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row>div:last-child{border-right:unset}.igv-roi-table>.igv-roi-table-row-container>.igv-roi-table-row-hover{background-color:rgba(0,0,0,.04)}.igv-roi-table>div:last-child{min-height:32px;height:32px;line-height:32px;border-top-color:#7f7f7f;border-top-style:solid;border-top-width:thin;border-bottom-color:rgba(0,0,0,0);border-bottom-left-radius:4px;border-bottom-right-radius:4px;border-bottom-width:0;background-color:#eee;display:flex;flex-flow:row;flex-wrap:nowrap;justify-content:space-around;align-items:center}.igv-roi-table-row-selected{background-color:rgba(0,0,0,.125)}.igv-roi-table-button{cursor:pointer;height:20px;user-select:none;line-height:20px;text-align:center;vertical-align:middle;font-family:"Open Sans",sans-serif;font-size:13px;font-weight:400;color:#000;padding-left:6px;padding-right:6px;background-color:#efefef;border-color:#000;border-style:solid;border-width:thin;border-radius:3px}.igv-roi-table-button:hover{font-weight:400;background-color:rgba(0,0,0,.13)}.igv-roi-region{z-index:64;position:absolute;top:0;bottom:0;pointer-events:none;overflow:visible;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch}.igv-roi-region>div{position:relative;width:100%;height:8px;pointer-events:auto}.igv-roi-menu-row{height:24px;padding-left:8px;font-size:small;text-align:start;vertical-align:middle;line-height:24px;background-color:#fff}.igv-roi-menu-row-edit-description{width:-webkit-fill-available;font-size:small;text-align:start;vertical-align:middle;background-color:#fff;padding-left:4px;padding-right:4px;padding-bottom:4px;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:stretch;align-items:stretch}.igv-roi-menu-row-edit-description>label{margin-left:2px;margin-bottom:0;display:block;width:-webkit-fill-available}.igv-roi-menu-row-edit-description>input{display:block;margin-left:2px;margin-right:2px;margin-bottom:1px;width:-webkit-fill-available}.picker_wrapper.no_alpha .picker_alpha{display:none}.picker_wrapper.no_editor .picker_editor{position:absolute;z-index:-1;opacity:0}.picker_wrapper.no_cancel .picker_cancel{display:none}.layout_default.picker_wrapper{display:flex;flex-flow:row wrap;justify-content:space-between;align-items:stretch;font-size:10px;width:25em;padding:.5em}.layout_default.picker_wrapper input,.layout_default.picker_wrapper button{font-size:1rem}.layout_default.picker_wrapper>*{margin:.5em}.layout_default.picker_wrapper::before{content:"";display:block;width:100%;height:0;order:1}.layout_default .picker_slider,.layout_default .picker_selector{padding:1em}.layout_default .picker_hue{width:100%}.layout_default .picker_sl{flex:1 1 auto}.layout_default .picker_sl::before{content:"";display:block;padding-bottom:100%}.layout_default .picker_editor{order:1;width:6.5rem}.layout_default .picker_editor input{width:100%;height:100%}.layout_default .picker_sample{order:1;flex:1 1 auto}.layout_default .picker_done,.layout_default .picker_cancel{order:1}.picker_wrapper{box-sizing:border-box;background:#f2f2f2;box-shadow:0 0 0 1px silver;cursor:default;font-family:sans-serif;color:#444;pointer-events:auto}.picker_wrapper:focus{outline:none}.picker_wrapper button,.picker_wrapper input{box-sizing:border-box;border:none;box-shadow:0 0 0 1px silver;outline:none}.picker_wrapper button:focus,.picker_wrapper button:active,.picker_wrapper input:focus,.picker_wrapper input:active{box-shadow:0 0 2px 1px #1e90ff}.picker_wrapper button{padding:.4em .6em;cursor:pointer;background-color:#f5f5f5;background-image:linear-gradient(0deg, gainsboro, transparent)}.picker_wrapper button:active{background-image:linear-gradient(0deg, transparent, gainsboro)}.picker_wrapper button:hover{background-color:#fff}.picker_selector{position:absolute;z-index:1;display:block;-webkit-transform:translate(-50%, -50%);transform:translate(-50%, -50%);border:2px solid #fff;border-radius:100%;box-shadow:0 0 3px 1px #67b9ff;background:currentColor;cursor:pointer}.picker_slider .picker_selector{border-radius:2px}.picker_hue{position:relative;background-image:linear-gradient(90deg, red, yellow, lime, cyan, blue, magenta, red);box-shadow:0 0 0 1px silver}.picker_sl{position:relative;box-shadow:0 0 0 1px silver;background-image:linear-gradient(180deg, white, rgba(255, 255, 255, 0) 50%),linear-gradient(0deg, black, rgba(0, 0, 0, 0) 50%),linear-gradient(90deg, #808080, rgba(128, 128, 128, 0))}.picker_alpha,.picker_sample{position:relative;background:linear-gradient(45deg, lightgrey 25%, transparent 25%, transparent 75%, lightgrey 75%) 0 0/2em 2em,linear-gradient(45deg, lightgrey 25%, white 25%, white 75%, lightgrey 75%) 1em 1em/2em 2em;box-shadow:0 0 0 1px silver}.picker_alpha .picker_selector,.picker_sample .picker_selector{background:none}.picker_editor input{font-family:monospace;padding:.2em .4em}.picker_sample::before{content:"";position:absolute;display:block;width:100%;height:100%;background:currentColor}.picker_arrow{position:absolute;z-index:-1}.picker_wrapper.popup{position:absolute;z-index:2;margin:1.5em}.picker_wrapper.popup,.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{background:#f2f2f2;box-shadow:0 0 10px 1px rgba(0,0,0,.4)}.picker_wrapper.popup .picker_arrow{width:3em;height:3em;margin:0}.picker_wrapper.popup .picker_arrow::before,.picker_wrapper.popup .picker_arrow::after{content:"";display:block;position:absolute;top:0;left:0;z-index:-99}.picker_wrapper.popup .picker_arrow::before{width:100%;height:100%;-webkit-transform:skew(45deg);transform:skew(45deg);-webkit-transform-origin:0 100%;transform-origin:0 100%}.picker_wrapper.popup .picker_arrow::after{width:150%;height:150%;box-shadow:none}.popup.popup_top{bottom:100%;left:0}.popup.popup_top .picker_arrow{bottom:0;left:0;-webkit-transform:rotate(-90deg);transform:rotate(-90deg)}.popup.popup_bottom{top:100%;left:0}.popup.popup_bottom .picker_arrow{top:0;left:0;-webkit-transform:rotate(90deg) scale(1, -1);transform:rotate(90deg) scale(1, -1)}.popup.popup_left{top:0;right:100%}.popup.popup_left .picker_arrow{top:0;right:0;-webkit-transform:scale(-1, 1);transform:scale(-1, 1)}.popup.popup_right{top:0;left:100%}.popup.popup_right .picker_arrow{top:0;left:0}.igv-ui-center-fixed{left:50%;top:50%;transform:translate(-50%, -50%)}.igv-container{all:initial;position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;padding-top:4px;user-select:none;-webkit-user-select:none;-ms-user-select:none;min-height:160px}.igv-viewport{position:relative;margin-top:5px;line-height:1;overflow-x:hidden;overflow-y:hidden}.igv-viewport-content{position:relative;width:100%}.igv-viewport-content>canvas{position:relative;display:block}.igv-column-container{position:relative;display:flex;flex-direction:row;flex-wrap:nowrap;justify-content:flex-start;align-items:stretch;width:100%}.igv-column-shim{width:1px;margin-left:2px;margin-right:2px;background-color:#545453}.igv-axis-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:50px}.igv-axis-column>div{position:relative;margin-top:5px;width:100%}.igv-axis-column>div>div{z-index:512;position:absolute;top:8px;left:8px;width:fit-content;height:fit-content;background-color:rgba(0,0,0,0);display:grid;align-items:start;justify-items:center}.igv-axis-column>div>div>input{display:block;margin:unset;cursor:pointer}.igv-column{position:relative;flex:auto;position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%}.igv-sample-info-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%}.igv-sample-name-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%}.igv-scrollbar-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:14px}.igv-scrollbar-column>div{position:relative;margin-top:5px;width:14px}.igv-scrollbar-column>div>div{cursor:pointer;position:absolute;top:0;left:2px;width:8px;border-width:1px;border-style:solid;border-color:#c4c4c4;border-top-left-radius:4px;border-top-right-radius:4px;border-bottom-left-radius:4px;border-bottom-right-radius:4px}.igv-scrollbar-column>div>div:hover{background-color:#c4c4c4}.igv-track-drag-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:12px;background-color:#fff}.igv-track-drag-column>.igv-track-drag-handle{z-index:512;position:relative;cursor:pointer;margin-top:5px;width:100%;border-style:solid;border-width:0;border-top-right-radius:6px;border-bottom-right-radius:6px}.igv-track-drag-column .igv-track-drag-handle-color{background-color:#c4c4c4}.igv-track-drag-column .igv-track-drag-handle-hover-color{background-color:#787878}.igv-track-drag-column .igv-track-drag-handle-selected-color{background-color:#0963fa}.igv-track-drag-column>.igv-track-drag-shim{position:relative;margin-top:5px;width:100%;border-style:solid;border-width:0}.igv-gear-menu-column{position:relative;display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:flex-start;box-sizing:border-box;height:100%;width:28px}.igv-gear-menu-column>div{display:flex;flex-direction:column;flex-wrap:nowrap;justify-content:flex-start;align-items:center;margin-top:5px;width:100%;background:#fff}.igv-gear-menu-column>div>div{position:relative;margin-top:4px;width:16px;height:16px;color:#7f7f7f}.igv-gear-menu-column>div>div:hover{cursor:pointer;color:#444}.igv-vertical-center{margin:0 !important;top:50% !important;-ms-transform:translateY(-50%) !important;transform:translateY(-50%) !important}'),r.adoptedStyleSheets=[e]}if(this.root=t({class:"igv-container"}),r.appendChild(this.root),this.alert=new Ud(this.root),this.columnContainer=t({class:"igv-column-container"}),this.root.appendChild(this.columnContainer),this.menuPopup=new md(this.columnContainer),this.menuUtils=new Bd(this),this.initialize(e),this.trackViews=[],this.constants={dragThreshold:3,scrollThreshold:5,defaultColor:"rgb(0,0,150)",doubleClickDelay:e.doubleClickDelay||500},e.listeners)for(let t of Object.keys(e.listeners))this.on(t,e.listeners[t]);this.on("trackremoved",(()=>{0===this.findTracks((e=>"function"==typeof e.getSamples)).length&&(this.sampleInfoControl.setButtonVisibility(!1),this.sampleNameViewportWidth=void 0,this.showSampleNames=!1,this.sampleNameControl.setState(this.showSampleNames),this.sampleNameControl.hide(),this.layoutChange())})),this.on("columnlayoutchange",(()=>{if(Ph.length>0){const e=Ph.length;for(let t=0;t1}isMultiLocusWholeGenomeView(){if(void 0===this.referenceFrameList||1===this.referenceFrameList.length)return!1;for(let e of this.referenceFrameList)if("all"===e.chr.toLowerCase())return!0;return!1}currentLoci(){const e=e=>`${e.chr}:${e.start+1}-${e.end}`;return void 0===this.referenceFrameList||0===this.referenceFrameList.length?"":1===this.referenceFrameList.length?e(this.referenceFrameList[0]):this.referenceFrameList.map((t=>e(t)))}toSVG(){const{x:e,y:t,width:i,height:r}=this.columnContainer.getBoundingClientRect(),s=Number.MAX_SAFE_INTEGER,o=new gh({width:i,height:s,backdropColor:"white",multiLocusGap:0,viewbox:{x:0,y:0,width:i,height:s}}),n={deltaX:0,deltaY:-t};for(let e of this.trackViews)e.renderSVGContext(o,n);return n.deltaX=e,o.setHeight(r),o.getSerializedSvg(!0)}saveSVGtoFile(e,t){let i=this.toSVG();if(t){const e=document.createElement("svg");e.innerHTML=i,t.appendChild(e)}const r=e||"igvjs.svg",s=URL.createObjectURL(new Blob([i],{type:"application/octet-stream"}));k(r,s),URL.revokeObjectURL(s)}savePNGtoFile(e){const t=this.toSVG(),i=new Blob([t],{type:"image/svg+xml"}),r=URL.createObjectURL(i),s=document.createElement("img");s.addEventListener("load",(()=>{const t=this.columnContainer.getBoundingClientRect(),i=window.devicePixelRatio,o=t.width*i,n=t.height*i,a=document.createElement("canvas");a.width=o,a.height=n;const c=a.getContext("2d");c.scale(i,i),c.drawImage(s,0,0);const l=a.toDataURL("image/png");k(e=e||"igvjs.png",l),URL.revokeObjectURL(r)})),s.src=r}async loadSession(e){let t;this.sampleInfo.initialize(),this.roiSets=[],t=e.url||e.file?await ny.loadSessionFile(e,this.config):e,await this.loadSessionObject(t)}static async loadSessionFile(e,t){const i=e.url||e.file;let r;if(e.url&&b(e.url)&&(e.url.startsWith("blob:")||e.url.startsWith("data:"))){const t=ny.uncompressSession(e.url);r=JSON.parse(t)}else{let t=e.filename;if(t||(t=e.url?await os(e.url):e.file.name),t.endsWith(".xml")){const e=Dh.KNOWN_GENOMES,t=await Rr.loadString(i);r=new UF(t,e)}else if(t.endsWith("hub.txt")){r={reference:(await Nh(i)).getGenomeConfig()}}else{if(!t.endsWith(".json"))throw Error("Unrecognized session file format:"+t);r=await Rr.loadJson(i)}}return fy(r,t),r}async loadSessionObject(e){if(this.cleanHouseForSession(),this.config=e,e.browsers&&(e=await async function(e){const t=e.browsers[0],i={},r=new Ov({url:t.url});await r.readHeaderAndFooter(),i.sampleNameViewportWidth=20,i.genome="hg38";const s=t.state.split(","),o=r.bpResolutions[Number.parseInt(s[2])],n=Number.parseInt(s[0]),a=Math.floor(Number.parseFloat(s[3])*o),c=a+Math.floor(1700*o);return i.locus=`${r.chromosomes[n].name}:${a}-${c}`,i.tracks=(t.tracks||[]).filter((e=>!("refgene"===e.format||"cellType"===e.name))),i.tracks.push({type:"shoebox",url:t.url,name:t.name,colorScale:t.colorScale,_hicFile:r}),i}(e)),this.navbar.sampleInfoControl.setButtonVisibility(!1),this.showSampleNames=e.showSampleNames||!1,this.navbar.sampleNameControl.setState(!0===this.showSampleNames),e.sampleNameViewportWidth&&(this.sampleNameViewportWidth=e.sampleNameViewportWidth),"left"===this.config.gearColumnPosition){const e=cs(this.columnContainer,"igv-gear-menu-column");!1===this.config.showGearColumn&&(e.style.width="0px")}const t=cs(this.columnContainer,"igv-axis-column");!1===this.config.showAxis&&(t.style.display="none"),void 0!==this.config.axisWidth&&(t.style.width=this.config.axisWidth+"px"),cs(this.columnContainer,"igv-sample-info-column"),cs(this.columnContainer,"igv-sample-name-column"),cs(this.columnContainer,"igv-scrollbar-column");const i=cs(this.columnContainer,"igv-track-drag-column");if(!1===this.config.showTrackDragHandles&&(i.style.display="none"),"left"!==this.config.gearColumnPosition){const e=cs(this.columnContainer,"igv-gear-menu-column");!1===this.config.showGearColumn&&(e.style.width="0px")}const r=e.reference||e.genome;if(!r)return void console.warn("No genome or reference object specified");const s=b(r)?await Dh.expandReference(this.alert,r):r,o=await this.loadReference(s,s.locus||e.locus);if(this.centerLineList=this.createCenterLineList(this.columnContainer),!1!==e.showIdeogram){const e=new RF(this),t=new Sd(this,this.columnContainer,e);this.trackViews.push(t)}if(!1!==e.showRuler){const e=new cd(this),t=new Sd(this,this.columnContainer,e);this.trackViews.push(t)}e.qtlSelections&&(this.qtlSelections=ty.fromJSON(e.qtlSelections)),void 0!==e.showROIOverlays&&(this.roiManager.showOverlays=e.showROIOverlays),this.roiManager.clearROIs(),e.roi?this.roiManager.loadROI(e.roi,o):await this.roiManager.reset();const n=[];if(e.sampleinfo){const t=Array.isArray(e.sampleinfo)?e.sampleinfo:[e.sampleinfo];for(const e of t)e.file?n.push(e.file):await this.sampleInfo.loadSampleInfo(e)}const a=s.tracks||[],c=e.tracks?a.concat(e.tracks):a;0===c.filter((e=>"sequence"===e.type&&!e.url&&!e.fastaURL)).length&&!1!==this.config.showSequence&&c.push({type:"sequence",order:Xl,removable:!1});const l=c.filter((e=>void 0!==e.file)).map((({file:e})=>e)),h=c.filter((e=>void 0!==e.indexFile)).map((({indexFile:e})=>e));h.length>0&&l.push(...h),n.length>0&&l.push(...n),l.length>0&&alert(`Local files cannot be loaded automatically.\nThis session contains references to these local files:\n${l.map((e=>` ${e}`)).join("\n")}`);const d=c.filter((e=>void 0===e.file));let u=1;for(let e of d)void 0===e.order&&(e.order=u++);const f=d.filter((e=>!0===e.hidden));for(const e of f){const t=El(e,this.genome);await t.getFeatures({chr:"1",start:0,end:Number.MAX_SAFE_INTEGER})}await this.loadTrackList(d)}cleanHouseForSession(){for(let e of this.trackViews)e.removeDOMFromColumnContainer();this.columnContainer.querySelectorAll(".igv-axis-column, .igv-column-shim, .igv-column, .igv-sample-info-column, .igv-sample-name-column, .igv-scrollbar-column, .igv-track-drag-column, .igv-gear-menu-column").forEach((e=>e.remove())),this.trackViews=[],this.circularView&&this.circularView.clearChords()}async loadReference(e,t){let i;this.removeAllTracks(),this.roiManager.clearROIs(),this.navbar.setEnableTrackSelection(!1),i=e.gbkURL?await _l(e.gbkURL):await ey.createGenome(e,this);const r=void 0===this.genome||this.genome.id!==i.id;this.genome=i,this.navbar.updateGenome(i);let s=t||i.initialLocus;if(void 0!==s.chr&&void 0!==s.start)await this.genome.loadChromosome(s.chr),await this.updateLoci([s],!0);else{Array.isArray(s)&&(s=s.join(" "));await this.search(s,!0)||(console.error(`Cannot set initial locus ${s}`),s!==i.initialLocus&&await this.search(i.initialLocus))}return r&&(this.fireEvent("genomechange",[{genome:i}]),this.circularView&&this.circularView.setAssembly({name:this.genome.id,id:this.genome.id,chromosomes:Kf(this.genome)})),i}async loadGenome(e){let t;e.genarkAccession&&(e.url=mh(e.genarkAccession)),e.url&&(b(e.url)&&e.url.endsWith("/hub.txt")?(e.hubURL=e.url,delete e.url):"gbk"===function(e){let t;if(e instanceof File)t=e.name;else{if("string"!=typeof e)throw new Error("Input must be a File object or a URL string");t=e}const i=t.split(".").pop();return i.split("?")[0]}(e.url)&&(e.gbkURL=e.url,delete e.url));if(e.hubURL||e.url&&b(e.url)&&e.url.endsWith("/hub.txt")){t=(await Nh(e.hubURL||e.url)).getGenomeConfig()}else t=b(e)||!(e.url||e.fastaURL||e.twoBitURL||e.gbkURL)?await Dh.expandReference(this.alert,e):e;let i;await this.loadReference(t),i=t.gbkURL||"gbk"===t.format?[{name:"Annotations",format:"gbk",url:t.gbkURL}]:t.tracks||[];return 0===i.filter((e=>"sequence"===e.type)).length&&i.push({type:"sequence",order:Xl}),await this.loadTrackList(i),this.genome}updateUIWithReferenceFrameList(){const e=this.referenceFrameList;this.isMultiLocusWholeGenomeView()||Dh.isWholeGenomeView(e[0].chr),this.navbar.navbarDidResize(),dy(this.trackViews,this.doShowTrackLabels),this.doShowCenterLine&&Dh.isWholeGenomeView(e[0].chr)&&this.navbar.centerLineButton.boundMouseClickHandler(),this.doShowCursorGuide&&Dh.isWholeGenomeView(e[0].chr)&&this.navbar.cursorGuideButton.boundMouseClickHandler(),this.setCenterLineAndCenterLineButtonVisibility(Dh.isWholeGenomeView(e[0].chr))}setCenterLineAndCenterLineButtonVisibility(e){e?this.navbar.centerLineButton.setVisibility(!1):this.navbar.centerLineButton.setVisibility(this.config.showCenterGuideButton);for(let t of this.centerLineList)e?this.setCenterLineVisibility(!e):this.setCenterLineVisibility(this.doShowCenterLine)}setTrackLabelVisibility(e){dy(this.trackViews,e)}setROITableVisibility(e){!0===e?this.roiManager.presentTable():this.roiManager.dismissTable()}setCursorGuideVisibility(e){e?this.cursorGuide.show():this.cursorGuide.hide()}setCustomCursorGuideMouseHandler(e){this.cursorGuide.customMouseHandler=e}setCenterLineVisibility(e){for(let t of this.centerLineList)!0===e?(t.show(),t.repaint()):t.hide()}async loadTrackList(e){let t=this.trackViews.length+1;for(let i of e)void 0===i.order&&(i.order=t++);const i=[];for(const t of e)i.push(this.#T(t));const r=await Promise.all(i);return this.trackViews.some((({track:e})=>e.selected))&&this.navbar.setEnableTrackSelection(!0),this.reorderTracks(),await ay.call(this),this.fireEvent("trackorderchanged",[this.getTrackOrder()]),r}async loadTrack(e){const t=await this.loadTrackList([e]);return e.autoscaleGroup&&this.updateViews(),t[0]}async#T(e){let t;b(e)&&(e=JSON.parse(e));try{t=await this.createTrack(e)}catch(t){let i=t.message||t.error||t.toString();const r={401:"Access unauthorized",403:"Access forbidden",404:"Not found"};r.hasOwnProperty(i)&&(i=r[i]),i=`${i} : ${x(e.url)?e.url.name:e.url}`;const s=new Error(i);throw console.error(s),s}return t?await this.addTrack(t):void 0}async addTrack(e){void 0===e.order&&(e.order=this.trackViews.length);const t=new Sd(this,this.columnContainer,e);if(this.trackViews.push(t),dy(this.trackViews,this.doShowTrackLabels),"function"==typeof e.postInit)try{t.startSpinner(),await e.postInit()}finally{t.stopSpinner()}return"function"==typeof e.hasSamples&&e.hasSamples()&&(this.sampleInfo.hasAttributes()&&this.sampleInfoControl.setButtonVisibility(!0),!1!==this.config.showSampleNameButton&&this.sampleNameControl.show()),e.trackView.enableTrackSelection(this.navbar.getEnableTrackSelection()),e}async loadROI(e){return this.roiManager.loadROI(e,this.genome)}clearROIs(){this.roiManager.clearROIs()}async getUserDefinedROIs(){if(this.roiManager){const e=this.roiManager.getUserDefinedROISet();if(void 0===e)return[];const t=await e.getAllFeatures(),i=[];for(let e of Object.values(t))i.push(...e);return i}return[]}getRulerTrackView(){const e=this.trackViews.filter((({track:e})=>"ruler"===e.id));return e.length>0?e[0]:void 0}async createTrack(e){let t=await async function(e){return"function"==typeof e?e():e} +/*! pako 2.1.0 https://github.com/nodeca/pako @license (MIT AND Zlib) */(e.url||e.fastaURL);if(b(t)&&(t=t.trim()),t)if(e.format)e.format=e.format.toLowerCase();else if(e.fastaURL)e.format="fasta";else if(e.sourceType)"htsget"===e.sourceType&&await hc.inferFormat(e);else{const t=await bf(e);t&&(e.format=t)}e.type&&Gd(e);let i=e.type?e.type.toLowerCase():void 0;if(!i){if(!e.format)throw Error(`Unrecognized track: ${JSON.stringify(e)}`);if("hic"===e.format){const t=new Ov(e);if(await t.readHeaderAndFooter(),!t.chromosomeIndexMap.celltype)throw Error("'.hic' files not supported");i="shoebox",e._hicFile=t}else if(i=Qd(e.format),"bedtype"===i){const t=El(e,this.genome);e._featureSource=t;const r=await t.trackType();i=r&&new Set(qF.keys()).has(r)?r:"annotation"}e.type=i}if(this.trackDefaults&&i){const t=this.trackDefaults[i];if(t)for(let i in t)t.hasOwnProperty(i)&&void 0===e[i]&&(e[i]=t[i])}const r=function(e,t,i){let r;switch(e){case"annotation":case"genes":case"fusionjuncspan":case"snp":r="feature";break;case"seg":case"maf":case"mut":r="seg";break;case"junctions":case"splicejunctions":r="junction";break;default:r=e}return qF.has(r)?qF.get(r)(t,i):void 0}(i,e,this);if(void 0!==r)return e.roi&&e.roi.length>0&&(r.roiSets=e.roi.map((e=>new Cv(e,this.genome)))),r;this.alert.present(new Error(`Error creating track. Could not determine track type for file: ${e.url||e}`),void 0)}reorderTracks(){this.trackViews.sort((function(e,t){const i=e=>"ideogram"===e.track.id?1:"ruler"===e.track.id?2:3,r=i(e),s=i(t);if(r===s){return(e.track.order||0)-(t.track.order||0)}return r-s}));for(let{axis:e,viewports:t,sampleInfoViewport:i,sampleNameViewport:r,outerScroll:s,dragHandle:o,gearContainer:n}of this.trackViews){e.remove();for(let{viewportElement:e}of t)e.parentNode.removeChild(e);i.viewport.remove(),r.viewport.remove(),s.remove(),o.remove(),n.remove()}const e=this.columnContainer.querySelectorAll(".igv-column");for(let{axis:t,viewports:i,sampleInfoViewport:r,sampleNameViewport:s,outerScroll:o,dragHandle:n,gearContainer:a}of this.trackViews){this.columnContainer.querySelector(".igv-axis-column").appendChild(t);for(let t=0;te.track&&e.track.name)).map((e=>e.track.name))}getSelectedTrackViews(){return this.trackViews.filter((e=>!0===e.track.selected))}removeTrackByName(e){const t=this.trackViews.slice();for(let i of t)e===i.track.name&&this.removeTrack(i.track)}removeTrack(e){for(let t of this.trackViews)if(e===t.track){this._removeTrack(t.track);break}}_removeTrack(e){e.disposed||(this.trackViews.splice(this.trackViews.indexOf(e.trackView),1),this.fireEvent("trackremoved",[e]),this.fireEvent("trackorderchanged",[this.getTrackOrder()]),e.trackView&&e.trackView.dispose())}removeAllTracks(){const e=this.trackViews;this.trackViews=[];for(let t of e)"ruler"!==t.track.id&&"ideogram"!==t.track.id?(this.fireEvent("trackremoved",[t.track]),t.dispose()):this.trackViews.push(t)}get ideogramTrackView(){return this.trackViews[0]}get rulerTrackView(){return this.trackViews[1]}findTracks(e,t){let i="function"==typeof e?t=>e(t.track):i=>t===i.track[e];return this.trackViews.filter(i).map((e=>e.track))}get tracks(){return this.trackViews.map((e=>e.track)).filter((e=>void 0!==e))}setTrackHeight(e){this.trackHeight=e,this.trackViews.forEach((function(t){t.setTrackHeight(e)}))}async visibilityChange(){this.layoutChange()}async layoutChange(){if(this.referenceFrameList.find((e=>e.bpPerPixel<0))){const e=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList)t.bpPerPixel=(t.end-t.start)/e}this.referenceFrameList&&this.navbar.navbarDidResize(),ay.call(this),this.roiManager.updateROIRegionPositions(),await this.updateViews()}async updateViews(){const e=this.trackViews;this.updateLocusSearchWidget();for(const{bpPerPixel:e,chr:t,start:i}of this.referenceFrameList)e<=10&&await this.genome.getSequence(t,i,i+1);for(const e of this.centerLineList)e.repaint();if(this.dragObject)for(const t of e)await t.updateViews();else{const t={},i=[];for(const r of e)if(r.track.autoscaleGroup){const e=r.track.autoscaleGroup;t[e]||(t[e]=[]),t[e].push(r)}else i.push(r);if(Object.entries(t).length>0)for(const[e,i]of Object.entries(t)){const e=await Promise.all(i.map((e=>e.getInViewFeatures()))),t=is(e.flat());for(const e of i)e.track.dataRange=Object.assign({},t),e.track.autoscale=!1;await Promise.all(i.map((e=>e.updateViews())))}await Promise.all(i.map((e=>e.updateViews())))}}repaintViews(){for(let e of this.trackViews)e.repaintViews()}updateLocusSearchWidget(){if(!this.referenceFrameList)return;const e=this.referenceFrameList,t=this.calculateViewportWidth(this.referenceFrameList.length);for(let i of e)i.end=i.start+i.bpPerPixel*t;const i=this.referenceFrameList.map((e=>e.getLocusString())).join(" "),r=1===e.length?this.genome.getChromosomeDisplayName(this.referenceFrameList[0].chr):"";this.navbar.updateLocus(i,r),this.fireEvent("locuschange",[this.referenceFrameList])}calculateViewportWidth(e){let{width:t}=this.columnContainer.getBoundingClientRect();const i=this.getSampleInfoViewportWidth(),r=this.getSampleNameViewportWidth();return t-=(!1===this.config.showAxis?0:50)+i+r+14+(!1===this.config.showTrackDragHandles?0:12)+(!1===this.config.showGearColumn?0:28),t-=5*(e-1),Math.floor(t/e)}updateReferenceFrames(e){for(const t of this.referenceFrameList)t.updateForViewportWidth(e)}updateViewportElements(e){for(let t=0;t{i===t||e.remove()})),this.columnContainer.querySelectorAll(".igv-column-shim").forEach((e=>e.remove()));for(let e of this.trackViews){const i=e.viewports[t];e.viewports.filter(((e,i)=>i!==t)).forEach((e=>e.dispose())),e.viewports=[i]}const i=this.calculateViewportWidth(1);e.bpPerPixel=(e.end-e.start)/i,this.referenceFrameList=[e],this.trackViews.forEach((({viewports:e})=>e.forEach((e=>e.setWidth(i))))),this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),await this.updateViews(!0)}async rescaleForMultiLocus(e){const t=this.calculateViewportWidth(this.referenceFrameList.length);for(let t of this.referenceFrameList)t.bpPerPixel*=e;for(let{viewports:e}of this.trackViews)for(let i of e)i.setWidth(t);this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),await this.updateViews()}async goto(e,t,i){await this.search(e+":"+t+"-"+i)}async search(e,t){const i=await async function(e,t){if(void 0===t||""===t.trim())return;const i=t.split(" ");let r=[];const s=async t=>{if("all"===t.trim().toLowerCase()||"*"===t)return e.genome.wholeGenomeView?{chr:"all",start:0,end:e.genome.getChromosome("all").bpLength}:void 0;let i,r;if(t.includes(":")&&(i=AF(t,e.isSoftclipped()),i&&(r=await e.genome.loadChromosome(i.chr))),!r){i=void 0;const s=await yF(e,t);s&&(i={chr:s.chr,start:s.start,end:s.end,name:(s.name||t).toUpperCase()}),i||(r=await e.genome.loadChromosome(t),r&&(i={chr:r.name}))}return i&&(r=r||await e.genome.loadChromosome(i.chr),i.chr=r.name,void 0===i.start&&void 0===i.end&&(i.start=0,i.end=r.bpLength)),i};for(let e of i){const t=await s(e);t&&r.push(t)}if(0===r.length){const e=await s(t.replaceAll(" ","+"));e&&r.push(e)}return 0===r.length?void 0:r}(this,e);return this.updateLoci(i,t)}async updateLoci(e,t){if(e&&e.length>0){this.referenceFrameList=function(e,t,i,r,s,o){return e.map((e=>{let n;if(e.bpPerPixel)n=new GF(t,e.chr,e.start,e.start+s*e.bpPerPixel,e.bpPerPixel);else{const a=Object.assign({},e);if(i&&a.name&&(a.start=Math.max(0,a.start-i),a.end+=i),!o){const e=t.getChromosome(a.chr);rs(e.bpLength,a,r)}n=new GF(t,a.chr,a.start,a.end,(a.end-a.start)/s)}return n}))}(e,this.genome,this.flanking,this.minimumBases(),this.calculateViewportWidth(e.length),this.isSoftclipped());for(let e of this.trackViews)e.removeViewportsFromColumnContainer();this.columnContainer.querySelectorAll(".igv-column-shim, .igv-column").forEach((e=>e.remove())),uv(this.columnContainer.querySelector(".igv-sample-info-column"),this.referenceFrameList.length),this.fireEvent("columnlayoutchange");for(let e of this.trackViews)e.createViewports(this,this.columnContainer,this.referenceFrameList);return this.centerLineList=this.createCenterLineList(this.columnContainer),this.updateUIWithReferenceFrameList(),t||await this.updateViews(),!0}return!1}async loadSampleInfo(e){await this.sampleInfo.loadSampleInfo(e),this.config.sampleinfo?this.config.sampleinfo.push(e):this.config.sampleinfo=[e];for(const{sampleInfoViewport:e}of this.trackViews)e.setWidth(this.getSampleInfoColumnWidth());const t=this.findTracks((e=>"function"==typeof e.getSamples));t.length>0&&(this.sampleInfoControl.performClickWithState(this,!0),this.sampleInfoControl.setButtonVisibility(!0));for(const{sampleInfoViewport:e}of this.trackViews)e.repaint()}async discardSampleInfo(){this.sampleInfo.discard();for(const{sampleInfoViewport:e}of this.trackViews)e.setWidth(this.getSampleInfoColumnWidth());const e=this.findTracks((e=>"function"==typeof e.getSamples));e.length>0&&(this.sampleInfoControl.performClickWithState(this,!1),this.sampleInfoControl.setButtonVisibility(!1));for(const{sampleInfoViewport:e}of this.trackViews)e.repaint();await this.layoutChange()}getSampleInfoColumnWidth(){if(this.sampleInfo.attributeCount){const e=this.findTracks((e=>"function"==typeof e.getSamples)),t=e.length>0,i=this.sampleInfo.hasAttributes(),r=this.sampleInfoControl.showSampleInfo;return t&&i&&r?this.sampleInfo.attributeCount*nd+8:0}return 0}on(e,t){this.eventEmitter.on(e,t)}un(e,t){this.eventEmitter.off(e,t)}off(e,t){this.eventEmitter.off(e,t)}fireEvent(e,t,i){return this.eventEmitter.emit(e,t,i)}dispose(){this.removeEventHandlers();for(let e of this.trackViews)e.dispose();this.roiManager&&this.roiManager.dispose()}toJSON(){const e={version:"3.5.0"};if(void 0!==this.showSampleNames&&(e.showSampleNames=this.showSampleNames),this.sampleNameViewportWidth&&(e.sampleNameViewportWidth=this.sampleNameViewportWidth),e.reference=this.genome.toJSON(),e.reference.fastaURL instanceof File)throw new Error(`Error. Sessions cannot include local file references ${e.reference.fastaURL.name}.`);if(e.reference.indexURL instanceof File)throw new Error(`Error. Sessions cannot include local file references ${e.reference.indexURL.name}.`);const t=[];let i=this.trackViews[0];for(let{referenceFrame:e}of i.viewports){const i=e.getLocusString();t.push(i)}e.locus=1===t.length?t[0]:t;const r=this.roiManager.toJSON();r&&(e.roi=r,this.roiManager.showOverlays||(e.showROIOverlays=!1)),this.qtlSelections.isEmpty()||(e.qtlSelections=this.qtlSelections.toJSON());const s=[],o=[];for(const{track:e}of this.trackViews)try{let t;"function"==typeof e.getState?t=ma.localFileInspection(e.getState()):e.config&&(t=ma.localFileInspection(e.config)),t&&(t.browser&&delete t.browser,t.order=e.order,s.push(t))}catch(t){const i=`Track: ${e.name}: ${t}`;console.error(i),o.push(i)}if(o.length>0){let e=1,t="Errors encountered saving session:
";for(let i of o)t+=` (${e++}) ${i.toString()}
`;throw Error(t)}e.tracks=s;const n=[];for(const e of s)for(const t of Object.keys(e))"file"!==t&&"indexFile"!==t||n.push(e[t]);const a=[];if(this.config.sampleinfo){e.sampleinfo=this.config.sampleinfo;for(const e of this.sampleInfo.sampleInfoFiles){const t=ma.localFileInspection({url:e});t.file&&a.push(t.file)}a.length>0&&n.push(...a)}return n.length>0&&alert(`This session includes reference(s) to local file(s):\n${n.map((e=>` ${e}`)).join("\n")}\nLocal files cannot be loaded automatically when a saved session is restored.`),e}compressedSession(){return function(e){const t=new Uint8Array(e.length);for(var i=0;i0?e.substring(0,t):e)+"?sessionURL=blob:"+this.compressedSession()}mouseDownOnViewport(e,t){var i;i=o(e),this.vpMouseDown={viewport:t,lastMouseX:i.x,mouseDownX:i.x,lastMouseY:i.y,mouseDownY:i.y,referenceFrame:t.referenceFrame}}cancelTrackPan(){const e=this.dragObject;this.dragObject=void 0,this.isScrolling=!1,this.vpMouseDown=void 0,e&&e.viewport.referenceFrame.start!==e.start&&(this.updateViews(),this.fireEvent("trackdragend",[e.viewport]))}isTrackPanning(){return this.dragObject}isSoftclipped(){return void 0!==this.trackViews.find((e=>!0===e.track.showSoftClips))}startTrackDrag(e){this.dragTrack=e}updateTrackDrag(e){if(e&&this.dragTrack){const t=this.dragTrack,i=this.trackViews.indexOf(e),r=this.trackViews.indexOf(t),s=this.trackViews;s[i]=t,s[r]=e;const o=this.trackViews[i].track.order;this.trackViews[r].track.order=o;const n=s.length;let a=o;if(i0;e--){const t=s[e].track;if(!(t.order>=a))break;t.order=Math.max(-Number.MAX_SAFE_INTEGER,a-1),a=t.order}this.reorderTracks()}}endTrackDrag(){this.dragTrack?(this.dragTrack=void 0,this.fireEvent("trackorderchanged",[this.getTrackOrder()])):this.dragTrack=void 0}addEventHandlers(){this.addWindowResizeHandler(),this.addRootMouseUpHandler(),this.addRootMouseLeaveHandler(),this.addColumnContainerEventHandlers(),this.addKeyboardHandler()}removeEventHandlers(){this.removeWindowResizeHandler(),this.removeRootMouseUpHandler(),this.removeRootMouseLeaveHandler(),this.removeColumnContainerEventHandlers(),this.removeKeyboardHandler()}addWindowResizeHandler(){this.boundWindowResizeHandler=ay.bind(this),window.addEventListener("resize",this.boundWindowResizeHandler)}removeWindowResizeHandler(){window.removeEventListener("resize",this.boundWindowResizeHandler)}addRootMouseUpHandler(){this.boundRootMouseUpHandler=ly.bind(this),this.root.addEventListener("mouseup",this.boundRootMouseUpHandler)}removeRootMouseUpHandler(){this.root.removeEventListener("mouseup",this.boundRootMouseUpHandler)}addRootMouseLeaveHandler(){this.boundRootMouseLeaveHandler=ly.bind(this),this.root.addEventListener("mouseleave",this.boundRootMouseLeaveHandler)}removeRootMouseLeaveHandler(){this.root.removeEventListener("mouseleave",this.boundRootMouseLeaveHandler)}addColumnContainerEventHandlers(){this.boundColumnContainerMouseMoveHandler=cy.bind(this),this.boundColumnContainerTouchMoveHandler=cy.bind(this),this.boundColumnContainerMouseLeaveHandler=ly.bind(this),this.boundColumnContainerMouseUpHandler=ly.bind(this),this.boundColumnContainerTouchEndHandler=ly.bind(this),this.columnContainer.addEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.columnContainer.addEventListener("touchmove",this.boundColumnContainerTouchMoveHandler),this.columnContainer.addEventListener("mouseleave",this.boundColumnContainerMouseLeaveHandler),this.columnContainer.addEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.columnContainer.addEventListener("touchend",this.boundColumnContainerTouchEndHandler)}removeColumnContainerEventHandlers(){this.columnContainer.removeEventListener("mousemove",this.boundColumnContainerMouseMoveHandler),this.columnContainer.removeEventListener("touchmove",this.boundColumnContainerTouchMoveHandler),this.columnContainer.removeEventListener("mouseleave",this.boundColumnContainerMouseLeaveHandler),this.columnContainer.removeEventListener("mouseup",this.boundColumnContainerMouseUpHandler),this.columnContainer.removeEventListener("touchend",this.boundColumnContainerTouchEndHandler)}addKeyboardHandler(){this.keyUpHandler=hy.bind(this),document.addEventListener("keyup",this.keyUpHandler)}removeKeyboardHandler(){console.log("Remove handler"),document.addEventListener("keyup",this.keyUpHandler)}static uncompressSession(e){let t;if(e.indexOf("/gzip;base64")>0){t=nr(e);let i="";for(let e of t)i+=String.fromCharCode(e);return i}return function(e){e=e.replace(/\./g,"+").replace(/_/g,"/").replace(/-/g,"=");const t=atob(e),i=[];for(let e=0;e{const s=e.data,o=s.mate;function n(e){e.chr=i.genome.getChromosomeName(e.refName);let t=!1;for(let r of i.referenceFrameList){const i=vf.fromLocusString(r.getLocusString());if(i.contains(e)){t=!0;break}if(i.overlaps(e)){r.extend(e),t=!0;break}}if(!t){const t=2e3,r=(e.start+e.end)/2;i.addMultiLocusPanel(e.chr,r-t,r+t)}}n(s),n(o)}})),this.circularViewControl=new pv(this.navbar.toggleButtonContainer,this),this.circularView.setAssembly({name:this.genome.id,id:this.genome.id,chromosomes:Kf(this.genome)}),this.circularViewVisible=t,this.circularView}get circularViewVisible(){return void 0!==this.circularView&&this.circularView.visible}set circularViewVisible(e){this.circularView&&(this.circularView.visible=e,this.circularViewControl.setState(e))}get overlayTrackButton(){return this.navbar.overlayTrackButton}get roiTableControl(){return this.navbar.roiTableControl}get sampleNameControl(){return this.navbar.sampleNameControl}get sampleInfoControl(){return this.navbar.sampleInfoControl}async blat(e){return Zl({sequence:e,browser:this,name:"Blat",title:"Blat"})}}async function ay(e){if(void 0===this.referenceFrameList||0===this.referenceFrameList.length)return;const t=this.calculateViewportWidth(this.referenceFrameList.length);this.updateReferenceFrames(t),this.updateViewportElements(t),await this.syncUIState()}function cy(e){e.preventDefault();const{x:t,y:i}=o(e);if(this.vpMouseDown){const{viewport:r,referenceFrame:s}=this.vpMouseDown,o=Math.abs(t-this.vpMouseDown.mouseDownX)>Math.abs(i-this.vpMouseDown.mouseDownY);if(!this.dragObject&&!this.isScrolling)if(o)this.vpMouseDown.mouseDownX&&Math.abs(t-this.vpMouseDown.mouseDownX)>this.constants.dragThreshold&&(this.dragObject={viewport:r,start:s.start});else if(this.vpMouseDown.mouseDownY&&Math.abs(i-this.vpMouseDown.mouseDownY)>this.constants.scrollThreshold){this.isScrolling=!0;const e=r.viewportElement.clientHeight,t=r.trackView.maxViewportContentHeight();this.vpMouseDown.r=e/t}if(this.dragObject){const i=!this.isSoftclipped();let o=this.vpMouseDown.lastMouseX-t;s.shiftPixels(o,r.viewportElement.clientWidth,i)&&this.updateViews(),this.fireEvent("trackdrag",[e])}if(this.isScrolling){const e=this.vpMouseDown.lastMouseY-i;r.trackView.scrollByPixels(e)}this.vpMouseDown.lastMouseX=t,this.vpMouseDown.lastMouseY=i}}function ly(e){this.cancelTrackPan(),this.endTrackDrag()}async function hy(e){if(this.referenceFrameList&&!(this.referenceFrameList.length>1)&&("KeyF"===e.code||"KeyB"===e.code)){const t=this.getSelectedTrackViews();if(t.length>0){const i=t[0].track;if("function"==typeof i.nextFeatureAfter){const t=this.referenceFrameList[0],r=t.viewport?t.viewport.getWidth():this.calculateViewportWidth(this.referenceFrameList.length),s="all"===t.chr.toLowerCase(),o=i.visibilityWindow;if(s||o&&o>0&&t.bpPerPixel*r>o)return;const n="KeyF"===e.code,a=t.chr,c=t.center,l=await i.nextFeatureAfter(a,c,n);if(l){const i=await this.genome.getChromosomeName(l.chr);if(a===i){const i=(l.start+l.end)/2;if(e.shiftKey){const e=this.config.minimumBases||40,s=Math.max(e,1.1*(l.end-l.start));t.start=Math.max(0,i-s/2),t.end=i+s/2,t.bpPerPixel=(t.end-t.start)/r}else t.shift(i-c);this.updateViews()}else{t.chr=i;const s=(l.start+l.end)/2;if(e.shiftKey){const e=this.config.minimumBases||40,i=Math.max(e,1.1*(l.end-l.start));t.start=Math.max(0,s-i/2),t.end=t.start+i,t.bpPerPixel=(t.end-t.start)/r}else t.start=s-r*t.bpPerPixel/2,t.end=t.start+r*t.bpPerPixel;this.updateViews()}}}}}}function dy(e,t){for(let{viewports:i}of e)for(let e of i)e.trackLabelElement&&(0===i.indexOf(e)&&!0===t?e.trackLabelElement.style.display="block":e.trackLabelElement.style.display="none")}let uy=[];function fy(e,t){void 0===t&&(t=py);for(const i of Object.keys(t))void 0===e[i]&&(e[i]=t[i]);return e}const py={minimumBases:40,showIdeogram:!0,showCytobandNames:!1,showCircularView:!1,showCircularViewButton:!1,showTrackLabelButton:!0,showTrackLabels:!0,showCursorTrackingGuideButton:!0,showCursorGuide:!1,showCenterGuideButton:!0,showCenterGuide:!1,showSampleNames:!1,showSVGButton:!0,showControls:!0,showNavigation:!0,showRuler:!0,flanking:1e3,pairsSupported:!0,tracks:[]},gy=Rr.setApiKey;const my=Rr.oauth;var wy={AlertDialog:Ao,TrackUtils:jd,IGVGraphics:Co,MenuUtils:Bd,DataRangeDialog:Od,createTrack:async function(e,t){return await ny.prototype.createTrack.call(t,e)},createBrowser:async function(e,t){void 0===t&&(t={}),Dh.KNOWN_GENOMES||await Dh.initializeGenomes(t),fy(t),t.queryParametersSupported&&function(e){var t,i,r,s,o,n,a,c,l;let h,d,u;if(a=window.location.href,o={},t=a.indexOf("?"),i=a.lastIndexOf("#"),t>=0)for(i<0&&(i=a.length),r=t+1;rt&&(i.indexURL=d[t]),u&&u.length>t&&(i.name=u[t]),e.tracks.push(i)}}}(t),t.apiKey&&Rr.setApiKey(t.apiKey),t.oauthToken&&Rr.setOauthToken(t.oauthToken),t.clientId&&!Cr()&&await async function(e){if(!google.accounts.oauth2.initTokenClient)throw new Error("Google accounts token client not loaded (https://accounts.google.com/gsi/client)");if(Cr())throw new Error("Google client is already initialized");const t={client_id:e.client_id||e.clientId,scope:e.scope||"https://www.googleapis.com/auth/userinfo.profile",state:e.state||"igv",error:e=>{throw new Error(e.type)},hint:e.hint,hosted_domain:e.hosted_domain},i=google.accounts.oauth2.initTokenClient(t);google.igv={tokenClient:i,apiKey:e.apiKey}}({client_id:t.clientId,apiKey:t.apiKey,scope:"https://www.googleapis.com/auth/userinfo.profile"}),t.formEmbedMode&&(Hd.FORM_EMBED_MODE=!0);const i=new ny(t,e);uy.push(i);const r=t.sessionURL||t.session||t.hubURL;return r?await i.loadSession({url:r}):await i.loadSessionObject(t),i.navbar.navbarDidResize(),i},removeBrowser:function(e){e.dispose(),e.root.remove(),uy=uy.filter((t=>t!==e))},removeAllBrowsers:function(){for(let e of uy)e.dispose(),e.root.remove();uy=[]},visibilityChange:async function(){for(let e of uy)await e.visibilityChange()},setGoogleOauthToken:function(e){return Rr.setOauthToken(e)},setOauthToken:function(e,t){return Rr.setOauthToken(e,t)},oauth:my,version:jF,setApiKey:gy,TrackBase:ma,registerTrackClass:function(e,t){qF.set(e,((e,i)=>new t(e,i)))},registerTrackCreatorFunction:function(e,t){qF.set(e,t)},registerFileFormats:function(e,t){na[e]={fields:t}},loadSessionFile:ny.loadSessionFile,loadHub:Nh,uncompressSession:ny.uncompressSession,createIcon:l};return wy})); //# sourceMappingURL=igv.min.js.map